body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have written this program after a lot of effort, and I was wondering about the efficiency of that solution and if it's neat.</p> <p>How plain is this program and is there any better way to rewrite it?</p> <pre><code>import string # Strength of operations: # -&gt; [] (brackets) # 6 -&gt; ~ (negative) # 5 -&gt; @, $, &amp; (average, maximum, minimum) # 4 -&gt; %, ! (modulo, factorial) # 3 -&gt; ^ (power) # 2 -&gt; *, / (multiplication, division) # 1 -&gt; +, - (addition, subtraction) def BinaryOperation(exp, idx): """ Gets an expression and an index of an operator and returns a tuple with (first_value, operator, second_value). """ first_value = 0 second_value = 0 #Get first value idx2 = idx -1 if idx2 == 0: first_value = exp[idx2:idx] else: while (idx2 &gt; 0) and (exp[idx2] in string.digits): idx2 -=1 if (exp[idx2] in ("-")) or (exp[idx2] in string.digits):#-5*3 first_value = exp[idx2:idx] else:#%5*3 first_value = exp[idx2+1:idx] #Get second value idx2 = idx +1 if exp[idx+1] not in string.digits: #If there is something like 1*+5, second_sign will be +. idx2 += 1 #idx2 will begin from the char after the sign. while (idx2 &lt; len(exp)) and (exp[idx2] in string.digits): idx2 += 1 second_value = exp[idx+1:idx2] return (first_value, exp[idx], second_value) def UnaryOperation(exp, idx): """ Gets an expression and an index of an operator and returns a tuple with (operator, value). """ #Get value idx2 = idx+1 if exp[idx+1] not in string.digits: #If there is something like ~-5, second_sign will be -. idx2 += 1 #idx2 will begin from the char after the sign. while (idx2 &lt; len(exp)) and (exp[idx2] in string.digits): idx2 +=1 return (exp[idx], exp[idx+1:idx2]) def Brackets(exp): idx = 0 while idx &lt; len(exp): if exp[idx] == "[": #Brackets close_bracket = exp.find("]") if close_bracket == -1: raise Exception("Missing closing bracket.") exp_brackets = exp[idx+1:close_bracket] value = str(solve(exp_brackets)) exp = exp.replace("[" + exp_brackets + "]", value) idx = 0 #The len has been changed, scan again. idx += 1 return Level6(exp) def Level6(exp): idx = 0 while idx &lt; len(exp): if exp[idx] in ("~"): #Negative sub_exp = UnaryOperation(exp, idx) value = ~int(sub_exp[1]) value = str(value) exp = exp.replace(''.join(sub_exp), value) idx = 0 #The len has been changed, scan again. idx += 1 return Level5(exp) def Level5(exp): idx = 0 while idx &lt; len(exp): if exp[idx] in ("@", "$", "&amp;"): #Average, Maximum and Minimum sub_exp = BinaryOperation(exp, idx) first_value = int(sub_exp[0]) second_value = int(sub_exp[2]) if sub_exp[1] == "@": value = (first_value + second_value)/2 if sub_exp[1] == "$": value = first_value if first_value &gt; second_value else second_value if sub_exp[1] == "&amp;": value = first_value if first_value &lt; second_value else second_value value = str(value) exp = exp.replace(''.join(sub_exp), value) idx = 0 #The len has been changed, scan again. idx += 1 return Level4(exp) def Level4(exp): idx = 0 while idx &lt; len(exp): if exp[idx] in ("%","!"): #Modulo and Factorial if exp[idx] == "%": sub_exp = BinaryOperation(exp, idx) value = int(sub_exp[0]) % int(sub_exp[2]) if exp[idx] == "!": sub_exp = UnaryOperation(exp, idx) value = reduce(lambda x,y:x*y, range(1, int(sub_exp[1])+1)) value = str(value) exp = exp.replace(''.join(sub_exp), value) idx = 0 #The len has been changed, scan again. idx += 1 return Level3(exp) def Level3(exp): idx = 0 while idx &lt; len(exp): if exp[idx] in ("^"): #Power sub_exp = BinaryOperation(exp, idx) value = int(sub_exp[0]) ** int(sub_exp[2]) value = str(value) exp = exp.replace(''.join(sub_exp), value) idx = 0 #The len has been changed, scan again. idx += 1 return Level2(exp) def Level2(exp): idx = 0 while idx &lt; len(exp): if exp[idx] in ("*", "/"): #Multiplication and Division sub_exp = BinaryOperation(exp, idx) if sub_exp[1] == "*": value = int(sub_exp[0]) * int(sub_exp[2]) if sub_exp[1] == "/": value = int(sub_exp[0]) / int(sub_exp[2]) value = str(value) exp = exp.replace(''.join(sub_exp), value) idx = 0 #The len has been changed, scan again. idx += 1 return Level1(exp) def Level1(exp): idx = 0 while idx &lt; len(exp): if (exp[idx] in ("+", "-")) and (idx != 0): #Addition and Subtraction sub_exp = BinaryOperation(exp, idx) if sub_exp[1] == "+": value = int(sub_exp[0]) + int(sub_exp[2]) if sub_exp[1] == "-": value = int(sub_exp[0]) - int(sub_exp[2]) value = str(value) exp = exp.replace(''.join(sub_exp), value) idx = 0 #The len has been changed, scan again. idx += 1 return exp def solve(exp): exp = Brackets(exp) return float(exp) if "." in exp else int(exp) def remove_whitespace(exp): """ Gets a string and removes all whitespaces and tabs """ exp = exp.replace(" ", "") exp = exp.replace("\t", "") return exp while True: exp = raw_input("") exp = remove_whitespace(exp) print solve(exp) </code></pre>
[]
[ { "body": "<p>Every <code>levelX</code> functions looks roughly the same:</p>\n\n<pre><code>idx = 0\nwhile idx &lt; len(exp):\n if exp[idx] in (...):\n //...\n\n value = str(value)\n\n exp = exp.replace(''.join(sub_exp), value)\n idx = 0 #The len has been changed, scan again.\n\n idx += 1\n</code></pre>\n\n<p>I don't like the idea of having 6 functions named <code>level#</code>. If I ask the question, \"where is exponentiation handled?\", the answer is \"check each <code>Level</code> function until you find it\" or \"search your code for the <code>^</code>\" character (I realize that you cheated and added a comment at the top to resolve this problem, but the ideal is for code to be mostly self-documenting). Both of these answers strikes me as less than ideal, though your code is short enough for it to be doable.</p>\n\n<p>Every level seems to be split up into a calculation section and a parsing section, the latter of which is identical (other than the token list) between functions. You should refactor this, separating out these two pieces of functionality. Consider using the strategy design pattern.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T18:57:09.570", "Id": "30902", "Score": "0", "body": "Thank you for your comment.\nI will check the strategy pattern out." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T18:43:26.253", "Id": "19306", "ParentId": "19291", "Score": "3" } }, { "body": "<p>The code would more straightforward if you used a lexer. A lexer does the very basic bits of parsing, transforming your incoming text into a list of tokens. So in this case, you might have</p>\n\n<pre><code>lexer(\"-5 + 4 * [7-3]^2\") == [-5, '+', 4, '*', '[', 7, '-', 3, ']', '^', 2]\n</code></pre>\n\n<p>This way all string manipulation will happen in the lexer, and the rest of your parsing code will be simplified. It just has to operate on the list of tokens.</p>\n\n<p>For parsing, I also like to have a Parser class. The Parser class will hold both the list of tokens and the current position. Then I have various utility functions on the Parser class. The process of parsing brackets should then look like:</p>\n\n<pre><code>parser.match( '[' )\nnumber = level6(parser)\nparser.match( ']' )\nreturn number\n</code></pre>\n\n<p><code>parser.match</code> will throw an exception if the expected element isn't there. Because the parser object takes care of the current location, you don't need to slice lists or anything.</p>\n\n<p>It would also be useful to have tests. Have a list of expressions with known values and then write code to loop over that list and assert that they have the same values. Add new items as you add features. That way if you ever break anything, the tests will catch it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T17:13:38.273", "Id": "30963", "Score": "0", "body": "Thank you for your comment.\nThe assignment was to use recursion and solve the \"strongest\" operations and then update the expression, until the weakest operation will be solved and then I can know that I finished solving the expression.\nWill I be able to solve the expressions with recursion if I split the expression to tokens?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T18:02:49.900", "Id": "30967", "Score": "0", "body": "@Lior: Yes, but the lexing step will not (and should not) be recursive. At a high level, a recursive calculator `Calculate(string)` which receives as input `\"5 * (34+1)\"` will eventually call `Calculate(\"34+1\")`. Winston's change just means you go from `Calculate(string)` to `Calculate(tokens)` (e.g., `Calculate(['5','*','(','34','+','1',')'])` calls `Calculate(['34','+','1'])` ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T19:09:47.450", "Id": "30970", "Score": "0", "body": "@Lior, as Brian says the lexer won't change the recursion at all. My suggestion of a parsing class probably would. It would still use recursion, but whether it fits your requirements I don't know." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T02:14:06.787", "Id": "19320", "ParentId": "19291", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T14:49:39.327", "Id": "19291", "Score": "3", "Tags": [ "python", "parsing" ], "Title": "Calculator for parsing user input" }
19291
<p>I created a function to calculate the font size to fit the width of the website I'm doing. I believe the code is a bit ugly and could use some improvement by creating a more logical function, faster and less heavy.</p> <p>Can someone look at the code and comment on it for my own improvement?</p> <pre><code>//Script jquery $(window).resize(function() { newWidthGhost = $('#ghostFontes').width(); widthFontsResize(); }); $(document).ready(function(){ $('body').find('*').addClass('wFonte'); $('.wFonte').each(function(i, el){ fontHeight[i] = $(el).css('font-size'); }); oldWidthGhost = $('#ghostFontes').width(); // TAMANHO WIDTH; widthFontsReady(); }); function widthFontsResize(){ $('.wFonte').each(function(i, el){ nFonte['e'+i] = parseInt((newWidthGhost * nFonte[i]) / oldWidthGhost); $(el).css({'font-size': nFonte['e'+i]+'px'}); }); } function widthFontsReady(){ $('.wFonte').each(function(i, el){ nFontHeigth[i] = parseInt(fontHeight[i].substr(0,2)); nFonte[i] = parseInt((oldWidthGhost * nFontHeigth[i]) / 1586); $(el).css({'font-size': nFonte[i]+'px'}); }); } </code></pre>
[]
[ { "body": "<h1>Use strict-mode</h1>\n\n<p>Start your code with <code>\"use strict\";</code>:<br>\n<a href=\"https://stackoverflow.com/questions/1335851/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it\">https://stackoverflow.com/questions/1335851/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it</a></p>\n\n<h1>Don't pollute the global namespace</h1>\n\n<p>When you don't use <code>var x;</code> to declare a variable, it is implicitly declared in the global namespace. If another script does the same, both scripts will be using the same variable.</p>\n\n<p>It is not very easy for this to happen with an odd name like <code>newWidthGhost</code>, but <code>fontHeight</code> sounds like a better candidate for these surprises.</p>\n\n<h1>Run the code through JSLint</h1>\n\n<p>Run your code through <a href=\"http://www.jslint.com/\" rel=\"nofollow noreferrer\">JSlint</a>, and try to understand the errors and suggestions it gives you.</p>\n\n<p>That alone will greatly improve the quality of your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T16:38:14.363", "Id": "30899", "Score": "0", "body": "I understand, but I'm wanting more of a technical code, where I can improve, logic, where I can slow down or I can use to improve or be a little less heavy. Because the code puts it in a class all tags (wFonte). As I said at the beginning'm new and want to learn better what I did: D. But still I appreciate the tip that is also very important" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T17:31:48.433", "Id": "30900", "Score": "0", "body": "I hope you get the advice you seek. Also: I understand, but I think it's important to first improve the foundations, before working on improving the house." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T16:29:35.410", "Id": "19298", "ParentId": "19292", "Score": "3" } }, { "body": "<p>From what I understand from your code, you are scaling the original fonts as the window resizes, am I correct?</p>\n\n<p>For a totally better approach, use the native <code>em</code> scaling technique. That is, change the parent <code>em</code> measurement, you also change the children within it. <a href=\"http://jsfiddle.net/yZg64/3/\" rel=\"nofollow\">Here's sample code</a> which is exponentially shorter than yours:</p>\n\n<pre><code>$(function() {\n //caching frequently used elements and values\n var ghostFontes = $('#ghostFontes'),\n $window = $(window),\n originalWidth = ghostFontes.width();\n\n $window.on('resize', function() {\n //scale the parent container's em measurement \n //with the ratio of width to original width\n ghostFontes.css('font-size',(ghostFontes.width() / originalWidth)+'em');\n\n });\n});​\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T00:59:50.660", "Id": "19319", "ParentId": "19292", "Score": "2" } } ]
{ "AcceptedAnswerId": "19319", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T15:49:38.503", "Id": "19292", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "Calculating the font size to fit the width of a website" }
19292
<p>Below is my current code for sorting an array, "$jobs_list".</p> <p>It's not very DRY and it's fugly. And there are several more similar case statements still to go in. How could I write it so my brain doesn't twitch to look at it?</p> <pre><code>switch ($sort) { case 'number': usort($jobs_list, function($a, $b){ return ( (int) $a-&gt;number &gt; (int) $b-&gt;number ); }); break; case 'client': usort($jobs_list, function($a, $b){ return strcmp($a-&gt;client_contact_last_name, $b-&gt;client_contact_last_name); }); break; case 'name': usort($jobs_list, function($a, $b){ return strcmp($a-&gt;name, $b-&gt;name); }); break; case 'status': usort($jobs_list, function($a, $b){ return ( (int) $a-&gt;status &gt; (int) $b-&gt;status ); }); break; case 'revenue': usort($jobs_list, function($a, $b){ return ( (float) $a-&gt;base_revenue &gt; (float) $b-&gt;base_revenue ); }); break; case 'profit': usort($jobs_list, function($a, $b){ return ( (float) $a-&gt;profit &gt; (float) $b-&gt;profit ); }); break; case 'margin': usort($jobs_list, function($a, $b){ return ( (float) $a-&gt;margin &gt; (float) $b-&gt;margin ); }); break; default: # do nothing... } </code></pre>
[]
[ { "body": "<p>I'd start by moving the <code>switch</code> statement into the callback function:</p>\n\n<pre><code>usort($jobs_list, function($a, $b){\n switch ($sort):\n case 'number':return ( (int) $a-&gt;number &gt; (int) $b-&gt;number ); break;\n case 'client':return strcmp($a-&gt;client_contact_last_name, $b-&gt;client_contact_last_name); break;\n //etc...\n endswitch;\n });\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T15:08:53.767", "Id": "30896", "Score": "2", "body": "This would be a lot worse performance wise" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T15:07:03.793", "Id": "19295", "ParentId": "19294", "Score": "-1" } }, { "body": "<p>First, it may make sense to make sure that the field you're checking in $sort, is the same as the propertyname of the object in $jobs_list.</p>\n\n<p>Also, it looks like there's a lot of identical sort functions; the only difference being that the property you're checking is different.</p>\n\n<p>You could just combine the switch statements that have an identical sorting strategy (revenue, status, profit, margin, etc..) and turn the field into a variable, such as:</p>\n\n<pre><code>switch ($sort) {\n case 'number':\n case 'status':\n case 'profit':\n case 'margin':\n usort($jobs_list, function($a, $b) use ($sort) {\n return ( (float) $a-&gt;$sort &gt; (float) $b-&gt;$sort );\n });\n break;\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T15:37:13.050", "Id": "30897", "Score": "0", "body": "Of course. I was looking at my code thinking \"this is... wrong\" - combining the case statements never occurred to me. Doh. Thank you - your point about checking the property name also taken on board :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T23:16:46.973", "Id": "30914", "Score": "0", "body": "Bad thing is: $sort is not always stating the property that should be compared. And I like it so - a mapping is a good idea in this spot, because requested ordering and existing object property need not correlate." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T15:12:38.613", "Id": "19296", "ParentId": "19294", "Score": "7" } }, { "body": "<p>I tried to minimise the obvious copy/paste repetition as much as possible, without sacrificing performance (which moving the switch into the comparator would do):</p>\n\n<pre><code>usort($jobs_list, get_sort_function($sort));\n\nfunction get_sort_function($sort) {\n switch ($sort) {\n case 'number':\n return function($a, $b) {\n return ( (int) $a-&gt;number &gt; (int) $b-&gt;number );\n }\n case 'client':\n return function($a, $b) {\n return strcmp($a-&gt;client_contact_last_name, $b-&gt;client_contact_last_name);\n }\n }\n}\n</code></pre>\n\n<p>I don't have a PHP interpreter to hand so I apologise in advance if this isn't quite the right syntax, but hopefully you get the idea from the code anyway.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T20:45:44.207", "Id": "19311", "ParentId": "19294", "Score": "2" } }, { "body": "<p>I came across this solution, avoiding the switch statement alltogether:</p>\n\n<pre><code>$sort_functions = array(\n 'number' =&gt; function($a, $b){ return ( (int) $a-&gt;number &gt; (int) $b-&gt;number ); },\n 'client' =&gt; function($a, $b){ return strcmp($a-&gt;client_contact_last_name, $b-&gt;client_contact_last_name); },\n 'name' =&gt; function($a, $b){ return strcmp($a-&gt;name, $b-&gt;name); },\n 'status' =&gt; function($a, $b){ return ( (int) $a-&gt;status &gt; (int) $b-&gt;status ); },\n 'revenue' =&gt; function($a, $b){ return ( (float) $a-&gt;base_revenue &gt; (float) $b-&gt;base_revenue ); },\n 'profit' =&gt; function($a, $b){ return ( (float) $a-&gt;profit &gt; (float) $b-&gt;profit ); },\n 'margin' =&gt; function($a, $b){ return ( (float) $a-&gt;margin &gt; (float) $b-&gt;margin ); },\n);\n\nif (isset($sort_functions[$sort])) {\n usort($jobs_list, $sort_functions[$sort]);\n}\n</code></pre>\n\n<p>Bonus: It is easily extensible should new fields appear. Negative: Still a lot of code duplication for three basic comparisons... But we will address it:</p>\n\n<p>Extracting all basic functions into separate variables (an array would work here, too), and adding the field that should be compared to this function, you get an almost universal arsenal of comparison of object properties.</p>\n\n<pre><code>$intcompare = function($a, $b, $field){ return ( (int) $a-&gt;$field &gt; (int) $b-&gt;$field ); };\n$stringcompare = function($a, $b, $field){ return strcmp($a-&gt;$field, $b-&gt;$field); };\n$floatcompare = function($a, $b, $field){ return ( (float) $a-&gt;$field &gt; (float) $b-&gt;$field); };\n</code></pre>\n\n<p>Call these functions by passing them into the anonymous functions for each field.</p>\n\n<pre><code>$sort_functions = array(\n 'number' =&gt; function($a, $b) use ($intcompare) { return $intcompare($a, $b, 'number'); },\n 'client' =&gt; function($a, $b) use ($stringcompare) { return $stringcompare($a, $b, 'client_contact_last_name'); },\n 'name' =&gt; function($a, $b) use ($stringcompare) { return $stringcompare($a, $b, 'name'); },\n 'status' =&gt; function($a, $b) use ($intcompare) { return $intcompare($a, $b, 'status' ); },\n 'revenue' =&gt; function($a, $b) use ($floatcompare) { return $floatcompare($a, $b, 'base_revenue' ); },\n 'profit' =&gt; function($a, $b) use ($floatcompare) { return $floatcompare($a, $b, 'profit' ); },\n 'margin' =&gt; function($a, $b) use ($floatcompare) { return $floatcompare($a, $b, 'margin' ); },\n);\n\nif (isset($sort_functions[$sort])) {\n usort($jobs_list, $sort_functions[$sort]);\n}\n</code></pre>\n\n<p>Testing if it works:</p>\n\n<pre><code>$jobs_list = array(\n (object) array('number' =&gt; 1),\n (object) array('number' =&gt; 0),\n );\n$sort = 'number';\n\nvar_dump($jobs_list);\n\nif (isset($sort_functions[$sort])) {\n usort($jobs_list, $sort_functions[$sort]);\n}\n\nvar_dump($jobs_list);\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>array(2) {\n [0] =&gt;\n class stdClass#11 (1) {\n public $number =&gt;\n int(1)\n }\n [1] =&gt;\n class stdClass#12 (1) {\n public $number =&gt;\n int(0)\n }\n}\n\narray(2) {\n [0] =&gt;\n class stdClass#12 (1) {\n public $number =&gt;\n int(0)\n }\n [1] =&gt;\n class stdClass#11 (1) {\n public $number =&gt;\n int(1)\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T23:12:53.697", "Id": "19315", "ParentId": "19294", "Score": "1" } }, { "body": "<p>So far I don't see anything indicating that you need something other than ASC sorting. The spaceship operator auto-magically compares numeric values as numeric values and non-numeric strings as strings, so it seems to me that there is currently no benefit to creating conditional sorting calls.</p>\n<p>Just pass the target column into <code>usort()</code> using <code>use()</code> (if under php7.4).</p>\n<pre><code>$column = 'name';\nusort(\n $jobs_list,\n function($a, $b) user($column) {\n return $a-&gt;{$column} &lt;=&gt; $b-&gt;{$column};\n }\n);\nvar_export($job_list);\n</code></pre>\n<p>Above PHP7.4, you can use arrow function syntax.</p>\n<pre><code>$column = 'name';\nusort($jobs_list, fn($a, $b) =&gt; $a-&gt;{$column} &lt;=&gt; $b-&gt;{$column});\nvar_export($job_list);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-28T05:19:44.173", "Id": "255315", "ParentId": "19294", "Score": "1" } } ]
{ "AcceptedAnswerId": "19296", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T15:00:23.627", "Id": "19294", "Score": "1", "Tags": [ "php", "sorting" ], "Title": "Sorting an array of jobs by various criteria" }
19294
<p>I've built a Connection class that uses a PDO connection, but it looks messy and im sure there are ways of improving it. Currently I only want 1 instance of the connection (singleton). </p> <pre><code>&lt;?php namespace AQEConnect { use \PDO as PDO; /** Includes */ require_once dirname(__DIR__) . '/config.php'; // Contains the database config (HOST, DBNAME, USERNAME, PASSWORD). /** * A static class that holds the database connection. */ class Connection { /** * @var null|PDO Contains the PDO connection to the database. */ private static $_connection = null; /** * Initialises a connection to the database if the connection is null. If PDOException is thrown then * it dies. */ private static function _connect() { $connection_attempt_limit = 5; // Maximum number of attempts to connect to Database. for ($con_attempt_num = 0; $con_attempt_num &lt;= $connection_attempt_limit; $con_attempt_num++) try { if (self::$_connection === null) { // Check if connection is currently null. self::$_connection = new PDO('mysql:host=' . HOST . ';port=' . PORT . ';dbname=' . DBNAME, USERNAME, PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND =&gt; 'SET NAMES utf8')); self::$_connection-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); } } catch (PDOException $exception) { /** Error occurred so roll the connection back and set it to null. */ self::$_connection-&gt;rollBack(); self::$_connection = null; /** If connection attempt number is at the maximum number of attempts then trigger an 'E_CORE_ERROR' * (and log it). */ if ($con_attempt_num == $connection_attempt_limit) { $trace = debug_backtrace(); trigger_error('Exception: [' . $exception . '] in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_ERROR); die; // If PDOException is thrown then die. } } } /** * @return bool Whether the class currently has a connection. */ public static function hasConnection() { return self::$_connection !== null; } /** * @return null|PDO Current connection. */ public static function get() { if (self::$_connection === null) self::_connect(); // If connection is currently null then connect. return self::$_connection; } /** * Stop Connection class from being cloned, as there is currently no * legitimate reason why it should ever need to be cloned. */ protected function __clone() { } /** * @return string Current Connection class details. */ public function __toString() { return self::hasConnection() ? 'Connected to: ' . DBNAME . '.' : 'No Connection.'; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T23:12:50.883", "Id": "30996", "Score": "1", "body": "I plan on writing a proper response at some point (probably Friday), but for the time being, you might should read http://stackoverflow.com/questions/4595964/who-needs-singletons/4596323#4596323. That's actually a very brief explanation of why singletons and PHP don't mix. I've yet to see a legitimate use of a singleton in PHP in the wild. Potentially also relevant: http://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton. In short, what I'm trying to say is that a class modeling a DB connection should never be a singleton." } ]
[ { "body": "<p>This is a little bit of a reworked class based on your code example. Some things to keep in mind while writing your version:</p>\n\n<ul>\n<li><p>Is this testable? Currently it is not; the db config is assumed, the toString is assuming a db credential ( DBNAME ), etc.</p></li>\n<li><p>Your db connectivity is coupled to this class. What would happen if you wanted to use this for another application?</p></li>\n<li><p>Your db connectivity is hinged on the fact that the assumption is made there is a config file. What will happen if there is no config.php? The path to the config is hardcoded to be the root of this <strong>DIR</strong>. What happens if this script is moved?</p></li>\n<li><p>Declaring database connection parameters as global definitions is generally not a good idea. Having PORT/HOST/DBNAME/USERNAME/PASSWORD out in the global space ( assuming you are defining them in the config.php ) is a security risk.</p></li>\n</ul>\n\n<p>Anyhow, here is a slighly reworked class.</p>\n\n<pre><code>namespace AQEConnect;\n\nclass Connection\n{\n/**\n * @var \\PDO|null\n */\nprivate static $connection;\n\n/**\n * Return whether or not there is a current database connection\n * or not.\n * \n * @return string\n */\npublic function __toString()\n{\n if (!is_defined('DBNAME')) {\n self::extractConfiguration();\n }\n\n return (!($connection instanceof \\PDO)) ? \n 'No Connection' : 'Connected to: ' . DBNAME;\n}\n\n/**\n * Based on a config static location, extract the necessary database\n * configuration from the required file.\n */\npublic static function extractConfiguration()\n{\n // Include config to local database credentials for connecting\n $configPath = dirname(__DIR__) . '/config.php';\n if (!file_exists($configPath)) {\n trigger_error('Exception: Failed to find database connection configuration.');\n die;\n }\n\n require_once dirname(__DIR__) . '/config.php';\n}\n\n/**\n * Connects to the database through the PDO abstraction layer\n * given a set of assumed database credentials. It will attempt\n * to connect 5 times before it fails.\n *\n * @return boolean\n */\npublic static function connect()\n{\n // Before we attempt any of this logic make sure that we do\n // not currently have a connection.\n if (self::$connection) {\n return true;\n }\n\n // Make sure the config credentials are loaded.\n self::extractConfiguration();\n\n $attemptsLimit = 5;\n $attempt = 0;\n while ($attempt &lt; $attemptsLimit) {\n self::$connection = new PDO(\n 'mysql:host=' . HOST . ';port=' . PORT . ';dbname=' . DBNAME, \n USERNAME, \n PASSWORD, \n array(\n PDO::MYSQL_ATTR_INIT_COMMAND =&gt; 'SET NAMES utf8'\n )\n );\n\n if (self::$connection) {\n break;\n }\n\n $attempt++;\n }\n\n // If we failed to get a connection at this point we want to go ahead\n // and kill the script and throw an error.\n if (!self::$connection) {\n $trace = debug_backtrace();\n trigger_error(\n 'Exception: [' . $exception . '] in ' . $trace[0]['file'] .\n ' on line ' . $trace[0]['line'], E_ERROR\n );\n die; \n }\n\n return true;\n}\n\n/**\n * Returns a boolean result which represents whether or not\n * an open connection is currently present.\n *\n * @return boolean\n */\npublic static function hasConnection()\n{\n return is_null(self::$connection);\n}\n\n/**\n * Returns an instance of the set database instance. If the\n * connection is null, it will attempt to connect.\n * \n * @return \\PDO\n */\npublic static function getInstance()\n{\n if (!self::$connection) {\n self::connect();\n }\n\n return self::$connection;\n}\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T07:25:11.690", "Id": "30921", "Score": "1", "body": "I just started to -1 this since the code in it is worse than what the question contains now, but then I realized that the question has been revised :). Even relative to the original code in the question though, this answer still has some major flaws. In particular, extractConfiguration cannot be called twice without issuing warnings, and constants are always global, even if defined in a method so your extractConfiguration is pointless anyway. (Edit: Actually, I didn't realize the question had been edited until it was too late to undo the downvote. Sorry.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T16:55:46.463", "Id": "19300", "ParentId": "19297", "Score": "0" } }, { "body": "<h2>Basic mistakes</h2>\n\n<ul>\n<li><p>Forget static, it's not object oriented, it's ugly and unreadable</p></li>\n<li><p>Forget constans in classes, inject them instead (global hyperspace is bad, untestable, uncontrolable)</p></li>\n</ul>\n\n<h2>Generic approach</h2>\n\n<pre><code>&lt;?php\n\ninterface ICredentials {\n\n function UserID();\n\n function Password();\n}\n\ninterface IDbProvider {\n\n /**\n * \n * @return array Driver specific options for PDO\n */\n function GetOptions();\n}\n\nclass MySQL implements IDbProvider {\n\n public function GetOptions() {\n return array(PDO::MYSQL_ATTR_INIT_COMMAND =&gt; 'SET NAMES utf8');\n }\n\n}\n\n/*abstract*/ class SqlConnection {\n\n /**\n *\n * @var \\PDO\n */\n private $_connection;\n private $_connectionString;\n\n /**\n *\n * @var \\ICredentials \n */\n private $_credentials;\n\n /**\n *\n * @var \\IDbProvider\n */\n private $_options;\n\n public function __construct($connectionString, \\ICredentials $credentials, \\IDbProvider $options) { //or protected, especially if abstract class\n $this-&gt;_connectionString = $connectionString;\n $this-&gt;_credentials = $credentials;\n $this-&gt;_options = $options;\n }\n\n /**\n * \n * @return \\PDO\n */\n public function Connection() { //or protected, especially if abstract class\n if ($this-&gt;_connection == NULL) {\n $options = $this-&gt;_options-&gt;GetOptions();\n $options[\\PDO::ATTR_ERRMODE] = \\PDO::ERRMODE_EXCEPTION;\n\n $this-&gt;_connection = new \\PDO($this-&gt;_connectionString, $this-&gt;_credentials-&gt;UserID(), $this-&gt;_credentials-&gt;Password(), $options);\n }\n\n return $this-&gt;_connection;\n }\n\n protected function _close() {\n if ($this-&gt;_connection != NULL) {\n $this-&gt;_connection = NULL;\n }\n }\n\n public function __destruct() {\n $this-&gt;_close();\n }\n\n}\n</code></pre>\n\n<h2>Usage #1</h2>\n\n<p>(First you have to implement IDbCredentials.)</p>\n\n<pre><code>$connection = new SqlConnection('mysql:host=localhost;dbname=testdb', $credentialsInstance, new MySQL());\n</code></pre>\n\n<h2>Usage #2 as abstract</h2>\n\n<p>The instantiating is the same, in this current example the options aren't injected (i would do this in a generated db specific object context class but in a general DbConnection as in the example).</p>\n\n<pre><code>class DbConnection extends SqlConnection {\n\n public function __construct($connectionString, \\ICredentials $credentials) {\n parent::__construct($connectionString, $credentials, new MySQL());\n }\n\n public function Execute($something /* ... parameters ... */) {\n try {\n $this-&gt;Connection()-&gt;beginTransaction();\n\n /* something */\n\n $this-&gt;Connection()-&gt;commit();\n } catch (\\PDOException $pdoExc) {\n if ($this-&gt;Connection() != NULL &amp;&amp; $this-&gt;Connection()-&gt;inTransaction()) {\n $this-&gt;Connection()-&gt;rollBack();\n }\n\n throw $pdoExc;\n }\n }\n\n}\n\n$connection = new DbConnection('mysql:host=localhost;dbname=testdb', $credentialsInstance);\n\n$connection-Execute(\"INSERT INTO ...\", array(/* params */));\n</code></pre>\n\n<ul>\n<li>Easy to read</li>\n<li>Easy to understand</li>\n<li>Easy to test</li>\n<li>Easy to reuse</li>\n<li>Maybe __clone can be implemented :)</li>\n</ul>\n\n<h2>Edit</h2>\n\n<p>You can create a derived class which constructor accepts only one object instance which is holding all the information what are needed to establish the connection. (The implementation can be read the configuration values from XML or any other source.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T19:46:02.580", "Id": "30906", "Score": "0", "body": "I like the format of that and is defiantly very reusable, but can you give me an example of how you would implement it (an example of opening a new connection). Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T22:24:05.247", "Id": "30912", "Score": "1", "body": "I have updated my answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T17:53:31.120", "Id": "19303", "ParentId": "19297", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T16:17:11.317", "Id": "19297", "Score": "1", "Tags": [ "php" ], "Title": "Connection class" }
19297
<p>I have been presented with a simple but slow performing LINQ to Entities query which I've pasted below.</p> <p>Could anybody give me some pointers on how to improve performance? The query below has been significantly improved since I inherited it but I don't know what else I can do without moving to the DB (which isn't an option at this stage)</p> <pre><code>var created = DateTime.Now.AddMonths(-6); return (from t1 in db.Opportunities from s1 in db.OpportunityStatus.Where(x =&gt; x.OpportunityStatus_ID == t1.StatusReason_ID) from t2 in db.Leads.Where(x =&gt; x.Lead_ID == t1.Lead_ID) from t3 in db.Tasks.Where(x =&gt; (x.Type_ID == 4) &amp;&amp; (x.Item_ID == t1.Opportunity_ID)).DefaultIfEmpty() from t4 in db.TaskAppointments.Where(x =&gt; x.Parent_Task_ID == t3.Task_ID).DefaultIfEmpty() from t5 in db.Addresses.Where(x =&gt; x.Address_ID == t4.Address_ID).DefaultIfEmpty() from n1 in db.Notes.Where(x =&gt; x.Type_ID == 4 &amp;&amp; (x.Item_ID == t1.Opportunity_ID)).DefaultIfEmpty() from n2 in db.Notes.Where(x =&gt; x.Type_ID == 5 &amp;&amp; (x.Item_ID == t1.Lead_ID)).DefaultIfEmpty() from t6 in db.Quotations.Where(x =&gt; x.OpportunityId == t1.Opportunity_ID).DefaultIfEmpty() from u1 in db.UserNames.Where(x =&gt; x.User_Username == t1.Owner).DefaultIfEmpty() from u2 in db.UserNames.Where(x =&gt; x.User_Username == t2.Owner).DefaultIfEmpty() where (t1.Company_ID == company) &amp;&amp; (t1.Created &gt;= created) orderby (t1.Created) descending group new { t1, t3, t4, s1, t6, u1, u2, n1, n2, t5 } by new { t1.Opportunity_Title, t2.Company_Name, s1.OpportunityStatus_Name, ts = u1.Name, fs = u2.Name } into g let latestAppointment = g.Max(uh =&gt; uh.t4.AppointmentStart) let latestAppointmentStatus = g.FirstOrDefault(x =&gt; x.t4.AppointmentStart == latestAppointment).t4.AppointmentStatu.Status_Name let latestAppointmentCity = g.FirstOrDefault(x =&gt; x.t4.AppointmentStart == latestAppointment).t5.City let latestNoteDate = g.Max(uh =&gt; uh.n2.Date) let latestNote = g.FirstOrDefault(x =&gt; x.n2.Date == latestNoteDate).n2.Note_Text let latestOpportunityNoteDate = g.Max(uh =&gt; uh.n1.Date) let latestQuotationDate = g.Max(uh =&gt; uh.t6.Created) select new PipelineViewModel { Id = 0, CompanyName = g.Key.Company_Name, OpportunityTitle = g.Key.Opportunity_Title, CompanyCity = latestAppointmentCity, OpportunityStatusName = g.Key.OpportunityStatus_Name, LastAppointmentDate = latestAppointment, LastAppointmentStatus = latestAppointmentStatus, LastOpportunityNoteDate = latestOpportunityNoteDate, LastNoteDate = latestNoteDate, LastNote = latestNote, LastQuoteDate = latestQuotationDate, TelesalesUserName = g.Key.ts, FieldSalesUserName = g.Key.fs }).Take(howMany); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T18:06:21.673", "Id": "30901", "Score": "6", "body": "I hope there is a *strong* reason why `db.Oportunities` has a `StatusReason_ID` and not a `StatusReason`, a `Lead_ID` and not a `Lead`, etc. Because all these joins? \"POOF GONE!\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T19:00:05.800", "Id": "30903", "Score": "1", "body": "What @ANeves said. Also, ordering then grouping probably isn't going to be doing what you want, especially since you're then transforming it later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T19:11:05.733", "Id": "30905", "Score": "1", "body": "Also, `let latestAppointmentStatus = g.FirstOrDefault(x => x.t4.AppointmentStart == latestAppointment).t4.AppointmentStatus.Status_Name` will throw a `NullReferenceException` under some circumstances." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T03:54:57.150", "Id": "30999", "Score": "1", "body": "Does the backing model have any navigation properties defined? Or it's a model with just tables thrown in and no relationships?" } ]
[ { "body": "<p>This can't be called \"simple\". And it's not possible to tell where bottleneck is because of so many joins and subqueries.</p>\n\n<p>Subqueries are certainly suspect, you can optimize them by using Dictionary&lt;> (as you would add indexes in real DB).</p>\n\n<p>I would also try to split this huge query into small ones, put ToArray() at the end of each one, and run a profiler to get some hints on what is slow.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T20:24:55.587", "Id": "19309", "ParentId": "19299", "Score": "5" } }, { "body": "<p>Here is my approach which has helped one of my friends to boost the performance of a similar complex query by <strong>450%</strong>:</p>\n\n<ol>\n<li>While opening your project in Visual Studio, set a breakpoint at the beginning of your query.</li>\n<li>Start with debugging <kbd>F5</kbd>.</li>\n<li>Wait till the execution hit your breakpoint (hold on).</li>\n<li>Run SQL profiler.</li>\n<li>Execute your query and wait till the execution is finished.</li>\n<li>Grab the SQL query that the SQL profiler has caught.</li>\n<li>Open a new query window in SQL server.</li>\n<li>Paste your generated SQL query.</li>\n<li>Right click, then select \"Analyze Query in Database Engine Tuning Advisor\".</li>\n<li>When the \"Database Engine Tuning Advisor\"\" hit \"Start Analysis\".</li>\n<li>It may take some time to look for suggestions to optimize your query, but when finished, it will tell you the recommended performance gain when applying the recommended modifications.</li>\n<li>If the wizard suggested some sort of recommendations, I highly recommend you to apply them, open up \"Tools=> Apply Recommendations\"</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T04:44:28.403", "Id": "31000", "Score": "0", "body": "Great comments, but the OP said he wasn't ready to start changing the database." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T00:09:12.193", "Id": "19349", "ParentId": "19299", "Score": "4" } }, { "body": "<p>You have gone through the hard way when you should follow the easy way!! \nWhy do you need to load so much data all at once?? </p>\n\n<p>My suggestion is to break that (stupendous) query into smaller queries and call each one when is needed...(even if you need all at the same time). </p>\n\n<p>But before anything, take a picture of that piece of art! :D </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T12:17:59.023", "Id": "35912", "ParentId": "19299", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T16:43:43.730", "Id": "19299", "Score": "6", "Tags": [ "c#", "linq" ], "Title": "LINQ to Entities query with lots of grouping" }
19299
<p>Mask.html</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="mask.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" type="text/css" href="mask.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="div1" style="margin: 5px; border: 1px solid red; height: 100px; width: 500px;"&gt;&lt;/div&gt; &lt;div id="div2" style="margin: 5px; border: 1px solid blue; height: 100px; width: 500px"&gt; &lt;div id="div3" style="margin: 5px; border: 1px solid red; height: 88px; width: 235px; float:left;"&gt;&lt;/div&gt; &lt;div id="div4" style="margin: 5px; border: 1px solid green; height: 88px; width: 235px; float:left;"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Mask.js</p> <pre><code>(function ($) { $.fn.Mask = function () { if ($(this).find('.Mask').length &gt; 0) return null; var __ctrl = $(this)[0]; if (__ctrl.tagName != 'DIV') return null; var containerCssPaddingTop = $(__ctrl).css('padding-top'); var containerCssPaddingRight = $(__ctrl).css('padding-right'); var containerCssPaddingBottom = $(__ctrl).css('padding-bottom'); var containerCssPaddingLeft = $(__ctrl).css('padding-left'); $(__ctrl).css('position', 'relative'); $(__ctrl).css('overflow', 'hidden'); var mask = '&lt;div class="Mask"&gt;&lt;div class="MaskContent"&gt;&lt;img src="PleaseWait.gif"/&gt;&lt;/div&gt;&lt;/div&gt;'; $(__ctrl).prepend(mask); var m = $(this).find('.Mask'); var mc = $(this).find('.MaskContent'); m.css('margin-top', '-' + containerCssPaddingTop); m.css('margin-right', '-' + containerCssPaddingRight); m.css('margin-bottom', '-' + containerCssPaddingBottom); m.css('margin-left', '-' + containerCssPaddingLeft); // The 16 just comes from the fact that the image displayed is 32x32 mc.css('left', m.width()/2 - 16 + "px"); var toReturn = { RemoveMask: function () { m.remove(); } }; return toReturn; }; })(jQuery); </code></pre> <p>mask.css</p> <pre><code>.Mask { background-image: -webkit-radial-gradient(center, ellipse farthest-side, #FFFFFF 0%, #EEEEEE 100%); height: 100%; opacity: 0.8; position: absolute; width: 100%; z-index: 4; } .MaskContent { background: none; position: absolute; top: 30%; z-index: 5; } </code></pre> <p>The real code I would like reviewed/criticized is in Mask.js and Mask.css</p> <p>The idea is that this extends jQuery so you can block a div while it is being updated.</p> <p>You would use it by running</p> <pre><code>v = $('#div1').Mask() </code></pre> <p>then, to remove it, one would do</p> <pre><code>v.RemoveMask(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T19:04:35.400", "Id": "30904", "Score": "4", "body": "Quick comment: PascalCase is only for constructors which are meant to be called with `new`. All other methods should use **camelCase**." } ]
[ { "body": "<p>The code looks fine to me. Just a couple minor points:</p>\n\n<ol>\n<li><p>Why do you change the <code>div</code>'s <code>position</code> to <code>relative</code>? If the function is called on a <code>div</code> with absolute positioning, it would mess up the layout. And you should revert the CSS changes on <code>RemoveMask()</code> to what they were when <code>Mask()</code> was called because the <code>div</code>'s content might depend on a certain <code>overflow</code> value.</p></li>\n<li><p>If the <code>div</code> changes size while masked, the image will no longer be horizontally centered. I would suggest using CSS instead of JS to center it:</p>\n\n<pre><code>.MaskContent {\n background: none;\n position: absolute;\n width: 32px;\n height: 32px;\n top: 30%;\n left: 50%;\n margin-left: -16px;\n z-index: 5;\n}\n</code></pre></li>\n<li><p>Your mask background currently only supports webkit browsers; you should add the CSS3 variations for the other browsers.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T14:25:15.193", "Id": "19739", "ParentId": "19304", "Score": "2" } } ]
{ "AcceptedAnswerId": "19739", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T18:18:14.190", "Id": "19304", "Score": "6", "Tags": [ "javascript", "jquery", "html", "css" ], "Title": "DIV mask implemented in JavaScript/CSS" }
19304
<p>I've written a die roller which can be run from the command line. It currently exists as three files, but I'll say later why I'd like to make it four. The files are as follows:</p> <ul> <li><strong>die.py</strong>: Defines the <code>Side</code> and <code>Die</code> classes and extends <code>Die</code> with the <code>NSided</code> and <code>Fudge</code> classes.</li> <li><strong>summer.py</strong>: Defines the default <code>Summer</code> class and extends it with <code>Highest</code>, a class that will sum the highest values in a set of rolls.</li> <li><strong>parser.py</strong>: Implements main functionality of the application by creating and calling instances of die and summer classes, as well as predefined values. Takes arguments from the user and returns the sum of all values.</li> </ul> <p>I feel that <em>die.py</em> is well implemented but am willing to hear how it can be improved. The other files are less concise and will likely get more of my attention.</p> <pre><code>from random import choice class Side(dict): """A side contains all info needed by a die and roller. &gt;&gt;&gt; d = Side(4, 'death') &gt;&gt;&gt; print d death &gt;&gt;&gt; print d.keys() ['char', 'num'] &gt;&gt;&gt; print d.values() ['death', 4] &gt;&gt;&gt; """ def __init__(self, num, char): """ Args: num (int) - Used to calculate value of roll. char (str) - Used to display face of roll. """ self['num'] = num self['char'] = char def __repr__(self): return str(self['char']) __str__ = __repr__ class Die(list): """A die is a list of sides, all of equal probability.""" def __init__(self, sides): for side in sides: self.append(side) def roll(self): return choice(self) class NSided(Die): """Returns an n-sided die. Args: numsides (int) - The highest value on the die. &gt;&gt;&gt; d = NSided(6) &gt;&gt;&gt; print d [1, 2, 3, 4, 5, 6] &gt;&gt;&gt; """ def __init__(self, numsides): sides = [] for i in range(numsides): sides.append(Side(i+1, str(i+1))) Die.__init__(self, sides) class Fudge(Die): """Returns a Fudge die. &gt;&gt;&gt; d = Fudge() &gt;&gt;&gt; print d [-, , +] &gt;&gt;&gt; """ def __init__(self): sides = [] sides.append(Side(-1, '-')) sides.append(Side(0, ' ')) sides.append(Side(1, '+')) Die.__init__(self, sides) if __name__ == '__main__': import doctest doctest.testmod() </code></pre> <p><em>summer.py</em> was difficult to write because I was indecisive about the extent of its role. It works, and for now that's good enough, but I'd like to revisit this file and consider how to improve upon the idea. This was the first time I found a use for generators and using one threw new problems at me.</p> <p>Summers are used in a single die declaration to determine the final value given when throwing a set of dice. In DnD, an ability roll is a set of four six-sided dice with the lowest removed; the rest are summed. This is implemented in the <code>Highest</code> class which could simulate this behavior as <code>Highest(NSided(6), '3,4').sum()</code>. For regular old arithmetic type summing, the <code>Summer</code> class does just fine.</p> <pre><code>class Summer(object): def __init__(self, die, summer_args): """Sums a series of die rolls.""" # (Die) object self.die = die # (int) dice of the same type, (dict) self.number_of_dice, self.args = self.parse_args(summer_args) self.roller = self.get_roller() def get_roller(self): """Returns a generator which yields die sides.""" # print "self.number_of_dice" + ", " + str(type(self.number_of_dice)) + ", " + str(self.number_of_dice) return (self.die.roll() for i in range(self.number_of_dice)) def parse_args(self, arg): try: num_dice = int(arg) except ValueError: num_dice = 1 return num_dice, {} def sum(self): rolls = [] while True: try: rolls.append(self.roller.next()['num']) except StopIteration: break return sum(rolls) class Highest(Summer): def parse_args(self, arg): number_of_dice = int(arg[arg.find(',')+1:]) number_to_count = int(arg[:arg.find(',')]) return number_of_dice, {'number_to_count': number_to_count} def sum(self): rolls = [] while True: try: rolls.append(self.roller.next()['num']) if len(rolls) &gt; self.args['number_to_count']: rolls.remove(min(rolls)) except StopIteration: break return sum(rolls) </code></pre> <p>This is my first, successful attempt at writing a parser. <em>parser.py</em> will accept a series of arguments and return the sum of their values.</p> <pre><code>$ python parser.py 1d20 7 combat_advantage 15 </code></pre> <p>It can accept die declarations (<code>1d20</code>), integers (<code>7</code>) and predefined values (<code>combat_advantage</code>).</p> <p>Integers can be positive or negative and are directly added to the total.</p> <p>Die declarations are handled simply. A summer and die are declared, separated by a 'd'. If either the summer or die is an integer, the default is called. The default summer is <code>Summer</code> and the default die is <code>NSided</code>. The following are all valid die declarations: <code>1d20 2d4 4dF H3,4d6</code>. When indicating a summer or die, a single-character flag can be used to specify a non-default type. Summers are passed the slice between the flag and 'd'. Dice take no arguments, with the exception of <code>NSided</code>, which needs a number of sides.</p> <p>Predefined values are the part that became most interesting to me. They can be as simple as giving a string an integer value (<code>'difficult_terrain': -2,</code>) but can also contain references to other values (<code>VALUES['CA'] = VALUES['combat_advantage']</code>) or to nested declarations (<code>'fudge': '4dF',</code>). This nesting can be as deep or complex as the user wants. A user might define a common attack with its die declaration and modifier, then call that attack by its name. They could then write <code>my_sword_attack combat_advantage</code> or even use synonyms, <code>SAtt CA</code>.</p> <p>Overall, this file does its job. I'm happy with that, but I'm not convinced it does it well. The other files were built to be extended. I can't say the same for the parser. Of the three, it is most at risk of being entirely re-written.</p> <pre><code>#!/usr/bin/python import die as _die import summer as _summer # Die and summer flags must be a single letter. Lowercase 'd' is not valid. DICE = { 'default': _die.NSided, 'F': _die.Fudge, } SUMMERS = { 'default': _summer.Summer, 'H': _summer.Highest, } # Values must begin with a letter or underscore VALUES = { 'ability': 'H3,4d6', 'combat_advantage': 2, 'difficult_terrain': -2, 'fudge': '4dF', } # Synonyms... VALUES['CA'] = VALUES['combat_advantage'] VALUES['DT'] = VALUES['difficult_terrain'] def is_int(arg): try: int(arg) return True except ValueError: return False def main(args): values = [] for arg in args: # print "arg: %s" % arg values.append(parse(arg)) # return values return sum(values) def parse(arg): # If it is a number, return it, else continue. try: # print "value: %i" % int(arg) return int(arg) except ValueError: pass # If it is a predefined value, evoke recursion, else continue. try: # print "value: %s" % VALUES[arg] return main(str.split(str(VALUES[arg]))) except KeyError: pass left = arg[:arg.find('d')] right = arg[arg.find('d')+1:] # Get die type. if is_int(right): die = DICE['default'](int(right)) else: die = DICE[right]() # Get summer type. if is_int(left): summer, summer_args = SUMMERS['default'], left else: summer, summer_args = SUMMERS[left[0]], left[1:] # print str(summer) + ", " + str(die) + ", " + summer_args return summer(die, summer_args).sum() if __name__ == '__main__': from sys import argv # print argv[1:] print main(argv[1:]) </code></pre> <p>These are the three problems I see with my code:</p> <ul> <li><p>I practiced writing more professional documentation on <em>die.py</em> but did not spend the same effort on the other files. A little time would greatly improve them as they are not very explicit in their functionality. I'll accept any tips if my documentation style needs improvement.</p></li> <li><p>In previous attempts to write this application, I spent time writing and rewriting error handlers, and only made decent progress once I abandoned them altogether. They don't seem necessary, but I could use the exercise adding them where ever they might be most beneficial.</p></li> <li><p>The <code>VALUES</code> codeblock should be in a separate file. A user should be able to edit predefined values without looking at code. The easiest way would be to write another python file with the values defined there, then import it into the <code>VALUES</code> global.</p></li> </ul> <p>In my own usage, I made a bash alias called <code>dice</code> that runs <em>parser.py</em>:</p> <pre><code>$ dice fudge 3 -1 </code></pre>
[]
[ { "body": "<pre><code>from random import choice\n\nclass Side(dict):\n</code></pre>\n\n<p>You should almost never inherit from the builtin python collections. This is certainly not a case where you should. A side is not a kind of dictionary, it shouldn't try and inherit from <code>dict</code></p>\n\n<pre><code> \"\"\"A side contains all info needed by a die and roller.\n\n &gt;&gt;&gt; d = Side(4, 'death')\n &gt;&gt;&gt; print d\n death\n</code></pre>\n\n<p>Is that really a useful way to print a Side?</p>\n\n<pre><code> &gt;&gt;&gt; print d.keys()\n ['char', 'num']\n</code></pre>\n\n<p>What possible use do you have for <code>Side</code> supporting a <code>keys</code> method?</p>\n\n<pre><code> &gt;&gt;&gt; print d.values()\n ['death', 4]\n &gt;&gt;&gt;\n\n \"\"\"\n\n def __init__(self, num, char):\n \"\"\"\n Args:\n num (int) - Used to calculate value of roll.\n char (str) - Used to display face of roll.\n\n \"\"\"\n\n self['num'] = num\n self['char'] = char\n</code></pre>\n\n<p>Use attributes, there is no reason to by using a dictionary here.</p>\n\n<pre><code> def __repr__(self):\n return str(self['char'])\n</code></pre>\n\n<p>Repr should return something like <code>Side(4, \"death\")</code> </p>\n\n<pre><code> __str__ = __repr__\n\n\n\nclass Die(list):\n</code></pre>\n\n<p>Again don't do that. A Die is not a list, don't pretend it is.</p>\n\n<pre><code> \"\"\"A die is a list of sides, all of equal probability.\"\"\"\n\n def __init__(self, sides):\n for side in sides: self.append(side)\n</code></pre>\n\n<p>Use <code>self.extend(sides)</code>, or better yet store the list as an attribute.</p>\n\n<pre><code> def roll(self):\n return choice(self)\n</code></pre>\n\n<p>This class is pretty marginally useful, it raises the question of whether you actually need it. </p>\n\n<pre><code>class NSided(Die):\n \"\"\"Returns an n-sided die.\n\n Args:\n numsides (int) - The highest value on the die.\n\n &gt;&gt;&gt; d = NSided(6)\n &gt;&gt;&gt; print d\n [1, 2, 3, 4, 5, 6]\n &gt;&gt;&gt;\n\n \"\"\"\n\n def __init__(self, numsides):\n sides = []\n for i in range(numsides):\n sides.append(Side(i+1, str(i+1)))\n Die.__init__(self, sides)\n\n\n\nclass Fudge(Die):\n \"\"\"Returns a Fudge die.\n\n &gt;&gt;&gt; d = Fudge()\n &gt;&gt;&gt; print d\n [-, , +]\n &gt;&gt;&gt;\n\n \"\"\"\n\n def __init__(self):\n sides = []\n sides.append(Side(-1, '-'))\n sides.append(Side(0, ' '))\n sides.append(Side(1, '+'))\n</code></pre>\n\n<p>Use a list literal, rather then several appends.</p>\n\n<pre><code> Die.__init__(self, sides)\n</code></pre>\n\n<p>I'd make these functions which return Die rather then Die subclasses. </p>\n\n<pre><code>class Summer(object):\n\n def __init__(self, die, summer_args):\n \"\"\"Sums a series of die rolls.\"\"\"\n\n # (Die) object\n self.die = die\n # (int) dice of the same type, (dict)\n self.number_of_dice, self.args = self.parse_args(summer_args)\n</code></pre>\n\n<p>Don't use a self.args, just store arguments as attributes on the objects. </p>\n\n<pre><code> self.roller = self.get_roller()\n\n\n def get_roller(self):\n \"\"\"Returns a generator which yields die sides.\"\"\"\n # print \"self.number_of_dice\" + \", \" + str(type(self.number_of_dice)) + \", \" + str(self.number_of_dice)\n return (self.die.roll() for i in range(self.number_of_dice))\n</code></pre>\n\n<p>I suggest</p>\n\n<pre><code> for i in range(self.number_of_dice):\n yield self.die.roll()\n</code></pre>\n\n<p>I think it easier to follow</p>\n\n<pre><code> def parse_args(self, arg):\n try:\n num_dice = int(arg)\n</code></pre>\n\n<p>You should really depend on the user of the class to do this, and not try to manipulate input here</p>\n\n<pre><code> except ValueError:\n num_dice = 1\n</code></pre>\n\n<p>Don't do this. If somebody passes your class invalid data you should never never never try to replace it with something valid and carry on. You should probably just throw an exception here. \n return num_dice, {}</p>\n\n<p>This would be way simpler to just do in the constructor.</p>\n\n<pre><code> def sum(self):\n rolls = []\n while True:\n try:\n rolls.append(self.roller.next()['num'])\n except StopIteration:\n break\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>for roll in self.roller:\n rolls.append(roll['num'])\n</code></pre>\n\n<p>You should almost never need to deal with StopIteration directly.</p>\n\n<p>Actually, you can even do:</p>\n\n<p>rolls = [roll['num'] for roll in self.roller]</p>\n\n<pre><code> return sum(rolls)\n\n\n\nclass Highest(Summer):\n\n def parse_args(self, arg):\n number_of_dice = int(arg[arg.find(',')+1:])\n number_to_count = int(arg[:arg.find(',')])\n</code></pre>\n\n<p>Again, parsing the input really doesn't fit here. That should happen in your parsing code.</p>\n\n<pre><code> return number_of_dice, {'number_to_count': number_to_count}\n</code></pre>\n\n<p>This whole thing would still make more sense in a constructor.</p>\n\n<pre><code> def sum(self):\n rolls = []\n while True:\n try:\n rolls.append(self.roller.next()['num'])\n if len(rolls) &gt; self.args['number_to_count']: rolls.remove(min(rolls))\n</code></pre>\n\n<p>that's going to be inefficient</p>\n\n<pre><code> except StopIteration:\n break\n return sum(rolls)\n</code></pre>\n\n<p>Do something like</p>\n\n<p>rolls = [roll['num'] for roll in self.roller]\n rolls.sort(reverse = True)\n return sum(rolls[:self.number_to_count])</p>\n\n<pre><code>#!/usr/bin/python\n\nimport die as _die\nimport summer as _summer\n</code></pre>\n\n<p>Why are you importing them like that?</p>\n\n<pre><code># Die and summer flags must be a single letter. Lowercase 'd' is not valid.\nDICE = {\n 'default': _die.NSided,\n</code></pre>\n\n<p>Suspiciously useful, given 'default' isn't special to the dict class.</p>\n\n<pre><code> 'F': _die.Fudge,\n}\nSUMMERS = {\n 'default': _summer.Summer,\n 'H': _summer.Highest,\n}\n\n# Values must begin with a letter or underscore\nVALUES = {\n</code></pre>\n\n<p>Bad name, call it PREDEFINED or something</p>\n\n<pre><code> 'ability': 'H3,4d6',\n 'combat_advantage': 2,\n 'difficult_terrain': -2,\n 'fudge': '4dF',\n}\n# Synonyms...\nVALUES['CA'] = VALUES['combat_advantage']\nVALUES['DT'] = VALUES['difficult_terrain']\n\n\ndef is_int(arg):\n try:\n int(arg)\n return True\n</code></pre>\n\n<p>Put the last line in an else block</p>\n\n<pre><code> except ValueError:\n return False\n\n\ndef main(args):\n values = []\n for arg in args:\n # print \"arg: %s\" % arg\n values.append(parse(arg))\n</code></pre>\n\n<p>Use <code>values = map(parse, args)</code></p>\n\n<pre><code> # return values\n return sum(values)\n\ndef parse(arg):\n # If it is a number, return it, else continue.\n try:\n # print \"value: %i\" % int(arg)\n return int(arg)\n except ValueError:\n pass\n</code></pre>\n\n<p>Duplicate of is_int...</p>\n\n<pre><code> # If it is a predefined value, evoke recursion, else continue.\n try:\n # print \"value: %s\" % VALUES[arg]\n return main(str.split(str(VALUES[arg])))\n except KeyError:\n pass\n\n left = arg[:arg.find('d')]\n right = arg[arg.find('d')+1:]\n\n # Get die type.\n if is_int(right):\n die = DICE['default'](int(right))\n else:\n die = DICE[right]()\n\n # Get summer type.\n if is_int(left):\n summer, summer_args = SUMMERS['default'], left\n else:\n summer, summer_args = SUMMERS[left[0]], left[1:]\n\n # print str(summer) + \", \" + str(die) + \", \" + summer_args\n return summer(die, summer_args).sum()\n</code></pre>\n\n<p>I don't really like your parser. Sadly, I don't know the format well enough to suggest improvements. Haphazard string manipulation is difficult to follow and error prone. I'd look into regular expressions.</p>\n\n<pre><code>if __name__ == '__main__':\n from sys import argv\n # print argv[1:]\n print main(argv[1:])\n</code></pre>\n\n<p>Overall, your code is much more complicated then it needs to be, here is my approach:</p>\n\n<pre><code>import re\nimport random\nimport sys\n\n# load the PREDEFINED from an external file\nwith open('predefined.txt') as predefined_file:\n PREDEFINED = dict(line.strip().split(' ', 1) for line in predefined_file)\n\n# regular expression matches the various versions of rolls\nROLL_EXP = re.compile(r'(?:H(\\d+),)?(\\d+)d(\\d+|F)')\n# H(keep),(dice)d(sides)\ndef handle_roll(match):\n \"\"\"\n Handle the rolls matched by ROLL_EXP\n \"\"\"\n keep, dice, number = match.groups()\n\n # massage the data\n dice = int(dice)\n\n # if keep is None means that There is not (H3,) section\n if keep is None:\n keep = dice\n else:\n keep = int(keep)\n\n # F indicates a fudge die, \n if number == 'F':\n roll = [random.randint(-1, 1) for x in xrange(dice)]\n else:\n roll = [random.randint(1, int(number)) for x in xrange(dice)]\n\n # sum up the remaining die\n roll.sort(reverse = True)\n return sum(roll[:keep])\n\n# making the constant\nCONSTANT = re.compile(r'-?\\d+')\ndef handle_constant(match):\n # just use python's builtin int to understand the number\n return int(match.group(0))\n\n# store a list of possible methods\nMETHODS = [\n (ROLL_EXP, handle_roll),\n (CONSTANT, handle_constant),\n]\n\nclass BadRoll(Exception):\n \"\"\"\n This exception is thrown to indicate a failure to understand what the user \n specified\n \"\"\"\n\ndef parse_roll(argument):\n \"\"\"\n Given a basic roll, either return the summation or raise a BadRoll\n \"\"\"\n for method_re, method_handler in METHODS:\n # try to match it\n match = method_re.match(argument)\n if match is not None:\n return method_handler(match) \n else:\n raise BadRoll(argument)\n\ndef handle_argument(argument):\n \"\"\"\n Return the summation of described rolls\n \"\"\"\n # continually lookup up the argument in PREDEFINED\n # until we find nothing, then use parse_roll\n while True:\n try:\n argument = PREDEFINED[argument]\n except KeyError:\n return parse_roll(argument)\n\n\n\n\ndef main(args):\n try:\n # sum up the description of the arguments\n print sum(map(handle_argument, args[1:]))\n except BadRoll as error:\n # print what we didn't understand\n print &gt;&gt; sys.stderr, \"Did not understand:\", str(error)\n\nif __name__ == '__main__':\n main(sys.argv)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T06:04:36.937", "Id": "30920", "Score": "0", "body": "+1 \"You should almost never inherit from the builtin python collections. \" Why? And when could I? Any reference?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T17:06:30.693", "Id": "30960", "Score": "2", "body": "@miracle173, prefer composition to inheritance: http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance, essentially, inheritance is good for making special lists or dicts, but that's rarely what you are doing with them. Usually, its better model as something which holds a list or dict." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T02:23:57.467", "Id": "30998", "Score": "0", "body": "Thanks for looking over my code. I'll take several of your comments into consideration as I revisit these files." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T22:18:07.323", "Id": "19314", "ParentId": "19305", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T18:26:46.473", "Id": "19305", "Score": "4", "Tags": [ "python", "parsing", "random", "dice" ], "Title": "Die Roller for command line" }
19305
<pre><code>@implementation User - (void)refreshProperties { assert(!self.isSyncing); NetworkOperation *op = [[NetworkOperation alloc] initWithEndPoint:GetUserDetails parameters:nil]; [self setupCompletionForRefresh:op]; [self setNetworkOperation:op]; [self setSyncing:YES]; [[NetworkManager sharedManager] enqueueOperation:op]; } </code></pre> <p>The above code is used by a UIViewController subclass to update the properties of a User instance (i.e. the view controller calls <code>[aUser refreshProperties]</code> in pull-to-refresh).</p> <p>Concerted efforts have been made to make sure there are clear lines defining the separation of concerns:</p> <ul> <li>Network Operation class only deals with getting data from the network</li> <li>Network Manager class deals with enqueuing operations and watching reachability</li> <li>User class houses the strings, numbers, bools, etc that make up a User instance</li> </ul> <p>However, there are some problems with the above method. First and foremost is it's hard to test. There isn't any way to mock a network operation or network manager and get them inside the method call without swizzling. Also, it couples the User class with the NetworkOperation and NetworkManager classes.</p> <p>While the above code works, I would like to refactor it.</p> <p>Looking through GoF, it looks like there are some ways to remove the dependency between User and Network-Operation/Manager: adapter, dependency inversion (using a protocol), etc. From what I can tell, that code would look something like:</p> <pre><code>[aUser setNetworkOperation:&lt;object conforming to protocol&gt;]; [aUser setNetworkManager:&lt;object conforming to protocol&gt;]; [aUser refreshProperties]; </code></pre> <p>But... isn't this just shifting the dependency? The above calls would happen in the view controller, and now it has to know about and use three classes instead of just the main one it was originally concerned with - User.</p> <p>Thoughts, discussion, resources, or code examples are greatly appreciated!</p>
[]
[ { "body": "<p>In <a href=\"http://mac.github.com\">GitHub for Mac</a>, we use a combination of <a href=\"https://github.com/AFNetworking/AFNetworking\">AFNetworking</a> and our own <a href=\"https://github.com/github/Mantle\">Mantle</a> and <a href=\"https://github.com/github/ReactiveCocoa\">ReactiveCocoa</a> frameworks for API requests.</p>\n\n<p>AFNetworking makes it trivial to create your own \"network manager\" type object as a subclass of <code>AFHTTPClient</code>. We enqueue requests on it, ask them to hand back a certain kind of <code>MTLModel</code> subclass, and then subscribe to the resulting signal.</p>\n\n<p>The resulting code looks something like this in the caller:</p>\n\n<pre><code>GHGitHubClient *client = [GHGitHubClient clientForUser:loggedInUser];\n[[[client enqueueRequestWithMethod:@\"GET\" path:@\"user\" parameters:nil resultClass:GHGitHubUser.class]\n deliverOn:RACScheduler.mainThreadScheduler]\n subscribeNext:^(GHGitHubUser *user) {\n // Do something with the fetched user here.\n } error:^(NSError *error) {\n // Handle errors here.\n }];\n</code></pre>\n\n<p>There are several advantages to this:</p>\n\n<ul>\n<li>You're building on the strength of AFNetworking. There's really no reason to write networking code from scratch anymore – this framework is validated in many, many applications, and can do almost anything you'd need.</li>\n<li><code>MTLModel</code> provides a way to parse model objects knowing only the desired class. <code>GHGitHubClient</code> can drive the parsing without being coupled to the specific model types.</li>\n<li>Signals in ReactiveCocoa are composable, so this code can be easily modified to manipulate and transform the <code>GHGitHubUser</code>, or even perform other fetches and combine the results, before delivering to the main thread.</li>\n<li>Your domain model isn't doing network activity. I firmly believe that domain models should care only about data, not the mechanics of persisting or fetching it.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-07T22:37:28.787", "Id": "42160", "Score": "0", "body": "can you share GHGitHubClient source code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-07T23:11:13.163", "Id": "42161", "Score": "1", "body": "@YosiTaguri It's since been released as part of [octokit.objc](https://github.com/octokit/octokit.objc) (though renamed to `OCTClient`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-16T14:26:02.077", "Id": "71902", "Score": "0", "body": "While ReactiveCocoa provides for an awesome way to handle the complexity of one or several chained async requests, I'm not too sure about type safety. How do you handle the case that the client actually doesn't know that the request signal returns objects of type `GHGitHubUser`? I wouldn't get any compiler warnings if I expected the wrong type, would I?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-17T15:24:58.550", "Id": "72094", "Score": "1", "body": "@fabb Indeed, you would not. This is a limitation of Objective-C's type system, and unfortunately there's no easy fix. However, it's comparable to using `NSArray` or `NSDictionary`—you either have to assume that you retrieved a value of the correct type, or else add assertions everywhere (which still only help at runtime)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T00:24:13.150", "Id": "19372", "ParentId": "19307", "Score": "14" } }, { "body": "<pre><code>git checkout -b fetch_remote_users\n</code></pre>\n\n<p>Let's start by reviewing the concerns we want the system to address. We will need:</p>\n\n<ol>\n<li>A place to store the set of attributes which define a \"user\".</li>\n<li>A request (to some URI with some set of parameters) which defined how we can obtain an updated view of a user.</li>\n<li>A queue of requests to perform with the ability to suspend execution of those requests when the network is unavailable and retry network failures. We probably also want this queue to be an ordered set of requests so we can avoid enqueuing duplicate requests.</li>\n<li>A way to react to successful requests so that we can merge and persist the newly received set of User attributes.</li>\n<li>An interface to allow user interaction in some view to enqueue a new request and possibly to see some indication of the request's state (in progress, failed, finished).</li>\n</ol>\n\n<p>That's a reasonable number of concerns and it'll be easy to end up with a confused our tightly coupled design trying to express all of them but let's see what we can do.</p>\n\n<p>Starting with <strong>#1</strong>. We can define a <code>User</code> model to store our \"user\" attributes. It is likely that we'll find some behaviors which should also belong to this model but let's start simple.</p>\n\n<pre><code>@interface User : NSObject\n\n@end\n</code></pre>\n\n<p>So far so good. No coupling and while we haven't been motivated to write a test yet we could easily test this <code>User</code> in isolation.</p>\n\n<p>On to <strong>#2</strong>. <code>NetworkOperation</code> is probably still a good name for this since we're probably going to be dealing with create, read, update, or destroy operations in order to synchronize the state of our User resource. We've only talked about reads so far but it might be useful to capture the type of an operation when we create it so that we know what it is trying to accomplish.</p>\n\n<p>This might be a good place to start writing tests. Let's think about creating a <code>NetworkOperation</code> (using <a href=\"https://github.com/allending/Kiwi\" rel=\"nofollow\">Kiwi</a>'s BDD styntax).</p>\n\n<pre><code>describe(@\"NetworkOperation\", ^{\n context(@\"when created\", ^{\n __block NetworkOperation *operation;\n beforeEach(^{\n operation = [NetworkOperation operationOfType:CRUDOperationTypeRead URL:[NSURL URLWithString:@\"example.com/users/1\"] withParameters:nil];\n });\n it(@\"has an operation type\", ^{\n [[theValue(operation.type) should] equal: theValue (CRUDOperationTypeRead)];\n });\n it(@\"use the specified URI\", ^{\n [[operation.URL should] equal:[NSURL URLWithString:@\"example.com/users/1\"]];\n });\n });\n});\n</code></pre>\n\n<p>That's easy enough to build.</p>\n\n<pre><code>typedef enum {\n CRUDOperationTypeCreate,\n CRUDOperationTypeRead,\n CRUDOperationTypeUpdate,\n CRUDOperationTypeDelete\n} CRUDOperationType;\n\n@interface NetworkOperation : NSObject\n@property(readonly) CRUDOperationType operationType;\n@property(readonly) NSURL *URL;\n\n- (id)operationOfType:(CRUDOperationType)type URL:(NSURL *)url withParameters:(NSDictionary *)parameters;\n@end\n</code></pre>\n\n<p>So we can create a <code>NetworkOperation</code> to encapsulate a request. That should also give us a good place to parse the response from whatever format was sent over the wire, we'll see about how to map it to our <code>User</code> domain object later. Who then should be responsible for actually creating <code>NetworkOperation</code>s?</p>\n\n<p>We could follow the example in the original question and create operations inline when needed but, as noted, that's going to become hard to test and contributes to the coupling between the User model and the network classes. In order to separate the responsibilities of these classes it might be useful to be able to consider just the creation of a NetworkOperation as its own role. A Factory for building NetworkOperations for fetching Users.\nIt does however seem reasonable for User to be the authority on how to locate its remote representation. We can use a Strategy to allow our domain model objects to act as Factories for their appropriate NetworkOperations.</p>\n\n<pre><code>describe(@\"User\", ^{\n __block User *user;\n beforeEach(^{\n user = [[User alloc] init];\n });\n describe(@\"as a RemoteResource\", ^{\n it(@\"builds a read operation\", ^{\n NetworkOperation *read = [user buildReadOperation];\n [[theValue(read.operationType) should] equal:theValue(CRUDOperationTypeRead)];\n });\n });\n});\n\n@protocol RemoteResource\n- (NetworkOperation *)buildReadOperation;\n@end\n\n@interface User : NSObject &lt;RemoteResource&gt;\n\n@end\n</code></pre>\n\n<p>Now Users can define the NetworkOperations needed to update themselves but the consumer of those operations can work with generic RemoteResources (some of whom happen to be users).</p>\n\n<p>On to <strong>#3</strong>!</p>\n\n<p>We probably want to have an object which manages our network operations and it is going to need to exist for most, if not all, of the life of our application so that it can keep track of the state of our operation queue as we wait for operations to finish. Sounds like a good fit for a service (often presented as part of the controller layer of MVC but not a view controller and certainly not a UIViewController).</p>\n\n<pre><code>describe(@\"RemoteResourceManager\", ^{\n context(@\"given an existing resource\", ^{\n context(@\"reading the resource\", ^{\n pending(@\"enqueues the read network operation\");\n pending(@\"sets a success callback block\");\n pending(@\"sets a failure callback block\");\n });\n });\n});\n</code></pre>\n\n<p>Hang on a second! That's sounds like a nice interface for updating a RemoteResource but we're not talking about NetworkOperations anymore. We could have this RemoteResourceManager maintain a queue of the operations it is using but that seems like an internal detail that would be hard to test. Looks like we skipped a step, let's create another service instead. Something the RemoteResourceManager can depend on to manage operations but which doesn't need to know anything about RemoteResources.</p>\n\n<pre><code>describe(@\"NetworkOperationManager\", ^{\n context(\"@enqueuing an operation\", ^{\n pending(@\"adds the operation to the queue\");\n context(@\"when an equivalent operation is already in the queue\", ^{\n pending(@\"does not add the operation\");\n });\n });\n context(@\"when an operation succeeds\", ^{\n __block id mockOperation;\n beforeEach(^{\n mockOperation = [NetworkOperation mock];\n });\n pending(@\"calls the operation's success callback\");\n pending(@\"sends a notification containing the resource's identifier\");\n });\n context(@\"when an operation fails\", ^{\n pending(@\"calls the operation's failure callback\");\n pending(@\"sends a failure notification containing the resource's identifier\");\n });\n});\n</code></pre>\n\n<p>Now we can revist our RemoteResourceManager.</p>\n\n<pre><code>describe(@\"RemoteResourceManager\", ^{\n __block RemoteResourceManager *manager;\n __block id mockNetworkOperationManager;\n beforeEach(^{\n mockNetworkOperationManager = [NetworkOperationManager mock];\n manager = [[RemoteResourceManager alloc] initWithNetworkOperationManager:mockNetworkOperationManager];\n });\n context(@\"given an existing resource\", ^{\n context(@\"reading the resource\", ^{\n __block id mockOperation;\n __block id mockResource;\n beforeEach(^{\n mockOperation = [NetworkOperation mock];\n mockResource = [KWMock mockForProtocol:RemoteResource];\n [mockResource stub:@selector(buildReadOperation) andReturn:mockOperation];\n });\n it(@\"enqueues the read network operation\", ^{\n [[[mockNetworkOperationManager should] receive] enqueueOperation:mockOperation];\n [manager read:mockResource];\n });\n pending(@\"sets a success callback block\");\n pending(@\"sets a failure callback block\");\n });\n });\n});\n</code></pre>\n\n<p>...and so on.</p>\n\n<p>For <strong>#4</strong> we might extend the RemoteResource protocol to define a method to which we can pass data from our NetworkOperations in our success callbacks to apply updates to the model.</p>\n\n<p><strong>#5</strong> is a little tricky and really depends on what UX we aim to provide. We can probably start by providing our view controller with a shared RemoteResourceManager. \nWe could do that via a singleton but I'm reluctant to do so. A singleton would introduce a strong and non-obvious coupling between the view controller and the resource manager. Besides its not wrong to have several resource managers in our app. We just want them to be able to outlive view controllers so that they have time to finish their operations even if the view controller that started them is no longer needed. The fact that the singleton would be hard to replace with a double in a test is a good hint that this might be a poor design decision.\nInstead I would provide an instance of an existing resource manager either via a dependency injection framework or explicitly pass one to the controller from its creator. Either way, we can easily substitute a test double for the resource manager to test our controller's interaction with it.\nThe NetworkOperationManager spec hints at how we might update the UI to reflect the state of the operation queue. Our resource manager supplies callback blocks to react to the success and failure of operations. On the other hand our view controller may no longer exist (or at least no longer be visible) when the operation finishes. Instead of callbacks we can listed for notifications about the particular resource we are interested in. If the controller gets a notification we can update the view to show that an update has started or finished. When we no longer need to maintain that view the controller unsubscribes from the notifications and ignores them.</p>\n\n<pre><code>git add .\ngit commit -m\"stream of consciousness networking refactor\"\ngit push codereview 19307/dependency-inversion-injection-networking-code-in-model-classes\n</code></pre>\n\n<p>Hope that's useful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-27T19:13:14.587", "Id": "89703", "Score": "0", "body": "Thanks, that was quite useful. You covered a lot of relevant topics." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T00:54:27.773", "Id": "19373", "ParentId": "19307", "Score": "4" } } ]
{ "AcceptedAnswerId": "19373", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T19:16:19.607", "Id": "19307", "Score": "6", "Tags": [ "objective-c", "ios" ], "Title": "Dependency Inversion / Injection? - Networking code in model classes" }
19307
<p>I've created a class that's used for cleaning variables for use. You set a name, value and options and it will set the value if it matches the criteria/options.</p> <p>It is used like this:</p> <pre><code>$var = new Variable(); $var-&gt;clean('username', $_POST['username'], '3,13,alphanumeric,True'); echo 'Username', $var-&gt;clean("username"); echo 'Username', $var-&gt;html("username"); </code></pre> <p>It seems very messy and as though it could be done in a better way.</p> <pre><code>&lt;?php include_once __DIR__ . '/header.php'; class Variable { var $clean = array(); // Filtered data var $html = array(); // Escaped htmlentities() data /** * variable-&gt;addClean() * * @param mixed $name - Name of clean value * @param mixed $value - Value to clean * @param string $options - Options in the format specified * @return mixed - Clean value. * * Options format: * {min length} - set to -1 to ignore. * {max length} - set to -1 to ignore. * {type} - set to null to ignore. Types: * - Numeric. * - AlphaNumeric. * - Alpha. * {trim} - default is true. * * eg. * $var = new Variable(); * $var-&gt;clean('username', $_POST['username'], '3,13,alphanumeric,True'); * echo 'Username', $var-&gt;clean("username"); * */ public function clean($name, $value = null, $options = '') { if ($value === null &amp;&amp; $name !== null) return isset($this-&gt;clean[$name]) ? $this-&gt;clean[$name] : null; else if ($value !== null &amp;&amp; $name !== null) { if (!empty($options)) { list($minlen, $maxlen, $type, $trim) = array_pad(explode(',', (string)$options), 4, ''); if (strtolower($trim) !== 'false') $value = trim($value); if ($minlen !== '-1') if (!(strlen($value) &gt; $minlen)) return false; if ($maxlen !== '-1') if (!(strlen($value) &lt; $maxlen)) return false; switch (strtolower($type)) { case 'numeric': if (is_numeric($value)) $this-&gt;clean[$name] = intval($value); break; case 'alphanumeric': if (ctype_alnum($value)) $this-&gt;clean[$name] = $value; break; case 'alpha': if (ctype_alpha($value)) $this-&gt;clean[$name] = $value; break; default: $this-&gt;clean[$name] = $value; break; } } else $this-&gt;clean[$name] = $value; } return isset($this-&gt;clean[$name]); } public function isClean($name) { return isset($this-&gt;clean[$name]); } public function html($name) { if (!isset($this-&gt;html[$name]) &amp;&amp; isset($this-&gt;clean[$name])) $this-&gt;html[$name] = htmlentities($this-&gt;clean[$name], ENT_QUOTES, 'UTF-8'); return (isset($this-&gt;html[$name]) ? $this-&gt;html[$name] : null); } } </code></pre>
[]
[ { "body": "<p>Yes, your class does too much.</p>\n\n<p>First of all, it actually lying: It does not handle one variable as the name of the class suggest, but it does handle multiple variables at once.</p>\n\n<p>Second, I do not like the overloading of the <code>clean</code> method. It is used both for getting a value inside, and for getting the same value back outside. Why are there not two methods?</p>\n\n<p>Third point: Your clean method does too much! It should not be its responsibility to actually decide which filter to apply - this should be the task of a dedicated class that just deals with on single aspect.</p>\n\n<p>Summarizing all this, your list of improvements would be like this:</p>\n\n<p>a) Get rid of the multi-value-behaviour. One class instance per value. If you really need multiple values inside a structure, use a different class.</p>\n\n<p>b) Move the actual filtering out of the class, into dedicated filter elements that do one task very good, but nothing else. </p>\n\n<p>For example, create an \"Alphanumeric\" class that is configured with the rest of the parameters \"3,13,true\" that does exactly deal with strings, checks their min and max length and optionally trims them. </p>\n\n<p>Create another class that deals with numeric representation. I doubt it would be useful to check for a <strong>string</strong> length in this case, but your implementation dictates that it has to be like this. On the other hand, there is no way to implement a min or max <strong>value</strong>.</p>\n\n<p>The checking class should be passed as a parameter to the constructor of your class <code>Variable</code>, which means that you have to create the checking class beforehand.</p>\n\n<p>c) Passing a string as configuration would then be somehow obsolete, because your new checking classes do not have any other parameters, so giving them four separate parameters isn't likely to overflow the parameter list. But remember that you do not need to make every class' parameter list the same - if some class does not need a configuration value, you can omit it. If another class needs more: Add one.</p>\n\n<p>d) In the end you might come to a point where creating more than one instance of <code>Variable</code> is cumbersome because of all the additional stuff. This is where a factory comes in handy. It would take a configuration array that defines which instances of variable cleaners are needed, instantiates all necessary classes and would probably return an array of <code>Variable</code> objects.</p>\n\n<p>e) One final suggestion: When implementing different classes for basically the same task, use an interface as a type hint to guarantee that you never mix something up. When using an IDE you get code completion as a bonus. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T20:43:34.557", "Id": "19310", "ParentId": "19308", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T19:48:23.957", "Id": "19308", "Score": "3", "Tags": [ "php" ], "Title": "Variable cleaning class" }
19308
<p>I tried to write a <code>nullptr_t</code> class based on <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2431.pdf">the official proposal</a> to be used in C++03 only. The only differences with the proposal are that we can compare two <code>nullptr_t</code> instances and that it is convertible to <code>bool</code> via an overload to <code>void*</code> to avoid unwanted behaviour such as <code>int a = nullptr;</code> for example. Here is the class:</p> <pre><code>const class nullptr_t { public: // Return 0 for any class pointer template&lt;typename T&gt; operator T*() const { return 0; } // Return 0 for any member pointer template&lt;typename T, typename U&gt; operator T U::*() const { return 0; } // Used for bool conversion operator void*() const { return 0; } // Comparisons with nullptr bool operator==(const nullptr_t&amp;) const { return true; } bool operator!=(const nullptr_t&amp;) const { return false; } private: // Not allowed to get the address void operator&amp;() const; } nullptr = {}; </code></pre> <p>I would like to know if there is any actual flaw in this completed implementation or if there is a difference in the behaviour compared to the C++11 type <code>std::nullptr_t</code> besides the namespace that I can't see.</p>
[]
[ { "body": "<p>At the moment, your implementation allows</p>\n\n<pre><code>auto&amp; p = nullptr;\n</code></pre>\n\n<p>This is forbidden in C++11 as <code>nullptr</code> is an rvalue. You also do not allow the following:</p>\n\n<pre><code>auto p = nullptr;\nauto pp = &amp;p;\n</code></pre>\n\n<p>While C++11 does allow it. You are also missing overloads for comparison operators.</p>\n\n<p>A simple workaround would be to remove the <code>operator&amp;</code> overload and add a macro:</p>\n\n<pre><code>#define nullptr (nullptr_t())\n</code></pre>\n\n<p>Also, I'd generally use <code>struct X { ... } const x;</code> instead of <code>const struct X { ... } x;</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T15:28:36.273", "Id": "19337", "ParentId": "19316", "Score": "13" } }, { "body": "<p>Another thing I forgot at the time is that the standard specifies that <code>sizeof(nullptr)</code> shall be equal to <code>sizeof(void*)</code>.</p>\n<blockquote>\n<p>3.9.1 - Fundamental types</p>\n<p>3.9.1.10 A value of type <code>std::nullptr_t</code> is a null pointer constant (4.10). Such values participate in the pointer and the pointer to member conversions (4.10, 4.11). <code>sizeof(std::nullptr_t)</code> shall be equal to <code>sizeof(void*)</code>.</p>\n</blockquote>\n<p>So technically speaking, I should have added padding to my <code>class</code>:</p>\n<pre><code>class nullptr_t\n{\n // To ensure the size\n // Should be correctly aligned\n void* padding;\n // ...\n} const nullptr;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-10T21:44:11.517", "Id": "251558", "Score": "1", "body": "Could you provide full implementation including C++11 improvements to nullptr ... I would be grateful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-19T11:27:32.090", "Id": "379098", "Score": "0", "body": "That `sizeof` requirement is a nuisance. I see two issues with adding that `padding`:\n1) I'm not sure that copying around an uninitialized `void *` is well-defined. I considered replacing it with `unsigned char padding[sizeof(void *)]`, but that didn't solve the next issue, nor would adding empty copy operators.\n2) Including a `private` non-`static` member variable breaks POD-ness, at least before C++11. I don't see a good way around this." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-22T11:06:41.607", "Id": "26465", "ParentId": "19316", "Score": "7" } } ]
{ "AcceptedAnswerId": "19337", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T23:18:08.020", "Id": "19316", "Score": "11", "Tags": [ "c++", "c++11", "reinventing-the-wheel", "c++03" ], "Title": "Custom nullptr_t class" }
19316
<p>I have finished my router and would like your thoughts on anything that may be inefficient of could be done better!:</p> <p><code> class Router {</p> <pre><code>public $start_page = 'Dashboard' ; // Change to your home/default page. public $staticRoutes = array( 'alias' =&gt; 'ActualController', ) ; function __construct() { $url = substr(rtrim($_SERVER['REQUEST_URI'], '/'), 6) ; if($url) { $components = explode('/', $url, 3) ; if(array_key_exists($class, $this-&gt;staticRoutes)) { $class = $this-&gt;staticRoutes[$class] ; } else { $class = preg_replace('/[^a-z-]/', '', $components[0]) ; } if(class_exists($class)) { if(isset($components[1])) // has method... { $method = preg_replace('/[^a-z-]/', '', $components[1]) ; if(method_exists($class, $method)) { if(isset($components[2])) // has params... { $params = explode('/', $components[2]) ; call_user_func_array(array($class, $method), $params) ; } else { $controller = new $class ; $controller-&gt;$method() ; } } else { $e = 'Method '.$components[1].' does not exist.' ; new Error(array('msg' =&gt; $e), 'Method Error') ; } } else { // No method so just go to default index if exists... $controller = new $class ; if(method_exists($controller, 'index')) { $controller-&gt;index() ; } else { $e = 'Class '.$class.' has no default index method.' ; new Error(array('msg' =&gt; $e), 'Class Index Error') ; } } } else { $e = 'Class '.$components[0].' does not exist.' ; new Error(array('msg' =&gt; $e), 'Class Error') ; } } else { $controller = new $this-&gt;start_page ; $controller-&gt;index() ; } } </code></pre> <p>}</code></p> <p>Note that I have not implements the static routes functionality yet.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T22:27:01.430", "Id": "30991", "Score": "0", "body": "It has access to global state (in $_SERVER), which is a bad idea. Wrap all data from the request into a request object and pass it to the router. There you can examine it without accessing global state. You can also test your router in a unit test, which does not know about any real HTTP requests. And by the way: Your Router is actually more like a FrontController." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T22:28:43.427", "Id": "30992", "Score": "0", "body": "What about throwing an exception if an error occurs?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T19:01:50.153", "Id": "31074", "Score": "0", "body": "@Sven do you know of any examples of a request object? What do you mean throwing an exception? If an error occurs the user is sent to an error page (class Error)." } ]
[ { "body": "<p>Your constructor is doing too much. Just because the only thing you are going to do with your router is initialize it, that doesn't mean you can't have more methods. And as Sven pointed out, it probably shouldn't have access to the global state. Inject whatever you need.</p>\n\n<p>You have two public properties, one uses underscores the other camelCase. I would suggest picking a particular naming scheme and sticking to it. Consistency is important.</p>\n\n<p>Your code seriously violates the arrow anti-pattern. You might consider refactoring to remove some of the indentation and if/else statements. For instance, reversing the first if/else and returning early will allow you to then drop the else, thus removing one level of indentation from your entire method.</p>\n\n<pre><code>if( ! $url ) {\n $controller = new $this-&gt;start_page;\n $controller-&gt;index();\n return;\n}\n\n//etc...\n</code></pre>\n\n<p>I've never been one for magic numbers and these vague array keys bug me. It shouldn't be necessary to provide comments to understand what each array key does. I would consider padding an array to ensure the size then creating a list. At the same time you can run each component through a loop to clean it. I'm wanting to say you can use <code>array_map()</code> or <code>array_walk()</code> instead of the loop, but I don't feel like trying to figure that out right now. I'm not quite sure what your REGEX is doing so I don't know if there is a better way, but check out <code>filter_var()</code>, that may do what you need.</p>\n\n<pre><code>$components = explode( '/', $url, 3 );\nforeach( $components as $key =&gt; $component ) {\n $components[ $key ] = preg_replace( '/[^a-z-]/', '', $component );\n}\n$components = array_pad( $components, 3, FALSE );\n\nlist( $class, $method, $params ) = $components;\n</code></pre>\n\n<p>By the way, where did <code>$class</code> originally come from? The first time I see it is when you check to see if it exists in the <code>$staticRoutes</code> property. If that is a global you should know that globals are evil and you should be ashamed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-20T22:35:51.083", "Id": "19827", "ParentId": "19323", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T09:19:20.803", "Id": "19323", "Score": "0", "Tags": [ "php", "object-oriented", "mvc", "controller" ], "Title": "Review: Finished router class for custom mini framework" }
19323
<p>This is one of a classes (that sends email based on object type to AM (role)) that is executed by an engine. I also have commands like <code>SendEmailToAOCommand</code> that send email to a role AO based on object type and so one.</p> <pre><code>namespace SFE.Workflow.Commands { public class SendEmailToAMCommand : ActionCommand { private readonly Func&lt;IApplicationRepository&gt; applicationRepository; private readonly IClientRepository clientRepository; private readonly Func&lt;IEmailService&gt; emailService; private readonly Func&lt;IUserRepository&gt; userRepository; public SendEmailToAMCommand( Func&lt;IEmailService&gt; _emailService, Func&lt;IUserRepository&gt; _userRepository, Func&lt;IApplicationRepository&gt; _applicationRepository, IClientRepository _clientRepository) { emailService = _emailService; CommandFor = Modules.All; userRepository = _userRepository; applicationRepository = _applicationRepository; clientRepository = _clientRepository; } public override string CommandDescription { get { return "Sends email to AM"; } } public override void Body(object _obj, object _objInPreviousState) { if (_obj == null) throw new ArgumentNullException("first param is null"); string message = string.Empty; string subject = string.Empty; if (_objInPreviousState == null) { var emailParams = Param as Dictionary&lt;string, string&gt;; if (emailParams != null) { message = emailParams["Message"]; subject = emailParams["Subject"]; } } if (_obj is Application) { var app = (Application)_obj; var email = userRepository().GetManagerForUser(app.UserID).Email; Client borrower = clientRepository.GetMainBorrower(app.ID); if (_objInPreviousState == null) { emailService().SendEmail("", email, message, subject); } else { emailService().SendEmail("", email,"Application: " + borrower.CompanyName + " (" + app.ID +") changed decision status: " +Enum.GetName(typeof(AppStatus), app.ApplicationStatus),"Check following application: " + app.ID); } } else if (_obj is Product) { var product = (Product)_obj; var email = userRepository().GetManagerForUser(product.Application.UserID).Email; Client borrower = clientRepository.GetMainBorrower(product.ApplicationID); if (_objInPreviousState == null) { emailService().SendEmail("", email, message, subject); } else { emailService().SendEmail("", email,"Product: " + product.ID + " for application " + borrower.CompanyName +" (" + product.ApplicationID + ") changed decision status: " +Enum.GetName(typeof(AppStatus), product.ProductStatusType),"Check following application: " + product.ApplicationID); } } else if (_obj is CES) { var ces = (CES)_obj; User user = applicationRepository().GetByID(ces.ApplicationID).User; var email = userRepository().GetManagerForUser(user.UserName).Email; Client borrower = clientRepository.GetMainBorrower(ces.ApplicationID); if (_objInPreviousState == null) { emailService().SendEmail("", email, message, subject); } else { emailService().SendEmail("", user.Email,"CES for application " + borrower.CompanyName + " (" +ces.ApplicationID + ") changed decision status: " +Enum.GetName(typeof(CesStatuses), ces.Status),"Check following application: " + ces.ApplicationID); } } else if (_obj is Comment) { var comment = (Comment)_obj; Client borrower = clientRepository.GetMainBorrower(comment.ApplicationID); emailService().SendEmail("", comment.User.Email,"Comment for the following application: " + borrower.CompanyName + " (" +comment.ApplicationID + ") with message: " + comment.Message + " on date: " +comment.CreatedDate,"Comment for the following application: " + comment.ApplicationID); } else if (_obj is Memo) { var memo = (Memo)_obj; var email = userRepository().GetManagerForUser(memo.UserID).Email; Client borrower = clientRepository.GetMainBorrower(memo.ApplicationID); if (_objInPreviousState == null) { emailService().SendEmail("", email, message, subject); } else { emailService().SendEmail("", email, "Memo for application : " + borrower.CompanyName + " (" + memo.ApplicationID + ") changed decision status: " + Enum.GetName(typeof(AppStatus), memo.Status), "Check following memo for application: " + memo.ApplicationID); } } Logger.InfoLine("Sending Email done" + " @" + CommandName); } } } </code></pre> <p>The problem: this pattern is used in all of other commands. How can I improve this so this will not have same code in over and over again?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T10:49:48.087", "Id": "30928", "Score": "1", "body": "You want to modify your in a specific way, you're not asking us to review it and look for possible improvements. Because of that, I think your question doesn't fit on codereview well and would be better suited for SO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T17:34:28.447", "Id": "31025", "Score": "0", "body": "@svick: Wouldn't SO have a tendency to close this as too localized?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-15T09:02:49.920", "Id": "61875", "Score": "0", "body": "This doesn't seem to be about generics. Generics methods are basically like duck typing but in a statically defined manner -- you have an algorithm that does something, and instead of copy/pasting and the search and replace on the types, you use generics and end up with just one function just as you would if c# did duck typing. It is statically defined, so the type has to support all of the operations used (generally through interfaces but sometimes through inheritance and base types)." } ]
[ { "body": "<p>You don't provide any example of how <code>SendEmailToAOCommand</code> would differ from <code>SendEmailToAMCommand</code>, so I can't be more specific, but here's the gist of what you should do:</p>\n\n<pre><code>public abstract class SendEmailBase : ActionCommand\n{\n private readonly Func&lt;IApplicationRepository&gt; applicationRepository;\n private readonly IClientRepository clientRepository;\n private readonly Func&lt;IEmailService&gt; emailService;\n private readonly Func&lt;IUserRepository&gt; userRepository;\n\n\n public SendEmailBase(\n Func&lt;IEmailService&gt; _emailService,\n Func&lt;IUserRepository&gt; _userRepository,\n Func&lt;IApplicationRepository&gt; _applicationRepository,\n IClientRepository _clientRepository)\n {\n emailService = _emailService;\n CommandFor = Modules.All;\n userRepository = _userRepository;\n applicationRepository = _applicationRepository;\n clientRepository = _clientRepository;\n }\n\n public override string CommandDescription\n {\n get { return \"Sends email to \" + EmailRecipient; }\n }\n public abstract string EmailRecipient { get; }\n\n public override void Body(object _obj, object _objInPreviousState)\n {\n if (_obj == null)\n throw new ArgumentNullException(\"first param is null\");\n\n string message = string.Empty;\n string subject = string.Empty;\n if (_objInPreviousState == null)\n {\n var emailParams = Param as Dictionary&lt;string, string&gt;;\n if (emailParams != null)\n {\n message = emailParams[\"Message\"];\n subject = emailParams[\"Subject\"];\n }\n }\n if (_obj is Application)\n {\n var app = (Application)_obj;\n var email = userRepository().GetManagerForUser(app.UserID).Email;\n Client borrower = clientRepository.GetMainBorrower(app.ID);\n if (_objInPreviousState == null)\n {\n emailService().SendEmail(\"\", email, message, subject);\n }\n else\n {\n emailService().SendEmail(\"\", email,\"Application: \" + borrower.CompanyName + \" (\" + app.ID +\") changed decision status: \" +Enum.GetName(typeof(AppStatus), app.ApplicationStatus),\"Check following application: \" + app.ID);\n }\n }\n else if (_obj is Product)\n {\n var product = (Product)_obj;\n var email = userRepository().GetManagerForUser(product.Application.UserID).Email;\n Client borrower = clientRepository.GetMainBorrower(product.ApplicationID);\n if (_objInPreviousState == null)\n {\n emailService().SendEmail(\"\", email, message, subject);\n }\n else\n {\n emailService().SendEmail(\"\", email,\"Product: \" + product.ID + \" for application \" + borrower.CompanyName +\" (\" + product.ApplicationID + \") changed decision status: \" +Enum.GetName(typeof(AppStatus), product.ProductStatusType),\"Check following application: \" + product.ApplicationID);\n }\n }\n\n else if (_obj is CES)\n {\n var ces = (CES)_obj;\n User user = applicationRepository().GetByID(ces.ApplicationID).User;\n var email = userRepository().GetManagerForUser(user.UserName).Email;\n Client borrower = clientRepository.GetMainBorrower(ces.ApplicationID);\n if (_objInPreviousState == null)\n {\n emailService().SendEmail(\"\", email, message, subject);\n }\n else\n {\n emailService().SendEmail(\"\", user.Email,\"CES for application \" + borrower.CompanyName + \" (\" +ces.ApplicationID + \") changed decision status: \" +Enum.GetName(typeof(CesStatuses), ces.Status),\"Check following application: \" + ces.ApplicationID);\n }\n }\n else if (_obj is Comment)\n {\n var comment = (Comment)_obj;\n Client borrower = clientRepository.GetMainBorrower(comment.ApplicationID);\n emailService().SendEmail(\"\", comment.User.Email,\"Comment for the following application: \" + borrower.CompanyName + \" (\" +comment.ApplicationID + \") with message: \" + comment.Message + \" on date: \" +comment.CreatedDate,\"Comment for the following application: \" + comment.ApplicationID);\n }\n else if (_obj is Memo)\n {\n var memo = (Memo)_obj;\n var email = userRepository().GetManagerForUser(memo.UserID).Email;\n Client borrower = clientRepository.GetMainBorrower(memo.ApplicationID);\n if (_objInPreviousState == null)\n {\n emailService().SendEmail(\"\", email, message, subject);\n }\n else\n {\n emailService().SendEmail(\"\", email, \"Memo for application : \" + borrower.CompanyName + \" (\" + memo.ApplicationID + \") changed decision status: \" + Enum.GetName(typeof(AppStatus), memo.Status), \"Check following memo for application: \" + memo.ApplicationID);\n }\n }\n Logger.InfoLine(\"Sending Email done\" + \" @\" + CommandName);\n\n }\n}\n\npublic class SendEmailToAMCommand : SendEmailBase\n{\n public SendEmailToAMCommand(\n Func&lt;IEmailService&gt; _emailService,\n Func&lt;IUserRepository&gt; _userRepository,\n Func&lt;IApplicationRepository&gt; _applicationRepository,\n IClientRepository _clientRepository) : base(_emailService, _userRepository, _applicationRepository, _clientRepository) { }\n public override string EmailRecipient { get { return \"AM\"; } }\n}\n</code></pre>\n\n<p>Everything that's the same gets put into <code>SendEmailBase</code>. Everything which could vary is defined as an <code>abstract</code> method or property, and then the subclasses implement just those things which make it different.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T15:54:44.120", "Id": "19359", "ParentId": "19324", "Score": "1" } } ]
{ "AcceptedAnswerId": "19359", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T09:22:26.393", "Id": "19324", "Score": "1", "Tags": [ "c#", "generics" ], "Title": "Sending email based on object type" }
19324
<p>I am having trouble designing a module, can anybody help me?</p> <p>Because it will be hard to maintain this kind of module, I also think that this can test my skill of design pattern usage.</p> <h1>Requirement</h1> <p>This is basically an agricultural project (web application). I need to design a module where some calculation takes place.</p> <p>There are different crops involved like maize, tomato, okra etc. Each of these crops has different traits.</p> <p>Each trait has a measurement scale which lies in integer like 200-1000. Now let's say I have planted the crop and done measurement noted down the traits. Now I want to do some sort of measurement. Some measurements are simple and some are complex.</p> <h1>Example</h1> <p>Lets take an example of crop maize. I have recorded observations for 15 traits. (We'll use trait1-trait15 as examples, the actual name can be like plt_ht, yld, etc.)</p> <p>I recorded 5 observations for each trait:</p> <blockquote> <p>trait1 trait2 trait3 trait5 trait6..... trait15<br /> 01,02,03,04 01,02,03,04 01,02,03,04</p> </blockquote> <p>User logs into system and selects his crops and enters data for these observations. I have to calculate either average or sum of the data entered for each trait.</p> <h1>Complexity / centre of the problem</h1> <p>So far it's simple but complexity comes when I have some different formulas for some of the traits.</p> <p>Example: trait YLD has a formula based on which I have to calculate its value, which may also depend on some other traits. Each different crop can have different traits.</p> <p>All this I am able to do - whenever user selects crop I will check for those specific traits and do calculations (if it's not a special trait then I either average or sum it, based on db entry), but there is a lot of hard coding.<br /> I would like to have suggestions on a better way of handling this.</p> <p>My code needs to handle both simple and complex calculations.<br /> Simple calculations are easy, I have take average of value entered for trait.<br /> The problem comes when I have to do complex calculations, since each crop have different traits with their own formulas, so to calculate I have to check for crop and then for complex trait. So I have to hardcode the trait name of complex traits.<br /> Can any tell me how I can design this using <strong>Java</strong> oops [?!?] so that I can make it generic?</p> <p>I have about 10 different crops. Some calculations are specific to crops, so there will be lot of code like the <code>if</code> below:</p> <pre><code> hasZeroValue = (HashMap&lt;String, ArrayList&lt;String&gt;&gt;) dataValues[1]; } else if(cropId.equalsIgnoreCase(&quot;MZ&quot;) &amp;&amp; traitName.equalsIgnoreCase(&quot;Shelling&quot;)) { avg=HybridTestDataUtility.calculateAvg(traitName, dataPoint, dataTraits, traitValues,dataPvalues, dataPoint, type); avg=avg*dataPoint; traitAvg=getMaizeYeild(traitName, traitAvg, population, avg, hybrid, area); } else if(cropId.equalsIgnoreCase(&quot;OK&quot;) &amp;&amp; traitName.equalsIgnoreCase(&quot;YLDGM&quot;)) { avg=HybridTestDataUtility.calculateAvg(traitName, dataPoint, dataTraits, traitValues,dataPvalues, dataPoint, type); //avg=avg*dataPoint; Object[] dataValues=getOKRAYield(traitName, traitAvg, population, avg, dividend,hasZeroValue,hybrid,repl); traitAvg = (HashMap&lt;String, Float&gt;) dataValues[0]; hasZeroValue = (HashMap&lt;String, ArrayList&lt;String&gt;&gt;) dataValues[1]; } else if(cropId.equalsIgnoreCase(&quot;HP&quot;) &amp;&amp; traitName.equalsIgnoreCase(&quot;w1-w10&quot;)) { avg=HybridTestDataUtility.calculateAvg(traitName, dataPts, dataTraits, traitValues,dataPvalues, dataPoint, type); avg=avg*dataPoint; Object[] dataValues=getHotPepperYield(traitName, traitAvg, population, avg,dividend,hasZeroValue,hybrid,repl); traitAvg = (HashMap&lt;String, Float&gt;) dataValues[0]; hasZeroValue = (HashMap&lt;String, ArrayList&lt;String&gt;&gt;) dataValues[1]; } else if(cropId.equalsIgnoreCase(&quot;TO&quot;) &amp;&amp; traitName.equalsIgnoreCase(&quot;TLSSG_70&quot;)) { traitAvg=calculateTLCV(traitName, traitAvg,dataPoint, dataTraits, hybrid, repl, traitValues, dataPvalues,50); } else if(cropId.equalsIgnoreCase(&quot;TO&quot;) &amp;&amp; traitName.equalsIgnoreCase(&quot;TLSSG_100&quot;)) { traitAvg=calculateTLCV(traitName, traitAvg,dataPoint, dataTraits, hybrid, repl, traitValues, dataPvalues,50); } else if(cropId.equalsIgnoreCase(&quot;TO&quot;) &amp;&amp; traitName.equalsIgnoreCase(&quot;YVMV_60&quot;)) { traitAvg=tomatoYVMVCalculation(traitName, traitAvg,dataPoint, dataTraits, hybrid, repl, traitValues, dataPvalues); } else if(cropId.equalsIgnoreCase(&quot;TO&quot;) &amp;&amp; traitName.equalsIgnoreCase(&quot;YVMV_90&quot;)) { traitAvg=tomatoYVMVCalculation(traitName, traitAvg,dataPoint, dataTraits, hybrid, repl, traitValues, dataPvalues); } else if(cropId.equalsIgnoreCase(&quot;TO&quot;) &amp;&amp; traitName.equalsIgnoreCase(&quot;YVMV_120&quot;)) { traitAvg=tomatoYVMVCalculation(traitName, traitAvg,dataPoint, dataTraits, hybrid, repl, traitValues, dataPvalues); } else if(cropId.equalsIgnoreCase(&quot;TO&quot;) &amp;&amp; traitName.equalsIgnoreCase(&quot;ELCV_60&quot;)) { traitAvg=tomatoYVMVCalculation(traitName, traitAvg,dataPoint, dataTraits, hybrid, repl, traitValues, dataPvalues); } else if(cropId.equalsIgnoreCase(&quot;TO&quot;) &amp;&amp; traitName.equalsIgnoreCase(&quot;ELCV_90&quot;)) { traitAvg=tomatoYVMVCalculation(traitName, traitAvg,dataPoint, dataTraits, hybrid, repl, traitValues, dataPvalues); } else if(cropId.equalsIgnoreCase(&quot;TO&quot;) &amp;&amp; traitName.equalsIgnoreCase(&quot;ELCV_120&quot;)) { traitAvg=tomatoYVMVCalculation(traitName, traitAvg,dataPoint, dataTraits, hybrid, repl, traitValues, dataPvalues); } else if(cropId.equalsIgnoreCase(&quot;OK&quot;) &amp;&amp; traitName.equalsIgnoreCase(&quot;YVMV_60&quot;)) { traitAvg=tomatoYVMVCalculation(traitName, traitAvg,dataPoint, dataTraits, hybrid, repl, traitValues, dataPvalues); } else if(cropId.equalsIgnoreCase(&quot;OK&quot;) &amp;&amp; traitName.equalsIgnoreCase(&quot;YVMV_90&quot;)) { traitAvg=tomatoYVMVCalculation(traitName, traitAvg,dataPoint, dataTraits, hybrid, repl, traitValues, dataPvalues); } else if(cropId.equalsIgnoreCase(&quot;OK&quot;) &amp;&amp; traitName.equalsIgnoreCase(&quot;YVMV_120&quot;)) { traitAvg=tomatoYVMVCalculation(traitName, traitAvg, dataPoint, dataTraits, hybrid, repl, traitValues, dataPvalues); } else if(cropId.equalsIgnoreCase(&quot;OK&quot;) &amp;&amp; traitName.equalsIgnoreCase(&quot;ELCV_60&quot;)) { </code></pre> <p>Can anybody think of a way to make a generic approach to this?</p> <p>TO Make things more understandable</p> <p>There are crops and each crop have traits , traits are actually a mesuremet scale to decide growth of a seed of a particular crop. This module is to for planters to observe growth of seeds sowed of certain crops and take down n no of observation for each trait and upload in csv format.Once they enter data i have to either avg out the values or sum the values or sometimes there are more complex function that i have to apply it may differe for each trait .This is the whole module about.Just to give an idea about how they will enter data</p> <pre><code>Hyubrid(seed) trait1 trait2 trait3 trait5 trait6..... trait15 Hybrid1 01 02 03 04 01 HYbrid2 04 06 08 04 01 HYbrid2 04 06 08 04 01 HYbrid2 04 06 08 04 01 HYbrid2 04 06 08 04 01 </code></pre> <p>Once they enter data in this format i have to give result something like this.</p> <p>Here avg colum does not necessaryly mean avg it can be sum or any formula based resutl.Hybrid is the seed for which they record the observation. I have shown avg column only for two tratis it is actually for all the traits.</p> <pre><code>Hyubrid(seed) trait1 Avg trait2 avg trait3 trait5 trait6..... trait15 Hybrid1 01 01 02 04 03 04 01 HYbrid2 04 04 06 10 08 04 01 HYbrid2 04 04 06 12 08 04 01 HYbrid2 04 04 06 14 08 04 01 HYbrid2 04 04 06 12 08 04 01 </code></pre> <p>Hope this clarifies atleat a but</p> <p>The data are not correctly indented but there is no way i can format it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T11:40:01.603", "Id": "30930", "Score": "2", "body": "Next time please **make an effort** when asking. You can as a bare minimum avoid spelling mistakes by using your browser's [spelling tools](https://addons.mozilla.org/en-US/firefox/addon/british-english-dictionary-/). I am exhausted after this edit..." } ]
[ { "body": "<p>I'm not entirely sure of what you're asking, but try this:</p>\n\n<ul>\n<li>Create a Crop class\n<ul>\n<li>Crop has a list of Traits</li>\n</ul></li>\n<li>Create a Trait class\n<ul>\n<li>Trait has an Enum to define which calculation it uses (for example: <code>Calculations.Average</code>, <code>Calculations.TLCV</code>, <code>Calculations.TomatoTVMV</code>, and so on)</li>\n<li>Trait has a list of Observations</li>\n<li>Trait has a Calculate() function, which processes all Observations according to the specified calculation.</li>\n</ul></li>\n</ul>\n\n<p>You'll still need to code each calculation function, but you don't need to manually attach each calculation to a specific crop or trait. You can just have a database table which tells the code \"Crop + Trait = Enum value\"</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T05:28:10.387", "Id": "31048", "Score": "0", "body": "I have implemented it it my own way but what i thought this module could be case study where developers can think from extensebility maintainbility point of view so any design pattern suggestion will be helpfull" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T07:42:54.077", "Id": "31318", "Score": "0", "body": "Just added some more things to clarify" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T10:04:25.003", "Id": "32897", "Score": "0", "body": "Can you please explain more on Enum Bobson" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-15T14:25:23.857", "Id": "32907", "Score": "0", "body": "@VIckyb - [Here's](http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html) the Enum documentation, and I added an example of the values that you'd put into the enum." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T07:06:10.080", "Id": "32970", "Score": "0", "body": "Thanks Bobson , only problem i have is that there could be about 100 traits is this feasible to do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T14:25:22.447", "Id": "32988", "Score": "1", "body": "There's no limit on the number of values in an Enum, but with that many options you're going to need to centralize all the logic which changes based on the value, so you only have to maintain it in one place." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T10:30:27.437", "Id": "33074", "Score": "0", "body": "Can you please explain me more on this \"but with that many options you're going to need to centralize all the logic which changes based on the value, so you only have to maintain it in one place\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T14:30:59.737", "Id": "33085", "Score": "1", "body": "Create a single function: `RunCalculations()`. Inside that is a giant `switch` statement which does the right calculation for your `Enum` value. Everything which needs a calculation calls that one function. Thus, if you modify the possible values, you only have one place to change it." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T15:01:16.147", "Id": "19357", "ParentId": "19326", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T10:14:40.683", "Id": "19326", "Score": "0", "Tags": [ "java", "algorithm", "design-patterns" ], "Title": "Redesign a module to be generic" }
19326
<p>I would like to know if there is a more efficiency way to speed up below code. It uses a procedure where subsampling is required in the nested loop (which a <a href="https://stackoverflow.com/a/13629611/1176697">previous answer</a> helped to make more efficient). </p> <p>R has a tendency to hang when <code>B=500</code>, although computer OS isn't unduly affected. The goal is to run the below code with <code>B=1000</code> and using larger <code>m</code> values(<code>m=75, m=100, m=150</code>)</p> <p>I have detailed the procedure in the code below and included a link to a reproducible data set.</p> <pre><code>#Estimation of order m `leave one out' hyperbolic efficiency scores #The procedure sequentially works through each observation in `IOs' and #calculates a DEA order M efficiency score by leaving out the observation # under investigation in the DEA reference set # Step 1: Load the packages, create Inputs (x) and Outputs (y), choose # m(the order of the partial frontier or reference set to be used in DEA) # and B the number of monte carlo simulations of each m order DEA estimate # Step 2: For each observations a in x, x1 and y1 #are create which 'leaves out' this observation. # Step 3: From these matrices subsamples (xref, yref) of size [m,] are # taken and used in DEA estimation. # Step 4: The DEA estimation uses the m subsample from step 3 # as a reference set and evaluates the efficiency of the observation that # has been 'left out' #(thus the first two arguments in DEA are matrices of order [1,3] ) # Step 5: Steps 3 and 4 are repeated B times to obtain B simulations of the # order m efficiency score and a mean and standard deviation are # calculated and placed in effm. # IOs data can be found here: https://dl.dropbox.com/u/1972975/IOs.txt # From IOs an Input matrix (x[1376,3]) and an Output matrix (y[1376,3]) # are created. library(Benchmarking) x &lt;- IOs[,1:3] y&lt;-IOs[,4:6] A&lt;-nrow(x) effm &lt;- matrix(nrow = A, ncol = 2) m &lt;- 50 B &lt;- 500 pb &lt;- txtProgressBar(min = 0, max = A, style=3) for(a in 1:A) { x1 &lt;- x[-a,] y1 &lt;- y[-a,] theta &lt;- numeric(B) xynrow&lt;-nrow(x1) mB&lt;-m*B xrefm &lt;- x1[sample(1:xynrow, mB, replace=TRUE),] # get all of your samples at once(https://stackoverflow.com/a/13629611/1176697) yrefm &lt;- y1[sample(1:xynrow, mB, replace=TRUE),] deaX &lt;- as.matrix(x[a,], ncol=3) deaY &lt;-as.matrix(y[a,], ncol=3) for(i in 1:B){ theta[i] &lt;- dea(deaX, deaY, RTS = 'vrs', ORIENTATION = 'graph', xrefm[(1:m) + (i-1) * m,], yrefm[(1:m) + (i-1) * m,], FAST=TRUE) } effm[a,1] &lt;- mean(theta) effm[a,2] &lt;- sd(theta) / sqrt(B) setTxtProgressBar(pb, a) } close(pb) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T12:52:48.230", "Id": "30931", "Score": "0", "body": "Session infommation:R version 2.15.2 (2012-10-26) Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit) locale: [1] C/en_US.UTF-8/C/C/C/C attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] Benchmarking_0.21 ucminf_1.1-3 lpSolveAPI_5.5.2.0-5 loaded via a namespace (and not attached): [1] tools_2.15.2" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T17:19:28.007", "Id": "60875", "Score": "0", "body": "I don't see anything that is obviously wrong; you've pre-allocated your vectors and pulled just about everything out of loops (I suppose you could make a list of length `B` with values `(1:m)+(i-1)*m`, but I don't think this really is your slowdown). Since the loops over `B` are independent, I don't see any specific reason why it should hang at 500." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T17:24:54.827", "Id": "61024", "Score": "0", "body": "Hi Brian, Thanks for the response on this. I have since updated the software and there is no longer any hang. I will close this question now." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T12:52:15.907", "Id": "19328", "Score": "4", "Tags": [ "r", "simulation" ], "Title": "Speed up a monte carlo simulation with nested loop" }
19328
<p>I have been reading some NumPy guides but can't seem to figure it out. My TA told me I should be able to speed up my code by using a NumPy array instead of a <code>for</code> loop in the following segment of code.</p> <pre><code>for neighbor in get_neighbors(estimates,i,j): pXgivenX_ *= edge_model(True,neighbor)*observation_model(obs,True) pX_givenX_ *= edge_model(False,neighbor)*observation_model(obs,False) </code></pre> <p>Here is the entire code of the method it is in:</p> <pre><code>def gibbs_segmentation(image, burnin, collect_frequency, n_samples): """ Uses Gibbs sampling to segment an image into foreground and background. Inputs ------ image : a numpy array with the image. Should be Nx x Ny x 3 burnin : Number of iterations to run as 'burn-in' before collecting data collect_frequency : How many samples in between collected samples n_samples : how many samples to collect in total Returns ------- A distribution of the collected samples: a numpy array with a value between 0 and 1 (inclusive) at every pixel. """ (Nx, Ny, _) = image.shape total_iterations = burnin + (collect_frequency * (n_samples - 1)) pixel_indices = list(itertools.product(xrange(Nx),xrange(Ny))) # The distribution that you will return distribution = np.zeros( (Nx, Ny) ) # Initialize binary estimates at every pixel randomly. Your code should # update this array pixel by pixel at each iteration. estimates = np.random.random( (Nx, Ny) ) &gt; .5 # PreProcessing preProObs = {} for (i,j) in pixel_indices: preProObs[(i,j)] = [] preProObs[(i,j)].append(observation_model(image[i][j],False)) preProObs[(i,j)].append(observation_model(image[i][j],True)) for iteration in xrange(total_iterations): # Loop over entire grid, using a random order for faster convergence random.shuffle(pixel_indices) for (i,j) in pixel_indices: pXgivenX_ = 1 pX_givenX_ = 1 for neighbor in get_neighbors(estimates,i,j): pXgivenX_ *= edge_model(True,neighbor)*preProObs[(i,j)][1] pX_givenX_ *= edge_model(False,neighbor)*preProObs[(i,j)][0] estimates[i][j] = np.random.random() &gt; pXgivenX_/(pXgivenX_+pX_givenX_) if iteration &gt; burnin and (iteration-burnin)%collect_frequency == 0: distribution += estimates return distribution / n_samples def edge_model(label1, label2): """ Given the values at two pixels, returns the edge potential between those two pixels. Hint: there might be a more efficient way to compute this for an array of values using numpy! """ if label1 == label2: return ALPHA else: return 1-ALPHA </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T03:22:04.067", "Id": "30932", "Score": "1", "body": "What is `neighbor`? What does `observation_model(obs,True)` return?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T03:29:42.743", "Id": "30933", "Score": "0", "body": "neighbor is a boolean corresponding to whether the pixel is currently believed to be in the foreground or background.\nobservation_model(obs,True) returns a number corresponding to the probability of observing True given that you are at obs (where True corresponds to the pixel being in the foreground)." } ]
[ { "body": "<p>Since this is homework, I won't give you the exact answer, but here are some hints. </p>\n\n<ol>\n<li><p><code>==</code> is overloaded in numpy to return an array when you pass in an array. So you can do things like this: </p>\n\n<pre><code>&gt;&gt;&gt; numpy.arange(5) == 3\narray([False, False, False, True, False], dtype=bool)\n&gt;&gt;&gt; (numpy.arange(5) == 3) == False\narray([ True, True, True, False, True], dtype=bool)\n</code></pre></li>\n<li><p>You can use boolean arrays to assign to specific locations in an array. For example:</p>\n\n<pre><code>&gt;&gt;&gt; mostly_true = (numpy.arange(5) == 3) == False\n&gt;&gt;&gt; empty = numpy.zeros(5)\n&gt;&gt;&gt; empty[mostly_true] = 5\n&gt;&gt;&gt; empty\narray([ 5., 5., 5., 0., 5.])\n</code></pre></li>\n<li><p>You can also negate boolean arrays; together, these facts allow you to conditionally assign values to an array. (<a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html\"><code>numpy.where</code></a> can be used to do something similar.):</p>\n\n<pre><code>&gt;&gt;&gt; empty[~mostly_true] = 1\n&gt;&gt;&gt; empty\narray([ 5., 5., 5., 1., 5.])\n</code></pre></li>\n<li><p>You can then multiply those values by other values:</p>\n\n<pre><code>&gt;&gt;&gt; empty * numpy.arange(5)\narray([ 0., 5., 10., 3., 20.])\n</code></pre></li>\n<li><p>And many different numpy functions (really <a href=\"http://docs.scipy.org/doc/numpy/reference/ufuncs.html\">ufuncs</a>) provide a <code>reduce</code> method that applies the function along the entire array:</p>\n\n<pre><code>&gt;&gt;&gt; results = empty * numpy.arange(5)\n&gt;&gt;&gt; numpy.multiply.reduce(results)\n0.0\n</code></pre></li>\n</ol>\n\n<p>You should be able to completely eliminate that <code>for</code> loop using only the above techniques. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T03:53:26.353", "Id": "30934", "Score": "0", "body": "If it is True then I want to multiply by ALPHA and if it is false I multiply by 1-ALPHA but how can I do this in one line?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T03:54:01.970", "Id": "30935", "Score": "0", "body": "Nevermind I looked at np.where" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T03:40:59.840", "Id": "19330", "ParentId": "19329", "Score": "6" } } ]
{ "AcceptedAnswerId": "19330", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-04T02:31:53.703", "Id": "19329", "Score": "3", "Tags": [ "python", "image", "numpy", "vectorization" ], "Title": "Using Gibbs sampling to segment an image" }
19329
<p>I'd like some tips on optimizing the following code.</p> <p>I'm a bit concerned that I'm 'polluting the global namespace' by not wrapping it in a function. The commented out <code>var rotator { init {</code> came from a JavaScript tutorial but I'm not sure it's the jQuery way? Should I wrap it in <code>$(function()</code>... instead?</p> <pre><code>$(document).ready(function() { //Promos rotation var $accordionList = $('.accordion').find('li'); // var rotator = { // init: function() { var numberOfItems = $accordionList.length; var currentItem = 0; // Set first item to active $accordionList.eq(currentItem).addClass('active').find('.content').slideToggle(800, function() {}); var infiniateLoop = setInterval(function() { if(currentItem == numberOfItems - 1){ currentItem = 0; } else { currentItem++; } // Remove active class, if is has it, and close content $accordionList.parent().find('li.active').removeClass('active') .find('.content').slideToggle(800, function() { }); // Add active class and open content $accordionList.eq(currentItem).addClass('active').find('.content').slideToggle(800, function() { }); }, 4000 ); //$('.accordion li').on('click', function () { $accordionList.on('click', function () { // Stop rotation clearInterval(infiniateLoop); var $accordionHead = $(this); // Remove active class, if is has it, and close content $accordionHead.parent().find('li.active').removeClass('active') .find('.content').slideToggle(800, function() { }); // Add active class and open content $accordionHead.addClass('active').find('.content').slideToggle(800, function() { }); }); // } // }; // rotator.init(); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T10:54:44.483", "Id": "30936", "Score": "1", "body": "_\"I'm not sure it's the JQuery way?\"_ jQuery way? `$(function(){}) === $(document).ready(function(){})`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T10:56:16.773", "Id": "30937", "Score": "0", "body": "you are wrapping it in a function... `$(document.ready(function`..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T10:56:24.397", "Id": "30938", "Score": "2", "body": "Since you wrapped your code in $(document).ready() and you are using the `var` keyword you are surely not polluting the global namespace" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T10:57:45.077", "Id": "30939", "Score": "0", "body": "yes but shouldn't I wrap it in another function so it doesn't conflict with other fucntion (yet to be written) that are also in the document.ready ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T10:56:19.640", "Id": "30941", "Score": "0", "body": "Your code as it is does not polute any global namespace, as it's all contained within a function being called by `$(document).ready`. The addition or removal of the `rotator` object does not change this fact. Either way it's wholey contained within a `function`" } ]
[ { "body": "<p>To your question ( confirmed by the comments ), you are not polluting the namespace because you are</p>\n\n<ol>\n<li>Wrapping already inside <code>$(document).ready(function() {</code> </li>\n<li>Using <code>var</code> for every variable.</li>\n</ol>\n\n<p>Furthermore, from what I can see that is left over from <code>rotator</code>, it was probably a better approach than what you have now.</p>\n\n<p>From a once over:</p>\n\n<ul>\n<li>Spelling is important: infiniateLoop -> infiniteLoop</li>\n<li><code>slideToggle(800, function() {});</code> can simply be written as <code>slideToggle(800);</code></li>\n<li>You could use a ternary for increasing <code>currenItem</code> : <code>currentItem = currentItem == numberOfItems - 1 ? 0 : ++currentItem;</code></li>\n<li>Please remove commented out code, also please re-indent after taking out <code>rotator</code></li>\n<li>It is considered good practice to have one big var at the start instead of multiple vars: </li>\n</ul>\n\n<blockquote>\n<pre><code>var $accordionList = $('.accordion').find('li'),\n numberOfItems = $accordionList.length,\n currentItem = 0;\n\n // Set first item to active\n $accordionList.eq(currentItem).addClass('active').find('.content').slideToggle(800);\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Jshint could not find a single flaw</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T20:36:11.367", "Id": "39415", "ParentId": "19331", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T10:52:38.380", "Id": "19331", "Score": "3", "Tags": [ "javascript", "jquery", "namespaces" ], "Title": "jQuery accordion list" }
19331
<p>This nests Google Maps Event Listener for click or drag. How should I refactor the last part where it reuses the function <code>getAddressComponents()</code>? If there are other parts to be refactored, please do offer suggestions.</p> <pre><code> function getAddressComponents() { geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { clearValue(); if (results[0]) { // Get address_components for (var i = 0; i &lt; results[0].address_components.length; i++) { var addr = results[0].address_components[i]; if (addr.types[0] == 'street_address') $('#spot_street_address').val(addr.long_name); } } else { alert('No results found. Please revise the address or adjust the map marker.'); } } }); } // Add drag listener to marker for reverse geocoding google.maps.event.addListener(marker, 'drag', function() { getAddressComponents(); }); // Add click listener to marker for reverse geocoding google.maps.event.addListener(map, 'click', function(event) { marker.setMap(null); addMarker(event.latLng); getAddressComponents(); google.maps.event.addListener(marker, 'drag', function() { getAddressComponents(); }); }); </code></pre> <p>The map will have existing marker, which is draggable and geocodable. But once I click on the map to create a marker (thus, removing the existing marker), that new marker as I drag it, can't be geocodable. That's why I have to nest the listener to get it working. What have I done wrong?</p>
[]
[ { "body": "<pre><code>google.maps.event.addListener(marker, 'drag', fgetAddressComponents);\n</code></pre>\n\n<p>And you don't need to add it twice. No need to add it in the <code>click</code> handler again.</p>\n\n<p>Otherwise it's mostly ok, except for the <code>==</code> (instead of <code>===</code>), I just have styling nitpicks to say about this code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T14:37:54.497", "Id": "19336", "ParentId": "19335", "Score": "1" } } ]
{ "AcceptedAnswerId": "19336", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T14:23:34.650", "Id": "19335", "Score": "1", "Tags": [ "javascript", "google-maps" ], "Title": "Nested Google Maps Listener" }
19335
<p>I've just made this class, which supports caching. I'd really appreciate any comments on how to make it better etc.</p> <p><a href="https://github.com/Prashles/PHP-Currency-Convert-Class" rel="nofollow">Code</a></p> <pre><code>&lt;?php /* * * PHP Validation Class * * The currency rates are fetched and cached for the whole day * * http://prash.me * http://github.com/prashles * * Uses http://rate-exchange.appspot.com/currency currency API * Returns JSON - based on Google's API * * @author Prash Somaiya * */ Class Convert { /* * Constructor sets to TRUE if $cacheFolder is writable * * FALSE by default */ private $cachable = FALSE; /* * The folder where the cache files are stored * * Set in the constructor. //convert by default */ private $cacheFolder; /* * Length of cache in seconds * * Default is 1 day */ private $cacheTimeout; /* * Check if folder is writable for caching * * Set $cache to FALSE on call to disable caching * $folder is where the cache files will be stored * * Set $folder to 'dcf' for the default folder * * Set $cacheTimeout for length of caching in seconds */ public function __construct($cache = TRUE, $folder = 'dcf', $cacheTimeout = 86400) { $this-&gt;cacheFolder = ($folder == 'dcf') ? dirname(__FILE__).'/convert/' : $folder; if (is_writable($this-&gt;cacheFolder) &amp;&amp; $cache == TRUE) { $this-&gt;cachable = TRUE; $this-&gt;cacheTimeout = $cacheTimeout; } } /* * Main function for converting * * Set $round to FALSE to return full amount */ public function convert($amount = 1, $from = 'GBP', $to = 'USD', $round = TRUE) { # Check if cache file exists and pull rate $rate = $this-&gt;get_cache($from.$to); if ($rate !== FALSE) { $return = $rate * $amount; } else { if (!$this-&gt;validate_currency($to, $from)) { throw new Exception('Invalid currency code - must be exactly 3 letters'); } $response = $this-&gt;fetch($amount, $from, $to); if (isset($response['err'])) { throw new Exception('Invalid input'); } $return = $response['v']; $this-&gt;new_cache($from.$to, $response['rate']); } return ($round) ? abs(round($return, 2)) : abs($return); } /* * Fetches data from external API */ protected function fetch($amount, $from, $to) { $url = "http://rate-exchange.appspot.com/currency?q={$amount}&amp;from={$from}&amp;to={$to}"; $amount = (float) $amount; if (in_array('curl', get_loaded_extensions())) { $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, "http://rate-exchange.appspot.com/currency?q={$amount}&amp;from={$from}&amp;to={$to}"); $response = json_decode(curl_exec($ch), true); } else { $response = json_decode(file_get_contents($url), true); } # Caches the rate for future $this-&gt;new_cache($from.$to, $response['rate']); return $response; } /* * Checks if file is cached then returns rate */ protected function get_cache($file) { if ($this-&gt;cachable &amp;&amp; file_exists($this-&gt;cacheFolder.strtoupper($file).'.convertcache')) { $file = file($this-&gt;cacheFolder.$file.'.convertcache'); if ($file[0] &lt; (time() - $this-&gt;cacheTimeout)) { return FALSE; } return $file[1]; } return FALSE; } /* * Calculates amount needed in currency to achieve finish currency * * Set $round to FALSE to get full value */ public function amount_to($finalAmount, $from, $to, $round = TRUE) { $finalAmount = (float) $finalAmount; if ($finalAmount == 0) { return 0; } if (!$this-&gt;validate_currency($from, $to)) { throw new Exception('Invalid currency code - must be exactly 3 letters'); } # Gets the rate $rate = $this-&gt;get_rate($from, $to); # Work it out $out = $finalAmount / $rate; return ($round) ? round($out, 2) : $out; } /* * Returns rate of two currencies */ public function get_rate($from = 'GBP', $to = 'USD') { # Check cache $rate = $this-&gt;get_cache($from.$to); if (!$rate) { $rate = $this-&gt;fetch(1, $from, $to); $rate = $rate['rate']; } return $rate; } /* * Deletes all .convertcache files in cache folder */ public function clear_cache() { $files = glob($this-&gt;cacheFolder.'*.convertcache'); if (!empty($files)) { array_map('unlink', $files); } } /* * Validates the currency identifier */ protected function validate_currency() { foreach (func_get_args() as $val) { if (strlen($val) !== 3 || !ctype_alpha($val)) { return FALSE; } } return TRUE; } /* * Checks if file is cacheable then creates new file */ protected function new_cache($file, $rate) { if ($this-&gt;cachable) { $file = strtoupper($file).'.convertcache'; $data = time().PHP_EOL.$rate; file_put_contents($this-&gt;cacheFolder.$file, $data); } } } </code></pre> <p>Usage:</p> <pre><code>&lt;?php require_once 'classes/convert.php'; $convert = new Convert; # Convert 15 USD to GBP echo $convert-&gt;convert(10, 'USD', 'GBP'); echo '&lt;br/&gt;'; # Displays how much USD you need to get 100 INR - won't show the rounded value echo $convert-&gt;amount_to(100, 'USD', 'INR', FALSE); </code></pre>
[]
[ { "body": "<p>Your class does too much. Split it up into multiple pieces:</p>\n\n<ol>\n<li>It converts currencies.</li>\n<li>It validates currency identifier.</li>\n<li>It fetches HTTP resources</li>\n<li>It caches fetched HTTP resources.</li>\n</ol>\n\n<p>Although it does plenty of things, it has no answer to the problem of how to actually recognize which currency any amount is in. Adding two amounts might be valid, because you add GBP and GBP, but might actually be invalid because of GBP and USD. Your variable would only contain the integer or float value.</p>\n\n<p>So split it up. First create a class that actually represents an amount of money in a specified currency. This can be as easy as making a class with two public values, $amount and $currency, but usually you do not want to allow write access to these, so the two values should go into the constructor, stored as private properties, and be accessible via get methods.</p>\n\n<pre><code>class Money_Currency\n{\n /**\n * @var float\n */\n private $_amount;\n\n /**\n * @var string\n */\n private $_currency;\n\n public function __construct($amount, $currency)\n {\n $this-&gt;_amount = $amount;\n $this-&gt;_currency = $currency;\n }\n\n public function getAmount()\n {\n return $this-&gt;_amount;\n }\n\n public function getCurrency()\n {\n return $this-&gt;_currency;\n }\n}\n</code></pre>\n\n<p>Adding or subtracting monetary values is a common task. How can we add two amounts of the same currency? Simple addition. Let's add a method for it. Note that I add the method to the Money_Currency class, which can be discussed. If I do not want to do this, I'd need an independent class that does all the math. If you have such a class, try this different approach. If not, continue following me...</p>\n\n<pre><code> public function addAmount(Money_Currency $money)\n {\n if ($this-&gt;_currency !== $money-&gt;getCurrency()) {\n throw new InvalidArgumentException('Can only add money from the same currency');\n }\n\n $this-&gt;_amount += $money-&gt;getAmount();\n }\n</code></pre>\n\n<p>So now we are able to do a simple math operation:</p>\n\n<pre><code>$m1 = new Money_Currency(20, 'USD');\n$m2 = new Money_Currency(30, 'USD');\n\n$m1-&gt;addAmount($m2);\n\necho $m1-&gt;getAmount() . \" \" . $m1-&gt;getCurrency();\n</code></pre>\n\n<p>Outputs </p>\n\n<pre><code>50 USD\n</code></pre>\n\n<p>Easy. And completely unrelated to your currency conversion so far, but it solves a problem you might have, unless you are only offering a web service that inputs amount and currencies and translates this to the other value.</p>\n\n<p>What about currency conversion? What about adding two different currencies? Decorator pattern to the rescue!</p>\n\n<p>You can build a decorator that implements the same interface, which wraps around a currency object and does the calculations for converting the currency.</p>\n\n<p>Let's fix the interface stuff first:</p>\n\n<pre><code>interface Money_Currency\n{\n public function getAmount();\n\n public function getCurrency();\n}\n\nclass Money_Currency_Value implements Money_Currency\n{\n // instead of Money_Currency class from above\n</code></pre>\n\n<p>Then the converter:</p>\n\n<pre><code>class Money_Currency_Converter implements Money_Currency\n{\n /**\n * @var Money_Currency\n */\n private $_money;\n\n /**\n * @var float\n */\n private $_conversionrate;\n\n /**\n * @var string\n */\n private $_sourcecurrency;\n\n /**\n * @var string\n */\n private $_targetcurrency;\n\n public function __construct($conversionrate, $sourcecurrency, $targetcurrency)\n {\n $this-&gt;_conversionrate = $conversionrate;\n $this-&gt;_sourcecurrency = $sourcecurrency;\n $this-&gt;_targetcurrency = $targetcurrency;\n }\n\n public function setMoney(Money_Currency $money)\n {\n if ($this-&gt;_sourcecurrency !== $money-&gt;getCurrency()) {\n throw new InvalidArgumentException('The money value is in an incorrect currency for this converter');\n }\n\n $this-&gt;_money = $money;\n }\n\n public function getAmount()\n {\n return $this-&gt;_money-&gt;getAmount() * $this-&gt;_conversionrate;\n }\n\n public function getCurrency()\n {\n return $this-&gt;_targetcurrency;\n }\n}\n</code></pre>\n\n<p>Now some test (continues with the objects from above):</p>\n\n<pre><code>$m3 = new Money_Currency_Value(10, 'GBP');\n\n$convertGbpToUsd = new Money_Currency_Converter(1.5, 'GBP', 'USD');\n\n$convertGbpToUsd-&gt;setMoney($m3);\n\necho \"Converted \". $m3-&gt;getAmount() .\" \". $m3-&gt;getCurrency() . \" into \". $convertGbpToUsd-&gt;getAmount() . \" \" . $convertGbpToUsd-&gt;getCurrency();\n\ntry {\n $m1-&gt;addAmount($m3); // fails\n} catch (Exception $e) {\n}\n\n$m1-&gt;addAmount($convertGbpToUsd);\n\necho $m1-&gt;getAmount() . \" \" . $m1-&gt;getCurrency();\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Converted 10 GBP into 15 USD\n65 USD\n</code></pre>\n\n<p>(we started with the 50 USD object from above, the conversion rate is completely arbitrary).</p>\n\n<p>What have we got now? We can add amounts of the same currency. We can convert an amount into a different currency. We can also add amounts in different currencies via wrapping them into a converter first. That's pretty much all currency stuff should do.</p>\n\n<p>Now how do you get this nice converter? It is simply a call to a class that generates it for you. This class should only deal with generating the proper conversion object when asked to provide one for conversion from currency A to B. To fulfill this, it needs access to a resource of knowledge, but this resource could be anything. For example, a HTTP client. But the client cannot be universal, it has to be customized for the web service you are using. So in reality you need to create something like a factory that is able to make a request for converting currencies to a certain web service. This call triggers a basic HTTP request with some parameters.</p>\n\n<p>Caching should be done as decorator pattern as well. Decorating an HTTP call with a cache means that in the decorator you see if there is a matching entry in the cache that is still valid (might expire to fetch new updates), if not, it forwards the function call to the real client.</p>\n\n<p>I apologize for not going into details for these tasks at this moment. I hope you got the idea of how to split up responsibilities between classes from the currency conversion example.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T22:23:55.100", "Id": "30990", "Score": "0", "body": "Some more thoughts on your current implementation: What happens if the curl extension is not present? What if I want to use a different web service? What if my conversion rates are inside a database? What if I want to use a different cache system like memcache? How about unit testing the whole stuff? But also: How is the programmer supposed to use this stuff in an easy way. Your approach is completely easy, but not configurable, adaptable and extendable for different uses." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T17:17:59.767", "Id": "31071", "Score": "0", "body": "Thank you so much for that! So, by splitting it up, should I have the separate classes in different files, or the multiple classes in the same file? When people use this, I don't want there to be too many files where it can get confusing with directories etc" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T17:41:19.247", "Id": "31072", "Score": "0", "body": "Autoloading will solve this. And if you offer your module via Composer, then it will take care of this. However, the standard is to put one class per file, with a reasonable naming scheme. Read the \"PSR-0\" standard on how to correctly name your classes: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T22:18:17.940", "Id": "19347", "ParentId": "19338", "Score": "5" } }, { "body": "<ul>\n<li><p>Your implementation should conform with the basic principles of Object Oriented Programming. Keep your classes simple and focused on one type of task only. When your classes start doing more than they should, they become procedural code locked into classes. </p></li>\n<li><p>Never perform the live fetching of currency data from within your application. The right way is to run a cron job which regularly updates a configuration file loaded by your application. A check twice a day would be sufficient. Get the cron script to email you if something goes wrong but you would have at the very least the last fetched data to work with. I have seen a class somewhere online that actually parses a Google search to retrieve the currency amount. The more dependency you create within your code, the more trouble you are likely to encounter.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-29T00:16:55.673", "Id": "88288", "ParentId": "19338", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T15:45:11.443", "Id": "19338", "Score": "3", "Tags": [ "php", "object-oriented", "converting", "cache", "finance" ], "Title": "Currency conversion class with caching" }
19338
<p>I have a class that uses the SqlBulkCopy to bulk insert data into a SQL Server database. My original implementation just passed the <code>m_buffer</code> (which is a reference to a class that implements IDataReader) directly into the <code>WriteToServer</code>. Now a new requirement has been added that, upon failure, the process should retry the Bulk Insert command. Why you ask? Because <em>one</em> of our clients get intermittent SQL exceptions because they have crappy hardware. </p> <p>Okay, I digress, since IDataReader is read-once I needed to come up with something different. I chose to load the IDataReader into a DataTable first and then pass the DataTable into the <code>WriteToServer</code> method. Now my problem is that I will be using more memory and since I do not know anything about the data (the number of columns nor the amount of data in each row) I wanted to attempt to make the code safe from an OutOfMemoryException.</p> <p>Unfortunately I could not find a good way to determine the amount of available memory, so instead I chose to dump the data every 50,000 rows or when the memory allocation reaches an arbitrary number (1 gig), whichever comes first.</p> <p>Does this sound like a sound approach or is there a better way?</p> <pre><code>// m_buffer is a read-once cache (implements IDataReader) that pulls // data from an external source as needed so it uses very little memory. // My original implementation just used m_buffer as the parameter of // WriteToServer but now I have to add retry logic into the process. // The retry logic is in the PutDataIntoDatabase method. const long MAX_MEMORY_TO_USE = 1073741824; // 1 gig DataTable dataTable = new DataTable(m_tableName); foreach (DataField d in m_buffer.GetColumns()) dataTable.Columns.Add(new DataColumn(d.FieldName, d.FieldType)); while (m_buffer.Read()) { DataRow row = dataTable.NewRow(); for (int i = 0; i &lt; m_buffer.FieldCount; i++) row[i] = m_buffer.GetValue(i); dataTable.Rows.Add(row); long totalMemory = GC.GetTotalMemory(false); if (rowCount++ &gt; 50000 || totalMemory &gt; MAX_MEMORY_TO_USE) { PutDataIntoDatabase(dataTable); dataTable.Clear(); rowCount = 0; } } if (dataTable.Rows.Count &gt; 0) PutDataIntoDatabase(dataTable); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T17:57:32.177", "Id": "30966", "Score": "0", "body": "What if you could tell how much RAM is available? If `taskmgr.exe` knows that info, then there must be a way. http://veskokolev.blogspot.com/2008/03/how-to-get-free-available-memory-with-c.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T18:49:22.173", "Id": "30969", "Score": "0", "body": "How does the source (that implements `IDataReader`) look like? Is a network source, a file source, or anything else?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T19:31:32.160", "Id": "30976", "Score": "0", "body": "@Leonid I would need to know the amount of memory available to that process. It would not have to be exact either, a rough estimate would work. But it does not seem that that is even possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T19:34:01.073", "Id": "30977", "Score": "0", "body": "@almaz It could be anything although it is unlikely to be a network source but you never know (I am constantly amazed at the \"crazy\" things clients want to do). Most often it will be a database but could also be a file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T19:40:14.833", "Id": "30979", "Score": "0", "body": "I would start the chunk size at 64k and then change it adaptively - e.g. divide it by two if you do encounter an out of memory error and try to double it randomly once in a while. There must be existing known algorithms for this sort of thing; I just do not know what they are called." } ]
[ { "body": "<p>Based on your comments it looks like your code is actually some sort of library used by different clients in different environments. If that's the case I would rather let clients define the batch size they want rather than writing tricks around memory management on your own. </p>\n\n<p>If you do need to manage the memory - I would suggest to reduce the frequency of <code>GC.GetTotalMemory</code> calls, e.g. check it once per 1000 rows or so. Bear in mind that since your component is not the only one in the application it may turn out that application has already consumed 1GB of RAM thus causing you to reduce the batch size to minimum.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T17:50:50.753", "Id": "31028", "Score": "0", "body": "You could also detect how much RAM the user has at run time and drop the batch size if it is below some threshold. Not as effective as a setting, but means one less setting." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T14:20:18.557", "Id": "19356", "ParentId": "19339", "Score": "2" } } ]
{ "AcceptedAnswerId": "19356", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T17:28:46.790", "Id": "19339", "Score": "1", "Tags": [ "c#", "sql", "sql-server" ], "Title": "Is this a good way to limit the occurrence of OutOfMemoryException?" }
19339
<p>I have made a small project and I am just wondering if I could add more functionality to the project e.g more classed etc. Is a better way of displaying my results and what error handling I could do?</p> <p>I was also wondering what would be the best way to add Inheritance to the this project.I was thinking a <code>EveningCourse</code> class or <code>PostGrad</code>, <code>UnderGrad</code> class. What would be the best way to go about it? </p> <p>The user enters student name, age, year and student number.</p> <pre><code>package david; public class Student { private String name; private int age; private int year; private String studentNum; public Student(String name, int age, int year, String studentNum) { this.name = name; this.age = age; this.year = year; this.studentNum = studentNum; } // Setters and getters (Name, Age, Year and Student Number) public String getName() // name { return name; } public void setName(String name) { this.name = name; } public int getAge() // age { return age; } public void setAge(int age) { this.age = age; } public int getYear() // year { return year; } public void setYear(int year) { this.year = year; } public String getstudentNum() // studentNum { return studentNum; } public void setstudentNum(String studentNum) { this.studentNum = studentNum; } } package david; // David Needham - G00263842. // Student information program. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class TestStudents { public static void main(String[] args) throws IOException { System.out.println("============" + "================="); System.out.println("Students " + "Personal Details"); System.out.println("============" + "================="); String name; int age; int year; String studentNum; List&lt;Student&gt; studentsList = new ArrayList&lt;Student&gt;(); for (int i = 0; i &lt; 2; i++) { int studentNumber = (i + 1); System.out.println(""); System.out.println("Please enter " + "data for student " + studentNumber); InputStreamReader converter = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(converter); System.out.println("Enter Student "+ studentNumber + " Name:"); name = in.readLine(); System.out.println("Enter Student " + studentNumber + " Age (Integer):"); age = Integer.valueOf(in.readLine()); System.out.println("Enter Student " + studentNumber + " Year (Integer):"); year = Integer.valueOf(in.readLine()); System.out.println("Enter Student " + studentNumber + " Student Number:"); studentNum = in.readLine(); Student student = new Student(name, age, year, studentNum); studentsList.add(student); // add student } for (int j = 0; j &lt; studentsList.size(); j++) { Student st = studentsList.get(j); System.out.println("Student : " + (j + 1)); System.out.println("Name: " + st.getName() + " - Age: " + st.getAge() + " - Year: " + st.getYear() + " - Student Number: " + st.getstudentNum()); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-02T10:04:02.607", "Id": "60461", "Score": "0", "body": "You could have used a single function for the `name`, `age`, `year` and `studentnum`." } ]
[ { "body": "<p>Yes, you can add more functionality to your project. You can take this in many different directirons such as adding courses that students and register for. </p>\n\n<p>As for a error handling, you could add a check in your set functions of the <code>Student</code> class to check for formatting or content and return a boolean value based on if they pass the validation or not. For example, since <code>studentnum</code> is a string, you can check to make sure that the format of letters and numbers if correct, if there is a certain format.</p>\n\n<p>You could also use a try-catch block around the code where you read in the values from the user. Or validate that the user enter an acceptable value for each entry such as checking that when the user is asked to enter the age, check to make sure that they did indeed enter a number.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T20:42:53.200", "Id": "30986", "Score": "0", "body": "Thanks very much for this feedback, now I know where to start!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T20:38:35.910", "Id": "19342", "ParentId": "19341", "Score": "4" } }, { "body": "<p>Some general stuff. Your use of whitespace and indentation is messy, fix it!</p>\n\n<p>Java normally uses a modified K&amp;R style with the opening braces on the same line, like this:</p>\n\n<pre><code>function test() {\n if (condition) {\n // Stuff\n } else {\n // Stuff\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>package david;\n</code></pre>\n\n<p>In this case it's minor and/or unnecessary, but keep in mind that package names should give some information about the package, f.e. who wrote it.</p>\n\n<pre><code>package com.yourcompany.department.package;\npackage com.gmail.youremailname.package;\n</code></pre>\n\n<hr>\n\n<pre><code>public String getName() // name\n</code></pre>\n\n<p>Whenever possible use <a href=\"http://en.wikipedia.org/wiki/Javadoc\" rel=\"nofollow\">JavaDoc</a>, it can be consumed by various tools and IDEs and can make your life a lot easier.</p>\n\n<pre><code>/**\n * The (full, first and last) name of the Student.\n */\npublic String getName()\n</code></pre>\n\n<hr>\n\n<p>Instead of making local variables and creating the object afterwards, you could add an empty constructor and fill the object directly.</p>\n\n<pre><code>Student student = new Student();\nstudent.setName(fromInput);\nstudent.setAge(fromInput);\n...\n</code></pre>\n\n<hr>\n\n<pre><code>List&lt;Student&gt; studentsList = new ArrayList&lt;Student&gt;(); \n</code></pre>\n\n<p>This variables would be better named <code>students</code>. From the plural you can already perceive that is some sort of collection, and looking at the definition tells you that it is a List. There's no need for any sort of hungarian notation.</p>\n\n<hr>\n\n<p>You could extract the reading of the values into it's own class, something that allows you to do something like this:</p>\n\n<pre><code>InputReader reader = new InputReader(System.out, System.in);\n//Inside the for\nStudent student = new Student();\nstudent.setName(reader.getString(\"Please enter the name: \"));\nstudent.setAge(reader.getInt(\"Please enter the ager: \"));\n...\n</code></pre>\n\n<hr>\n\n<pre><code>for (int j = 0; j &lt; studentsList.size(); j++)\n {\n\n Student st = studentsList.get(j);\n</code></pre>\n\n<p>Use appropriate loops, in this case a <code>for each</code>:</p>\n\n<pre><code>for(Student student : studentsList) {\n</code></pre>\n\n<hr>\n\n<pre><code>private String studentNum;\n</code></pre>\n\n<p>This variable would be better named <code>ID</code>, that would make the Object a lot cleaner:</p>\n\n<pre><code>student.getID();\nstudent.setID(id);\n</code></pre>\n\n<hr>\n\n<pre><code>studentsList.add(student); // add student\n</code></pre>\n\n<p>Comments should mostly explain <em>why</em> you do something the way you do, and partly <em>how</em>. You never need to explain \"obvious\" things, like incrementing an integer. In this case your comment says exactly the same thing as your code, actually, the code is more precise.</p>\n\n<hr>\n\n<pre><code>public static void main(String[] args) throws IOException \n</code></pre>\n\n<p>This is baaaad. Your application should handle exceptions gracefully, <code>main()</code> should never throw exceptions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-02T13:16:26.710", "Id": "32134", "ParentId": "19341", "Score": "3" } }, { "body": "<p>You could make Student an abstract class, and then have UnderGrad and PostGrad classes as concrete implementations of it with their own variations on how they implement the base methods. </p>\n\n<p>This would then give you the flexibility of accommodating other types of student. For example students attending a short language course before starting their undergrad.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-03T09:29:42.060", "Id": "32174", "ParentId": "19341", "Score": "1" } } ]
{ "AcceptedAnswerId": "19342", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T19:47:23.860", "Id": "19341", "Score": "8", "Tags": [ "java" ], "Title": "Student information system" }
19341
<p>I'm trying to come up with a way to make a drop down box that is displayed through a jquery mouse hover event and with nested dropdown boxes displayed through hovering over elements of the original drop down box. I wrote some terribly inefficient code and I'm struggling to find ways of simplifying it. If anyone has any suggestions that will help me shorten this code and get a better idea of how to take advantage of functions of JQuery, please help. </p> <p>here is the link:</p> <p><a href="http://cs-dev.dreamhosters.com/dropd.php" rel="noreferrer">http://cs-dev.dreamhosters.com/dropd.php</a></p> <pre><code>$(document).ready(function(){ $(".tab, .drop").hover(function(){ $(".tab").css("color","#FF7722"); $(".drop").css("display","block"); $("#tv, .droptv").hover(function(){ $(this).css("color","#FF7722"); $(".droptv").css("display","block"); $(".droptv").hover(function(){ $("#tv, .droptv").css("color","#FF7722"); },function(){ $(".droptv").css("color","#005BAB"); }); },function(){ $(this).css("color","#005BAB"); $(".droptv").css("display","none"); }); $("#interact").hover(function(){ $(this).css("color","#FF7722"); },function(){ $(this).css("color","#005BAB"); }); $("#online").hover(function(){ $(this).css("color","#FF7722"); },function(){ $(this).css("color","#005BAB"); }); $("#vod, .dropvod").hover(function(){ $(this).css("color","#FF7722"); $(".dropvod").css("display","block"); $(".dropvod").hover(function(){ $("#dai").hover(function(){ $(this).css("color","#FF7722"); },function(){ $(this).css("color","#005BAB"); }); $("#iguide").hover(function(){ $(this).css("color","#FF7722"); },function(){ $(this).css("color","#005BAB"); }); $("#vod").css("color","#FF7722"); },function(){ $(".dropvod").css("color","#005BAB"); }); },function(){ $(this).css("color","#005BAB"); $(".dropvod").css("display","none"); }); $("#tablet").hover(function(){ $(this).css("color","#FF7722"); },function(){ $(this).css("color","#005BAB"); }); $("#mobile").hover(function(){ $(this).css("color","#FF7722"); },function(){ $(this).css("color","#005BAB"); }); },function(){ $(".tab").css("color","#005BAB"); $(".drop").css("display","none"); }); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T10:08:45.090", "Id": "31008", "Score": "0", "body": "Try using JavaScript for state and CSS for style. It would make this code **so** much simpler!" } ]
[ { "body": "<p>Your code is very big and messy so this a bit tricky to really see what you are trying to do. A few obvious things to make the code more readable:</p>\n\n<ul>\n<li>Replace <code>.css(\"display\",\"block\")</code> with <code>.show()</code></li>\n<li>Replace <code>.css(\"display\",\"none\")</code> with <code>.hide()</code></li>\n<li><p>You repeat the same color changing hover over and over again. Instead, group all your elements together and specify this function only once:</p>\n\n<p>$(\"#containo div\").hover(function() {<br>\n $(this).css(\"color\",\"#FF7722\");<br>\n},function() {<br>\n $(this).css(\"color\",\"#005BAB\");<br>\n}); </p></li>\n<li><p>Do not nest hovers inside other hovers. <code>.hover()</code> creates a new event handler when it is called. If you nest them then you each time you move your mouse over the parent, the child is assigned a new event handler. You do not want these duplicates. Instead assign all of your events in the root level.</p></li>\n</ul>\n\n<p>&nbsp;</p>\n\n<p>This, plus a little refactoring could reduce your code considerably. Maybe from here the code will be easier to work with so could see how to reduce it further.</p>\n\n<pre><code>$(document).ready(function() {\n\n function on(selector) {\n $(selector).css(\"color\",\"#FF7722\");\n };\n function off(selector) {\n $(selector).css(\"color\",\"#005BAB\");\n };\n\n $(\"#interact,#online,#tablet,#mobile,#dai,#iguide,#tv,.droptv,#vod,.dropvod\")\n .hover(function(){\n on(this)\n },function(){\n off(this)\n });\n\n $(\"#tv, .droptv\").hover(function(){\n $(\".droptv\").show();\n },function(){\n $(\".droptv\").hide();\n });\n\n $(\"#vod, .dropvod\").hover(function(){\n on(\"#vod\");\n $(\".dropvod\").show();\n },function(){\n off(\".dropvod\");\n $(\".dropvod\").hide();\n });\n\n $(\".tab, .drop\").hover(function(){\n on(\".tab\");\n $(\".drop\").show();\n },function(){\n off(\".tab\");\n $(\".drop\").hide();\n });\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T22:04:20.490", "Id": "19346", "ParentId": "19343", "Score": "4" } }, { "body": "<p>I would also suggest, in addition to Buh Buh's answer:</p>\n\n<ul>\n<li><p><strong>Save the references to the elements in a variable,</strong> so that instead of <code>$('.tv')</code> and making jQuery perform a search through the DOM every time, you can refer to your variable and apply jQuery methods to it. Furthermore, this can help if you also can give meaningful names to those variables. For example</p>\n\n<p>var $mainCombos = $('.tv');\n// later on\n$mainCombos.show();</p></li>\n</ul>\n\n<p>I always use a dollar sign to indicate which of my variables are jQuery objects versus regular variables, but it is really not needed. </p>\n\n<p><em>Beware</em> that this may bring you problems if you're dynamically adding or removing elements from the DOM. If this is the case, you may use alternative versions of this, like re-setting the reference variable each time your code is called, or applying live events and grasping the references with <code>$(this)</code>.</p>\n\n<ul>\n<li><strong>Chain calls to jQuery methods whenever possible</strong>. This prevents jQuery from searching all over again for those elements (also useful if you can't apply my first suggestion). For instance:</li>\n</ul>\n\n<p>Instead of</p>\n\n<pre><code>$('.droptv').show();\n$('.droptv').hover(...);\n</code></pre>\n\n<p>You could use</p>\n\n<pre><code>$('.droptv').show()\n .hover(...);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T14:55:44.633", "Id": "19405", "ParentId": "19343", "Score": "3" } } ]
{ "AcceptedAnswerId": "19346", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-05T20:45:19.423", "Id": "19343", "Score": "5", "Tags": [ "javascript", "jquery", "html", "css" ], "Title": "Simplifying Code for Drop-Down-Box in JQuery and HTML" }
19343
<p>How I can rewrite or refactor my controller code? I have the same SQL query (@plan_gp_users) in all <code>def</code>s.</p> <pre><code> class PlanGpsController &lt; ApplicationController def index @search = PlanGp.joins(:user).search(params[:q]) @plan_gps = @search.result.order("created_at DESC").page(params[:page]).per(15) @plan_gp_users = User.where("users.ab_id = :abs_id AND users.id != :user_id AND is_admin IS NULL AND role != 'head'", {:abs_id =&gt; current_user.ab_id,:user_id =&gt;current_user.id}) respond_to do |format| format.js format.html # index.html.erb format.json { render json: @plan_gps } end end def show @plan_gp = PlanGp.find(params[:id]) @plan_gp_users = User.where("users.ab_id = :abs_id AND users.id != :user_id AND is_admin IS NULL AND role != 'head'", {:abs_id =&gt; current_user.ab_id,:user_id =&gt;current_user.id}) respond_to do |format| format.js format.html # show.html.erb format.json { render json: @plan_gp } end end # GET /plan_gps/new # GET /plan_gps/new.json def new @plan_gp = PlanGp.new # 3.times { render @plan_gp.user_id } # .joins("LEFT JOIN plan_gps ON plan_gps.user_id = users.id and strftime('%Y-%m','now') = strftime('%Y-%m',plan_gps.month)") AND plan_gps.user_id is null @plan_gp_users = User.where("users.ab_id = :abs_id AND users.id != :user_id AND is_admin IS NULL AND role != 'head'", {:abs_id =&gt; current_user.ab_id,:user_id =&gt;current_user.id}) # raise @plan_gp_users.to_sql respond_to do |format| format.js format.html # new.html.erb format.json { render json: @plan_gp } end end # GET /plan_gps/1/edit def edit @plan_gp = PlanGp.find(params[:id]) @plan_gp_users = User.where("users.ab_id = :abs_id AND users.id != :user_id AND is_admin IS NULL AND role != 'head'", {:abs_id =&gt; current_user.ab_id,:user_id =&gt;current_user.id}) end # POST /plan_gps # POST /plan_gps.json def create @plan_gp = PlanGp.new(params[:plan_gp]) @plan_gp_users = User.where("users.ab_id = :abs_id AND users.id != :user_id AND is_admin IS NULL AND role != 'head'", {:abs_id =&gt; current_user.ab_id,:user_id =&gt;current_user.id}) User.where("id IN (:user_ids) AND role != :role", {:user_ids =&gt; params[:plan_gp]["user_id"],:role =&gt;'head'}).select("id").map do|m| @plan_gp = PlanGp.new(params[:plan_gp]) @plan_gp.user_id = m.id @plan_gp.abs_id = current_user.ab_id if @plan_gp.save @plan_gp_save = true else @plan_gp_save = false end end @plan_gp.abs_id = current_user.ab_id respond_to do |format| if @plan_gp_save format.js format.html { redirect_to plan_gps_url } format.json { render json: @plan_gp, status: :created, location: @plan_gp } else format.js format.html { redirect_to plan_gps_url } format.json { render json: @plan_gp.errors, status: :unprocessable_entity } end end end # PUT /plan_gps/1 # PUT /plan_gps/1.json def update @plan_gp = PlanGp.find(params[:id]) @plan_gp_users = User.where("users.ab_id = :abs_id AND users.id != :user_id AND is_admin IS NULL AND role != 'head'", {:abs_id =&gt; current_user.ab_id,:user_id =&gt;current_user.id}) respond_to do |format| if @plan_gp.update_attributes(params[:plan_gp]) format.js format.html { redirect_to @plan_gp, notice: 'Plan gp was successfully updated.' } format.json { head :no_content } else format.js format.html { render action: "edit" } format.json { render json: @plan_gp.errors, status: :unprocessable_entity } end end end # DELETE /plan_gps/1 # DELETE /plan_gps/1.json def destroy @plan_gp = PlanGp.find(params[:id]) @plan_gp.destroy respond_to do |format| format.js format.html { redirect_to plan_gps_url } format.json { head :no_content } end end end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T23:53:17.243", "Id": "64970", "Score": "0", "body": "It looks like much of the code is double-spaced (has extra blank lines). Is that an accident of cut-and-paste?" } ]
[ { "body": "<p>You should use a named Scope in your model</p>\n\n<pre><code>class User &lt; ...\n scope :by_ab_without_user, lambda do |ab_id, id| \n where(:ab_id =&gt; ab_id, :is_admin =&gt; null).\n where(\"id != :user_id AND role != 'head'\", { :user_id =&gt; id })\n end\n ...\nend\n</code></pre>\n\n<p>You can then use it from your controller with</p>\n\n<pre><code>User.by_ab_without_user(current_user.ab_id, current_user.id)\n</code></pre>\n\n<p>I'm not a big fan of writing another scope for each query which occurs in a controller though (which might end up only used once). That just increases the noise in the model. So you should strive for <em>orthogonal</em> scopes which can be combined easily. So for the above example you might do:</p>\n\n<pre><code>class User &lt; ...\n scope :not_admin, where(:is_admin =&gt; null)\n scope :not_head, where(\"role != 'head'\")\n scope :not_user, lambda { |id| where(\"id != ?\", id) }\n scope :by_ab, lambda { |ab_id| where(:ab_id =&gt; ab_id) }\n ...\nend\n</code></pre>\n\n<p>Then you could use them like this</p>\n\n<pre><code>User.not_admin.not_head.not_user(current_user).by_ab(current_user.ab_id)\n</code></pre>\n\n<p>Or if you need this particular combination often you can define a specialized scope with them (yes you can use other scopes in scope definitions).</p>\n\n<p>But of course it depends on the problem domain wether or not you need that flexibility. So it's probably best to start with specialized scopes and orthogonalize later when you see fit.</p>\n\n<p>Another thing you should do is to put common action initialization code in a before filter</p>\n\n<pre><code>class PlanGpsController &lt; ApplicationController\n before_filter :init_plan_gp_users, :except =&gt; :destroy\n ...\n\nprivate\n\n def init_plan_gp_users\n @plan_gp_users = ...\n end\nend\n</code></pre>\n\n<p>But you still should use named scopes, because they improve code reusability across controllers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T00:59:09.183", "Id": "34083", "ParentId": "19353", "Score": "2" } } ]
{ "AcceptedAnswerId": "34083", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T07:11:24.647", "Id": "19353", "Score": "1", "Tags": [ "ruby", "sql", "ruby-on-rails", "controller", "active-record" ], "Title": "Duplicate SQL code in controller" }
19353
<p>One thing I realized while going through code yesterday at my internship is that I run sql queries quite often. So I decided to write a function to keep all of the calls in one place and reduce the number of lines of code. It doesn't cover all possible sql calls but it does cover the basic calls I believe.</p> <p>So my question is, are there any coding practices I could improve upon or have violated while writing this?</p> <p>EDIT: I broke the function up into four separate functions. When it comes to PDO my bosses said they did that behind the scenes with each $db_function(there is a different sequence for each server they access) that is called. I'm simply preparing the string that they manipulate. Also I've always viewed associative arrays as field value pairs so I welcome any suggestions in alternative names.</p> <pre><code> &lt;? * INPUT: * (string) Db_function: Which sql function to call * (string) Table: The table to use * (string/array) Fields: The values to be manipulated along with valid sql statements/modifiers(e.g DISTINCT or aliases) , * its a string for SELECT/DELETE or an array for INSERT/UPDATE. * (string) Conditional: Statements that go at the end of the query such as WHERE, ORDER BY, JOIN etc. * * OUTPUT: * TRUE for SELECT/DELETE or the query results for INSERT/UPDATE */ function sql_Select($Db_Function,$Table, $Fields, $Conditional = NULL){ $sql = "SELECT $Fields FROM $Table"; if(!is_null($Conditional)){ $sql .= $Conditional; return $Db_Function($sql,1,1,1); } return $Db_Function($sql,1,1,1); } function sql_Update($Db_Function,$Table, $Fields, $Conditional = NULL){ $sql = "UPDATE $Table SET"; foreach($Fields as $field =&gt; $value){ $sql .= is_numeric($value) ? " $field = $value , " : " $field = '$value' , " ; } $sql = preg_replace('/,$/', '', trim($sql)); //Removes the extra ',' if(!is_null($Conditional)){ $sql .= $Conditional; return $Db_Function($sql,0,0,0); } return $Db_Function($sql,0,0,0); } function sql_Insert($Db_Function,$Table, $Fields, $Conditional = NULL){ $Field_Name = implode(',',array_keys($Fields)); $sql = "INSERT INTO $Table ($Field_Name) VALUES ( "; foreach($Fields as $field =&gt; $value){ $sql .= is_numeric($value) ? " $value, " : " '$value', " ; } $sql = preg_replace('/,$/', '', trim($sql)); //Removes the extra ',' $sql .= ')'; if(!is_null($Conditional)){ $sql .= $Conditional; return $Db_Function($sql,0,0,0); } return $Db_Function($sql,0,0,0); } function sql_delete($Db_Function,$Table, $Fields, $Conditional = NULL){ $sql = "DELETE FROM $Table"; if(!is_null($Conditional)){ $sql .= $Conditional; return $Db_Function($sql,0,0,0) } return $Db_Function($sql,0,0,0) } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T16:35:01.167", "Id": "31023", "Score": "0", "body": "So what's your question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T17:17:01.720", "Id": "31024", "Score": "0", "body": "Opps, Forget to post that heh." } ]
[ { "body": "<h1>Argggh, my eyes burn!</h1>\n\n<p><strong>SQL Injections</strong></p>\n\n<p>You should understand SQL injections. This code is likely to promote SQL injections. Read up about prepared statements. It looks like you are probably passing in a <code>mysql_*</code> function as a string. This stops you from using prepared statements.</p>\n\n<p><a href=\"http://bit.ly/phpmsql\" rel=\"nofollow\"><strong>Please, don't use <code>mysql_*</code> functions in new code</strong></a>. They are no longer maintained and the <a href=\"http://j.mp/Rj2iVR\" rel=\"nofollow\">deprecation process</a> has begun on it. See the <a href=\"http://j.mp/Te9zIL\" rel=\"nofollow\"><strong>red box</strong></a>? Learn about <a href=\"http://j.mp/T9hLWi\" rel=\"nofollow\"><em>prepared statements</em></a> instead, and use <a href=\"http://php.net/pdo\" rel=\"nofollow\">PDO</a> or <a href=\"http://php.net/mysqli\" rel=\"nofollow\">MySQLi</a> - <a href=\"http://j.mp/QEx8IB\" rel=\"nofollow\">this article</a> will help you decide which. If you choose PDO, <a href=\"http://j.mp/PoWehJ\" rel=\"nofollow\">here is a good tutorial</a>.</p>\n\n<p><strong>One Size Fits None</strong></p>\n\n<p><strike>\nYour function is overly complex. It should be broken into methods for each action. This will remove the need for the big switch and if statements and make it more readable. Your code will be easier to test.\n</strike>\nThis also causes you to have a variable function call <code>$Db_Function($sql, 0, 0, 0);</code>. It is easy to have errors by calling non-existent functions with this.</p>\n\n<p><sub><strong>Response To Edit:</strong> It looks better with separate functions now. </sub></p>\n\n<p><strong>Method Naming</strong></p>\n\n<p>You really have an awful naming scheme. Is this dictated to you by your bosses? Personally I already think they are silly for wanting a class like this that would promote SQL Injections. You have a mixed pascal case name <code>aaaa_Bbbb_Cccc</code>? Sane choices are <code>camelCase</code>, <code>UpperCamelCase</code>, <code>Pascal_Case</code>, <code>lower_pascal_case</code>.</p>\n\n<p>The methods should not have <code>sql_</code> preceding them. Their usage should be like this:</p>\n\n<pre><code>$sql = new sql; // Or whatever your class is called.\n$sql-&gt;insert(/* params go here */);\n</code></pre>\n\n<p>It should be obvious from the object that you create that you have an sql type object. The <code>sql_</code> in front of the method names then just gets in the way.</p>\n\n<p><strong>Unused Parameter</strong></p>\n\n<p>The <code>sql_delete</code> method does not use the <code>$Fields</code> parameter and it should therefore be removed.</p>\n\n<p><strong>Magic Numbers</strong></p>\n\n<p>Magic <code>0</code>'s and <code>1</code>'s are a sign of poor design. </p>\n\n<p><strong>Consistency</strong></p>\n\n<p>Please find a consistent way to name variables. <code>$sql</code>, <code>$fields</code>, <code>$value</code> are in the minority. I dislike Pascal_Case for variables in PHP, but inconsistency is even worse.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T13:29:46.947", "Id": "31055", "Score": "0", "body": "BTW, the Consistency section, although it is at the end of my answer was what made my eyes burn." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T20:05:09.933", "Id": "31077", "Score": "0", "body": "Made some changes." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T13:23:14.430", "Id": "19384", "ParentId": "19355", "Score": "3" } }, { "body": "<p>Even with the changes, this new code still falls underneath all of the categories that Paul posted earlier. On top of this, I would add the extra following problems:</p>\n\n<ul>\n<li><p>How is this code testable?</p></li>\n<li><p>If a new person comes along, how is this easy to understand? TRUE for SELECT/DELETE or the query results for INSERT/UPDATE? Logic like this would confuse me immensely.</p></li>\n<li><p>This is a very PHP 4ish way of going about solving a problem. Have you considered moving towards an OOP approach?</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T15:31:54.053", "Id": "19429", "ParentId": "19355", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T13:22:13.197", "Id": "19355", "Score": "0", "Tags": [ "php" ], "Title": "Generalized Sql Query Function" }
19355
<p>This code basically changes the color of the lines and move text for menu navigation. Is there a simpler way of writing it?</p> <pre><code>$('.nav1 a').click(function () { $('.nav1').addClass("current_nav1"); $('.sf_menu li').removeClass('current_nav2 current_nav3 current_nav4 current_nav5 current_nav6'); $('#content, #home').slideDown(2000); $('#design, #seo, #galery, #about, #contact').slideUp(2000); }); $('.nav2 a').click(function () { $('.nav2').addClass("current_nav2"); $('.sf_menu li').removeClass('current_nav1 current_nav3 current_nav4 current_nav5 current_nav6 '); $('#content, #design').slideDown(2000); $('#home, #seo, #galery, #about, #contact').slideUp(2000); }); $('.nav3 a').click(function () { $('.nav3').addClass("current_nav3"); $('.sf_menu li').removeClass('current_nav1 current_nav2 current_nav4 current_nav5 current_nav6'); $('#content, #seo').slideDown(2000); $('#home, #design, #galery, #about, #contact').slideUp(2000); }); $('.nav4 a').click(function () { $('.nav4').addClass("current_nav4"); $('.sf_menu li').removeClass('current_nav1 current_nav2 current_nav3 current_nav5 current_nav6'); $('#content, #galery').slideDown(2000); $('#home, #design, #seo, #about, #contact').slideUp(2000); }); $('.nav5 a').click(function () { $('.nav5').addClass("current_nav5"); $('.sf_menu li').removeClass('current_nav1 current_nav2 current_nav3 current_nav4 current_nav6'); $('#content, #about').slideDown(2000); $('#home, #design, #seo, #galery, #contact').slideUp(2000); }); $('.nav6 a').click(function () { $('.nav6').addClass("current_nav6"); $('.sf_menu li').removeClass('current_nav1 current_nav2 current_nav3 current_nav4 current_nav5 '); $('#content, #contact').slideDown(2000); $('#home, #design, #seo, #galery, #about').slideUp(2000); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T17:36:21.370", "Id": "31027", "Score": "1", "body": "Is there anyway you can show your relevant html also? It would probably be easier for testing purposes" } ]
[ { "body": "<p>Why do you need different <code>navXXX</code> and <code>current_navXXX</code> classes? Just have a single</p>\n\n<pre><code>var menus = {//you need some kind of mapping between elements clicked and menu items\n id1: '#home',\n id2: '#design',\n id3: '#seo',\n id4: '#galery',\n id5: '#about',\n id6: '#contact'\n};\n\n$('.nav a').click(function () {\n $('.sf_menu li').removeClass('current_nav');\n $(this).addClass(\"current_nav\");\n\n var selected = menus[$(this).attr('id')];\n $('#content, ' + selected).slideDown(2000);\n\n for (var menu in menus) {\n if (menus[menu] != selected)\n $(menus[menu]).slideUp(2000);\n }\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T17:56:31.370", "Id": "31029", "Score": "0", "body": "updated answer as I misread original code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T19:14:20.053", "Id": "31033", "Score": "0", "body": "Awesome thanks. Adapted this as each nav is assigned to separate color" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T17:40:54.577", "Id": "19363", "ParentId": "19362", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T17:14:24.977", "Id": "19362", "Score": "2", "Tags": [ "javascript", "jquery", "event-handling" ], "Title": "Changing line colors and move text for menu navigation" }
19362
<p>I created a simple wordfeud solver that checks what words can be created with the supplied letters.</p> <pre><code>public void GetResults(string characters) { // place all the characters we have in a dictionary with key=letter, value=amount var charCount = SplitCharacters(characters); // get all the unique letters (the keys) char[] individualChars = charCount.Keys.ToArray(); // create a regex for these letters, because only those letters are allowed in a word string regex = @"^[" + new string(individualChars) + "]+$"; // get all the words that contain only the letters we have on our board IEnumerable&lt;string&gt; possibleWords = _words.Where(x =&gt; Regex.IsMatch(x, regex)); // walk through the words that have only the letters on our board, and check if // there are sufficient letters on our board to create that word IEnumerable&lt;string&gt; results = possibleWords .Where(x =&gt; SplitCharacters(x).All(y =&gt; charCount[y.Key] &gt;= y.Value) &amp;&amp; x.Length &gt; 1) .OrderByDescending(x =&gt; x.Length) .Take(25); // convert the words to ViewModel objects to display in the view foreach (string result in results) { Results.Add(new ResultViewModel { Word = result }); } } private Dictionary&lt;char, int&gt; SplitCharacters(string characters) { char[] chars = characters.ToLower().ToCharArray(); var charCount = new Dictionary&lt;char, int&gt;(); foreach (char c in chars) { if (!charCount.ContainsKey(c)) { charCount[c] = 1; } else { charCount[c]++; } } return charCount; } </code></pre> <p>It works, but I think this can be done more efficient. I worked this out on my own, but I feel like I'm creating too many new arrays/enumerables for all the steps in the algorithm. It runs quite fast on my PC (core i7 2600) but it's a little bit slow on my Surface tablet.</p> <p>Can this be done more efficiently?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T18:22:58.710", "Id": "31031", "Score": "0", "body": "Is your list of words (`_words`) fixed, or it changes all the time? How many words you expect to be there?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T19:13:14.170", "Id": "31032", "Score": "0", "body": "ah, _words is an IEnumerable<string> and the content of it may change when the user selects a different language. There are probably between 1 and 5 million strings in the IEnumerable each time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T19:39:42.427", "Id": "31036", "Score": "0", "body": "Yikes! Can you do any caching on that data (such as storing the alphabetized form of the word)?" } ]
[ { "body": "<p>Nice task for brains :). First of all you should prepare your available list of words for faster search: extract all letters, sort them and order by descending length (so that you don't need to sort results later. Make sure to cache it somewhere as that would be the most time-consuming operation.</p>\n\n<p>I've written almost all, leaving you the method to compare 2 sorted character arrays :). </p>\n\n<pre><code>public class Solver : Controller\n{\n //index of available words: char[] is the ordered list of letters in the word, string[] is the list of all words that consist from these letters.\n private readonly Tuple&lt;char[], string[]&gt;[] _wordIndex;\n\n public Solver(IEnumerable&lt;string&gt; words)\n {\n _wordIndex = words\n .GroupBy(GetLetters)\n .OrderByDescending(g =&gt; g.Key.Length)\n .Select(g =&gt; Tuple.Create(g.Key, g.ToArray()))\n .ToArray();\n }\n\n private static char[] GetLetters(string word)\n {\n return word.ToLowerInvariant().ToCharArray().OrderBy(c =&gt; c).ToArray();\n }\n\n /// &lt;summary&gt;Checks whether &lt;paramref name=\"availableLetters\"/&gt; is a superset of &lt;paramref name=\"toBeChecked\"/&gt;.&lt;/summary&gt;\n /// &lt;param name=\"availableLetters\"&gt;Ordered list of letters available.&lt;/param&gt;\n /// &lt;param name=\"toBeChecked\"&gt;Ordered list of letters present in a word&lt;/param&gt;\n /// &lt;returns&gt;&lt;c&gt;true&lt;/c&gt; if all letters in &lt;paramref name=\"toBeChecked\"/&gt; are present in &lt;paramref name=\"availableLetters\"/&gt;&lt;/returns&gt;\n private bool IsSuperSet(char[] availableLetters, char[] toBeChecked)\n {\n throw new NotImplementedException();\n }\n\n public void GetResults(string characters)\n {\n var letters = GetLetters(characters);\n\n var results = _wordIndex\n .Where(indexEntry =&gt; IsSuperSet(letters, indexEntry.Item1))\n .SelectMany(indexEntry =&gt; indexEntry.Item2)\n .Take(25);\n\n // convert the words to ViewModel objects to display in the view\n foreach (string result in results)\n {\n Results.Add(new ResultViewModel { Word = result });\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T19:16:18.373", "Id": "31034", "Score": "0", "body": "Most efficient `IsSuperSet` would have O(N+M) complexity where N,M - lengths of input parameters" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T11:15:09.237", "Id": "31052", "Score": "2", "body": "Out of curiosity compared original solution with Bobson's and mine (see the code [here](https://gist.github.com/ec4cf8a4d7b3387f2b3a)), using the list of words from [here](http://www.sil.org/linguistics/wordlists/english/wordlist/wordsEn.txt). On my machine results are: original solution - 9.8 seconds, Bobson's - 14.7 seconds, mine - 1.07 second" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T14:46:30.463", "Id": "31062", "Score": "0", "body": "@almaz - Can you put up your `wordsEn.txt` too?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T14:48:27.503", "Id": "31063", "Score": "0", "body": "@Bobson I've included a link to the file in previous comment. Just put this file in a root folder of the project and set \"copy if newer\" in file properties" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T14:57:13.290", "Id": "31064", "Score": "1", "body": "Thanks. Your solution has the same bug with the Alphabetize() function that mine did. `return forRegex ? String.Join(\"?\", arr) + \"?\" : new string(arr);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T15:20:53.137", "Id": "31066", "Score": "0", "body": "@almaz - Both of our algorithms return 211 total results, but the original code returns 209 results. No question that yours is a faster algorithm, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T15:33:59.620", "Id": "31067", "Score": "0", "body": "@Bobson The 2 words are empty word (slipped through from file) and \"a\" - in original solution there is filter to accept words with `length > 1`. Updated the test code with your fix" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T19:11:22.600", "Id": "31075", "Score": "0", "body": "@almaz I believe it's a valid assumption that 1-letter words aren't valid words for wordfeud/scrabble? (To be honest: I never played the game myself, but it sounds pretty logical to me)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T20:25:43.430", "Id": "31078", "Score": "0", "body": "@LeonCullens I agree, I just explained the reason for discrepancy. This case (one-letter words) should actually be excluded from dictionary" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T18:56:17.697", "Id": "19366", "ParentId": "19364", "Score": "2" } }, { "body": "<p>Here's a different approach. You'll need to test it to see if it's more efficient or not.</p>\n\n<pre><code>public static string Alphabetize(this string input, bool forRegex = false)\n{\n var arr = input.ToCharArray();\n Array.Sort(arr);\n if (forRegex) return String.Join&lt;char&gt;(\"?\",arr) + \"?\";\n else return new string(arr);\n}\n</code></pre>\n\n<p>This would produce a regex like <code>b?e?e?e?k?k?o?o?p?r?</code> for <code>bookkeeper</code>. And then in your code:</p>\n\n<pre><code>string regex = @\"^\" + characters.Alphabetize(true) + \"$\";\nIEnumerable&lt;string&gt; results = _words.Where(x =&gt; Regex.IsMatch(x.Alphabetize(), regex));\nforeach (string result in results)\n...\n</code></pre>\n\n<p>You could use <code>.OrderBy()</code> instead of the <code>.Alphabetize()</code> in the second case, but I seem to remember reading that it's faster to do as an array than with LINQ.</p>\n\n<hr>\n\n<p>As an alternative, since you already have the letters and their counts, sort the string then make the regex <code>b{0,1}e{0,3}k{0,2}o{0,2}p{0,1}r{0,1}</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T19:36:07.973", "Id": "31035", "Score": "0", "body": "I like the word \"bookkeeper\" for examples like this, for some reason." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T14:17:13.883", "Id": "31057", "Score": "1", "body": "Bug: `Alphabetize(\"bac\", true)` will return `a?b?c`, without a \"?\" in the end." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T14:31:23.150", "Id": "31060", "Score": "0", "body": "@ANeves - Good catch. Trivial fix implemented." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T19:05:07.340", "Id": "19367", "ParentId": "19364", "Score": "2" } }, { "body": "<p>This is a rather interesting problem, first let's analyze a couple of algorithms and their respective algorithmic complexities.</p>\n\n<p>We say that <code>A</code> is the set of characters given to us from the Wordfeud game: the set of characters from which we can form words. <code>B</code> is the lexigraphically sorted set of all valid words we can form, in practise, the words of a dictionary. The set of words in <code>B</code> that we can form from the characters in <code>A</code> is <code>C</code>.</p>\n\n<h2>Naive algorithms</h2>\n\n<p>The naive algorithm for this problem is to simply loop through all elements of <code>B</code> and check whether these words can be formed from the characters in <code>B</code>, with a regex like proposed here, or with a frequency map. If so, we put the word in <code>C</code>. For an average word length <code>k</code> and <code>n</code> words in <code>B</code> this runs in worst-case <code>O(n k)</code> time. </p>\n\n<p>This is the fastest we can go without doing some kind of precomputation. In my tests, this algorithm runs in about <code>2s</code> on the dictionary in <code>/usr/share/dict/words</code> in Ruby on <code>2 Ghz</code>. This is the mean running time from different sets of <code>A</code> of 25 characters of which about 15 letters are distinct.</p>\n\n<p>A simple iteration on this naive algorithm, is the observation that if a character is not in <code>A</code>, then we do not have to loop through all the words that start with this letter in <code>B</code>. E.g. if there's no letter <code>c</code> in <code>A</code>, we can skip to the words beginning with <code>d</code> when we encounter the first word which begins with <code>c</code> in <code>B</code> and so on. We can precompute a table that stores this information, i.e. the intervals at which the words start with a letter <code>k</code>. E.g. words with index 1..3482 in <code>B</code> all start with <code>a</code>. Thus if <code>A</code> does not contain <code>a</code>, we can just jump to the word with index the 3482 + 1.</p>\n\n<p>The speed of this iteration depends on how many words in <code>B</code> start with each character in <code>A</code>. Say that <code>v</code> is the highest number of words that starts with any character in <code>B</code>, and <code>i</code> is the number of distinct characters from which we can form words, then this runs in worst-case <code>O(v i)</code> time. In my tests, this was about twice as fast as the previous algorithm.</p>\n\n<p>Another iteration is threading it. For each segment we check (e.g. the words from a..b) we create a thread that checks this. With native threads, this halves the run time once again. This got me down to about <code>0.5s</code> with the above setup running on JRuby.</p>\n\n<h2>Using a Trie</h2>\n\n<p>A trie is a tree data structure to store prefixes of strings. You start with a root node, and from there you have 25 edges, one for each character in the alphabet. If you follow one of these edges, e.g. the edge for the letter 'a' there will be <code>X</code> new edges. For each of those edges the prefix a + that letter exists in <code>B</code>. For instance one of the edges in <code>X</code> could be <code>p</code> and from there we could follow another edge <code>e</code>.</p>\n\n<p>The vertex we landed at after following <code>e</code> is marked, because if we follow the edges back to the root node and save the characters on the way to the root in reverse order, we get a word in <code>B</code>: <code>ape</code>. The edge <code>p</code> existed because <code>ap</code> is a prefix of <code>ape</code>, and thus a prefix in <code>B</code>, as stated in the previous definition.</p>\n\n<p>With this data structure in mind, we can design a new algorithm. Build a freqency map with default value <code>0</code> from <code>A</code>, i.e. a map where the key is the letter in <code>A</code> and the value of that key is the amount of times this letter occurs in <code>A</code>.</p>\n\n<p>Traverse the tree with a depth-first search where you recursively traverse all options that you can do while all keys in the frequency map are <code>&gt; 0</code>. Every time you hit a vertex which is marked, you traverse up to the root node to determine the word and add this word to <code>C</code>. </p>\n\n<p>In reality you might want to pay the memory cost of storing the word at the vertex so you avoid traversing back to the root node every time you hit a marked vertex.</p>\n\n<p>I won't get into algorithmic complexity analysis of this one, since it is rather complicated to analyze. However, in my tests, creating the trie from the dictionary takes less than <code>1s</code> (e.g. for a web-service this penalty can just be paid when starting the app) and querying with a frequency table of <code>A</code> takes about <code>0.05s</code>.</p>\n\n<p>I do not know C#, however, I <a href=\"https://gist.github.com/4182223\" rel=\"nofollow\">implemented this algorithm in Ruby</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T15:09:10.953", "Id": "19390", "ParentId": "19364", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T18:12:19.607", "Id": "19364", "Score": "4", "Tags": [ "c#", "algorithm", "performance" ], "Title": "How to improve wordfeud solver algorithm?" }
19364
<p>Is the following PHP laid out fine to go inside the mail function? </p> <pre><code>$to = "My Name &lt;myemail@mydomain.com&gt;"; $subject = "Contact Form: $name"; $message = "Name: $name\r\nEmail: $email\r\nMessage:\r\n$message"; $headers = "From: Contact Form &lt;contactform@mydomain.com&gt;"; mail($to, $subject, $message, $headers); </code></pre> <p>Should there be any spaces around the <code>\r\n</code>? Any important headers to include?</p> <p>Any tips on how to improve it are welcome. </p> <p>If you're interested, please the full script below. It is <a href="http://www.tutwow.com/htmlcss/create-a-simple-and-secure-contact-form-with-jquery-and-php/" rel="nofollow">adapted from here</a> — it's allegedly secure... is it?</p> <pre><code>&lt;?php // Clean up the input values foreach($_POST as $key =&gt; $value) { if(ini_get('magic_quotes_gpc')) $_POST[$key] = stripslashes($_POST[$key]); $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key])); } // Assign the input values to variables for easy reference $name = $_POST["name"]; $email = $_POST["email"]; $message = $_POST["message"]; // Test input values for errors $errors = array(); if(strlen($name) &lt; 2) { if(!$name) { $errors[] = "You must enter a name."; } else { $errors[] = "Name must be at least 2 characters."; } } if(!$email) { $errors[] = "You must enter an email."; } else if(!validEmail($email)) { $errors[] = "You must enter a valid email."; } if(strlen($message) &lt; 10) { if(!$message) { $errors[] = "You must enter a message."; } else { $errors[] = "Message must be at least 10 characters."; } } if($errors) { // Output errors and die with a failure message $errortext = ""; foreach($errors as $error) { $errortext .= "&lt;li&gt;".$error."&lt;/li&gt;"; } die("&lt;span class='failure'&gt;The following errors occured:&lt;ul&gt;". $errortext ."&lt;/ul&gt;&lt;/span&gt;"); } // Send the email $to = "YOUR_EMAIL"; $subject = "Contact Form: $name"; $message = "$message"; $headers = "From: $email"; mail($to, $subject, $message, $headers); // Die with a success message die("&lt;span class='success'&gt;Success! Your message has been sent.&lt;/span&gt;"); // A function that checks to see if // an email is valid function validEmail($email) { $isValid = true; $atIndex = strrpos($email, "@"); if (is_bool($atIndex) &amp;&amp; !$atIndex) { $isValid = false; } else { $domain = substr($email, $atIndex+1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); if ($localLen &lt; 1 || $localLen &gt; 64) { // local part length exceeded $isValid = false; } else if ($domainLen &lt; 1 || $domainLen &gt; 255) { // domain part length exceeded $isValid = false; } else if ($local[0] == '.' || $local[$localLen-1] == '.') { // local part starts or ends with '.' $isValid = false; } else if (preg_match('/\\.\\./', $local)) { // local part has two consecutive dots $isValid = false; } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { // character not valid in domain part $isValid = false; } else if (preg_match('/\\.\\./', $domain)) { // domain part has two consecutive dots $isValid = false; } else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&amp;`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) { // character not valid in local part unless // local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; } } if ($isValid &amp;&amp; !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) { // domain not found in DNS $isValid = false; } } return $isValid; } ?&gt; </code></pre> <p>I ended up using the <a href="http://www.validformbuilder.org" rel="nofollow">ValidForm Builder</a> because it has better security, great customizability, and an easy implementation — quoting from their site:</p> <blockquote> <ul> <li>The API generates XHTML Strict 1.0 compliant code.</li> <li>Field validation on the client side to minimize traffic overhead.</li> <li>Field validation on the server side to enforce validation rules and prevent tempering with the form through SQL injection.</li> <li>Client side validation displays inline to improve user satisfaction. No more annoying popups that don't really tell you anything.</li> <li>Easy creation of complex form structures.</li> <li>Uses the popular jQuery Javascript library for DOM manipulation.</li> <li>Completely customizable using CSS.</li> <li>Automatic creation of field summaries for form mailers in both HTML and plain text.</li> </ul> </blockquote> <p>Quoting other benefits: </p> <blockquote> <ul> <li>First of all, it's open source and therefore completely free!</li> <li>Super fast web form creation.</li> <li>Get rid of SQL injection problems.</li> <li>Create standards based CSS forms. No tables inside.</li> <li>Make form entry fun for the user. More feedback from your website.</li> </ul> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T01:09:19.650", "Id": "31046", "Score": "0", "body": "What do you mean by secure? The link you posted also does not define secure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T12:11:34.770", "Id": "31053", "Score": "0", "body": "Well, for PHP: http://php.net/manual/en/security.php" } ]
[ { "body": "<p>As far as I think, your script is good and will achieve the required task. But before finalising on this script, you should read about PHPMAILER. It is easy to implement and will provide you many features like to add CC, BCC, and attachments. The <code>mail()</code> function is the easiest way, but as far as I think, it is a bit limited. Also, PHPMailer is easily available on the Internet.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T04:54:12.227", "Id": "19376", "ParentId": "19365", "Score": "4" } }, { "body": "<p>Before writing your own mailing class, please please please try to not reinvent the wheel and save yourself some time. There are a lot of fundamental problems with this mailing script, and could be resolved by using something premade from one of the major PHP frameworks;</p>\n\n<ul>\n<li><a href=\"http://symfony.com/doc/2.0/cookbook/email/email.html\" rel=\"nofollow\">Symfony 2's mailer</a></li>\n<li><a href=\"http://framework.zend.com/manual/2.0/en/modules/zend.mail.message.html\" rel=\"nofollow\">Zend 2 Mail</a></li>\n</ul>\n\n<p>Either one of those is a testable, and extendable solution to your problem and will be much easier to implement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T23:22:04.017", "Id": "31139", "Score": "0", "body": "I didn't write this mailing class — please see the link. But what problems are there with it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-28T14:02:14.753", "Id": "477023", "Score": "0", "body": "454/5000\nThis is the most depressing answer I have read here, someone should have given this answer to the mind behind Dropbox, or the creator of Zoom, don't go reinventing the wheel, there are many premade solutions out there ... \n\nMan, you are a dream killer !\n\nSince we are in it Mr _sudobangbang_, why learn CSS ?, just use pre-built templates, you don't want to invent your own CMS, use WordPress, you don't want to do programming, just sell tacos." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T15:23:40.227", "Id": "19428", "ParentId": "19365", "Score": "2" } } ]
{ "AcceptedAnswerId": "19376", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T18:14:05.837", "Id": "19365", "Score": "3", "Tags": [ "php", "security", "email" ], "Title": "Is this a secure and best-practice PHP mail() function?" }
19365
<p>The <a href="http://www.zlib.net" rel="nofollow">zlib library</a> is a venerable piece of C software. The copyright for the decompression routine goes back to 1995, with the last rewrite in 2002. It is used daily by millions.</p> <p>To be perfect, the decompression routine should not invoke undefined behavior, even if passed a maliciously crafted buffer. I have the opportunity to detect a number of places where it is not obvious that the library does not invoke undefined behavior on some input. Would users of this site help me in confirming these issues? We would improve an already great piece of Open Source software, and there is always something to learn in reading code that has passed the test of time.</p> <p>Assuming this is okay, for my first post, I would like to suggest looking at function <code>inflate()</code> in version 1.2.7 of the library.</p> <pre><code>int ZEXPORT inflate(strm, flush) z_streamp strm; int flush; { struct inflate_state FAR *state; state = (struct inflate_state FAR *)strm-&gt;state; /*** strm-&gt;state was previously allocated with malloc(), apparently. Function malloc(), when it succeeds, returns an uninitialized block of memory. */ ... for (;;) switch (state-&gt;mode) { ... case MATCH: if (left == 0) goto inf_leave; copy = out - left; if (state-&gt;offset &gt; copy) { /* copy from window */ /*** It is unclear if state-&gt;offset always contains initialized contents at this point, line 1125 in inflate.c. */ ... </code></pre> <p>So my question is, is it possible to reach line 1125 in inflate.c without having initialized <code>state-&gt;offset</code>?</p> <p>I linked the library with the following <code>main()</code> function to identify the possible issue, so I guess that an input vector, if one exists, could be based on this <code>main()</code>, simply initializing array <code>in[]</code> to values that cause the issue. This <code>main()</code> is using the library correctly, I hope, otherwise the flagged issue may be meaningless.</p> <pre><code>#include "zlib.h" #define CHUNK 100 z_stream strm; unsigned char in[CHUNK]; unsigned char out[CHUNK]; int ret; main(){ int i; /* allocate inflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit(&amp;strm); if (ret != Z_OK) return ret; for (i=0; i&lt;CHUNK; i++) in[i] = any(); strm.next_in = in; strm.avail_in = CHUNK; strm.next_out = out; strm.avail_out = CHUNK; ret = inflate(&amp;strm, Z_NO_FLUSH); } </code></pre> <p>Of course, if the apparently dangerous access at line 1125 is in fact safe, then a great answer would be an explanation why.</p>
[]
[ { "body": "<p>I am not an expert in the <code>zlib</code> source tree nor am I familiar with the coding style of its authors, but I found this to be an interesting question. I'd say <s>it looks safe and</s> my guess is the original authors are expecting <code>offset</code> to be initialized to zero. <b>Update:</b> OK, I misread an <code>if</code> statement; looking at it again it looks like it might be unsafe without a custom allocator, so we'd have to look at <code>inflateInit</code> et al. and the actual inflate logic to know for sure.</p>\n\n<p>Explanation follows:</p>\n\n<p>It looks like <code>inflate_state</code> is allocated with the <code>ZALLOC</code> macro.</p>\n\n<p>That macro resolves to:</p>\n\n<pre><code>#define ZALLOC(strm, items, size) \\\n (*((strm)-&gt;zalloc))((strm)-&gt;opaque, (items), (size))\n</code></pre>\n\n<p>According to comments in <code>zlib.h</code>, correct use of the library requires the caller to initialize the <code>zalloc</code> member being called:</p>\n\n<blockquote>The application must initialize zalloc, zfree and opaque before\n calling the init function.</blockquote>\n\n<p>If <code>strm-&gt;zalloc</code> is <code>NULL</code>, which I'd expect most callers to do, the library uses its own default implementation, <code>zcalloc</code>.</p>\n\n<p><s><code>zcalloc</code>, with some exceptions for ancient MS-DOS compilers and so long as <code>sizeof(unsigned int)</code> is greater than 1, ends up calling <code>calloc</code>.</p>\n\n<p><code>calloc</code> by definition zeroes out its data.</s></p>\n\n<p>So, I'd say it's safe under the following conditions:</p>\n\n<ol>\n<li>If you use a custom allocator, make sure it zeroes out the data.</li>\n</ol>\n\n<p><s>2. <code>sizeof(unsigned int)</code> must be > 1. (I'm guessing the standard guarantees that but I'm not certain.)</s></p>\n\n<p><b>After the update:</b> Now realizing that the allocations are not necessarily zeroed, I'd say it all depends on whether or not the local variable <code>here</code> can be used uninitialized, as the only assignment I see is based on that value.</p>\n\n<p>Note that <code>inflateInit</code>, which calls <code>inflateReset</code>, which calls <code>inflateResetKeep</code>, seems to initialize the members that the assignments to <code>here</code> depends on, notably <code>lenbits</code>. It looks like there are lots of size checks for overflow as well, eg: <code>if ((unsigned)(here.bits) &lt;= bits) break;</code>. I haven't given it a thorough audit but I'd say everything I've seen so far looks safe.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T22:18:37.017", "Id": "31039", "Score": "0", "body": "When I analyzed it, I got this call stack: malloc <- zcalloc <- inflateInit2_ <- inflateInit_ <- main. I had to provide `malloc()`, and I provided an allocation function that does not initialize (since `malloc()` doesn't. Let me investigate and come back to you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T22:21:27.987", "Id": "31040", "Score": "0", "body": "@PascalCuoq Set it to `NULL` and you should be fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T22:23:50.233", "Id": "31041", "Score": "0", "body": "I set `strm.zalloc` to `NULL` (see the `main()`) in my question). You must be referring to `sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : (voidpf)calloc(items, size)` in zutil.c:310. This resolves to a call to `malloc()` on many architectures, including the one my analysis is tuned for (`sizeof(uInt)==4`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T22:26:41.857", "Id": "31042", "Score": "0", "body": "@PascalCuoq - Yeah I looked back and it and it was backwards from how I read it the first time. Whoops." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T22:41:08.240", "Id": "31043", "Score": "0", "body": "Yes, the only assignment to `state->offset` is from `here` at line inflate.c:1103. The way I see the question is, if it possible to craft an input where `case MATCH:` is taken before `case DIST:`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T22:46:24.017", "Id": "31044", "Score": "0", "body": "@PascalCuoq - Doesn't look like it. The only `state->mode = MATCH;` line comes from the `DISTEXT` state which can only come from `DIST`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T22:49:23.130", "Id": "31045", "Score": "0", "body": "Well solved. Meanwhile, I have confirmed that the analyzer's worry is not that `state->offset` might be assigned the contents of an uninitialized `here`, but that the sequence might be wrong (the thing you just pointed out cannot happen). I will have to force it to track `state->mode` more carefully to avoid more false positives of the same vein." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T22:10:56.293", "Id": "19370", "ParentId": "19368", "Score": "3" } } ]
{ "AcceptedAnswerId": "19370", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-06T21:38:23.270", "Id": "19368", "Score": "3", "Tags": [ "c" ], "Title": "Potential uninitialized access in zlib" }
19368
<p>I have two different ideas on how to handle this Update method in my MVC Model class "DataAccess" And I'm wondering if in the first, I'm handling my class incorrectly or ambiguously, because I'm using members from the same object for two different purposes.</p> <p>The man Class has 2 relevant members. ID, which is the primary key of the entity, and Name, which is the description</p> <pre><code> public DbResult Update(Man man) { DbResult dbResult; var query = from person in _MyDBEntities.Men where person.ManID == man.ManID // Man with ManID is what we're looking for. select person; try { foreach (Man m in myQuery) { m.Name = man.Name; // man.Name is the new name } dbResult = DbResult.Success("Record updated"); } catch (Exception e) { dbResult = DbResult.Failed(e.ToString()); } return dbResult; } </code></pre> <p>And this version of the method, which uses the variables passed in differently.</p> <pre><code> public DbResult Update(int idToLookFor, string newName) { DbResult myResult; var query = from person in _MyDBEntities.Men where person.ManID == idToLookFor select person; try { foreach (Man m in myQuery) { m.Name = newName; } dbResult = DbResult.Success("Record updated"); } catch (Exception e) { dbResult = DbResult.Failed(e.ToString()); } return dbResult; } </code></pre> <p>is my first method a better or ok approach to the problem? Because what if I have an update method later on that uses 8 members, and need to create more versions of this function for updating other entities?</p> <p>## UPDATED ##</p> <p>Including a new class here: </p> <pre><code>public class InputValidation//&lt;T&gt; where T: class { /// &lt;summary&gt; /// Delegate that matches the signature of TryParse, method defined for all primitives. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Output type of This Delegate&lt;/typeparam&gt; /// &lt;param name="input"&gt;input for this Delegate to translate to type T&lt;/param&gt; /// &lt;param name="output"&gt;The translated variable to return via out parameter&lt;/param&gt; /// &lt;returns&gt;Whether the Parse was successful or not, and output as output&lt;/returns&gt; public delegate bool TryParse&lt;T&gt;(string input, out T output); public bool ValidateInputType&lt;T&gt;(string input, TryParse&lt;T&gt; TypeValidator, out T result) { return TypeValidator(input, out result); } public bool ValidateInputRange&lt;T&gt;(ref T result, int lower, int upper) { // How can I use relational operators like &gt; &lt; = on T? without forcing T result to an int? return isValidRange(int.Parse(result.ToString()), lower, upper); } public bool isValidRange(int item, int lower, int upper) { return (lower &lt;= item &amp;&amp; item &lt;= upper); } } </code></pre>
[]
[ { "body": "<p>The second one seams to me a better approach but you say that the ManID is a primary key, so why are you handling it as a non primary key and using the query result as a sequance?</p>\n\n<pre><code>public DbResult Update(int idToLookFor, string newName)\n{\n return Update(_MyDBEntities.Men.Single(p =&gt; p.ManID == idToLookFor), newName);\n}\n\npublic DbResult Update(Man person, string newName)\n{\n try\n {\n person.Name = newName;\n //saving missing?\n return DbResult.Success(\"Record updated\");\n }\n catch (Exception e)\n {\n return DbResult.Failed(e.ToString());\n }\n}\n</code></pre>\n\n<p>And the real saving missing or it's placed to elsewhere so why are you setting here the DbResult?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T22:00:29.103", "Id": "31080", "Score": "0", "body": "I have my own DataAccess.SaveChanges() method that's called by the controller after program flow returns to the controller. However, now you have me thinking it would be just better to put the standard savechanges method in the update method instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T22:05:22.957", "Id": "31081", "Score": "0", "body": "No-no-no, it is a good think that you saving changes somewhere outside this update method becouse this way you can handle transaction-s (even nested transactions) correctly. The bad smell is the usage of the DbResult." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T22:32:00.330", "Id": "31082", "Score": "0", "body": "DbResult is a wrapper class that I use to encapsulate a bool and string, the bool tells if the database operation was successful and the string holds the message (which either is a \"success! you did it\" or \"exception goes here\" everyone tells me it's a bad idea to return an exception so i'm returning a string that has the exception in it. But now i'm starting to understand why that may be bad to do. The user doesn't care what went wrong, he wants it to go right." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T22:40:47.270", "Id": "31083", "Score": "0", "body": "Actually, How else can I return the information without using the wrapper class DbResult? I have been told about the bad smell of DbResult, and I'm trying to figure out a way around it, but you see, the controller calls this method, and expects to know what went wrong, if anything. so that the controller can pass the error message to the UI class for printing to console." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T22:42:29.267", "Id": "31084", "Score": "0", "body": "You are missing one point in the saving process: validation. Validation is that step which can provide useful messages to the user anything beyound that is exception, general error, nothing to the end user." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T23:26:39.493", "Id": "31089", "Score": "0", "body": "hm.. are you referring to the class that I just added above called `InputValidaton`? I use it in my interface class. or do you mean another validation class, something that validates data that gets put into the database?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T07:29:42.547", "Id": "31090", "Score": "0", "body": "I mean to decorate your model classes with DataAnnotations (RangeAttribute for example) and create the validation logic (\"if something has this value than it should not have the other property with X value\") in your business logic with the option to send back messages to the presentation layer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T18:13:28.160", "Id": "31094", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/6661/discussion-between-matt-rohde-and-peter-kiss)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T07:04:48.480", "Id": "19380", "ParentId": "19371", "Score": "1" } } ]
{ "AcceptedAnswerId": "19380", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T00:13:08.360", "Id": "19371", "Score": "1", "Tags": [ "c#", "entity-framework" ], "Title": "Passing an entity to use it's fields to update method is ok to do?" }
19371
<p>I load in static setting via an ini file. Ini file have the benefits</p> <ul> <li>of NOT being server by most web servers by default. </li> <li>easier to edit than XML</li> <li>even simplier than JSON</li> </ul> <p>Setting get loaded in Application.cfc</p> <pre><code>void function setupApplication() output="false" { ... application.stAdminSetting = application.loadini("admin\standard.ini"); ... } </code></pre> <p>Application.cfc has this as a function...</p> <pre><code>&lt;cffunction name="loadini" output="false" returnType="struct"&gt; &lt;cfargument name="configfile" required="true" type="string" hint="reads from currentTemplate"&gt; &lt;cfscript&gt; var stResult = {}; var iniFilePath = "#GetDirectoryFromPath(GetBaseTemplatePath())##arguments.configfile#"; var stSection = getProfileSections(iniFilePath); for(var section in stSection) { var CurrentSection = evaluate("stSection.#section#"); var stData = {}; for(var i = 1; i &lt;= ListLen(CurrentSection); i++) { var key = ListGetAt(CurrentSection, i); stData[key] = getProfileString(iniFilePath, section, key); } setvariable("stResult.#section#", stData); } return stResult; &lt;/cfscript&gt; &lt;/cffunction&gt; </code></pre> <p>The ini file can have any number of setting. In particular my ini file has:</p> <pre><code>[ws] comment=http://xxxxx.com/resource/comment.cfc?wsdl ior=http://xxxxx.com/resource/ior.cfc?wsdl node=http://xxxxx.com/resource/node.cfc?wsdl pref=http://xxxxx.com/resource/pref.cfc?wsdl traffic=http://xxxxx.com/resource/traffic.cfc?wsdl </code></pre> <p>What kinds of things can I do to improve this?</p>
[]
[ { "body": "<p>What kind of things are you looking to improve? Your solution looks pretty straightforward. The only problem with an ini file is that ColdFusion can't instantly/natively parse it. Whereas XML/JSON can be parsed directly into a Coldfusion Struct.</p>\n\n<pre><code>&lt;cfscript&gt;\npublic struct function loadini( required string configFile) {\n var stResult = {};\n var iniFilePath = \"#GetDirectoryFromPath(GetBaseTemplatePath())##arguments.configfile#\";\n var stSection = getProfileSections(iniFilePath);\n\n // loop over the sections\n for (section in stSection) {\n // loop over the list of variables in the ini file\n for (var i=0;i&lt;=listLen(stSection[section]);i++) {\n // result.section.variable = value \n stResult[section][listGetAt(stSection[section],i)] = GetProfileString(iniFilePath, section, listGetAt(stSection[section],i) ) ;\n }\n }\n return stResult; \n}\n&lt;/cfscript&gt;\n\n&lt;cfdump var=\"#loadini('test.ini')#\"&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-18T11:14:37.290", "Id": "20672", "ParentId": "19375", "Score": "4" } }, { "body": "<p>You don't need <code>evaluate()</code> here:</p>\n\n<pre><code>var CurrentSection = evaluate(\"stSection.#section#\"); \n</code></pre>\n\n<p>Simply do this:</p>\n\n<pre><code>var CurrentSection = stSection[section]); \n</code></pre>\n\n<p>Similarly you don't need to use <code>setVariable()</code>:</p>\n\n<pre><code>setvariable(\"stResult.#section#\", stData);\n</code></pre>\n\n<p>Simply:</p>\n\n<pre><code>stResult[section] = stData;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-04T07:20:23.240", "Id": "25802", "ParentId": "19375", "Score": "3" } } ]
{ "AcceptedAnswerId": "25802", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T04:36:18.127", "Id": "19375", "Score": "2", "Tags": [ "coldfusion", "configuration", "cfml" ], "Title": "Loading site configuration from ini file" }
19375
<p>I am a new developer therefore I have many questions:</p> <p>In this class I get file path on the disk (wireshark file that needs to be converted to pcap format extension) and convert it with the method <code>convertFileToPcap()</code>, in the constructor I am calling <code>convertFileToPcap()</code> and from the main after create the Editcap object I am receiving the new file path (pcap format) with the property <code>getNewFileName()</code> who return <code>_newFileName</code> (class member) and I want to know if there is a better way or appropriate way to do it.</p> <pre><code>public class Editcap { #region members private string _editpcap; private ProcessStartInfo _editpcapProcess; private FileInfo _fileInfo; private string _newFileName; #endregion #region c'tor public Editcap(FileInfo fileinfo) { _fileInfo = fileinfo; _newFileName = ""; convertFileToPcap(); } #endregion public void convertFileToPcap() { string oldFileExtension = _fileInfo.Extension; _newFileName = _fileInfo.FullName.Replace(oldFileExtension, "_new") + ".pcap"; _editpcapProcess = new ProcessStartInfo(string.Format("\"{0}\"", _editpcap)); _editpcapProcess.Arguments = (string.Format("{2}{0}{2} -F libpcap {2}{1}{2}", _fileInfo.FullName, _newFileName, "\"")); _editpcapProcess.WindowStyle = ProcessWindowStyle.Hidden; _editpcapProcess.RedirectStandardOutput = true; _editpcapProcess.RedirectStandardError = true; _editpcapProcess.CreateNoWindow = true; _editpcapProcess.UseShellExecute = false; _editpcapProcess.ErrorDialog = false; Process capinfosProcess = Process.Start(_editpcapProcess); capinfosProcess.WaitForExit(); } public string getNewFileName() { return _newFileName; } } </code></pre>
[]
[ { "body": "<p>Hello and welcome to Code Review!</p>\n\n<ul>\n<li>I'd like to first direct you to Microsoft's official <a href=\"http://msdn.microsoft.com/en-us/library/xzf533w0.aspx\">naming\nguidelines</a> for C# development. Your code goes against a few of\nthose, and if that's your company's or team's guidelines, than great!\nIf you don't have an official style, start with the ones I linked to.</li>\n<li>I'd definitely <strong>not</strong> call the convert method from the constructor.\nThis could throw exceptions that would prevent the object from being\ncreated. Keep your processing methods separate and let the caller\ncall it. It IS <code>public</code>, after all!</li>\n<li>your member variables seem a little too, well, global, in some cases.\nOnly <code>_fileInfo</code> and <code>_newFileName</code> are used in more than one method.\nKeep the others local to their methods.\n<ul>\n<li>As part of this, note that <code>_editpcap</code> never gets assigned and is\nalways <code>null</code>. I don't think that's what you're intending.</li>\n</ul></li>\n<li>the <code>getNewFileName</code> method looks very Java-like as Java didn't have\nthe concept of properties. This is a prime candidate for being made a\nproperty.</li>\n<li>the <code>Process</code> class is <code>IDisposable</code>, so wrapping it in a <code>using</code>\nblock is idiomatic.</li>\n<li>now I'm just getting into minor nitpicking, the fields set in the\nconstructor are invariant after construction, so make the intent\nknown by using the <code>readonly</code> keyword. Also, you can employ modern C#\namenities as object initializers and the <code>var</code> keyword.</li>\n</ul>\n\n<p>All this being said, here is my proposed refactor of the code:</p>\n\n<pre><code>public class Editcap\n{\n #region members\n private readonly FileInfo fileInfo;\n private string newFileName = string.Empty;\n #endregion\n\n #region c'tor\n public Editcap(FileInfo fileinfo)\n {\n if (fileinfo == null)\n {\n throw new ArgumentNullException(\"fileInfo\");\n }\n\n this.fileInfo = fileinfo;\n }\n #endregion\n\n public void ConvertFileToPcap()\n {\n this.newFileName = this.fileInfo.FullName.Replace(this.fileInfo.Extension, \"_new\") + \".pcap\";\n\n string editpcap = null; // still not set, need to fix!\n var editpcapProcess = new ProcessStartInfo(string.Format(\"\\\"{0}\\\"\", editpcap))\n {\n Arguments = string.Format(\"{2}{0}{2} -F libpcap {2}{1}{2}\", this.fileInfo.FullName, this.newFileName, \"\\\"\"),\n WindowStyle = ProcessWindowStyle.Hidden,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n CreateNoWindow = true,\n UseShellExecute = false,\n ErrorDialog = false\n };\n\n using (var capinfosProcess = Process.Start(editpcapProcess))\n {\n capinfosProcess.WaitForExit();\n }\n }\n\n public string NewFileName\n {\n get\n {\n return this.newFileName;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T15:47:01.493", "Id": "31068", "Score": "1", "body": "Definitely cleaner, but regions are considered ugly by some plus I do not see any need for saving the state, so a class is only useful as a namespace (and C# does not allow having functions outside of a class). So, I would have no constructor but a single public static method that takes `FileInfo` and returns a string. That way you get a nice black box. The implementation can be split up amongst several `private static` methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T15:56:27.647", "Id": "31069", "Score": "0", "body": "Yeah, I didn't address the `region` thing as I have experience inheriting a large codebase from 2003 following the recommended usage then. One hell of a cleanup effort." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T15:07:32.580", "Id": "19389", "ParentId": "19385", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T13:29:59.627", "Id": "19385", "Score": "3", "Tags": [ "c#" ], "Title": "Is this common way to build this class and method?" }
19385
<p>I was being troubled a lot by Robocopy (or maybe anti-virus or maybe Network Hardware). I copy files from the Dynamic View of Clearcase to the local machine for a fresh build. The copy would frequently fail due to:</p> <blockquote> <p>2012/12/06 15:35:07 ERROR 64 (0x00000040)... </p> <p>The specified network name is no longer available.</p> </blockquote> <p>The server and all network hardware resides in another geographical location, so there is no way to ascertain the hardware issues. The anti-virus can never be disabled as per some policy. The Snapshot View cannot be used as per another weird policy or prejudice.</p> <p>I am left with just one option: to make Robocopy resilient. The following is what I have come up with, which is a wrapper for Robocopy. Please review this.</p> <p><strong>Summary:</strong> </p> <ol> <li>Call Robocopy with parameters</li> <li>Give it some time and certain number of tries for proper execution</li> <li>First try is allowed 10 minutes. The subsequent tries will have an increment of 5 minutes. Maximum 5 tries and 30 minutes are allowed.</li> <li>Catch all Robocopy error codes(0, 1 and 2 are success codes) and re-try.</li> </ol> <p></p> <pre><code>namespace ResilientRobocopy { class Program { static int Main(string[] args) { string commandLine = string.Empty; int count = 0; foreach (string str in args) { string temp = string.Empty; if ((count == 0) || (count == 1)) { temp = "\"" + str + "\"" + " "; } else { temp = str + " "; } commandLine = commandLine + temp; count += 1; } Console.WriteLine("--------------------------------------------------------------------"); Console.WriteLine("Robocopy Command Line: " + commandLine); int returnCode = -1; int tries = 0; while (((returnCode == -1) || (returnCode == -2)) &amp;&amp; (tries != 5)) { Console.WriteLine("Calling Robocopy"); returnCode = StartCopy(commandLine, tries); tries += 1; } Console.WriteLine("--------------------------------------------------------------------"); return returnCode; } static int StartCopy(string commandLine, int tries) { Process robocopy = new Process(); try { robocopy = Process.Start("C:\\Windows\\SysWOW64\\robocopy.exe", commandLine); int timeLimit = 120 + (60 * tries); for (int i = 0; i &lt;= timeLimit; i++) { Thread.Sleep(1000 * 5); if (!robocopy.HasExited) { continue; } else { if (robocopy.ExitCode &gt; 2) { Console.WriteLine("Robocopy exited with code: " + robocopy.ExitCode.ToString()); Console.WriteLine("Retrying..."); return -1; } else { Console.WriteLine("Robocopy exited with code: " + robocopy.ExitCode.ToString()); Console.WriteLine("Robocopy Done!"); return robocopy.ExitCode; } } } if (!robocopy.HasExited) { Console.WriteLine("Killing Robocopy. Took too much time. Try try again till you succeed..."); robocopy.Kill(); return -1; } else { if (robocopy.ExitCode &gt; 2) { Console.WriteLine("Robocopy exited with code: " + robocopy.ExitCode.ToString()); Console.WriteLine("Retrying..."); return -1; } else { Console.WriteLine("Robocopy exited with code: " + robocopy.ExitCode.ToString()); Console.WriteLine("Robocopy Done!"); return robocopy.ExitCode; } } } catch(Exception ex) { Console.WriteLine("Exception: " + ex.ToString()); return -2; } finally { robocopy.Close(); } } } } </code></pre>
[]
[ { "body": "<p><strong>Naming</strong> </p>\n\n<p>The method <code>StartCopy()</code> implies that the copy process can also be stopped. So we should better rename it to <code>CopyFiles()</code>. </p>\n\n<p><strong>Refactoring</strong> </p>\n\n<p>First step would be to refactor the composition of the commandline to a separate method which we will name <code>ComposeCommandline</code>.</p>\n\n<pre><code>private static String ComposeCommandline(string[] args)\n{\n int count = 0;\n StringBuilder sb = new StringBuilder(1024);\n\n foreach (string str in args)\n {\n if ((count == 0) || (count == 1))\n {\n sb.Append(\"\\\"\").Append(str).Append(\"\\\"\");\n }\n else\n {\n sb.Append(str);\n }\n sb.Append(\" \");\n count += 1;\n } \n return sb.ToString();\n}\n</code></pre>\n\n<p>The next what sprung in our eyes is the multiple calling to <code>Console.WriteLine</code>, so we create a method <code>Print(String,params Object[])</code> so this can be called with additional parameters also. </p>\n\n<pre><code>private static void Print(String message, params Object[] args)\n{\n String content = String.Empty;\n if (args.Length != 0)\n {\n content = String.Format(message, args);\n }\n else\n {\n content = message;\n }\n Console.WriteLine(content);\n} \n</code></pre>\n\n<p>Now we should put some of the text which has been used to call <code>Console.WriteLine</code> and also the magic numbers <code>1000 * 5</code>, <code>120</code> and <code>60</code> to constants. </p>\n\n<pre><code>private static const String Separator = \"--------------------------------------------------------------------\";\nprivate static const String RobocopyExitMessage = \"Robocopy exited with code: {0}\";\nprivate static const String RobocopyDone = \"Robocopy Done!\";\nprivate static const String RobocopyRetry = \"Retrying...\";\nprivate static const String RobocopyCommandline = \"Robocopy Command Line: {0}\";\nprivate static const String RobocopyCalling = \"Calling Robocopy\";\nprivate static const String RobocopyKilling = \"Killing Robocopy. Took too much time. Try try again till you succeed...\";\nprivate static const String RobocopyException = \"Exception: {0}\";\nprivate static const int MilliSecondsToSleep = 5000; \nprivate static const int Initial5SecondIterations = 120;\nprivate static const int Additional5SecondIterations = 60;\n</code></pre>\n\n<hr>\n\n<p>Now it is also easier to change the strings, as this only happen in one place.</p>\n\n<p>If we now extract the <code>while</code> loop to a overloaded method <code>CopyFiles()</code> </p>\n\n<pre><code>private int CopyFiles(String commandLine)\n{\n int returnCode = -1;\n int tries = 0;\n int maxSleepingIterations = Initial5SecondIterations + (Additional5SecondIterations * tries);\n while (((returnCode == -1) || (returnCode == -2)) &amp;&amp; (tries != 5))\n {\n Print(RobocopyCalling);\n maxSleepingIterations = Initial5SecondIterations + (Additional5SecondIterations * tries);\n returnCode = StartCopy(commandLine, maxSleepingIterations);\n tries += 1;\n }\n return returnCode;\n}\n</code></pre>\n\n<p>the <code>Main()</code> method would look like </p>\n\n<pre><code>static int Main(string[] args)\n{\n String commandLine = ComposeCommandline(args);\n\n Print(Separator);\n Print(RobocopyCommandline,commandLine);\n\n int returnCode = CopyFiles(commandLine);\n\n Print(Separator);\n\n return returnCode;\n} \n</code></pre>\n\n<p>Now we should refactor the initial <code>StartCopy()</code> method. </p>\n\n<blockquote>\n<pre><code>if (!robocopy.HasExited)\n{\n continue;\n}\n</code></pre>\n</blockquote>\n\n<p>if we invert the condition we will reduce the indentationlevel by 1 which is more readable. And if we refactor the former <code>else</code> part to just use <code>break</code> we reduce the code duplication a lot. </p>\n\n<pre><code>static int CopyFiles(string commandLine, int maxSleepingIterations)\n{\n Process robocopy = new Process();\n try\n {\n robocopy = Process.Start(\"C:\\\\Windows\\\\SysWOW64\\\\robocopy.exe\", commandLine);\n for (int i = 0; i &lt;= maxSleepingIterations; i++)\n {\n Thread.Sleep(MilliSecondsToSleep);\n if (robocopy.HasExited)\n {\n break;\n }\n }\n if (robocopy.HasExited)\n {\n Print(RobocopyExitMessage, robocopy.ExitCode);\n if (robocopy.ExitCode &gt; 2)\n {\n Print(RobocopyRetry);;\n return -1;\n }\n else\n {\n Print(RobocopyDone);\n return robocopy.ExitCode;\n }\n }\n else\n {\n Print(RobocopyKilling);\n robocopy.Kill();\n return -1;\n }\n }\n catch(Exception ex)\n {\n Print(RobocopyException, ex.ToString());\n return -2;\n }\n finally\n {\n robocopy.Close();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-22T09:37:29.763", "Id": "60786", "ParentId": "19386", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T14:05:53.203", "Id": "19386", "Score": "5", "Tags": [ "c#" ], "Title": "Resilient Wrapper for Robocopy in C#" }
19386
<pre><code>def dec_to_bin(ip): ip_array = ip.split(".") ip_array = filter(None, ip_array) if len(ip_array) != 4: return "Invalid IP Address format" else: ip_bin = [] for x in range(len(ip_array)): # Formatting example referenced from: # http://stackoverflow.com/a/10411108/1170681 ip_bin.append('{0:08b}'.format(int(ip_array[x]))) ip_bin.append(".") ip_bin.pop() return ''.join(ip_bin) </code></pre> <p>This is a simple parser that will take a IP address in decimal form and convert it into its binary representation.</p> <p>I'm looking for any tips on coding styles and improving the efficiency of the code.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T19:16:57.090", "Id": "31096", "Score": "0", "body": "Beware: This will not work for IPv6." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T11:44:23.653", "Id": "54808", "Score": "0", "body": "@luiscubal: [this solution supports both ipv4 and ipv6 addresses](http://codereview.stackexchange.com/a/34093/6143)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T14:54:26.677", "Id": "54811", "Score": "0", "body": "How does `split('.')` and `append(\".\")` for addresses that use `:` instead of `.`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T16:54:53.887", "Id": "54812", "Score": "0", "body": "@luiscubal: click the link" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T22:28:25.513", "Id": "56815", "Score": "0", "body": "@J.F.Sebastian I've read that answer and I still don't understand how. If nothing else, because your answer is very different from the code in the question. `::1`.split('.') (a valid IPv6 address) returns `['::1']`. The len is 1, not 4, so it returns \"Invalid IP Address format\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T22:33:35.973", "Id": "56816", "Score": "0", "body": "@luiscubal: there is no `.split()` in my code. \"this solution\" refers to [my answer](http://codereview.stackexchange.com/a/34093/6143)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T22:38:36.383", "Id": "56817", "Score": "0", "body": "@J.F.Sebastian Ah, sorry. I misinterpreted your comment." } ]
[ { "body": "<pre><code>def dec_to_bin(ip):\n\n ip_array = ip.split(\".\")\n ip_array = filter(None, ip_array)\n</code></pre>\n\n<p>Why do you need to filter it?</p>\n\n<pre><code> if len(ip_array) != 4:\n return \"Invalid IP Address format\"\n</code></pre>\n\n<p>Never return strings to indicate errors, raise an exception</p>\n\n<pre><code> else:\n ip_bin = []\n\n for x in range(len(ip_array)):\n</code></pre>\n\n<p>Use <code>for ip_element in ip_array:</code>, you should almost never have to iterate over <code>range(len(...))</code>.</p>\n\n<pre><code> # Formatting example referenced from: \n # http://stackoverflow.com/a/10411108/1170681\n\n ip_bin.append('{0:08b}'.format(int(ip_array[x])))\n</code></pre>\n\n<p>What happens if the user put something else besides numbers in there? I'd suggest matching the ip address against a regular expression to make it more robust.</p>\n\n<pre><code> ip_bin.append(\".\")\n\n ip_bin.pop()\n return ''.join(ip_bin)\n</code></pre>\n\n<p>Instead use <code>'.'join(ip_bin)</code> and don't try putting the '.' in the list. It'll be simpler.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T15:25:38.947", "Id": "19391", "ParentId": "19388", "Score": "3" } }, { "body": "<p><strong>Code simplification and related:</strong></p>\n\n<p>Line 4: remove line 3 and replace line 4 with</p>\n\n<pre><code>ip_array = filter(None, ip.split('.'))\n</code></pre>\n\n<p>Line 7:\nCreate an exception, to prevent that a caller gets a string of error instead of the actual result.</p>\n\n<p>Line 12: assuming this is not python3, it's better if you use xrange() instead of range(), because range would create an actual list listing all the items in specified range. xrange(), instead, returns the next item in the sequence without creating the list. This behaviour is the same as the range() function in python3.\nAnyway, for your purposes changing it with:</p>\n\n<pre><code>for el in ip_array:\n ip_bin.append('{0:08b}'.format(int(el)))\n</code></pre>\n\n<p>or, even better:</p>\n\n<pre><code>ip_bin = ['{0:08b}'.format(int(el)) for el in ip_array]\n</code></pre>\n\n<p>Last line:\ninstead of appending the \".\" after each element, join over the dot:</p>\n\n<pre><code>return '.'.join(ip_bin)\n</code></pre>\n\n<p><strong>Style:</strong>\nPursue consistency in all the code: if you use double-quotes for defining strings, use them everywhere, same thing with single-quotes (which i personally prefer for strings, reserving double ones for docstrings).</p>\n\n<p>Reassuming:</p>\n\n<pre><code>def dec_to_bin(ip):\n\n ip_array = filter(None, ip.split('.'))\n\n if len(ip_array) != 4:\n raise NotValidIPException('Invalid IP Address format.')\n else:\n ip_bin = ['{0:08b}'.format(int(el)) for el in ip_array]\n return '.'.join(ip_bin)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T15:38:38.313", "Id": "19392", "ParentId": "19388", "Score": "5" } }, { "body": "<p>In Python 3.3:</p>\n\n<pre><code>import ipaddress\n\ndec_to_bin = lambda ip: bin(int(ipaddress.ip_address(ip)))\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/4017219/4279\">It supports both ip4 and ip6</a>.</p>\n\n<p>On older Python versions, you could use <code>socket</code> and <code>struct</code> modules. <a href=\"https://stackoverflow.com/a/9539079/4279\">To convert ipv4 address</a>:</p>\n\n<pre><code>import socket\nimport struct\n\ndec_to_bin = lambda ip4: bin(struct.unpack('!I', socket.inet_pton(socket.AF_INET, ip4))[0])\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>&gt;&gt;&gt; dec_to_bin('192.168.1.1')\n'0b11000000101010000000000100000001'\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/11895244/4279\">To convert ipv6 address</a>:</p>\n\n<pre><code>import socket\nimport struct\n\ndef int_from_ipv6(addr):\n hi, lo = struct.unpack('!QQ', socket.inet_pton(socket.AF_INET6, addr))\n return (hi &lt;&lt; 64) | lo\n\ndec_to_bin = lambda ip6: bin(int_from_ipv6(ip6))\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>&gt;&gt;&gt; dec_to_bin(\"2002:c0a8:0101::\").rstrip('0')\n'0b1000000000001011000000101010000000000100000001'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T01:19:54.793", "Id": "57095", "Score": "1", "body": "Why are you defining it as a `lambda` instead of using `def`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T01:51:46.210", "Id": "57096", "Score": "0", "body": "no reason. It is slightly more convenient to work with in a plain REPL." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-09T11:43:47.620", "Id": "34093", "ParentId": "19388", "Score": "1" } } ]
{ "AcceptedAnswerId": "19392", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T14:50:41.837", "Id": "19388", "Score": "5", "Tags": [ "python", "converting", "ip-address" ], "Title": "Decimal-to-binary converter for IP addresses" }
19388
<p>This class acts like a synchronization context except the work could be done on any one of the available threads.</p> <p>I've done quite a bit testing on my own, but I'm generally concerned about potential deadlocks. (I'm also curious if there are better ways to accomplish my goal.)</p> <p>I created it because I have a 3rd party library that can only be executed on threads that have been setup to execute, this setup and teardown is expensive (and if not done, causes a resource leak). The 3rd party library accessed via a remoted object, so I cannot control the thread that requests appear on. A recent change made to the software made the resource leak apparent, and now it needs to be fixed... (previously it was leaking to slow to notice)</p> <pre><code>public delegate void WorkerThreadTask(); public sealed class MultiThreadWorker { private const int WORKER_THREAD_BUSY = 1; private const int WORKER_THREAD_FREE = 0; public const int MaxThreads = 8; private string m_Name; private int m_ThreadCount; private SemaphoreSlim m_Semaphore; private int[] m_ThreadStates; private WorkerThreadData[] m_Threads = null; private bool m_Started; private object m_StartStopSync = new object(); public MultiThreadWorker(int threadCount, string name) { if (threadCount &gt; MaxThreads) { throw new ArgumentOutOfRangeException("threadCount", threadCount, "threadCount cannot be greater than MaxThreads."); } m_ThreadCount = threadCount; m_Name = name; m_Threads = new WorkerThreadData[threadCount]; m_ThreadStates = new int[threadCount]; for (int threadIdx = 0; threadIdx &lt; threadCount; threadIdx++) { string threadName = String.Empty; if (name != String.Empty) { threadName = String.Format("{0}_{1}", name, threadIdx); } m_Threads[threadIdx] = new WorkerThreadData(threadName); m_Threads[threadIdx].InitializeThread += OnInitializeThread; m_Threads[threadIdx].ThreadTerminating += OnThreadTerminating; m_ThreadStates[threadIdx] = 0; } m_Semaphore = new SemaphoreSlim(0, threadCount); m_Started = false; } public bool Started { get { return m_Started; } } public void Start() { lock (m_StartStopSync) { if (!m_Started) { m_Started = true; for (int threadIdx = 0; threadIdx &lt; m_ThreadCount; threadIdx++) { m_Threads[threadIdx].Start(); } m_Semaphore.Release(m_ThreadCount); } } } public void Stop() { lock (m_StartStopSync) { if (m_Started) { // Wait until all pending work is complete. for (int i = 0; i &lt; m_ThreadCount; i++) { m_Semaphore.Wait(); } m_Started = false; // Stop the child threads. for (int i = 0; i &lt; m_ThreadCount; i++) { m_Threads[i].Stop(); } } } } public void Invoke(WorkerThreadTask work) { m_Semaphore.Wait(); try { if (!Started) { throw new InvalidOperationException("Cannot do work on an unstarted worker."); } // Pick a thread int threadIndex = -1; for (int tIndex = 0; tIndex &lt; m_ThreadCount; tIndex++) { // Atomicly set thread state to 1 if it is currently 0. int threadState = Interlocked.CompareExchange(ref m_ThreadStates[tIndex], WORKER_THREAD_BUSY, WORKER_THREAD_FREE); if (threadState == WORKER_THREAD_FREE) { threadIndex = tIndex; break; } } Debug.Assert(threadIndex &gt;= 0); m_Threads[threadIndex].Invoke(work); Interlocked.Exchange(ref m_ThreadStates[threadIndex], WORKER_THREAD_FREE); } finally { m_Semaphore.Release(); } } private event EventHandler&lt;EventArgs&gt; m_InitializeThread; public event EventHandler&lt;EventArgs&gt; InitializeThread { add { m_InitializeThread += value; } remove { m_InitializeThread -= value; } } private void OnInitializeThread(object sender, EventArgs e) { var handlers = m_InitializeThread; if (handlers != null) { handlers(this, e); } } private event EventHandler&lt;EventArgs&gt; m_ThreadTerminating; public event EventHandler&lt;EventArgs&gt; ThreadTerminating { add { m_ThreadTerminating += value; } remove { m_ThreadTerminating -= value; } } private void OnThreadTerminating(object sender, EventArgs e) { var handlers = m_ThreadTerminating; if (handlers != null) { handlers(this, e); } } public int[] Counts { get { return m_Threads.Select(t =&gt; t.ExecutionCount).ToArray(); } } public override string ToString() { return "MultiThreadWorker"; } } internal class WorkerThreadData { bool m_Started = false; string m_Name = String.Empty; Thread m_Thread = null; Object m_ThreadSync = new object(); int m_ExecutionCount = 0; WorkerThreadTask m_Work = null; public WorkerThreadData(string name) { m_Name = name; } public void Start() { if (!m_Started) { m_Started = true; Debug.Assert(m_Thread == null); m_Thread = new Thread(ThreadLoop); m_Thread.IsBackground = true; if (m_Name != String.Empty) { m_Thread.Name = m_Name; } m_Thread.Start(); } } public void Stop() { if (m_Started) { m_Started = false; Invoke(() =&gt; { }); m_Thread.Join(); m_Thread = null; } } public void Invoke(WorkerThreadTask work) { lock (m_ThreadSync) { Debug.Assert(m_Work == null); System.Threading.Monitor.Pulse(m_ThreadSync); m_Work = work; System.Threading.Monitor.Wait(m_ThreadSync); Debug.Assert(m_Work == null); } } private void ThreadLoop() { OnInitializeThread(); lock (m_ThreadSync) { while (m_Started) { System.Threading.Monitor.Wait(m_ThreadSync); if (m_Work != null) { m_Work(); m_Work = null; } m_ExecutionCount++; System.Threading.Monitor.Pulse(m_ThreadSync); } } OnThreadTerminating(); } private event EventHandler&lt;EventArgs&gt; m_InitializeThread; public event EventHandler&lt;EventArgs&gt; InitializeThread { add { m_InitializeThread += value; } remove { m_InitializeThread -= value; } } private void OnInitializeThread() { var handlers = m_InitializeThread; if (handlers != null) { handlers(this, e); } } private event EventHandler&lt;EventArgs&gt; m_ThreadTerminating; public event EventHandler&lt;EventArgs&gt; ThreadTerminating { add { m_ThreadTerminating += value; } remove { m_ThreadTerminating -= value; } } private void OnThreadTerminating() { var handlers = m_ThreadTerminating; if (handlers != null) { handlers(this, e); } } public int ExecutionCount { get { return m_ExecutionCount; } } } </code></pre> <p>I intend to use the class like this (the actual class has 90 methods):</p> <blockquote> <pre><code>public class RemotedWrapperObject { // Initialization not shown. private MultiThreadWorker m_Worker; private Some3rdPartyLibrary m_Instance; public void Initialize() { m_Worker = new MultiThreadWorker(4, "LibraryThread"); m_Worker.Start(); m_Worker.InitializeThread += m_Worker3_InitializeThread; m_Worker.ThreadTerminating += m_Worker3_ThreadTerminating; } void m_Worker_ThreadTerminating(object sender, EventArgs e) { m_Instance.ThreadCleanup(); } void m_Worker_InitializeThread(object sender, EventArgs e) { m_Instance.ThreadSetup(); } public bool SomeMethod(int param1, int param2) { bool retValue = false; m_Worker.Invoke(() =&gt; { retValue = m_Instance.SomeMethod(param1, param2); }); return retValue; } public void SomeResult(int param1, out int param2) { int param2Out = 0; m_Worker.Invoke(() =&gt; { m_Instance.SomeResult(param1, out param2Out); }); param2 = param2Out; } } </code></pre> </blockquote> <p>A couple of notes:</p> <ol> <li>Most of the code I am modifying is very old this <code>MultiThreadWorker</code> is new. (i.e. the remoting portions cannot be changed at this stage)</li> <li>I've removed all the xmldoc comments above the methods to save space.</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T22:48:58.130", "Id": "31085", "Score": "0", "body": "Which .NET version are you targeting?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T23:01:44.777", "Id": "31088", "Score": "0", "body": "@almaz Sorry, .NET 4.0. (w/VS2010)" } ]
[ { "body": "<p>It looks to me like you've reinvented the thread pool. What exactly is this giving you that the thread pool doesn't have? I see you've got events for termination and whatnot, but if you use TPL you can easily emulate everything you've written.</p>\n\n<p>One thing I would like to point out is that the way you fire events isn't thread-safe. Don't do this:</p>\n\n<pre><code>if(m_foo != null) m_foo(this, e);\n</code></pre>\n\n<p>You should instead do this:</p>\n\n<pre><code>var foo = m_foo;\nif(foo != null) foo(this, e);\n</code></pre>\n\n<p>Why? Because <code>m_foo</code> could potentially become <code>null</code> between your conditional and your invocation.</p>\n\n<p>Also you said you have 90 methods on a class? That's a code smell right there. It sounds like it's doing too much.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T23:00:36.477", "Id": "31087", "Score": "0", "body": "I cannot use the ThreadPool because every time the ThreadPool uses a new thread the library must initialize the thread. (this initialization is expensive.) Additionally, I didn't mention, but once I call the clean-up routine the thread can no longer be used (I don't know why). Since I cannot control the creation and termination of the ThreadPool threads they cannot be used.\n\nRegarding the events, I will fix the event issuing, thanks!\n\nAnd, finally, yes this code stinks. Refactoring it is at the end of a very long list of things that need to be fixed. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T22:41:49.440", "Id": "19398", "ParentId": "19394", "Score": "0" } }, { "body": "<p>Some initial thoughts about your code (I would recommend ReSharper to detect most of them):</p>\n\n<ul>\n<li>don't use Hungarian notation (<code>m_VariableName</code>)</li>\n<li>in most cases you don't need to define events explicitly (with add/remove)</li>\n<li>do use <code>readonly</code> where possible</li>\n<li>no need to initialise fields with their default values (<code>bool _b = false</code>, <code>string[] _arr = null</code>)</li>\n</ul>\n\n<p>But the main issue is that you're trying to do all the synchronisation yourselves instead of using support from the .NET framework. Your task is a typical producer/consumer problem where producers generate workload (request some work to be done on one of the threads), and consumers are the threads that execute that work. Producer and consumer communicate with each other via queue, and for multithreaded environment .NET offers <code>ConcurrentQueue&lt;T&gt;</code>. Since we need to wait for new items we'll use <code>BlockingCollection&lt;T&gt;</code> (with <code>ConcurrentQueue&lt;T&gt;</code> under the hood).</p>\n\n<pre><code>public sealed class MultiThreadWorker\n{\n public const int MaxThreads = 8;\n\n private readonly object _startStopSync = new object();\n private readonly int _threadCount;\n private Task[] _tasks;\n private bool _started;\n private CancellationTokenSource _cancellationTokenSource;\n\n private readonly BlockingCollection&lt;AsyncJob&gt; _queue = new BlockingCollection&lt;AsyncJob&gt;();\n\n public event EventHandler InitializeThread;\n public event EventHandler ThreadTerminating;\n\n public MultiThreadWorker(int threadCount)\n {\n if (threadCount &gt; MaxThreads)\n throw new ArgumentOutOfRangeException(\"threadCount\", threadCount, \"threadCount cannot be greater than MaxThreads.\");\n\n _threadCount = threadCount;\n }\n\n public bool Started { get { return _started; } }\n\n private static void RunAsyncJob(AsyncJob asyncJob)\n {\n try\n {\n asyncJob.Job();\n asyncJob.TaskCompletionSource.SetResult(null); //notifying that task has completed\n }\n catch (Exception ex)\n {\n asyncJob.TaskCompletionSource.SetException(ex); //notifying that task has failed with exception\n }\n }\n\n private bool TryDequeue(CancellationToken cancellationToken, out AsyncJob asyncJob)\n {\n try\n {\n asyncJob = _queue.Take(cancellationToken);\n return true;\n }\n catch (OperationCanceledException)\n {\n asyncJob = null;\n return false;\n }\n }\n\n private void MainTaskCycle(CancellationToken cancellationToken)\n {\n OnInitializeThread();\n\n AsyncJob asyncJob;\n while (!cancellationToken.IsCancellationRequested &amp;&amp; TryDequeue(cancellationToken, out asyncJob))\n {\n RunAsyncJob(asyncJob);\n }\n\n OnThreadTerminating();\n }\n\n private void OnInitializeThread()\n {\n var handlers = InitializeThread;\n if (handlers != null)\n handlers(this, null);\n }\n\n private void OnThreadTerminating()\n {\n var handlers = ThreadTerminating;\n if (handlers != null)\n handlers(this, null);\n }\n\n public void Start()\n {\n if (_started)\n return;\n\n lock (_startStopSync)\n {\n if (_started)\n return;\n\n _started = true;\n\n _cancellationTokenSource = new CancellationTokenSource();\n\n _tasks = Enumerable.Range(0, _threadCount)\n .Select(i =&gt; Task.Factory.StartNew(() =&gt; MainTaskCycle(_cancellationTokenSource.Token), _cancellationTokenSource.Token)).ToArray();\n }\n }\n\n public void Stop()\n {\n if (!_started)\n return;\n\n lock (_startStopSync)\n {\n if (!_started)\n return;\n\n _cancellationTokenSource.Cancel();\n Task.WaitAll(_tasks);\n _started = false;\n }\n }\n\n public Task InvokeAsync(Action action)\n {\n var completionSource = new TaskCompletionSource&lt;object&gt;();\n _queue.Add(new AsyncJob { Job = action, TaskCompletionSource = completionSource });\n return completionSource.Task;\n }\n\n private class AsyncJob\n {\n public TaskCompletionSource&lt;object&gt; TaskCompletionSource { get; set; }\n public Action Job { get; set; }\n }\n}\n</code></pre>\n\n<p>And the usage will look like this (note that now all exceptions from third-party library will be passed through as if the code ran on the same thread)</p>\n\n<pre><code>public class RemotedWrapperObject\n{\n // Initialization not shown.\n private MultiThreadWorker _worker;\n private Some3rdPartyLibrary _instance;\n\n public void Initialize()\n {\n _worker = new MultiThreadWorker(4);\n _worker.InitializeThread += ThreadSetup;\n _worker.ThreadTerminating += ThreadCleanup;\n _worker.Start();\n }\n\n void ThreadSetup(object sender, EventArgs e)\n {\n _instance.ThreadSetup();\n }\n\n void ThreadCleanup(object sender, EventArgs e)\n {\n _instance.ThreadCleanup();\n }\n\n public bool SomeMethod(int param1, int param2)\n {\n bool retValue = false;\n\n _worker.InvokeAsync(() =&gt;\n {\n retValue = _instance.SomeMethod(param1, param2);\n }).Wait();\n\n return retValue;\n }\n\n public void SomeResult(int param1, out int param2)\n {\n int param2Out = 0;\n\n _worker.InvokeAsync(() =&gt;\n {\n _instance.SomeResult(param1, out param2Out);\n }).Wait();\n\n param2 = param2Out;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T21:30:55.033", "Id": "31098", "Score": "0", "body": "The events I'll change, I had an incorrect belief that using add/remove protected the invocation list (not sure were I picked that up). I had looked at the BlockingCollection but didn't know about the Tasks class. I also had not considered exceptions, that would have been an unfortunate oversight. I'll give this a try, thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T19:55:17.763", "Id": "19407", "ParentId": "19394", "Score": "1" } } ]
{ "AcceptedAnswerId": "19407", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T20:12:06.337", "Id": "19394", "Score": "3", "Tags": [ "c#", "multithreading", "thread-safety" ], "Title": "Invoking a callback on a pool of threads" }
19394
<p>I have created an api in php and I was hoping some clever individuals would mind reviewing it to see what I could do better. I have commented it heavily to explain my reasoning. please feel free to pick holes wherever you can!</p> <pre><code> //On my page 'localhost/api' if (!$_POST) { die('No direct access allowed'); } include('/api/gateway.php'); //Pull in my Gateway class try { $api = new Gateway($_POST); } catch (Exception $e) { //Catch any exceptions thrown in the api and return them as a bad request echo json_encode( array( 'status'=&gt; 400, 'params'=&gt; $_POST, 'data'=&gt; array( 'message'=&gt; $e-&gt;getMessage(), 'file'=&gt; $e-&gt;getFile(), 'line'=&gt; $e-&gt;getLine() ) )); } </code></pre> <p>My Gateway class then deals with the api call.</p> <pre><code>class Gateway { function __construct($params) { $this-&gt;params = (isset($params) ? $params : array()); if ( !isset($params['method']) ) { throw new Exception('No method passed to API'); } $method = explode('.', $params['method']); if ( !class_exists($method[0]) ) { throw new Exception('No class by the name of ' . $method[0]); } if ( !method_exists($method[0], $method[1]) ) { throw new Exception('No method in ' . $method[0] . ' called ' . $method[1]); } //Call my class and method without instantiating it. $result = $method[0]::$method[1]($params); if (!$result) { //This shouldn't really fire as it should be handled in the method. $this-&gt;error(); } else { $this-&gt;send(200, $result, $params); } } public $params; //$_POST parameters stored here to return if an error is thrown public function error($code = 400, $data = array(), $params = array()) { echo json_encode( array( 'status'=&gt; 400, 'params'=&gt; $this-&gt;$params, 'data'=&gt; $data )); } public function send($code = 200, $data = array(), $params = array()) { echo json_encode( array( 'status'=&gt; 200, 'params'=&gt; $this-&gt;params, 'data'=&gt; $data )); } } </code></pre> <p>Example of my api classes. These are currently in the same file as my Gateway class. Eventually these will be moved into a separate folder and pulled in dynamically.</p> <pre><code>class Sites { public function getSites($params) { return array( 'gotyou'=&gt; 'message' ); } } </code></pre>
[]
[ { "body": "<p>What you are really trying to accomplish here is taking http requests and dispatching them to the correct class. This is much better handled by one of many mvc frameworks in existence. That said, I see several problems with what you have here.</p>\n\n<ol>\n<li>Improper check for POST requests. $_POST is always available</li>\n<li>No validation of input. Do you want to allow unrestricted access to classes and methods?</li>\n<li>Gateway class (which seems more like a dispatcher) is concerned with too much. Not only is it dispatching the request, it is also formatting responses.</li>\n<li>No use of http header to properly instruct the client. Put the status codes (200, 404, etc) in the response header, not in the payload.</li>\n<li>You are potentially exposing sensitive information by passing back the Exception object's message. When things go wrong, YOU need to know what and why, but the client does not.</li>\n</ol>\n\n<p>Here is a rough improvement:</p>\n\n<p><strong>GatewayExeption.php</strong></p>\n\n<pre><code>&lt;?php\n//Use your own exception to distinguish from others\nclass GatewayException extends Exception {}\n</code></pre>\n\n<p><strong>Gateway.php</strong></p>\n\n<pre><code>&lt;?php\nclass Gateway\n{\n /**\n * @var array\n */\n private $apis;\n\n /**\n * Pass an array of pre-configured api class and actions\n * \n * array(\n * 'Foo' =&gt; array('bar', 'baz')\n * )\n * \n * @param array $apis\n */\n public function __construct($apis)\n {\n $this-&gt;apis = $apis;\n }\n\n /**\n * Invoke a pre-configured api\n * \n * @param string $apiName\n * @param string $action\n * @param null|array $args\n * @throws GatewayException\n */\n public function invokeApi($apiName, $action, $args = array())\n {\n if (! array_key_exists($apiName, $this-&gt;apis)) {\n throw new GatewayException('Invalid api name');\n }\n\n if (! in_array($action, $this-&gt;apis[$apiName])) {\n throw new GatewayException('Invalid action');\n }\n\n try {\n $obj = new $apiName;\n $result = call_user_func(array($obj, $action), $args);\n return $result;\n } catch (Exception $e) {\n throw new GatewayException('api error', null, $e);\n }\n }\n}\n</code></pre>\n\n<p><strong>Sites.php</strong></p>\n\n<pre><code>&lt;?php\nclass Sites\n{\n public function getSites($params)\n {\n return array(\n 'gotyou' =&gt; 'message'\n );\n }\n}\n</code></pre>\n\n<p><strong>index.php</strong></p>\n\n<pre><code>&lt;?php\nrequire 'GatewayException.php'\nrequire 'Gateway.php'\n\nif ( $_SERVER['REQUEST_METHOD'] !== 'POST') {\n header('HTTP/1.0 405 Method Not Allowed');\n exit;\n}\n\n//Provide an explicit list of available apis\n$validApis = array(\n 'Sites' =&gt; array('getSites')\n);\n$gateway = new Gateway($validApis);\n\n//initialize request parameters with defaults\n$api = array_key_exists('api', $_POST) ? $_POST['api'] : '';\n$action = array_key_exists('action', $_POST) ? $_POST['action'] : '';\n$params = array_key_exists('params', $_POST) ? $_POST['params'] : null;\n\n//all responses at this point will be json\nheader('Content-Type: application/json');\n\ntry {\n $result = $gateway-&gt;invokeApi($api, $action, $params);\n echo json_encode($result);\n} catch (GatewayException $e) {\n header('HTTP/1.0 400 Bad Request');\n echo json_encode( array(\n 'status'=&gt; $e-&gt;getMessage()\n ));\n} catch (Exception $e) {\n header('HTTP/1.0 500 Internal Server Error');\n //you should log $e-&gt;getMessage()\n //you probably do not want to reveal the Exception's message\n echo json_encode( array(\n 'status'=&gt; 'A system error occurred' \n ));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T21:23:13.840", "Id": "19410", "ParentId": "19397", "Score": "3" } }, { "body": "<p>Some links to common MVC Routers that will do exactly what you are looking for with a much better implementation; like Rob was talking about above:</p>\n\n<ul>\n<li>Symfony 2 Routing Component: <a href=\"http://symfony.com/doc/2.0/components/routing/introduction.html\" rel=\"nofollow\">http://symfony.com/doc/2.0/components/routing/introduction.html</a></li>\n<li>Zend 2 Routing: <a href=\"http://framework.zend.com/manual/2.0/en/modules/zend.mvc.routing.html\" rel=\"nofollow\">http://framework.zend.com/manual/2.0/en/modules/zend.mvc.routing.html</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T15:18:37.677", "Id": "19427", "ParentId": "19397", "Score": "1" } } ]
{ "AcceptedAnswerId": "19410", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T22:27:45.267", "Id": "19397", "Score": "1", "Tags": [ "php", "api" ], "Title": "PHP api design - anything done badly?" }
19397
<p>Please help me to make more readable and simple code like this. What if I had 20 components? Is it right to organize code like this?</p> <pre><code>package newpackage.view; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JRadioButton; import javax.swing.JTextField; public class UserPanel extends JPanel{ private JLabel idLbl; private JLabel nameLbl; private JLabel passwordLbl; private JRadioButton adminRad; private JRadioButton userRad; private JTextField idFld; private JTextField nameFld; private JPasswordField passwordFld; private JButton submitBtn; public UserPanel() { setLayout(new GridLayout(4,2)); idLbl = new JLabel("ID"); nameLbl = new JLabel("Name"); passwordLbl = new JLabel("Password"); adminRad = new JRadioButton("Admin"); userRad = new JRadioButton("User"); idFld = new JTextField(); nameFld = new JTextField(); passwordFld = new JPasswordField(); submitBtn = new JButton("Submit"); add(idLbl); add(idFld); add(nameLbl); add(nameFld); add(passwordLbl); add(passwordFld); add(adminRad); add(userRad); add(submitBtn); } } </code></pre>
[]
[ { "body": "<p>Creating UIs programmatically in Swing is verbose and error prone. There are visual tools that let you create your layout in a WYSIWYG style, and autogenerate the code for you. Many years ago I used NetBeans for this, I don't know what's today's flavor, if you use Eclipse you may want to check out this set of plugins:</p>\n\n<p><a href=\"http://code.google.com/p/visualswing4eclipse/\" rel=\"nofollow noreferrer\">http://code.google.com/p/visualswing4eclipse/</a></p>\n\n<p>Also, take a look at this question.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/564156/visual-swing-in-eclipse\">https://stackoverflow.com/questions/564156/visual-swing-in-eclipse</a></p>\n\n<p>I would restrict the programmatic approach to relatively simple UIs like yours. For 20 components it would be really cumbersome without a design tool, there's no way around it. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T05:57:32.563", "Id": "31144", "Score": "0", "body": "I use it. To much programmers say the same thing about this UI designers. I see this code which it creates I don't like it" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T21:33:23.170", "Id": "19440", "ParentId": "19401", "Score": "1" } }, { "body": "<p>Try to NOT add each UI component in Class fields. Keep then local if possible, as close to usage as possible. Too much class fields does not make class easy readable - as reader think that all of them are do matter.</p>\n\n<p>JLabel and other components, content(text) of which will never be changed, are good candidates to be declared as local variable or without variable at all:\n<code>\nadd(new JLabel(\"text\"));\n</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T22:05:12.000", "Id": "19441", "ParentId": "19401", "Score": "4" } }, { "body": "<p>Depending on your application structure, there are several ways to organize this.<br>\nIf you have only this window with small number of components, just use <code>add(new Compenent(...))</code> as Roman Ivanov suggested.</p>\n\n<p>If you have to communicate a bit and have more Frames and more logic behind it, you could pick some of this bullet points:</p>\n\n<ul>\n<li>Do not extend JPanel, instead have a private JPanel attribute and deal with it (Encapsulation). There is no need to give access to all JPanel methods for code dealing with a UserPanel instance. If you extend, you are forced to stay with this forever, if you encapsulate, you can change whenever you want without taking care of something outside the class.</li>\n<li>Use a create() method to init the GUI (or createAndGet() if you need a reference). In this way you make it clear what happens there. The GUI is created. It is not obvious if this happens in the constructor.</li>\n<li>Some of your attribute names look like you want to do something with them later on. So you will probably need listeners. You can add a addListeners() method which takes care about all the listeners.</li>\n<li>If your init method still has too much work inside, you could split it up (like createFirstPanel(), createUserField(), createPlots() and so on).</li>\n<li>Think about a cleaning up method/way. Do you want to destroy the window, reuse the window, clear the window? Have a single instance, multiple instances? You can handle all the different cases inside the class if you use encapsulation (and probably inside the controller, depends on your application model).</li>\n<li>Use good names. Do not abbreviate Label with Lbl. Write Label. It is better readable and with auto completion, no more work to write. I would suggest to put the type before the name, like jLabelId, jLabelName, jTextFieldName, ... This is more consistent.</li>\n</ul>\n\n<p>Just to say it again: If it is just a small class and no one will touch it ever again, use the easiest approach possible. Do not code for a future which is not clearly visible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T14:11:18.943", "Id": "19459", "ParentId": "19401", "Score": "4" } } ]
{ "AcceptedAnswerId": "19459", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T10:21:21.923", "Id": "19401", "Score": "5", "Tags": [ "java", "swing", "gui" ], "Title": "Readable code with many components (Swing)" }
19401
<p>How would you refactor this kind of code? I've unsuccessfully tried several approaches (NSArray, NSPointerArray, plain C array), but always ran into pointer type checking error.</p> <pre><code>NSError *error1; NSError *error2; NSError *error3; //imagine MANY of them [object1 methodWithError: &amp;error1]; [object2 methodWithError: &amp;error2]; [object3 methodWithError: &amp;error3]; BOOL wasErrorOfCode1 = ([error1 code] == 1) || ([error2 code] == 1) || ([error3 code] == 1); if (wasErrorOfCode1) { //do stuff </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T14:21:01.680", "Id": "31092", "Score": "0", "body": "With only three items, I wouldn't refactor it at all. With more items, I would put my errors in an array and iterate over them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T23:11:02.853", "Id": "31100", "Score": "0", "body": "I clarified my question (there can by many errors), but as I wrote - I could not get the array thing working because compiler (w ARC) would complain when passing pointer address (&) stored in array to method. I finally got it working with __autoreleasing variable though. Could you please take a look at my suggested solution?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T11:13:47.920", "Id": "31191", "Score": "1", "body": "@IvanTrančík When you have vars named `error1`, `error2` and `error3`, using an array should always be the first step. In Obj-C, always try to use `NSArray` first before C arrays." } ]
[ { "body": "<p>I found a solution using plain C array and __autoreleasing</p>\n\n<pre><code>int number = 3;\nNSError __autoreleasing *errors[number]; //without __autoreleasing, compiler (with ARC) will complain\n//imagine MANY of them\n[object1 methodWithError: &amp;errors[0]];\n[object2 methodWithError: &amp;errors[1]];\n[object3 methodWithError: &amp;errors[2]];\nBOOL wasErrorOfCode1 = NO;\nfor (int i = 0; i &lt; number; ++i) {\n wasErrorOfCode1 &amp;= ([errors[i] code] == 1);\n}\nif (wasErrorOfCode1) {\n//do stuff\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T23:03:38.863", "Id": "19412", "ParentId": "19403", "Score": "0" } }, { "body": "<p>I want to propose a differently structured code, that especially will be easier to adapt for more objects. </p>\n\n<pre><code>NSArray *objects = @[object1, object2, object3];\nNSMutableArray *errors = [NSMutableArray array];\n\n[objects enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {\n NSError *error;\n [obj methodWithError: &amp;error];\n if(error){\n [errors addObject: @{@\"error\":error,@\"object\":obj}];\n }\n}];\n</code></pre>\n\n<p>Now you can iterate over all errors and examine them along with the object the error occurred on. </p>\n\n<pre><code>[errors enumerateObjectsUsingBlock:^(NSDictionary *errorDict, NSUInteger idx, BOOL *stop) {\n NSError *error = errorDict[@\"error\"];\n id object = errorDict[@\"object\"];\n if(…){\n //add an appropriate test\n }\n}];\n</code></pre>\n\n<hr>\n\n<p>you can't add the errors into an array upfront, as </p>\n\n<pre><code>NSError *error1;\n</code></pre>\n\n<p>will result into a nil-object for the variable <code>error1</code>. NS(Mutable)Arrays can't handle nil objects. Same for dictionaries.<br>\nOn the other hand my solution allows adding the errors, as it only add them once an existing objects is assigned to the variable <code>error</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T12:03:58.197", "Id": "31152", "Score": "1", "body": "I like this approach, because it nicely solves the problem. Of course, there is no need for upfront allocation of error pointers for every object - as you correctly stated, it suffices to store only those errors that occurred." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T06:33:38.707", "Id": "19449", "ParentId": "19403", "Score": "1" } } ]
{ "AcceptedAnswerId": "19449", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T13:40:15.030", "Id": "19403", "Score": "3", "Tags": [ "objective-c", "error-handling", "cocoa" ], "Title": "Storing and iterating over multiple NSError pointers" }
19403
<p>Here is my new STL-like implementation of an unweighted graph. Could you please tell me what member functions I should include in my library?</p> <p><strong>unweighted_graph.hpp</strong></p> <pre><code>#include &lt;algorithm&gt; #include &lt;stdexcept&gt; #include &lt;vector&gt; #include &lt;map&gt; #include &lt;set&gt; using namespace std; #ifndef __UNWEIGHTED_GRAPH_HPP #define __UNWEIGHTED_GRAPH_HPP namespace lemon { template&lt; class T, bool dir &gt; class unw_graph { private: map&lt; T, set&lt; T &gt; &gt; adj; int vcnt; int ecnt; public: typedef typename map&lt; T, set&lt; T &gt; &gt;::iterator vertex_iterator; typedef typename map&lt; T, set&lt; T &gt; &gt;::const_iterator vertex_const_iterator; typedef typename set&lt; T &gt;::iterator link_iterator; typedef typename set&lt; T &gt;::const_iterator link_const_iterator; typedef pair&lt; T, T &gt; link_type; typedef size_t size_type; vertex_iterator begin() { return adj.begin(); } vertex_const_iterator begin() const { return adj.begin(); } vertex_iterator end() { return adj.end(); } vertex_const_iterator end() const { return adj.end(); } unw_graph( ) : adj( map&lt; T, set&lt; T &gt; &gt;() ), vcnt( 0 ), ecnt( 0 ) {} void insert_vertex( const T&amp; init ) { if( adj.find( init )!=adj.end() ) return; else { adj.insert( make_pair( init, set&lt; T &gt;() ) ); vcnt++; } } void insert_link( const pair&lt; T, T &gt; &amp;e ) { insert_vertex( e.first ); insert_vertex( e.second ); if( adj[ e.first ].find( e.second ) == adj[ e.first ].end() ) { adj[ e.first ].insert( e.second ); ecnt++; } if( !dir ) { if( adj[ e.second ].find( e.first ) == adj[ e.second ].end() ) { adj[ e.second ].insert( e.first ); } } } unw_graph( const vector&lt; pair&lt; T, T &gt; &gt; &amp;edge_list ) : adj( map&lt; T, set&lt; T &gt; &gt;() ), vcnt( 0 ), ecnt( 0 ) { typename vector&lt; pair&lt; T, T &gt; &gt;::iterator it; for( it=edge_list.begin(); it!=edge_list.end(); ++it ) { insert_link( *it ); } } void erase_link( const pair&lt; T, T &gt; &amp;e ) { if( adj.find( e.first ) == adj.end() || adj.find( e.second ) == adj.end() ) return; typename set&lt; T &gt;::iterator it=adj[ e.first ].find( e.second ); if( it!=adj[ e.first ].end() ) { adj[ e.first ].erase( it ); ecnt--; } if( !dir ) { it=adj[ e.second ].find( e.first ); if( it!=adj[ e.second ].end() ) { adj[ e.second ].erase( it ); } } } typename map&lt; T, set&lt; T &gt; &gt;::iterator find_vertex( const T&amp; vr ) { return adj.find( vr ); } typename map&lt; T, set&lt; T &gt; &gt;::const_iterator find_vertex( const T&amp; vr ) const { return adj.find( vr ); } bool connection( const pair&lt; T, T &gt; &amp;e ) { if( adj.find( e.first ) == adj.end() || adj.find( e.second ) == adj.end() ) return false; else return adj[ e.first ].find( e.second ) != adj[ e.first ].end(); } set&lt; T &gt;&amp; operator[] ( T idx ) { return adj[ idx ]; } const set&lt; T &gt;&amp; operator[] ( T idx ) const { return adj[ idx ]; } size_t vertices() const { return vcnt; } size_t links() const { return ecnt; } bool directed() const { return dir; } }; } #endif </code></pre> <p><strong>test1.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;algorithm&gt; #include "unweighted_graph.hpp" using namespace std; int main() { freopen( "file.in", "r", stdin ); lemon::unw_graph&lt; string, false &gt; g; int Ec; cin &gt;&gt; Ec; while( Ec-- ) { string a,b; cin &gt;&gt; a &gt;&gt; b; g.insert_link( make_pair( a, b ) ); } cout &lt;&lt; g.vertices() &lt;&lt; " " &lt;&lt; g.links() &lt;&lt; endl; lemon::unw_graph&lt; string, false &gt;::vertex_iterator i; for( i=g.begin(); i!=g.end(); ++i ) { cout &lt;&lt; i-&gt;first &lt;&lt; ": "; lemon::unw_graph&lt; string, false &gt;::link_iterator j; for( j=i-&gt;second.begin(); j!=i-&gt;second.end(); ++j ) { cout &lt;&lt; *j &lt;&lt; " "; } cout &lt;&lt; endl; } g.erase_link( make_pair( "athens", "lamia" ) ); cout &lt;&lt; g.vertices() &lt;&lt; " " &lt;&lt; g.links() &lt;&lt; endl; for( i=g.begin(); i!=g.end(); ++i ) { cout &lt;&lt; i-&gt;first &lt;&lt; ": "; lemon::unw_graph&lt; string, false &gt;::link_iterator j; for( j=i-&gt;second.begin(); j!=i-&gt;second.end(); ++j ) { cout &lt;&lt; *j &lt;&lt; " "; } cout &lt;&lt; endl; } return 0; } </code></pre> <p><strong>test2.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;algorithm&gt; #include "unweighted_graph.hpp" using namespace std; int main() { freopen( "file2.in", "r", stdin ); lemon::unw_graph&lt; int, true &gt; g; int N,M; cin &gt;&gt; N &gt;&gt; M; for( int i=0; i&lt;N; ++i ) { g.insert_vertex( i+1 ); } while( M-- ) { int from,to; cin &gt;&gt; from &gt;&gt; to; g.insert_link( make_pair( from, to ) ); } for( int i=1; i&lt;=N; ++i ) { cout &lt;&lt; i &lt;&lt; ": "; lemon::unw_graph&lt; int, false &gt;::link_iterator j; for( j=g[ i ].begin(); j!=g[ i ].end(); ++j ) { cout &lt;&lt; *j &lt;&lt; " "; } cout &lt;&lt; endl; } return 0; } </code></pre>
[]
[ { "body": "<h3>The big pain points:</h3>\n\n<ol>\n<li>Put the include guards first.<br>\nNo point in re-including header files if you don't need to</li>\n<li>Never use <code>using namespace std;</code> in a header file.<br>\nAnybody that includes your code now has all the standard stuff pushed into global namespace where it can cause huge problems in other peoples code.<br>\nI would even say never use this in your normal source files (but others think that is a bit far (I don't)). If you must import stuff keep it as confined as possable and only import what you need <code>using std::cout;</code> etc.. (still don't do that in global scope in a header file).</li>\n<li>Double underscore in an identifier is reserved.<br>\nDON'T DO IT WILL BREAK SOMETHING WHEN YOU LEAST EXPECT.</li>\n</ol>\n\n<h3>Interface design</h3>\n\n<p>Your graph looks like it wants to be treated as a container. Thus it is probably a good idea to make its types look like a standard container. So make the types of the iterators conform. begin() and end() shoud return iterator or const_iterator</p>\n\n<pre><code>typedef typename map&lt; T, set&lt; T &gt; &gt;::iterator vertex_iterator;\ntypedef typename map&lt; T, set&lt; T &gt; &gt;::const_iterator vertex_const_iterator;\n</code></pre>\n\n<p>Change too:</p>\n\n<pre><code>typedef typename std::map&lt;T, std::set&lt;T&gt; &gt; Store;\ntypedef typename Store::iterator iterator;\ntypedef typename Store::const_iterator const_iterator;\n\n// Now if the type changes you only need to change it in one place.\n</code></pre>\n\n<h3>Misunderstanding of basic std::map/std::set</h3>\n\n<pre><code>void insert_vertex( const T&amp; init ) {\n if( adj.find( init )!=adj.end() ) return;\n else {\n adj.insert( make_pair( init, set&lt; T &gt;() ) );\n vcnt++;\n }\n}\n</code></pre>\n\n<p>This is all wasted code. If the map does not contain an element then then operator[] will auto insert a default node using the default constructor for the value type (which in this case is the empty set).</p>\n\n<pre><code>void insert_vertex( const T&amp; init )\n{\n adj[init];\n vcnt = adj.size(); // which brings us to the question of why vcnt\n // is a separate member. When it is just the size of adj?\n}\n</code></pre>\n\n<p>I would say the same here for the set.</p>\n\n<pre><code> if( adj[ e.first ].find( e.second ) == adj[ e.first ].end() ) {\n adj[ e.first ].insert( e.second );\n ecnt++;\n }\n</code></pre>\n\n<p>The only reason here you actually need the test is because you need to decide weather to increment <code>ecnt</code>. I would just always insert (sets don't have multiple values the same so an insert of a value that already exists does nothing).</p>\n\n<pre><code> if (adj[e.first].insert(e.second).second)\n { ++ecnt;\n }\n // The result of an insert is a std::pair&lt;iterator,bool&gt;\n // Where the iterator points at the value inserted\n // And the bool indicates weather the insert worked (if there already exists\n // a value then it will fail).\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T20:40:34.093", "Id": "19589", "ParentId": "19404", "Score": "3" } }, { "body": "<p>Loki Astari's review is good, but I wanted to add a point or two to some future things you might want to address. <code>std::map</code> (and <code>std::set</code>) take a few extra parameters in their template arguments:</p>\n\n<pre><code>template &lt;typename Key, typename Value, typename Compare = std::less&lt;Key&gt;, typename Allocator&gt;\nclass map\n{ \n //...\n};\n</code></pre>\n\n<p><code>Allocators</code> are a bit tricky, so we'll ignore that for now. However, you should definitely look at including a <code>Compare</code> parameter for your graph. This will allow users to utilize their own classes for your template parameter <code>T</code>. For example:</p>\n\n<pre><code>struct some_class\n{\n int i;\n}\n\nstruct sc_compare\n{\n bool operator()(const some_class&amp; s1, const some_class&amp; s2) \n { \n return s1.i &lt; s2.i; \n }\n};\n</code></pre>\n\n<p>Then users can utilize <code>some_class</code> as verticies: <code>lemon::unw_graph&lt;some_class, false, sc_compare&gt;</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T03:08:09.603", "Id": "19682", "ParentId": "19404", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T14:30:22.510", "Id": "19404", "Score": "1", "Tags": [ "c++", "template", "graph", "stl" ], "Title": "unw_graph class (unweighted graph)" }
19404
<p>I have made a student details project. The user is asked to enter the info for two students, which is then displayed on the screen.</p> <p>Questions:</p> <ol> <li>Have I used inheritance correctly?</li> <li>What would be a better way of outputting the results?</li> </ol> <p></p> <pre><code> public class Person extends Test { // Variables String name; int age; String address; // Default Constructor Person() { name = ""; age = 0; address = ""; } Person(String name, int age, String address) { this.name = name; this.age = age; this.address = address; } String getName() { return name; } public void display() { System.out.println("Name = "+ name); System.out.println("Age = "+ age); System.out.println("address = "+ address); } } public class Student extends Person { int studentNum, semester; Student(String name, int age, String address, int studentNum, int semester) { super(name, age, address); // calls parent class’s constructor this.studentNum = studentNum; this.semester = semester; //this.course = course; } public String getName() // name { return name; } public void setName(String name) { this.name = name; } public int getAge() // age { return age; } public void setAge(int age) { this.age = age; } public String getAddress() // address { return address; } public void setAddress(String address) { this.address = address; } public int getStudentNum() // studentNum { return studentNum; } public void setStudentNum(int studentNum) { this.studentNum = studentNum; } public int getSemester() // semester { return semester; } public void setSemester(int semester) { this.semester = semester; } void Display() // Method Overriding { } } public class Course extends Student { String course; Course(String name, int age, String address, int studentNum, int semester, String course) { super(name, age, address, studentNum, semester); this.course = course; } public void display() { } } import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Test implements StudentFees { public static void main(String args[ ]) throws IOException { System.out.println("============" + "================="); System.out.println("Students " + "Personal Details"); System.out.println("============" + "================="); String name, address, course; int age, studentNum, semester; List&lt;Student&gt; studentsList = new ArrayList&lt;Student&gt;(); // array list to store user input for (int i = 0; i &lt; 2; i++) { int studentNumber = (i + 1); //System.out.println(""); //System.out.println("Please enter " + "data for student " + studentNumber); InputStreamReader converter = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(converter); System.out.println("Enter Student "+ studentNumber + " Name:"); name = in.readLine(); System.out.println("Enter Student " + studentNumber + " Age (Integer):"); age = Integer.valueOf(in.readLine()); System.out.println("Enter Student " + studentNumber + " Address:"); address = in.readLine(); System.out.println("Enter Student " + studentNumber + " Number:"); studentNum = Integer.valueOf(in.readLine()); System.out.println("Enter Student " + studentNumber + " Semester:"); semester = Integer.valueOf(in.readLine()); System.out.println("Enter Student " + studentNumber + " Course:"); course = in.readLine(); Student student = new Student(name, age, address, studentNum, studentNum); studentsList.add(student); // add student } for (int j = 0; j &lt; studentsList.size(); j++) { Student st = studentsList.get(j); System.out.println("Information of Student : " + (j + 1)); System.out.println(""); System.out.println("Name: " + st.getName() + " - Age: "+st.getAge() + " - Address: " + st.getAddress() + " - Student Number: " + st.getStudentNum() + " - Semester: " + st.getSemester() + " - Course: " + st.getCourse()); // print out results entered by user System.out.println(""); } } String course; public String getCourse() { return course; } public void setCourse(String course) { this.course = course; } public void payFees(float fees) { } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T08:43:54.177", "Id": "31105", "Score": "3", "body": "`Course` definitely should not extend `Student`. Inheritance represents an is-a relationship, and a Course is not a Student." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T14:33:54.230", "Id": "31106", "Score": "0", "body": "Ok should I make any new classes like EveningCourse extends course?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T09:23:56.257", "Id": "31187", "Score": "0", "body": "If you _need_ a new class `EveningCourse`, it should extend `Course`. Don't make them until you need them." } ]
[ { "body": "<p>You must remember that inheritance is good to avoid code duplication, but also you must know that you will have messy code if you will extends for one field or method, they must be connected logically Student extends Person it's OK, Cat extends Dog isn't OK. I think you don't need make Person extends Test. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T06:35:50.860", "Id": "19420", "ParentId": "19408", "Score": "2" } }, { "body": "<p>There is an approach: prefer composition instead of inheritance.</p>\n\n<p>Inherit only and only when you need to \"avoid copy-paste\" or use the same behaviour(the same method) and extend them.</p>\n\n<p>Student is a Person - ok.\nCourse have few Students - it is a composition(Student should be a field in class Course, and will be collection of students - List), not a inheritance.</p>\n\n<p>Why you did \" public class Person extends Test\" is unclear for me, can not explain it at all.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T22:14:38.080", "Id": "19442", "ParentId": "19408", "Score": "2" } }, { "body": "<p>Already said: Course should probably not extend a student. Always ask yourself: Is <code>subclass</code> a special thing of a <code>parentclass</code>?</p>\n\n<p>You could add a <code>List&lt;Course&gt; courses</code> attribute to <code>Student</code> and a <code>List&lt;Student&gt; students</code> attribute to <code>Course</code> (Both if n:m, only one if 1:n).</p>\n\n<p>Depending on the requirements, you could override the <code>toString()</code> method, then you could write <code>print(student)</code> instead of all the concatenations.</p>\n\n<p>Try to have a look at the <code>Scanner</code> class and some examples. It makes command line reading much easier.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T14:18:33.397", "Id": "19461", "ParentId": "19408", "Score": "1" } }, { "body": "<p>Talk yourself through your \"problem domain\" and write it as you go. Say a little, write a little. The details will come along. Don't worry about them all at once. Make sure the little you write each time compiles.</p>\n\n<p>For example</p>\n\n<p><em>Well, there's a Person</em></p>\n\n<pre><code>public Class Person {}\n</code></pre>\n\n<p><em>Is a Student a Person? Yes. Is a Person a student? Well, sometimes.</em></p>\n\n<pre><code>public Class Student extends Person {}\n</code></pre>\n\n<p><em>What's the basic stuff of a Person/Student? name, age, address, studentID, semester....</em></p>\n\n<pre><code>public class Student extends Person () {\n public string Name;\n public string Age;\n public string Address;\n public string ID;\n public string semester;\n}\n</code></pre>\n\n<p><em>Oh, some of those belong to all Persons, some are students only</em></p>\n\n<pre><code>public class Person () {\n public string Name;\n public string Age;\n public string Address;\n}\n\npublic class Student extends Person () {\n public string ID;\n public string semester;\n}\n</code></pre>\n\n<p><em>Students take courses. I need a course class. Is a course a student? no. vice versa? no. Oh - a student takes a course. Or a student has courses - <strong>has means composition not inheritance</em></strong></p>\n\n<pre><code>public class Student extends Person () {\n public string ID;\n public string semester;\n ArrayList courses;\n }\n public class Course {} // don't know what's inside this yet.\n</code></pre>\n\n<p><strong>OK, You get the idea.</strong></p>\n\n<p><strong>Displaying</strong></p>\n\n<p>Your basic idea of making strings of \"label: value\" is the right idea, but implemented wrong. And once implemented - use it!! </p>\n\n<p>All objects have a <code>toString()</code> method. Override it. Then all you have to \"say\" to use it is <code>System.out.println(someStudent.toString())</code> BAM! object oriented programming. Also, DO NOT use println in your toString(). toString() should build all the object information into a <em>single</em> formatted string and pass that. Then you use it as shown.</p>\n\n<pre><code>// in the Person class\npublic override string toString(){\n string me = \"\";\n me += \"Name: \" + this.Name + \"\\n\" //new line\n me += \"Age: \" + this.Age + \"\\n\";\n me += \"Address: \" + this.Address + \"\\n\";\n return me;\n}\n</code></pre>\n\n<p>Now, what class would this go into? Person. What about Student? The above already does most of what we need for Student too. Do we duplicate it in Student class? NO! Object Oriented Design to the rescue! </p>\n\n<pre><code>// in the Student class\npublic string toString(){\n string me = \"\";\n me += base.toString();\n me += \"semester: \" + this.semester + \"\\n\";\n ......\n return me;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T19:20:52.267", "Id": "19546", "ParentId": "19408", "Score": "7" } }, { "body": "<p>Alright, let's go through everything that is wrong with this code...</p>\n\n<pre><code>public class Person extends Test\n</code></pre>\n\n<p>^ A person is not a test. ^</p>\n\n<pre><code>// Variables\n\n String name;\n</code></pre>\n\n<p>^ Too much vertical white space. ^</p>\n\n<pre><code> String name;\n int age;\n String address;\n\n // Default Constructor\n\n Person()\n {\n name = \"\";\n age = 0;\n address = \"\";\n }\n</code></pre>\n\n<p>^ Very verbose. You can set the default values at the site of variable declaration and leave the default constructor empty. ^</p>\n\n<pre><code> String name;\n int age;\n String address;\n</code></pre>\n\n<p>^ You didn't specify that these member variables are private. They are public by default (which is unacceptable except for final values). ^</p>\n\n<pre><code> public void display()\n {\n\n System.out.println(\"Name = \"+ name);\n System.out.println(\"Age = \"+ age);\n System.out.println(\"address = \"+ address);\n\n\n\n }\n</code></pre>\n\n<p>^ Waaaaay too much vertical whitespace. ^</p>\n\n<pre><code>int studentNum, semester;\n</code></pre>\n\n<p>^ Avoid declaring multiple variables on one line in Java. It hampers readability and promotes using the same modifiers for all your variables when in reality they should be different (ex. final, volatile, etc). ^</p>\n\n<pre><code>public void setAge(int age)\n{\n this.age = age;\n}\n</code></pre>\n\n<p>^ The whole point of not accessing variables directly is to be able to control how they are modified. In this case, it doesn't make sense to change your age to any integer. You probably want to get rid of the setter and instead use a method that increments your age (assuming that your age can't ever go down). At the very least check to make sure that your age isn't negative.</p>\n\n<pre><code>void Display() // Method Overriding\n{\n\n\n\n}\n</code></pre>\n\n<p>^ Don't leave a comment saying \"// Method Overriding\"\". Instead, on the above line, write \"@Override\" (without the quotation marks). ^</p>\n\n<pre><code>public class Course extends Student\n</code></pre>\n\n<p>^ BIG HUGE TERRIBLE MISTAKE. NEVER EVER EVER EVER USE INHERITANCE THIS WAY. A course is not a specific type of student. Student has an instance of course. Student has an array of courses and student should be able to add and drop courses from the array.^</p>\n\n<pre><code>public class Test implements StudentFees\n</code></pre>\n\n<p>You're using inheritance wrong. Every time you use inheritance, ask yourself \"is type X a subclassification of type Y\".</p>\n\n<p>Example:</p>\n\n<pre><code>public class Dog extends Animal\n</code></pre>\n\n<p>Is type dog a sub-classification of type animal? Are all dogs animals? Yes. Good. We are using inheritance the right way.</p>\n\n<p>Now try this:</p>\n\n<pre><code>public class Fish extends Bird\n</code></pre>\n\n<p>Is type fish a sub-classification of type bird? Are all fishes birds? No. Bad. We are using inheritance the wrong way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-21T13:21:24.147", "Id": "198891", "Score": "0", "body": "You wrote a good answer Michael! Though it's the first time I see this kind of writing style (Using ^^), I'm not 100% it's the best format to write answers. *But*, you're answer is great!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-21T13:25:44.720", "Id": "198892", "Score": "0", "body": "I most certainly agree with TopinFrassi on both points! Excellent answer! I would also consider using a line separator and headings instead of `^^`. The line separator in Markdown is formatted by three hyphens (`---`), and headings with `#`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-06T05:48:28.893", "Id": "106696", "ParentId": "19408", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T20:34:08.620", "Id": "19408", "Score": "4", "Tags": [ "java" ], "Title": "Student details project" }
19408
<p>Here is Python code written to perform the following operations:</p> <ol> <li>Find each occurrence of a three-letter sequence in a character array (e.g. a sequence such as <code>('a','b','c')</code>), including overlapping sequences of up to 2 shared characters.</li> <li>Count the characters between the start of each sequence and the start of all identical sequences following it.</li> <li>Every time the same number of characters results from #2, increment a counter for that specific number of characters (regardless of which character sequence caused it).</li> <li>Return a dictionary containing all accumulated counters for character distances.</li> </ol> <p></p> <pre><code>counts = {} # repeating groups of three identical chars in a row for i in range(len(array)-2): for j in range(i+1,len(array)-2): if ((array[i] == array[j]) &amp; (array[i+1] == array[j+1]) &amp; (array[i+2] == array[j+2])): if counts.has_key(j-i) == False: counts[j-i] = 1 else: counts[j-i] += 1 </code></pre> <p>This code was originally written in another programming language, but I would like to apply any optimizations or improvements available in Python.</p>
[]
[ { "body": "<p>The first way to improve the code that I can see is: make it more readable, more expressive. In one word: refactoring.</p>\n\n<p>Try to avoid so many one-letter variables and long lines as they obstruct the meaning of the code. Also, you're using two nested loops and two nested if statements with a pretty long condition. </p>\n\n<p>Try assigning those to more meaningful variables.</p>\n\n<p>Your code sample is also incomplete, not showing what the \"array\" really is. Python doesn't have \"arrays\" so I guess you're using a standard list type. Something that can speed up this kind of lookup could be \"dynamic programming\", i.e. caching of some re-occuring computations. But this would require to refactor into more readable blocks first.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T15:07:25.963", "Id": "31108", "Score": "0", "body": "thank you for tips. but the variables which I am using for the for loops (i and j) are only iterating variables, so I think, they should be ok there. the nested fors and ifs are exactly what I have talked about. it seems to me also \"not good\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T15:43:57.960", "Id": "31109", "Score": "0", "body": "Actually it does matter. I recommend you try starting with a simpler question first regarding how to refactor code so it becomes \"beautiful\". Deflecting on a possible solution won't help." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T23:57:16.160", "Id": "19414", "ParentId": "19409", "Score": "0" } }, { "body": "<p>Instead of taking three elements at a time and comparing them to every other three elements, which takes O(n<sup>2</sup>) comparisons, you can use the following, which only requires traversing the array once:</p>\n\n<pre><code>from collections import defaultdict\n\ncounts = defaultdict(int)\nfor i in xrange(len(string) - 2):\n counts[tuple(string[i:i+3])] += 1\n</code></pre>\n\n<p>Using <a href=\"https://stackoverflow.com/questions/5878403/python-equivalent-to-rubys-each-cons\">this answer</a> about a Python equivalent to Ruby's <a href=\"http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-each_cons\" rel=\"nofollow noreferrer\">each_cons</a>, you can make this even nicer, though I don't know about the performance.</p>\n\n<p>As the array contains characters, you may as well call it a string.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T12:57:33.280", "Id": "31155", "Score": "0", "body": "This doesn't do the same thing as the OP's code: in his `counts` dictionary the keys are the distance between the repetitions, whereas in yours the keys are the repeated triples." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T18:30:49.377", "Id": "19436", "ParentId": "19409", "Score": "0" } }, { "body": "<p>You can use simple python dictionary and list comprehensions to achieve your goal:</p>\n\n<pre><code>import re\nstring = \"test test test test test\"\naTuplePositions = {string[y:y+3]:[m.start() for m in re.finditer(''.join([string[y],'(?=',string[y+1:y+3],')']), string)] for y in range(len(string)-2) }\naTupleDistances = [t-u for z in aTuplePositions for a,u in enumerate(aTuplePositions[z]) for t in aTuplePositions[z][a+1:]]\ncounts = {y:aTupleDistances.count(y) for y in aTupleDistances if y &gt;= 0}\ncounts # returns {10: 12, 20: 2, 5: 17, 15: 7}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T12:58:12.237", "Id": "31156", "Score": "0", "body": "This doesn't do the same thing as the OP's code: in his `counts` dictionary the keys are the distance between the repetitions, whereas in yours the keys are the repeated triples." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T03:14:25.893", "Id": "31178", "Score": "0", "body": "The OP failed to phrase the question correctly, so downvote the question rather than my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T05:09:36.630", "Id": "31179", "Score": "0", "body": "@GarethRees I fixed the difference between my answer and the answer the OP wanted (but failed to correctly request)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T19:46:43.097", "Id": "31341", "Score": "0", "body": "@Barbarrosa sorry for misunderstanding, now I know that I have to formulate the questions more clearly, so I hope there will be no such problems. your answer is also very interesting, and I take valuable information from both of you." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T05:20:23.183", "Id": "19446", "ParentId": "19409", "Score": "0" } }, { "body": "<h3>1. Improving the code</h3>\n\n<p>Here are some ways in which you could improve your code, while leaving the algorithm unchanged:</p>\n\n<ol>\n<li><p>You can avoid the need to check <code>counts.has_key(j-i)</code> if you use <a href=\"http://docs.python.org/2/library/collections.html#collections.Counter\" rel=\"nofollow\"><code>collections.Counter</code></a>.</p></li>\n<li><p>You are looping over <em>all pairs of distinct indexes</em> between <code>0</code> and <code>len(array)-2</code>. The function <a href=\"http://docs.python.org/2/library/itertools.html#itertools.combinations\" rel=\"nofollow\"><code>itertools.combinations</code></a> provides a way to cleanly express your intention.</p></li>\n<li><p>Instead of comparing three pairs of array elements, you can compare one pair of array <em>slices</em>.</p></li>\n<li><p>Organize the code into a function with a <a href=\"http://docs.python.org/2/tutorial/controlflow.html#documentation-strings\" rel=\"nofollow\">docstring</a>.</p></li>\n<li><p>Generalize it from 3 to \\$k\\$.</p></li>\n<li><p>Python doesn't have an \"array\" type, but it does have <a href=\"http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange\" rel=\"nofollow\">sequences</a>. So your variables could be better named.</p></li>\n</ol>\n\n<p>Here's the revised code after making the above improvements:</p>\n\n<pre><code>from collections import Counter\nfrom itertools import combinations\n\ndef subseq_distance_counts(seq, k=3):\n \"\"\"Return a dictionary whose keys are distances and whose values\n are the number of identical pairs of `k`-length subsequences\n of `seq` separated by that distance. `k` defaults to 3.\n\n \"\"\"\n counts = Counter()\n for i, j in combinations(range(len(seq) - k + 1), 2):\n if seq[i:i + k] == seq[j:j + k]:\n counts[j - i] += 1\n return counts\n</code></pre>\n\n<p>It's possible to rewrite the body of this function as a single expression:</p>\n\n<pre><code> return Counter(j - i\n for i, j in combinations(range(len(seq) - k + 1), 2)\n if seq[i:i + k] == seq[j:j + k])\n</code></pre>\n\n<p>Some people prefer this style of coding, and others prefer the explicitness of the first version. It doesn't make much difference to the performance, so comes down to personal taste.</p>\n\n<h3>2. Improving the algorithm</h3>\n\n<p>Here's an alternative approach (that you could use if the subsequences are hashable). Your original algorithm is \\$ O(n^2) \\$, where \\$n\\$ is the length of the sequence. The algorithm below is \\$O(n + m)\\$, where \\$m\\$ is the number of repeated triples. This won't make any different in the worst case, where \\$m = Θ(n^2)\\$, but in cases where \\$m = ο(n^2)\\$ it should be an improvement.</p>\n\n<pre><code>def subseq_distance_counts(seq, k=3):\n \"\"\"Return a dictionary whose keys are distances and whose values\n are the number of identical pairs of `k`-length subsequences\n of `seq` separated by that distance. `k` defaults to 3.\n\n &gt;&gt;&gt; subseq_distance_counts('abcabcabc')\n Counter({3: 4, 6: 1})\n &gt;&gt;&gt; subseq_distance_counts('aaaaaa', 1)\n Counter({1: 5, 2: 4, 3: 3, 4: 2, 5: 1})\n\n \"\"\"\n positions = defaultdict(list) # List of positions where each subsequence appears.\n for i in range(len(seq) - k + 1):\n positions[seq[i:i + k]].append(i)\n return Counter(j - i\n for p in positions.itervalues()\n for i, j in combinations(p, 2))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T13:32:01.877", "Id": "19457", "ParentId": "19409", "Score": "4" } } ]
{ "AcceptedAnswerId": "19457", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T21:12:55.967", "Id": "19409", "Score": "3", "Tags": [ "python", "array", "search" ], "Title": "Array-search algorithm for identical sequences and character distances" }
19409
<p>I'm writing a custom dictionary which is to be used as a helper for caching. The reason I use delegates is because it must interface with generated code, so I can't change this. However, you can assume that the delegates are thread-safe. I did some preliminary tests that it's thread-safe, but I can always use an extra pair of eyes to spot possible concurrent issues.</p> <pre><code>//StoreToCache will handle removal, replacement, and addition to the cache public delegate object StoreToCache(string key, object value, CacheObject info); public delegate object GetFromCache(string key); /// &lt;summary&gt; /// A super fast concurrent "dictionary" which passes through to the generated Cache class which constructed it. /// &lt;/summary&gt; public class CacheDictionary&lt;K,V&gt; { ConcurrentDictionary&lt;K, string&gt; RealKeys=new ConcurrentDictionary&lt;K, string&gt;(); readonly string BaseKey; readonly CacheObject Info; StoreToCache StoreTo; GetFromCache GetFrom; /// &lt;summary&gt; /// This returns the amount of keys we are tracking within this CacheDictionary. /// Note: This does not necessarily indicate how many items are actually still in the cache! /// &lt;/summary&gt; /// &lt;returns&gt; /// The count. /// &lt;/returns&gt; public int TrackedCount { get { return RealKeys.Count; } } public CacheDictionary(string basekey, CacheObject info, StoreToCache store, GetFromCache get) { BaseKey=basekey; Info=info; StoreTo=store; GetFrom=get; } void Add (K key, V value) { string realkey=RealKeys.GetOrAdd(key, (s) =&gt; AddKey(key)); StoreTo(realkey, value, Info); } public V Remove (K key) { var res=StoreTo(GetKey(key), null, Info); string trash=null; RealKeys.TryRemove(key, out trash); if(res!=null &amp;&amp; res is V) { return (V)res; } else { return default(V); } } static long CurrentKey=0; string AddKey(K key) { long tmp=Interlocked.Increment(ref CurrentKey); string k=BaseKey+(tmp).ToString(); if(!RealKeys.TryAdd(key, k)) { return null; } return k; } string GetKey(K key) { string tmp=null; if(!RealKeys.TryGetValue(key, out tmp)) { return null; } return tmp; } public V this [K key] { get { string realkey=GetKey(key); if(realkey==null) { return default(V); } object tmp=GetFrom(realkey); if(tmp!=null &amp;&amp; tmp is V) { return (V)tmp; } else { string trash=null; RealKeys.TryRemove(key, out trash); //cleanup return default(V); } } set { if(value==null) { Remove(key); } else { Add (key, value); } } } public void Clear () { lock(RealKeys) { foreach(var key in RealKeys.Keys) { //don't worry about concurrency here. Iterating over the collection is so non-thread-safe it's not even funny. StoreTo(GetKey(key), null, Info); } RealKeys.Clear(); } } } </code></pre> <p>Is this code thread safe? Also assume that the delegates can return basically random values, because they pass through to cache. So, they may or may not have the value requested at anytime. If the delegate doesn't have the value requested, it will return <code>null</code>.</p> <p>This dictionary is always initialized as static as well, and can be accessed from basically an unlimited number of threads concurrently. IT should never throw an exception of any kind. If a value doesn't exist, it should return <code>null</code>.</p> <p>Is this thread-safe in all conditions? Also, is there anything that can make the code more clean? </p> <p>An example use-case is like this:</p> <pre><code>static ConcurrentDictionary&lt;int, string&gt; d=new ConcurrencyDictionary.... .... d[10]="foo"; //add a value if it doesn't exist d[10]=null; //remove value if it exists string tmp=d[1]; //read value. returns the value if it exists, else null </code></pre>
[]
[ { "body": "<p>Your code is not safe:</p>\n\n<ul>\n<li>simultaneous calls to getter of the indexer and setter for the same key may result in data missing in cache: \n<ul>\n<li>setter adds the key to <code>RealKeys</code></li>\n<li>getter reads it and looks for value in cache while it's not there yet</li>\n<li>setter add the value to cache</li>\n<li>getter cleans the cache</li>\n</ul></li>\n<li>lock in <code>Clear</code> doesn't prevent other methods from updating <code>RealKeys</code> since other methods don't lock on the <code>RealKeys</code>.</li>\n</ul>\n\n<p>Other issues with code worth noting:</p>\n\n<ul>\n<li>naming conventions. Private fields are usually named in camelCase, and often have an underscore prefix</li>\n<li>single-responsibility. <code>CacheDictionary</code> doesn't need to know about <code>CacheObject</code>. Instead it would be good if \"real cache\" implements an interface, and it's passed as cache implementation instead of 2 delegates.</li>\n<li>This cache stores mapping keys->real keys in memory, so real cache most likely is also in-memory. It might be a good idea just to use <code>ConcurrentDictionary&lt;TKey, TValue&gt;</code> or <code>System.Runtime.Caching.MemoryCache</code> instead.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T02:29:14.657", "Id": "31142", "Score": "0", "body": "I though that locking in `Clear` with the standard C# locks would prevent other non-locked code from executing. I'll have to research that. Also, good point about that very very subtle race condition. Any ideas on how to prevent that? Also, for the naming conventions, I'm fine with that. For single-responsibility, that would make sense and is doable without complicating my code-generator. And finally, for the in-memory cache bit, I can't do this because it's not guaranteed to be an in-memory cache. It could pass through to memcached or some such." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T02:48:58.477", "Id": "31143", "Score": "0", "body": "I'm actually considering scrapping the whole `RealKey` idea in favor of just requiring that a key type has a meaningful(and unique) `.ToString` and/or `.GetHashCode` method" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T14:30:46.490", "Id": "19425", "ParentId": "19411", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T21:28:06.403", "Id": "19411", "Score": "4", "Tags": [ "c#", "multithreading", "thread-safety", "hash-map" ], "Title": "Custom dictionary for caching assistance" }
19411
<p>Imagine a website that publishes the number of daily commuters in only a graphical form each day using a bar chart. I want to determine the number by reading the bar chart after saving the graphic as an image (the image stuff is not important here). The way I want to read the bar chart is by going to a pixel number (the #of commuters axis) and asking the question, "Is the pixel 'on' or 'off'?" (On means that the bar is present and off means that this guess too high) Note: that there is a lower bound of 0 and, technically, an infinite upper bound. But, in reality, 10000 may be the realistic upper bound. Also note, No Change from yesterday is a frequent finding.</p> <p><strong>Given a starting number from yesterday to guess, what's the most efficient way to find the number? Does my function provide the most efficient method?</strong> Efficient means fewest number of queries to ask if a pixel is on or off. There will be multiple bars to measure and keeping track of the iteration number might add unwanted complexity if it's not truly needed.</p> <p>My algorithm follows as a function. Any advice is most welcome. (brought to CR from SE, <a href="https://stackoverflow.com/questions/13782587/edge-finding-binary-search">https://stackoverflow.com/questions/13782587/edge-finding-binary-search</a> )</p> <pre><code>def EdgeFind(BlackOrWhite,oldtrial,high,low): # BlackOrWhite is a 0 or 1 depending on if the bar is present or not. A 1 indicates that you are below or equal to the true number. A 0 indicates that you are above the true number # the initial values for oldtrial, high, and low all equal yesterday's value factorIncrease = 4 #5 finished = 0 if BlackOrWhite == 1 and oldtrial==high: newtrial = oldtrial+factorIncrease*(high-low)+1 high = newtrial low = oldtrial elif BlackOrWhite == 1 and high-oldtrial==1: finished = 1 newtrial = oldtrial elif BlackOrWhite == 1: newtrial = oldtrial+(high-oldtrial)/2 low = oldtrial if BlackOrWhite == 0 and oldtrial==low: newtrial = (oldtrial)/2 high = oldtrial low = newtrial elif BlackOrWhite == 0 and oldtrial-low==1: finished = 1 newtrial = oldtrial-1 elif BlackOrWhite == 0: newtrial = oldtrial-(oldtrial-low+1)/2 high = oldtrial if (oldtrial==1) and low!=1: finished = 1 return finished,newtrial,high,low </code></pre>
[]
[ { "body": "<p>How about</p>\n\n<pre><code>if BlackOrWhite == 1:\n if oldtrial == high:\n newtrial = oldtrial+factorIncrease*(high-low)+1\n high = newtrial\n low = oldtrial\n elif high-oldtrial==1:\n finished = 1\n newtrial = oldtrial\n else:\n newtrial = oldtrial+(high-oldtrial)/2\n low = oldtrial\n</code></pre>\n\n<p>For simplifying your ifs?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T09:02:54.173", "Id": "19606", "ParentId": "19413", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T23:26:39.413", "Id": "19413", "Score": "4", "Tags": [ "python", "algorithm", "performance" ], "Title": "Edge finding binary search" }
19413
<p>I wanted to open Database (Mongo) connection only once when I start application and share the same connection across the application. What am doing as part of app.js is</p> <p>Creating connection </p> <pre><code>var dbConnection = mongoose.createConnection(config.database.address, config.database.dbName, config.database.port); </code></pre> <p>passing dbConnection in every route call</p> <pre><code>require('./services/MasterServices')(app , dbConnection); </code></pre> <p>Is it right approach or anything wrong here?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T19:01:17.160", "Id": "31101", "Score": "0", "body": "Does this code work for you, or are you having problems with it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T19:38:08.937", "Id": "31102", "Score": "0", "body": "I do not have any problem, I'm asking if something wrong with the design or any better approach available there." } ]
[ { "body": "<p>You can use the <code>connect</code> function, which returns the default connection.</p>\n\n<p>Just add <code>mongoose.connect('mongodb://username:password@host:port/database');</code> whenever you need it.</p>\n\n<p>See <a href=\"http://mongoosejs.com/docs/connections.html\" rel=\"nofollow\">http://mongoosejs.com/docs/connections.html</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T20:05:19.177", "Id": "31103", "Score": "0", "body": "Hi, So I should create connection in app.js and use connect method (in different class) to get connection reference?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T19:53:32.723", "Id": "19416", "ParentId": "19415", "Score": "1" } }, { "body": "<p>You could separate the connection into a file like \"db.js\", and then require it when necessary. So for example:</p>\n\n<pre><code>// db.js\nvar mongoose = require('mongoose'),\n config = require('./config.js');\n\nmodule.exports = mongoose.createConnection(\n config.database.address, config.database.dbName, config.database.port);\n</code></pre>\n\n<p>And then in your routes, you might do something like:</p>\n\n<pre><code>// route.js\nvar db = require('./db.js');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T21:54:53.753", "Id": "19417", "ParentId": "19415", "Score": "0" } }, { "body": "<p>if you have a module which looks after your db interaction, nodejs returns singleton objects for your module. This means you can create a connection in your module:</p>\n\n<pre><code>var connection mongoose. createConnection(); //only ever set up once. The first time it is required\n\n\n\nexports.getConnection = function (cb){\n if(! connection) {\n connection = mongoose.createConnection();\n cb(undefined,connection);\n }\n else cb(undefined, connection);\n};\n</code></pre>\n\n<p>Just an option.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T21:59:40.767", "Id": "19418", "ParentId": "19415", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-08T18:58:29.550", "Id": "19415", "Score": "1", "Tags": [ "javascript", "node.js" ], "Title": "Passing Database connection" }
19415
<p>I'm new to jQuery and played a bit with what can I do with radio button. I want to create <strong>ONLY</strong> one input type when I click the <kbd>Notice</kbd> radio button. I already using many way to achieve this, but this is the only way I can do this, you can see the following code.</p> <p>HTML</p> <pre><code>&lt;input type="radio" name="radio1" value="Immediate" /&gt; Immediate &lt;br/&gt; &lt;input type="radio" name="radio1" id="others" value="Notice" /&gt; Notice me in... &lt;br /&gt; &lt;div id="inputplace"&gt;&lt;/div&gt; </code></pre> <p>jQuery</p> <pre><code>$(function(){ $("#others").click(function(){ while($("#others").val()=="Notice") { var newElement = $(document.createElement('input')).attr({name:"noticeweeks", id:"noticeweeks"}); newElement.appendTo("#inputplace"); $("#others").val("Notice me in..."); } }); }); </code></pre> <p>With that jQuery, I changed the value of the radio button into "Notice me in...", so the <code>while</code> function will stop creating a new element since the value has been changed.</p> <p>Are there any others way to achieve the same result?</p>
[]
[ { "body": "<ul>\n<li><p>There's no need to use a <code>while</code> loop, as you only want to add the element once, after which the condition won't hold anymore. That's what <code>if</code> is for.</p></li>\n<li><p>There's a shorter way to create a new element</p></li>\n</ul>\n\n<p>So I get to:</p>\n\n<pre><code>$(function() {\n $(\"#others\").click(function() {\n if ($(\"#others\").val() == \"Notice\") {\n var newElement = $('&lt;input&gt;')).attr({name:\"noticeweeks\", id:\"noticeweeks\"}); \n newElement.appendTo(\"#inputplace\"); \n $(\"#others\").val(\"Notice me in...\");\n }\n });\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T17:34:52.403", "Id": "31117", "Score": "0", "body": "Ah yeah, actually I already changed it to if already and it works, than you anyway." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T17:03:44.593", "Id": "19430", "ParentId": "19421", "Score": "2" } }, { "body": "<p>You can go about the \"only once\" part in a couple of ways:</p>\n\n<ol>\n<li>Remove the event-listener once the new input has been added</li>\n<li>Always have the extra input, but have it hidden, and show it when necessary</li>\n<li>Have a closure variable that holds the input; if it's defined, don't redefine it</li>\n</ol>\n\n<p>And more. I'd personally go with #2, because it means that your inputs are actually in the markup, while the javascript <em>only</em> defines behavior. That is, keep elements in the markup, style and layout in CSS, and behavior in JS - don't mix it</p>\n\n<p>In other words:</p>\n\n<pre><code>&lt;input type=\"radio\" name=\"radio1\" value=\"Immediate\" /&gt; Immediate\n&lt;br/&gt;\n&lt;input type=\"radio\" name=\"radio1\" id=\"others\" value=\"Notice\" /&gt; Notice me in...\n&lt;br /&gt;\n&lt;!-- extra input, just hidden --&gt;\n&lt;input type=\"text\" name=\"noticeweeks\" id=\"noticeweeks\" value=\"\" style=\"display: none\" /&gt;\n</code></pre>\n\n<p>and the JS:</p>\n\n<pre><code>$(function(){\n // cache these!\n var radioButton = $(\"#others\"),\n noticeWeeks = $(\"#noticeweeks\");\n\n radioButton.change(function () { // listen for change - not click\n if( this.checked ) { // use the \"raw\" DOM property `checked`\n noticeWeeks.show();\n }\n });\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/W8Mp2/\" rel=\"nofollow\">Demo</a></p>\n\n<p>Of course, I get the feeling, that what you really want is to show the extra input, when \"Notice me in...\" is selected, and <em>hide</em> it when \"Immediate\" is selected.</p>\n\n<p>In that case, the JS could be</p>\n\n<pre><code>$(function(){\n // cache these!\n var radioButtons = $(\"[name=radio1]\"), // get both radiobuttons\n noticeWeeks = $(\"#noticeweeks\");\n\n radioButtons.change(function () {\n if( $(this).val() === \"Notice\" ) { // this time, we do need to check the value\n noticeWeeks.show();\n } else {\n noticeWeeks.hide();\n }\n });\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/W8Mp2/1/\" rel=\"nofollow\">Demo</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T17:35:37.103", "Id": "31118", "Score": "0", "body": "Ah no, actually if I select to Immediate using the JS I will remove it using .remove()\n\nBut anyway, thanks a bunch I will try your way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T20:05:23.860", "Id": "31133", "Score": "0", "body": "@Xtrader In that case, I'd use `noticeWeeks.prop('disabled', false).show();` and `noticeWeeks.prop('disabled', true).hide();` to show/hide _and_ enable/disable the input. That way it won't be visible _or_ submitted to the server when it's \"turned off\". Again, keep you markup in your markup; don't add and remove trivial stuff like this with JS." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T16:07:11.557", "Id": "31167", "Score": "0", "body": "Ah sorry, if I use prop will it creating an memory leak in IE 9? Because the documentation said so, should I use the .data() method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T17:17:43.413", "Id": "31169", "Score": "0", "body": "@Xtrader No. `disabled` is a standard HTML attribute you're setting on the element, so `data` won't work. Use `.prop()` or `.attr()`. And read the documentation again: The memory leak only happens in IE _below_ version 9, and it _doesn't happen at all_ for a boolean values, which is what this is." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T17:32:37.303", "Id": "19432", "ParentId": "19421", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T10:49:58.417", "Id": "19421", "Score": "1", "Tags": [ "javascript", "jquery", "dom" ], "Title": "Creating input when checking/clicking radio button" }
19421
<p>I want to store image (details) in my database, and want for each image the possibility to have from 1 to N versions.</p> <p>I want a single file (src) to be associated with a single version. There must not be more than one version for an single image with the same dimensions and format (no point having a version with 1920x1080 jpg and 1920x1080 jpg, whereas 1920x1080 jpg and 1920x1080 png would be ok).</p> <p>I have come out with the following tables :</p> <pre><code>-- --------------------------------------------------------------------------------- -- IMAGE TABLE -- --------------------------------------------------------------------------------- DROP TABLE IF EXISTS "image_e"; CREATE TABLE IF NOT EXISTS "image_e" ( "id" int unsigned NOT NULL AUTO_INCREMENT, "title" varchar(32) NOT NULL, "alt" varchar(16) NOT NULL, PRIMARY KEY ("id") ) ENGINE = MyISAM DEFAULT CHARSET = utf8 COLLATE = utf8_bin; -- --------------------------------------------------------------------------------- -- IMAGE VERSION TABLE -- --------------------------------------------------------------------------------- DROP TABLE IF EXISTS "image_version_e"; CREATE TABLE IF NOT EXISTS "image_version_e" ( "id" int unsigned NOT NULL AUTO_INCREMENT, "imageId" int unsigned NOT NULL, "format" varchar(4) NOT NULL, "size" int unsigned NOT NULL, "width" int unsigned NOT NULL, "height" int unsigned NOT NULL, "src" varchar(64) NOT NULL, PRIMARY KEY ("id") ) ENGINE = MyISAM DEFAULT CHARSET = utf8 COLLATE = utf8_bin; ALTER TABLE "image_version_e" ADD UNIQUE KEY ("imageId", "format", "width", "height"); ALTER TABLE "image_version_e" ADD UNIQUE KEY ("src"); </code></pre> <p>image_version_e.imageId references image_e.id</p> <p>This version is MyISAM, i will make a second version for InnoDB with this foreign key.</p> <p>I don't care about insert / update / delete speed, but i do care about select speed as i will use this for a wallpaper gallery with a search function.</p> <p>Are my unique keys done correctly ? Isn't it too much or not enough ? Is the schema well thought ? Is there a way to optimize it ?</p> <p>Thanks for reading and for your help :)</p>
[]
[ { "body": "<p>The unique keys will enforce the requirements you specified, but unless your data entry program either traps error codes returned by MySQL and prompts the user for correction or checks for uniqueness before saving the record, you will probably experience a lot of record rejections where you won't understand why.</p>\n\n<p>I would also use a much larger VARCHAR maximum length for the image_version_e.src column. Remember that VARCHAR columns only require as much storage space as needed for the actual data with trailing spaces stripped (usually). VARCHAR(255) or more is not unreasonable as it will accommodate those really long directory paths or URLs. Your data entry form field for it should be scrollable but much shorter... probably a multiline text field.</p>\n\n<p>See more details in <a href=\"http://dev.mysql.com/doc/refman/5.0/en/char.html\" rel=\"nofollow\">the MySQL documentation of CHAR and VARCHAR</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T16:43:02.210", "Id": "31203", "Score": "0", "body": "Thanks for taking the time to answer :) Thought no one would ever pass here :p Yes i do check for error codes. I'll use varchar(255) as you mentionned because i only want to store the filename of the image, not the whole path." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T07:48:08.923", "Id": "19482", "ParentId": "19431", "Score": "1" } } ]
{ "AcceptedAnswerId": "19482", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T17:05:56.493", "Id": "19431", "Score": "1", "Tags": [ "mysql", "sql" ], "Title": "Are these tables concepted correctly?" }
19431
<p>I will try to be as concise as I can:</p> <p><strong>The goal:</strong> trying to universalize a specific section of a project, that is dealing with the SQL database transactions.</p> <p>To assist you with your answer, I've pasted the following (just for reference):</p> <ul> <li><p>a usage code: <code>GetTestOfTablTime()</code> returns a <code>DataTable</code> </p></li> <li><p>class: <code>SQLDBInteraction</code> is another class - responsible for the final(SQL transaction) stage </p></li> </ul> <p>In this code below, I am constructing what I call: "Stored Procedure's Meta Data". That class is the one that holds all of the SQL Db SPs.</p> <p><code>HTSPs</code> (HT is the company's aliases) is holding each <code>SP</code> required) parameters. <code>HTSPs</code> class contains another sub Class. For all <code>SP</code>s Names, it only has <code>const string</code>s for each <code>SP</code> name.</p> <pre class="lang-C# prettyprint-override"><code>public sealed class HTSPs { //so for example this is one of the members of this class - a stored procedure //its mission: get evnents with specified id OF specified userId in spec' month, year.. public sealed class GetTimesWithCustomerNames { //if I DO need Constructor for its parameters how do I properly format the constructor? public GetTimesWithCustomerNames() { Userid.ParameterName = ParNameUserid; Month.ParameterName = ParNameMonth; Year.ParameterName = ParNameYear; EventId.ParameterName = ParNameReasonid; } const string ParNameUserId = "@userId", ParNameMonth = "@month", ParNameYear = "@year", ParNameEventId = "@eventId"; public static SqlParameter Userid = new SqlParameter(); public static SqlParameter Month = new SqlParameter(); public static SqlParameter Year = new SqlParameter(); public static SqlParameter EventId = new SqlParameter(); } } </code></pre> <p>The issue is: how do I initialize the contractor? What is the proper way to have your simple customized <code>StoredProcedure</code> "MetaData"? I've currently completed the implementation of the method below (apart from that issue).</p> <p><strong>USAGE</strong> </p> <p>This is a method that returns <code>DataTable</code> while using the <code>HTSPs</code> class / constructor.</p> <pre class="lang-C# prettyprint-override"><code>using SPTime = HT_DBSchema.HTSPs.GetTimesWithCustomerNames; private DataTable GetTestOfTablTime() { SQLDBInteraction.DataContainer DC_Time = new SQLDBInteraction.DataContainer(); SQLDBInteraction.SqlParamList parmsTime = new SQLDBInteraction.SqlParamList(); Dictionary&lt;SqlParameter, int&gt; SqlCmdParDict = new Dictionary&lt;SqlParameter, int&gt;(); parmsTime.SqlCmd.CommandType = CommandType.StoredProcedure; parmsTime.SqlCmd.CommandText = AppDb.MetaSqlSProc.Time.Name; parmsTime.SP_Name = AppDb.MetaSqlSProc.Time.Name; parmsTime.TableName = AppDb.MetaSqlTable.Time.Name; //While folowing implementation Does Work I comented it out to try using the SP Struct //ParmsTTime.SP_Params.Add(new SqlParameter(SPTime.ParNameMonth, 9)); //ParmsTTime.SP_Params.Add(new SqlParameter(SPTime.ParNameReasonid, 1)); //ParmsTTime.SP_Params.Add(new SqlParameter(SPTime.ParNameYear, 2012)); //ParmsTTime.SP_Params.Add(new SqlParameter(SPTime.ParNameUserid, 3571)); //here's where I'm currently stuck, in section below. trying to assign values for the SqlCommand parmsTime.SqlCmd.Parameters.AddWithValue(SPTime.ParNameMonth, 9); parmsTime.SqlCmd.Parameters.AddWithValue(SPTime.ParNameYear, 2012); parmsTime.SqlCmd.Parameters.AddWithValue(SPTime.ParNameReasonid, 1); SPTime.Userid.Direction = ParameterDirection.Input; SPTime.Userid.SqlValue = 3571; return DC_Time.LocalTbl_V3(ParmsTime); } </code></pre> <p><strong>UPDATE</strong></p> <p>The last lines of the code above is trying to implement the parameters assignment, thus it will no longer be required to use:</p> <p><code>SQLDBInteraction.SqlParamList.SP_Params</code> (which is <code>List&lt;SqlParameter&gt;</code>).</p> <p>And instead, I would really like to be able to use <code>SQLDBInteraction.SqlParamList.SqlCmd.Parameters</code> as it is already used for most of the required steps to interact with the database.</p> <p>This is how I will drop some unnecessary usage of extra variables while at the same time I wanted to assign SqlCmd (<code>parmsTime.SqlCmd.Parameters.Add(......)</code>) with the struct - <code>SPTime</code> Real <code>SqlParameters</code> instead of using the strings that represents their name (e.g. <code>parameter.name</code> - (<code>SPTime.ParNameMonth, someValue</code>)).</p> <p><strong>Final stage- SQL transaction</strong></p> <p>The <code>SQLDBInteraction</code> class that does the transaction:</p> <pre class="lang-C# prettyprint-override"><code>public class SQLDBInteraction { public class SqlParamList { public SqlCommand SqlCmd = new SqlCommand(); public List&lt;SqlParameter&gt; SP_Params = new List&lt;SqlParameter&gt;(); public String SP_Name; public string TableName; public string SelectCommand; ///public SqlCommandType SelectedCmdType; } public class DataContainer { public DataTable LocalTbl_V3(SqlParamList Params) { SqlConnection sqlConnection; DataTable Usrs = new DataTable(Params.TableName); SqlDataAdapter sqlDataAdapter; using (sqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["HTConn"].ConnectionString)) { sqlConnection.Open(); using (Params.SqlCmd.Connection = sqlConnection) { using (sqlDataAdapter = new SqlDataAdapter(Params.SqlCmd.CommandText, sqlConnection)) { if (sqlDataAdapter.SelectCommand.Parameters.Count &gt; 0 == false) { sqlDataAdapter.SelectCommand = Params.SqlCmd; sqlDataAdapter.Fill(Usrs); } } } } return Usrs; } </code></pre> <p>I will really appreciate it if someone will find what am I doing wrong with the part of the stored procedure's parameters assigned to the SQL command.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T18:14:43.407", "Id": "31121", "Score": "0", "body": "Have you read about ORMs, e.g. Entity Framework? Is there a strong reason to use `DataTables` rather than typed entities? Is there a strong reason to use stored procedures? Your code is absolutely not thread-safe and has too much of unnecessary classes involved in the simplest operations like reading the data from DB." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T18:19:41.557", "Id": "31122", "Score": "0", "body": "@almaz say, do you want to see how exactly the SP LOOKS LIKE or Did You Really Know As To What exactly Does It Do In DB ? did you think it is something like : `select * From Table` **??**, it has half a page or even almost a full page of code that makes a report of accouts" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T18:32:50.163", "Id": "31124", "Score": "0", "body": "@LoneXcoder almaz doesn't know what your stored procedure looks like, which is why I think he was asking you questions, not really giving suggestions. And ORMs can work with stored procedures." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T18:37:24.680", "Id": "31125", "Score": "0", "body": "well, based on parameter names ('userid', 'month', 'year', 'eventid') and the SP name 'GetTimesWithCustomerNames' it does look like a simple select with a couple of tables at most ;).\n\nOK, what about ORMs and usage of `DataTable`? Why do you need to do all the low-level work yourselves?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T18:37:49.093", "Id": "31126", "Score": "0", "body": "@svick i would like to keep it simple. this is WebForms , Not Mvc4 . The Website is `IIS6` `sql2005` `Winserver2003` AND `ASP` !! (CLASSIC) i am trying to do some touches ( and me also being still fresh Developer(just few month Self Learning) i'd like to implement it my self . any suggestions as to where to start ? a sample code . usage example for where would you start as it is to try atleast fine tuning the project ??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T18:47:00.110", "Id": "31127", "Score": "0", "body": "@almaz \"why...low level , my self\" , i am learning , i like low level some times if it does not smell like Sewerage while i try work on it (meaning too complex as if i will try `C` or `assembly` ) my brain will go dead that level, though , in `.net` with lots of sugar , i like to get as deep as i can , then and only then , as i am done, learn how `microsoft EF` or the company that is doing HiberSomthing ... works , i will be less dissoriented and i will be able to see through it , maybe , atleast see at all ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T18:47:08.627", "Id": "31128", "Score": "2", "body": "@LoneXcoder Well, using ORM could actually make your code simpler, it means you don't have to deal with `SqlConnection`s ` and `SqlDataAdapter`s and `DataTable`s, you get a nice, strongly-typed collection of objects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T18:18:23.303", "Id": "31171", "Score": "1", "body": "@LoneXcoder can you please avoid syntax errors in your questions? It goes a long way to improve the quality of the question, which will bring you more and better answers. (Example of a tool for it: http://support.mozilla.org/en-US/kb/how-do-i-use-firefox-spell-checker )" } ]
[ { "body": "<p>Just to give you idea how your code would look like if you use Entity Framework:</p>\n\n<pre><code>using (var db = new HpDatabaseContext())\n{\n return db.GetTimesWithCustomerNames(userId, month, year, reasonId).ToArray();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T20:02:00.747", "Id": "31131", "Score": "0", "body": "did you mention a 4 files scaterd around the folder xmls and some other UFO like extansions?, the key idea is to complete my code, then to compare it to `EF` (i am thinking of performance too i will check on this) ( by the way my implementaion logic is in these moments with this acutal question and goals to implemet querys as short as it could be you just need to initialize the struct : which table which sp you want to invoke.vwalla. just connect form fields to parameters in code behind=report is in page faster than ablink of an eye im ready to compare it to any new approach exists(speed wise)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T20:40:03.857", "Id": "31134", "Score": "2", "body": "You should not worry about performance since it is just a [premature optimisation](http://en.wikipedia.org/wiki/Program_optimization#When_to_optimize). And quite likely it will work faster than populating a `DataTable` with `SqlDataAdapter`. It's good to understand how things work under the hood, but if you want to learn how to write good maintainable production code it's better to start using proven techniques. The sooner you start using them the faster you'll learn how to use them properly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T19:50:27.997", "Id": "19437", "ParentId": "19433", "Score": "0" } }, { "body": "<p>this is aventually what i am using (atleast For now) </p>\n\n<p>...as there will ,i guess.. always be, further developments. </p>\n\n<p>i will mark this as the answer soon , though you are still very welcome to post comments, or better yet, your improved version .</p>\n\n<p>anyways this is an example for how a stored procedure is stored in my \"DbSchema\" namespace</p>\n\n<pre><code> public static class RobSelect_Update_tblTC_CPA_ByDDL_paramNames\n {\n static SqlParameter aDepartment, bUid, cMonth, dYear, eUpdateFirst;\n\n public static List&lt;SqlParameter&gt; SqlParlstCPA(string SelectedDepartmentID, string SelectedUserID, string SelectedMonth, string selectedYear, string AbitValuIfUpdateFirst)\n {\n aDepartment = new SqlParameter( a_UsrDepartment, SelectedDepartmentID);\n bUid = new SqlParameter(b_UsrID, SelectedUserID);\n cMonth = new SqlParameter(c_Month, SelectedMonth);\n dYear = new SqlParameter(d_Year, selectedYear);\n eUpdateFirst = new SqlParameter(e_Updateit_bit, AbitValuIfUpdateFirst);\n\n\n List&lt;SqlParameter&gt; RetSqlParLst = new List&lt;SqlParameter&gt;();\n RetSqlParLst.Add(aDepartment);\n RetSqlParLst.Add(bUid);\n RetSqlParLst.Add(cMonth);\n RetSqlParLst.Add(dYear);\n RetSqlParLst.Add(eUpdateFirst);\n\n return RetSqlParLst;\n }\n static readonly string a_UsrDepartment = \"@Department\",\n b_UsrID = \"@Uid\",\n c_Month = \"@month\",\n d_Year = \"@year\",\n e_Updateit_bit = \"@updateItFirst\";\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T22:06:18.277", "Id": "31531", "Score": "0", "body": "downvoters i dont count in those votes without a comment of why ,as it is being offensive approach Comments may help to explain what you think about it instead" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T00:00:25.197", "Id": "19473", "ParentId": "19433", "Score": "-1" } }, { "body": "<p>Maybe you are trying to do something like this</p>\n\n<pre><code>public interface DbProc\n{\n public SqlCommand GetCommand();\n}\n\npublic class MyProc : DbProc\n{\n private SqlCommand _cmd;\n\n public const string COMMAND_TEXT = \"spc_MyProc\";\n public const string PARAM1 = \"@Param1\";\n public const string PARAM2 = \"@Param2\"; \n\n public MyProc(int param1, string param2)\n {\n _cmd = new SqlCommand(COMMAND_TEXT);\n _cmd.CommandType = CommandType.StoredProcedure;\n _cmd.Parameters.AddWithValue(PARAM1, param1);\n _cmd.Parameters.AddWithValue(PARAM2, param2);\n }\n\n public SqlCommand GetCommand()\n {\n return _cmd;\n }\n}\n\npublic class Db\n{\n public DataTable ExecuteProc(DbProc proc)\n {\n SqlCommand cmd = proc.GetCommand();\n ConfigureCommand(cmd);\n // execute the command into a data table\n return result;\n }\n\n // Set the common settings for all commands\n private void ConfigureCommand(SqlCommand cmd)\n {\n cmd.CommandTimeout = 10000; \n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T18:34:21.223", "Id": "32721", "Score": "0", "body": "hi andy , thanks for your answer, I am in a little time-out so I can't really check on that solution , but I will review this further next week hopefully , in first glance it does look as a fine approach , thanks I will look in to it and try implement it instead of my answer , so it will be the right answer eventually if it works . thanks a lot mate." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T14:44:45.217", "Id": "20384", "ParentId": "19433", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T17:50:29.673", "Id": "19433", "Score": "1", "Tags": [ "c#", "optimization", "asp.net", "sql-server" ], "Title": "Using a Dedicated Class & Constructor to initialize Stored Procedure for SQL Transaction" }
19433
<p>I want to use this function to store 1024 bit keys in my Mysql database. If you call generateKey(128), you'll get a 128 byte string, same as 1024 bit string. I want to know if there is something wrong with this code or if I should be worried about inter-operability issues with MySQL, Java, Android, File Read/Write, etc.</p> <pre><code> public function generateKey($size){ $randomString = ""; $charUniverse = ""; for($i=0;$i&lt;256;$i++){ $charUniverse .= chr($i); } for($i=0;$i&lt;$size;$i++){ $randInt=mt_rand(0, strlen($charUniverse)-1); $randChar=$charUniverse[$randInt]; $randomString=$randomString.$randChar; } return $randomString; } </code></pre>
[]
[ { "body": "<ul>\n<li>Use <code>chr($randInt)</code> instead of <code>$charUniverse[$randInt]</code>, and abandon the <code>$charUniverse</code> variable altogether.</li>\n<li>Use the <code>$str .= \"str\"</code> dot-equals operator in PHP to append to your final string.</li>\n</ul>\n\n<p>Thus your code becomes:</p>\n\n<pre><code>public function generateKey($size){\n\n $randomString = \"\";\n $charDomainSize = 256;\n for($i=0;$i&lt;$size;$i++){\n $randInt=mt_rand(0, $charDomainSize-1);\n $randChar=chr($randInt);\n $randomString .= $randChar;\n }\n return $randomString; \n\n}\n</code></pre>\n\n<p>If we compress your code further, it becomes:</p>\n\n<pre><code>public function generateKey($size){\n $randomString = \"\";\n for($i=0;$i&lt;$size;$i++){\n $randomString .= chr(mt_rand(0, 255));\n }\n return $randomString;\n}\n</code></pre>\n\n<p>I conducted a speed test, as well. The new code is faster (1000 runs, varied sizes between 1128 and 1148). The units are seconds.</p>\n\n<ul>\n<li>Function 1 Average: 0.024438648223877 </li>\n<li>Function 2 Average: 0.015253195762634</li>\n</ul>\n\n<p>Only using 256 as a size, 1000 runs:</p>\n\n<ul>\n<li>Function 1 Average: 0.00031177306175232 </li>\n<li>Function 2 Average: 0.00017282342910767</li>\n</ul>\n\n<p>This is a little overkill, but I was bored.</p>\n\n<p>It should be very easy to port your random string generator to other platforms, although it may develop more or less dependable randomness based on the underlying generators. E.g. don't use Java's java.util.Random for security or scientific purposes (see <a href=\"https://stackoverflow.com/questions/11051205/difference-between-java-util-random-and-java-security-securerandom\">Difference between java.util.Random and java.security.SecureRandom</a>).</p>\n\n<p>You might also want to consider PHP's <a href=\"http://us1.php.net/manual/en/function.openssl-random-pseudo-bytes.php\" rel=\"nofollow noreferrer\"><code>openssl_random_pseudo_bytes</code></a>, depending on your intent. That may not be as easily ported, though, as your current code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T19:37:12.137", "Id": "31173", "Score": "0", "body": "brilliant coding, thank you for your time" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T00:24:03.533", "Id": "19443", "ParentId": "19434", "Score": "3" } }, { "body": "<p>FROM Php manual\nCaution</p>\n\n<p>This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-30T19:47:56.560", "Id": "167485", "Score": "1", "body": "Another answer already mentioned `openssl_random_pseudo_bytes`. This answer doesn't seem to add value." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-30T19:37:38.393", "Id": "92247", "ParentId": "19434", "Score": "1" } } ]
{ "AcceptedAnswerId": "19443", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T17:54:54.720", "Id": "19434", "Score": "2", "Tags": [ "php", "random", "cryptography" ], "Title": "1024 bit key generation in php" }
19434
<p>I've just written a validation routine for a UPC-A, which ensures the check digit matches the given UPC number (according to <a href="https://en.wikipedia.org/wiki/Universal_Product_Code#Check_digit_calculation" rel="nofollow noreferrer">rules I found on Wikipedia</a>).</p> <p>Below is the code, what do you think?</p> <pre><code>function valid_upc_a($value) { $odd_sum = $even_sum = 0; if(strlen($value) != 12) return FALSE; $chars = str_split($value); for($i=0;$i&lt;11;$i++) { $odd_sum += $i%2==0?$chars[$i]:0; $even_sum += $i%2==1?$chars[$i]:0; } $total_sum = $even_sum + $odd_sum*3; $modulo10 = $total_sum % 10; $check_digit = 10 - $modulo10; return (int)$chars[11] === $check_digit; } </code></pre> <p>It works for a couple of cases I made up, here it is on CodePad:</p> <p><a href="http://codepad.viper-7.com/QEqpFX" rel="nofollow noreferrer">http://codepad.viper-7.com/QEqpFX</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T15:31:35.163", "Id": "70412", "Score": "0", "body": "I took the liberty to roll back the changes. Please do not change the code after posting it except for errors which should not have been there in the first place (like typos when copying the code into the question)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T16:31:58.043", "Id": "70427", "Score": "0", "body": "Just so people know then, see the accepted answer for a bug-fix in the above." } ]
[ { "body": "<p>Two things I noticed.</p>\n\n<ol>\n<li>The return statement if the length is invalid should be on a separate line, and wrapped in braces</li>\n<li>What purpose does the int cast solve? I thought php was typeless.</li>\n</ol>\n\n<p>Other than that, the only other thing I noticed is to space out your operators. However, all the actual function seems to work fine </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T01:18:41.323", "Id": "31177", "Score": "1", "body": "PHP does have [types](http://php.net/manual/en/language.types.intro.php) and provides [type juggling](http://php.net/manual/en/language.types.type-juggling.php). The [Identical Operator](http://php.net/manual/en/language.operators.comparison.php) `===` assures that the variables are equal and of the same type, so a cast is required to make them the same type. Another option would have been to use the Equivalent Operator `==`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T17:32:38.657", "Id": "19466", "ParentId": "19438", "Score": "1" } }, { "body": "<p>I have made a cleaner version of yours put something in and get rid of other things:</p>\n\n<pre><code>&lt;?php\n\nfunction valid_upc_a($value) {\n $upc = strval($value);\n\n if(!isset($upc[11])) {\n return FALSE;\n }\n\n $odd_sum = $even_sum = 0;\n\n for($i = 0; $i &lt; 11; ++$i) {\n if ($i % 2) {\n $even_sum += $upc[$i];\n } else {\n $odd_sum += $upc[$i];\n }\n }\n\n $total_sum = $even_sum + $odd_sum * 3;\n $modulo10 = $total_sum % 10;\n $check_digit = 10 - $modulo10;\n\n return $upc[11] == $check_digit;\n}\n</code></pre>\n\n<p>It's not a huge modification but for example to me is more readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-30T16:27:37.243", "Id": "32025", "Score": "0", "body": "I have to ask why have you used strval against the value instead of str_split, to get it into an array of characters? Can we rely on strval to always provide us with a string that we can access with indicies?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-31T13:13:56.637", "Id": "32055", "Score": "0", "body": "strval() will not always return a string, if the value is an object without __toString() it will raise a Fatal Error if the parameter is an array it will return 'Array' and with parameter type resource it will return 'Resource id #2'. str_split can be a better choice becouse it will trigger an error if it's parameter is not a string (or stringable) which means array/resource can not be the parameter (beside objects without __toString())." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-27T02:32:15.607", "Id": "136215", "Score": "0", "body": "@PeterKiss: Please see my comment on the accepted answer above, `i%2` in the if condition is working backwards." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T18:08:15.150", "Id": "19467", "ParentId": "19438", "Score": "2" } }, { "body": "<p>Good function, only when $modulo10 is 0 it should not be substracted from 10, so it would be something like this:</p>\n\n<pre><code>function valid_upc_a($value) {\n $upc = strval($value);\n\n if(!isset($upc[11])) {\n return FALSE;\n }\n\n $odd_sum = $even_sum = 0;\n\n for($i = 0; $i &lt; 11; ++$i) {\n if ($i % 2) {\n $even_sum += $upc[$i];\n } else {\n $odd_sum += $upc[$i];\n }\n }\n\n $total_sum = $even_sum + $odd_sum * 3;\n $modulo10 = $total_sum % 10;\n\n if ($modulo10 &gt; 0)\n $check_digit = 10 - $modulo10;\n else \n $check_digit = 0; \n\n return $upc[11] == $check_digit;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T09:15:12.737", "Id": "70355", "Score": "0", "body": "Very good, surprised no one else spotted that. Many thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-27T02:29:22.107", "Id": "136214", "Score": "1", "body": "I think your odd and even are backwards. `$i % 2` will evaluate to `0` if the number is even, which is considered false. Your \"even\" condition is actually running when it's odd. You should also multiply the even sum by 3 ,not the odd sum. These errors together are probably producing the correct result, but is not doing what you think it is. You should put `$i%2===0` in your if condition because that will evaluate to a boolean, and more importantly, be `true` when the number is even, as intended." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:22:26.207", "Id": "40959", "ParentId": "19438", "Score": "3" } }, { "body": "<p>Version incorporating all fixed bugs from various answers, with my own take on how to deal with the case where the intermediate result is 10 (aka M from the definition @Wikipedia) by adding another mod 10 operation to the check digit calculation, results in 0 if the sum mod 10 is 10, or the check digit otherwise. I also deleted the conversion to string because the reality is you have to handle UPCs as a string. Using Integer to represent UPC is bogus because UPCs can have leading 0's which are lost upon conversion to Integer.</p>\n\n<p>At this point in time, all of the above have one or more bugs.</p>\n\n<pre><code> function valid_upc_a($upc) {\n\n if(!isset($upc[11])) {\n return FALSE;\n }\n\n $odd_sum = $even_sum = 0;\n\n for($i = 0; $i &lt; 11; ++$i) {\n if ($i % 2 == 0) {\n $even_sum += $upc[$i];\n }\n else {\n $odd_sum += $upc[$i];\n }\n }\n\n $total_sum = $even_sum + $odd_sum * 3;\n $modulo10 = $total_sum % 10;\n $check_digit = (10 - $modulo10) % 10;\n\n return $upc[11] == $check_digit;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-20T18:55:39.747", "Id": "446194", "Score": "2", "body": "\"with my own take on how to deal with the case where the intermediate result is 10\" could you explain in more detail what your take is? On Code Review we're looking for explanations on how to make the code better, not just better code! :) The key point is to explain why you've made some changes to OP's code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-20T18:57:40.980", "Id": "446195", "Score": "0", "body": "10 % 10 = 0, 10 % non-zero check digit = non-zero check digit. Submission updated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-20T19:00:14.173", "Id": "446196", "Score": "1", "body": "I understood it, I meant you should add it in your answer :) Comments aren't meant to hold valuable information" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-20T19:00:44.817", "Id": "446197", "Score": "0", "body": "Was doing while you were typing :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-20T19:03:15.587", "Id": "446198", "Score": "0", "body": "\"Accepted answer\" - wow, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-23T03:20:53.023", "Id": "446383", "Score": "0", "body": "@CodeWriter23 You're welcome :-) Although Nick's comment applies to this code https://codereview.stackexchange.com/questions/19438/upc-a-validation#comment136214_40959 - the $even_sum/$odd_sum logic is backwards." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-20T18:35:52.837", "Id": "229397", "ParentId": "19438", "Score": "2" } } ]
{ "AcceptedAnswerId": "229397", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-12-09T20:51:09.967", "Id": "19438", "Score": "4", "Tags": [ "algorithm", "php", "validation", "checksum" ], "Title": "UPC-A validation" }
19438
<p>I am building a time tracking application and my requirement says that any hours past 40 total should be counted as overtime and not regular hours.</p> <p>Which function is more clear? What can be done to clarify the function? Even the second one at ~ 10 lines seems wordy</p> <h1>Option #1</h1> <pre><code>function calculateOvertime(days) { var totalHours = 0; var over40 = false; return $.map(days, function(hours) { var ot = 0; totalHours += hours; if (totalHours &gt; 40 &amp;&amp; !over40) { ot = totalHours - 40; hours = hours - ot; over40 = true; } else if (over40) { ot = hours; hours = 0; } return { reg: hours, ot: ot}; }) } calculateOvertime([16,16,16,16]); </code></pre> <h1>Option #2</h1> <pre><code>function calculateOvertime(days) { var hoursUntilOT = 40; return $.map(days, function(hours) { var ot = 0; hoursUntilOT -= hours; if (hoursUntilOT &lt; 0) { ot = hoursUntilOT * -1; hours = hours - ot; hoursUntilOT = 0; } return { reg: hours, ot: ot}; }) } calculateOvertime([16,16,16,16]); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T01:11:07.470", "Id": "31140", "Score": "0", "body": "Does it need to be on a day-by-day basis? If overtime is defined here as > 40 hrs on a weekly basis, why not just sum the week's hours, and get \"40 regular, 24 overtime\" total. This code assumes the first two days are just \"regular workdays\", the 3rd is an 8 hour day plus overtime, and the 4th is all-overtime. In reality there'd be overtime _each_ day, wouldn't there? Alternatively, define overtime as > 8 hrs _per day_. It just seems random to do per-day calculation when the overtime is defined per-week." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T02:25:41.437", "Id": "31141", "Score": "0", "body": "Thanks for the reply. Yes, it needs to be on a day-by-day basis as its displayed for each day of the week" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T13:18:08.870", "Id": "31159", "Score": "0", "body": "...so again, why not define overtime as anything over 8 hours in a day? Again, if your workday is 9am to 5pm, but you work from 9am to 9pm, you've worked 8 regular hours, and 4 overtime. Yet your code could say that you've worked 12 regular hours with no overtime (wrong), or that everything is overtime (also wrong)." } ]
[ { "body": "<p>You can accomplish your task using only core Javascript, with no reference to JQuery code, in about that many lines. JQuery is overkill for this task. </p>\n\n<p>I applied the following changes to make your code more readable:</p>\n\n<ol>\n<li>Reduced knowledge required to understand it (removed JQuery).</li>\n<li>Reduced the complex portions (see <code>iCurrentOvertime</code>).</li>\n<li>Added Hungarian notation; i.e. prepending integers with \"i\", arrays with \"a\", etc.</li>\n<li>Encased added values together within parentheses (e.g. <code>iCurrentHours+iTotalHours</code> becomes <code>(iCurrentHours+iTotalHours)</code>).</li>\n</ol>\n\n<p>The new code is below:</p>\n\n<pre><code>function calculateOvertime(days) {\n var aHours = [];\n var iTotalHours = 0;\n for(var i=0;i&lt;days.length;i++){\n var iCurrentHours = days[i];\n var iNewHours = (iCurrentHours+iTotalHours);\n var iCurrentOvertime = Math.max(0,(iNewHours - Math.max(iTotalHours,40)));\n iTotalHours = iNewHours;\n aHours.push({\n reg: (iCurrentHours - iCurrentOvertime),\n ot: iCurrentOvertime\n });\n }\n return aHours;\n}\ncalculateOvertime([16,16,16,16]);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T04:22:47.203", "Id": "19445", "ParentId": "19439", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-09T21:28:00.343", "Id": "19439", "Score": "1", "Tags": [ "javascript", "functional-programming" ], "Title": "mapping & loops - counting up or counting down" }
19439
<p>I wrote a function in Scala to find out and return a loopy path in a directed graph.</p> <p>One of the arguments is a graph presented in an adjacent list, and the other is a start node. It returns a pair including a loopy path by a list of nodes.</p> <p>I wonder if there are more elegant ways of doing this.</p> <pre><code> def GetACycle(start: String, maps: Map[String, List[String]]): (Boolean, List[String]) = { def explore(node: String, visits: List[String]): (Boolean, List[String]) = { if (visits.contains(node)) (true, (visits.+:(node)).reverse) else { if (maps(node).isEmpty) (false, List()) else { val id = maps(node).indexWhere(x =&gt; explore(x, visits.+:(node))._1) if (id.!=(-1)) explore(maps(node)(id), visits.+:(node)) else (false, List()) } } } explore(start, List()) } </code></pre> <p>I felt I had to use the <code>indexWhere</code> in this situation, but I suppose it would have other ways to do that.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T14:33:20.830", "Id": "31162", "Score": "0", "body": "I am not familiar with scala. If the question is about the algorithm, yes there are some interesting ones. Start here: http://ostermiller.org/find_loop_singly_linked_list.html go there http://en.wikipedia.org/wiki/Cycle_detection or there: http://stackoverflow.com/questions/546655/finding-all-cycles-in-graph and continue with any scientific research for `cycle detection` (+ graphs). The Tortoise and Hare algorithm could be called short and easy while still valid. If this counts for elegant, you may give it a try." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T14:42:07.597", "Id": "31163", "Score": "0", "body": "@tb, I will look into these. Thanks for your suggestions! Fantastic!" } ]
[ { "body": "<p>You should use an array to check if you have already visited a node and not <code>visits.contains(node)</code>, it would give you the answer in constant time instead of linear time.</p>\n\n<p>The overall complexity of your algorithm is exponential. For instance, if you run your algorithm on this graph:</p>\n\n<pre><code>0 -&gt; 1, 2, ..., n\n1 -&gt; 2, ..., n\n...\n</code></pre>\n\n<p>where there are <code>n</code> nodes and there are edges from <code>i</code> to <code>j</code> iff <code>i&lt;j</code> then the node <code>i</code> will be explored <code>2^i</code> times.</p>\n\n<p>Again you can solve this problem using an array (one array for all nodes) to ensure that each node is explored at most one time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T15:36:02.437", "Id": "19465", "ParentId": "19447", "Score": "1" } } ]
{ "AcceptedAnswerId": "19465", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T05:31:01.217", "Id": "19447", "Score": "4", "Tags": [ "algorithm", "scala", "graph" ], "Title": "Finding and returning a loopy path in a directed graph" }
19447
<p>I'm trying to come up with the most basic example of making a JQuery slide show where you click on the current image you're viewing and you cycle through a gallery of photos. I know its probably not the most basic example, because if I want to add a new image I have to code more JQuery. Is there a more abstract approach where I don't have to code JQuery in terms of div id's and let classes take care of the work? Here is my JQuery </p> <pre><code>$(document).ready(function() { $("#pic1").click(function() { $("#pic1").hide(); $("#pic2").show(); }); $("#pic2").click(function() { $("#pic2").hide(); $("#pic3").show(); }); $("#pic3").click(function() { $("#pic3").hide(); $("#pic1").show(); }); }); </code></pre> <p>The rest is here. <a href="http://jsfiddle.net/XjdTX/3/" rel="nofollow">http://jsfiddle.net/XjdTX/3/</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T13:41:48.087", "Id": "31160", "Score": "0", "body": "You should include the main code in the question." } ]
[ { "body": "<p>This should do the trick:</p>\n\n<p><a href=\"http://jsfiddle.net/XjdTX/11/\" rel=\"nofollow\">http://jsfiddle.net/XjdTX/11/</a></p>\n\n<p>I changed the <code>&lt;div id=\"slideframe\"&gt;...&lt;/div&gt;</code> to use a class instead. This will allow you to have multiple slide shows functioning off the same code, as shown in the jsFiddle. For toggling through the pics, the <code>pic</code> class is used and cycles based on the index of the clicked image. </p>\n\n<p>There is also code in the jsFiddle that will fade the images instead of just toggling their visibility.</p>\n\n<pre><code>$(document).ready(function() {\n\n $('.slideframe').each(function() {\n\n var $pics = $(this).find('.pic'),\n max = $pics.length;\n\n $pics.on('click.slideframe', function(e) {\n var idx = $pics.index(this);\n if (idx &lt; 0) {\n return false;\n }\n $(this).hide();\n $pics.eq(++idx % max).show();\n });\n });\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T13:44:06.070", "Id": "31161", "Score": "3", "body": "You should use `$pics.on('click', handler)` instead of `$pics.click(handler)`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T08:39:26.423", "Id": "19450", "ParentId": "19448", "Score": "3" } }, { "body": "<pre><code>$(document).ready(function() {\n // set display:none for all &lt;img&gt; tags except the first\n $('.pic:gt(0)').hide();\n\n // stores all matches for class=\"pic\"\n var $slides = $('.pic');\n\n $slides.click(function(){\n // stores the currently-visible slide\n var $current = $(this); \n if( $current.is($slides.last()) ) {\n $current.hide();\n $slides.first().show();\n } \n // else, hide current slide and show the next one\n else {\n $current.hide().next().show(); \n }\n });\n});\n</code></pre>\n\n<p><strong>Edit</strong> Changed to include element caching, as per ANeves's suggestion.</p>\n\n<p>Full code here: <a href=\"http://jsfiddle.net/XRpeA/\" rel=\"nofollow\">http://jsfiddle.net/XRpeA/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T16:13:18.247", "Id": "31168", "Score": "1", "body": "You could suggest elements caching (e.g. `$(this)`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T01:16:46.067", "Id": "31176", "Score": "0", "body": "@ANeves, I am about as far from being comfortable with JS as people come, so thanks for the suggestion. Did you mean something like this: http://jsfiddle.net/ta4YU/2/ ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T11:02:01.863", "Id": "31190", "Score": "1", "body": "Precisely that!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T09:19:34.550", "Id": "19451", "ParentId": "19448", "Score": "3" } } ]
{ "AcceptedAnswerId": "19450", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T06:00:59.017", "Id": "19448", "Score": "0", "Tags": [ "javascript", "jquery", "html", "html5" ], "Title": "JQuery Slide Show Simplification" }
19448
<p>I've written an extension method to truncate strings:</p> <pre><code>/// &lt;summary&gt; /// Returns the string, or a substring of the string with a length of &lt;paramref name="maxLength"/&gt; if the string is longer than maxLength. /// &lt;/summary&gt; /// &lt;param name="maxLength"&gt;The maximum length of the string to return.&lt;/param&gt; /// &lt;exception cref="ArgumentException"&gt;If &lt;paramref name="maxLength"/&gt; is smaller than zero, an ArgumentException is raised.&lt;/exception&gt; /// &lt;![CDATA[ Documentation: /// If the string is null or an empty string, the input is returned. /// If the string is shorter than or equal to maxLength, the input is returned. /// If the string is longer than maxLength, the first N (where N=maxLength) characters of the string are returned. /// ]]&gt; public static String Truncate(this String input, int maxLength) { if (maxLength &lt; 0) { throw new ArgumentException("Must be &gt;= 0", "maxLength"); } if (String.IsNullOrEmpty(input) || input.Length &lt;= maxLength) { return input; } return input.Substring(0, maxLength); } </code></pre> <p>I have written these test cases:</p> <pre><code>[TestFixture] public class TruncateTests { String longString = "ABC"; String shortString = "A"; String nullOrEmptyString = null; String output = ""; [Test] public void LessThanOrEqual() { // If input is shorter than or equal to maxLength, the input is returned. output = longString.Truncate(longString.Length + 5); Assert.AreEqual(longString, output); output = longString.Truncate(longString.Length); Assert.AreEqual(longString, output); } [Test] public void GreaterThan() { // If input is longer than maxLength, the first N (where N=maxLength) characters of input are returned. output = longString.Truncate(1); Assert.AreEqual(shortString, output); } [Test] public void NullOrEmpty() { // If input is null or an empty string, input is returned. output = nullOrEmptyString.Truncate(42); Assert.AreEqual(output, nullOrEmptyString); nullOrEmptyString = ""; output = nullOrEmptyString.Truncate(42); Assert.AreEqual(output, nullOrEmptyString); } [ExpectedException(typeof(ArgumentException))] [Test] public void MaxLengthException() { // If maxLength is smaller than zero, an ArgumentException is raised. "".Truncate(-1); } //http://www.fileformat.info/info/unicode/char/1f3bc/index.htm string multiByteString = "\x1F3BC"; [Test] public void MultiByte() { Assert.IsTrue(multiByteString.Length == 2); output = multiByteString.Truncate(1); Assert.IsTrue(output.Length == 1); } } </code></pre> <p>Now how can I confirm that:</p> <ol> <li>The method <code>Truncate()</code> does what it is supposed to do?</li> <li>I have written test code to test al promises made?</li> <li>This test code follows practices and guidelines valid for unit testing? </li> </ol> <p>I'm especially curious about the last one. I've written a few tests in my time, but I'm never sure whether I'm testing enough and not too much at the same time. Can anyone shed a general light on this and maybe point me towards invaluable resources about unit testing?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T11:43:06.523", "Id": "31148", "Score": "0", "body": "I needed this for UI strings, so I made a version that adds ellipsis: https://gist.github.com/4250125" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T11:46:01.670", "Id": "31149", "Score": "0", "body": "Why do you throw when `maxLength < 0`, but not throw when someone calls `((string)null).Truncate(2)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T11:49:04.123", "Id": "31150", "Score": "0", "body": "@ANeves that's a design decision. I want to be able to run this methods on strings that may be null or of arbitrary length." } ]
[ { "body": "<ol>\n<li><p>About the function comment: </p>\n\n<p>You're over-complicating the summary. As of how I understand the function does <code>Get the first &lt;paramref=\"maxLength\"&gt; characters</code> as a summary. Special conditions are mentioned bellow. Those should be simplified as well. </p></li>\n<li><p>For <code>maxLength</code> I'd check for min/max integer as well as for -1/0/1 (does the function behave correctly at the limits?)</p></li>\n<li><p>Check <code>input</code> for <code>null</code> and additionally for those combinations:</p>\n\n<ul>\n<li>input.length &lt; maxLength</li>\n<li>input.length = maxLength</li>\n<li>input.length > maxLength</li>\n</ul></li>\n<li><p>You're not testing your code when testing for MB-functionality.</p></li>\n<li><p>Test one thing at a time. If <code>NullOrEmpty</code> fails, how to you know which of those assertions failed? Does it fail if <code>input</code> is empty or if it is <code>null</code>?\\</p></li>\n<li><p>Remove comments, make the test-names more clear instead. Tests are simple and easy to understand (at least they should be :)). Safe your time of writing comments and improve the test instead. </p>\n\n<ul>\n<li>For most of the functions you're just repeating the behavior asserted. However this is already written down by the assertion itself. The comment just duplicates the code.</li>\n<li>In my opinion, test names should be speaking of what they do. <code>NullOrEmpty</code> doesn't state anything about what actually happens. <code>NullInputReturnsNull</code> and <code>EmptyInputReturnsEmptyString</code> do however. Furthermore speaking test-names can be used as a documentation (i.e testdox). </li>\n</ul></li>\n<li><p>When are you done? Never. Eventually you (or someone else) will find bugs, misbehavior, ... (e.g. during integration). It's more important to keep the tests up to date at those times as well.</p></li>\n</ol>\n\n<p><strong>Update</strong></p>\n\n<p><strong>On 2.</strong> I'm testing for MAX_INT because your promise is this functions accepts integer values between [0, MAX_INT]. Imagine at some time there is a <code>maxLength + 1</code> statement for some reason. As a rule of thumb: always test the border values of parameters. Further reading: <a href=\"http://en.wikipedia.org/wiki/Equivalence_partitioning\" rel=\"nofollow\">equivalence partitioning</a> and <a href=\"http://en.wikipedia.org/wiki/Boundary-value_analysis\" rel=\"nofollow\">boundary value analysis</a></p>\n\n<p><strong>On 3.</strong> That'd be four tests. You should split those.</p>\n\n<p><strong>On 4.</strong> The point is your are testing the c# library, not your code. You don't have any code dedicated for MB handling. What you are actually doing is testing the <code>Substring</code> method and <code>Length</code> property for MB handling. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T11:53:13.960", "Id": "31151", "Score": "0", "body": "I agree with you on 1, 5, 6 and 7. For 2: why should I check for int limitations? You _can't_ input `Int32.MaxLength + 1`, because that won't fit in the `int` parameter, so why would I want to check for that? I can indeed add a test for maxLength 0. The other cases I'm already testing. 3: see comment on question, I don't want to throw on input == null. I already test the other cases, in `LessThenOrEqual()`, I will split those up in separate methods. 4: I do, aren't I? I'm checking whether a multibyte (2) character gets split into the amount of characters I expect (1)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T12:32:56.167", "Id": "31153", "Score": "0", "body": "@codecaster: answered in my answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T12:45:17.407", "Id": "31154", "Score": "0", "body": "For 2: _\"Imagine at some time there is a maxLength + 1 statement for some reason.\"_ - there currently isn't, so why should I test for something I know will never happen? Just in case I add a +1, sometimes, somewhere, and then forget to add a test for it? Then how far must one go (which basically is the question I asked)? Can you elaborate on that? :-) For 4: I want to make sure _my method_ returns 1 character when I pass maxLength of 1, regardless of the input size (as long as it's >= 1)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T13:00:59.450", "Id": "31157", "Score": "0", "body": "For 4: What which lines are dedicated for this feature? None. If this test fails this is because of a c# core function fails the MB-handling, not your code does. Test only stuff you are responsible for, not your dependencies (and speaking strictly, `String` is a dependency which could be moked)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T13:04:24.883", "Id": "31158", "Score": "0", "body": "For 2: I guess we'll have to decide if we want whitebox or blackbox tests then... Assuming blackbox we don't know the code and \"have go guess\" (see links above). In whitebox tests we could skip those. Choosing the values to test for and how far to go (e.g. how to find \"easter-eggs\") ... tricky questions with no definite answer :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T11:26:21.067", "Id": "19454", "ParentId": "19453", "Score": "5" } } ]
{ "AcceptedAnswerId": "19454", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T10:10:49.600", "Id": "19453", "Score": "3", "Tags": [ "c#", "unit-testing" ], "Title": "Do these unit tests cover my method under test?" }
19453
<p>I have to implement a tree programming here. What I mean by tree programming is I have data stored in tree format. I have a parent object which will have child objects of same type the level of depth can go any long:</p> <p>I am able to store objects in tree format and also able to display properly. I am facing problems when I have to filter some child nodes based on some conditions:</p> <p>I have two question:</p> <ul> <li>is this code fine?</li> <li>is there anything wrong with design?</li> </ul> <p>Plus, how can I handle removing child node in a tree where the child can be in any place?</p> <pre><code>package menu; import java.util.List; public class Links{ private String nodeName; private List&lt;Links&gt; children; public List&lt;Links&gt; getChildren(){ return children; } public void setChildren( List&lt;Links&gt; children ){ this.children = children; } public String getNodeName(){ return nodeName; } public void setNodeName( String nodeName ){ this.nodeName = nodeName; } } package menu; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.chartis.gp.support.util.BrokerSupportUtil; import com.chartis.gp.support.vo.Links; import com.chartis.kernel.user.UserVO; import com.chartis.kernel.utils.Utils; public class Utility{ /* IN this class NavModel,CModel,CNode are some dummy classes * which help us read contents form some resources which are stored in dummy format * as Example of tree format stored data below is the example * tree * child1 * child2 * child3 * child3-1 * child:q * child:r * child:a * child3-2 * * child4 */ private static void populateChildLinks(NavModel navModel, Object objectNode, Links parent ){ try{ List&lt;Links&gt; childLinks = new ArrayList&lt;Links&gt;(); Iterator it = navModel.getChildren( objectNode ); while( it.hasNext() ){ NavNode node = (NavNode) it.next(); CNode contentNode = node.getContentNode(); Links links = new Links(); links.setNodeName( contentNode.getNodeName() ); childLinks.add( links ); if( navModel.hasChildren( node ) ){ populateChildLinks( node, links ); } } parent.setChildren( childLinks ); } catch( Exception e ){ } } private static Links createCategoryLinks(String categoryLinkName){ Links categoryLinks = new Links(); categoryLinks.setNodeName( categoryLinkName ); return categoryLinks; } public static Links setupLinks(String categoryLinkName,String name) { Links categoryLinks=null; CModel contentModel = new CModel(); NavModel navModel = new NavModel(); categoryLinks = Utility.createCategoryLinks( categoryLinkName); Object objectNode = contentModel.getLocator().findByUniqueName(name); if( objectNode != null ){ if( navModel.hasChildren( objectNode ) ){ populateChildLinks( navModel,objectNode, categoryLinks ); } } } // This is where i am facing issue once i get list of links of childs // i have to delete how can i find that particular child in the list // do i have to iterate through all the links and delete or which // way is better private static void filterLinks( Links parentNode, List&lt;Links&gt; childNodeList ){ List&lt;Links&gt; filteredResourceList = new ArrayList&lt;Links&gt;(); if( childNodeList!=null ){ Iterator&lt;Links&gt; childNodeIt = childNodeList.iterator(); while( childNodeIt.hasNext() ){ Links childNode = (Links) childNodeIt.next(); if(childNode.getChildren().size() &gt;0 ){ filterLinks( childNode, childNode.getChildren() ); } boolean removeNode = filterContents( childNode); if(! removeNode ){ filteredResourceList.add( childNode ); } } } Iterator&lt;Links&gt; filteredResourceIt = filteredResourceList.iterator(); while( filteredResourceIt.hasNext() ){ Links childNode = (Links) filteredResourceIt.next(); parentNode.getChildren().remove( childNode ); } } // Let us consider this as some dummy method which returns true or false based on some conditions private static boolean filterContents( menu.Links childNode ){ return false; } } package menu; public class TreeDisplay{ public static void main( String[] args ){ Links link = Utility.setupLinks( "SomeName", "ResiyrbceBane" ); Utility.filterLinks( link, link.getChildren() ); } } </code></pre> <p>Once I have a list of objects, I have to delete since it is tree object. How canI delete a child? I know I have to do a recursive search, but how can I do that? Which way will I delete? In the above tree structure where I have commented in the code, how can I delete child:q?</p>
[]
[ { "body": "<p>It is not possible to test your classes, because of:</p>\n\n<pre><code>import com.chartis.gp.support.util.BrokerSupportUtil;\nimport com.chartis.gp.support.vo.Links;\nimport com.chartis.kernel.user.UserVO;\nimport com.chartis.kernel.utils.Utils;\n</code></pre>\n\n<p>But ok, the general idea is ( if we want to use recursion):</p>\n\n<pre><code>remove(child, tree):\n if tree.isLeaf: return false\n if tree.hasChild(child): tree.removeChild(child); return true;\n for all children of tree as subtree:\n if remove(child, subtree): return true;\n return false;\n</code></pre>\n\n<p>Methods you will most probably need:</p>\n\n<pre><code>public void addChild(Links child)\n{\n children.add(child);\n}\n\npublic boolean hasChild(Links child)\n{\n return children.contains(child);\n}\n\npublic boolean removeChild(Links child)\n{\n return children.remove(child);\n}\n\npublic boolean isLeaf()\n{\n return children.size() &lt;= 0;\n}\n\n@Override\npublic int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((nodeName == null) ? 0 : nodeName.hashCode());\n return result;\n}\n\n@Override\npublic boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n Links other = (Links) obj;\n if (nodeName == null) {\n if (other.nodeName != null)\n return false;\n }\n else if (!nodeName.equals(other.nodeName)) //hint: this only works if nodeName is unique! If not, use a unique static counter\n return false;\n return true;\n}\n</code></pre>\n\n<p>Take a look at some of the tree-classes of java to see some typical methods.</p>\n\n<p>And your method could look like:</p>\n\n<pre><code>public static boolean removeChildFromTree(Links child, Links tree)\n{\n if (tree.isLeaf()) //we are at a leave, we can not delete any children anymore\n return false;\n if (tree.hasChild(child)) //we found it, quickly delete it\n return tree.removeChild(child);\n //we have to search all children\n for (Links subTree : tree.getChildren())\n {\n if (removeChildFromTree(child, subTree)) //try to delete on subtree\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>Edit: Just to point out, this code is not for efficiency. It is written for clarity. Do not care about efficiency before you really have to.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T05:34:31.423", "Id": "31180", "Score": "0", "body": "Thank you for the ans-were can you kindly let me know why do we have to override equals and hashcode mehtods" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T09:05:55.343", "Id": "31185", "Score": "1", "body": "You need to override equals, if two different trees with the same content should be considered equal (the default implementation tests only for reference equality). For hashCode, see the remarks in the API doc: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals%28java.lang.Object%29" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T13:01:32.373", "Id": "31195", "Score": "0", "body": "Just a small addition to the comment from @Landei. The method `hasChild` calls the `contains` method from `List`. As one can expect, to know if something is inside a list, each element must be checked if it is equal to the given element. The contract is specified in the Java API: http://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains(java.lang.Object)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T14:55:11.143", "Id": "19463", "ParentId": "19455", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T11:32:03.227", "Id": "19455", "Score": "4", "Tags": [ "java", "algorithm", "recursion", "tree" ], "Title": "Recursive search to delete n'th child in tree" }
19455
<p>This is a try at implementing integers in <a href="http://www.idris-lang.org/" rel="nofollow">Idris</a>. Any advice or comments are most welcome.</p> <pre><code>-- tries to implement integers using fold and a generalized notion of 'reduction' instead of -- utilizing recursion explicitly in all operations./ -- maximum (reasonable) code reuse, information hiding and conciseness is emphasized through -- generalized mechanisms, particularly hiding the internal representation and avoiding excessive -- pattern matchings. -- integers are interpreted as distances from 0 on the negative or positive sides of the -- axis. 'reducing' (`fold` and `loop`) tries to (recursively) reach `Zero` which means -- either `suc` or `pred` depending on the sign (`bck`). module Z -- an integer has a sign (P or N) and a distance from 0 (the Nat part with a little quirk*) -- *the little quirk: -- if `P n` == +n and `N n` == -n then both `P O` (+0) and `N O` (-0) would represent 0 which is terrible -- since this should be taken care of throughout the module so I got smart, heeded the elders -- advice and decided to interpret n to mean n+1 in `P n` and `N n`. this way `P 0` means +1 and `N 2` means -3. -- so far only `Cast Z Int instance`, `pred` and `suc` had to pay. other parts of the module are -- totally agnostic to this quirk which probably means it is the right approach. data Z = P Nat | N Nat | Zero data Sign = pos | neg | zro -- picks an operation and performs it on `n` according to its sign and distance from 0 -- this is a powerful abstraction since many functions could be defined over it total match : (n : Z) -&gt; (zero : a) -&gt; (positive : Nat-&gt;a) -&gt; (negative : Nat-&gt;a) -&gt; a match Zero zero _ _ = zero match (P n) _ positive _ = positive n match (N n) _ _ negative = negative n -- same as `match` but works on Nats -- pay attention that input (`n`) comes last here -- because `nmatch` is used in situations that is more -- convenient with this arrangement total nmatch : (zero : a) -&gt; (nonzero : Nat-&gt;a) -&gt; (n:Nat) -&gt; a nmatch zero _ O = zero nmatch _ nonzero (S k) = nonzero k -- move left total pred : Z -&gt; Z pred n = match n (N O) (nmatch Zero P) (N . S) -- move right total suc : Z -&gt; Z suc n = match n (P O) (P . S) (nmatch Zero N) -- converts a constant of type `a` to a function that accepts a `b` and returns an `a` -- useful in places that expect a function but a simple value would suffice. -- parameters `a` and `b` make this mechanism very flexible. instance Cast a (b-&gt;a) where cast c = (\x=&gt;c) -- sign of an integer total sgn : Z -&gt; Sign sgn n = match n zro (cast pos) (cast neg) -- employs the above Cast to prevent writing (\n=&gt; ...) -- distance from Zero as a positive `Z`. contrast with `match` arguments that receives the same thing as a `Nat` total abs : Z -&gt; Z abs n = match n Zero P P -- negation total ngt : Z -&gt; Z ngt n = match n Zero N P -- transforms `n` depending on its sign -- basically `match` but passes the whole `n` instead of it's distance, effectively -- removing duplication in such functions as `fwd` and `bck` total caseOnSgn : (n:Z) -&gt; (zero:a) -&gt; (positive : Z-&gt;a) -&gt; (negative : Z-&gt;a) -&gt; a caseOnSgn n zero positive negative = match n zero (positive . P) (negative . N) -- move one number away from Zero total fwd : Z -&gt; Z fwd n = caseOnSgn n Zero suc pred -- move one number towards Zero -- since Zero is the base case for almost all functions operating on integers, this -- effectively defines the reducing mechanism for the whole Z as demonstrated in `fold` total bck : Z -&gt; Z bck n = caseOnSgn n Zero pred suc -- folding from Zero towards `n` -- uses `bck` instead of explicit pattern matching on `n` thus eliminating -- duplication , resulting in a more point-free style implementation %assert_total total fold : (i : Z) -&gt; (f: Z-&gt;Z-&gt;Z) -&gt; (n:Z) -&gt; Z fold i _ Zero = i fold i f n = let acc = fold i f (bck n) in f acc n -- `acc` introduced for clarity -- like fold but ignores the index -- useful in situations where the intermediate indices are irrelevant (`add`) loop : (i:Z) -&gt; (f:Z-&gt;Z) -&gt; (n:Z) -&gt; Z loop i f n = fold i (\acc,index=&gt;f acc) n -- just discards the `index` -- addition -- very simple and expressive interpretation of addition -- m+n means : -- moving `n` units to the right from `m` if `n` is positive -- moving `n` units to the left from `m` if `n` is negative -- or just `m` if `n` is Zero add : Z -&gt; Z -&gt; Z add n m = caseOnSgn m n (loop n suc) (loop n pred) -- `suc` : move to the right, `pred` : move to the left -- subtraction -- n-m = n + (-m) sub : Z -&gt; Z -&gt; Z sub n m = add n (ngt m) instance Cast Z Int where cast Zero = 0 cast (P k) = cast {to=Int} (S k) -- (S k) =&gt; the little quirk, see definition of `Z` cast (N k) = -1 * cast {to=Int} (S k) instance Show Z where show n = show $ cast {to=Int} n instance Show Sign where show zro = "0" show pos = "+" show neg = "-" </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-20T23:40:25.020", "Id": "135173", "Score": "1", "body": "You might want to use [Literate Haskell](https://www.haskell.org/haskellwiki/Literate_programming) if you write this many comments." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T11:46:34.463", "Id": "19456", "Score": "1", "Tags": [ "haskell", "functional-programming" ], "Title": "Integer implementation in Idris" }
19456
<p>This is a working example that I am trying to improve. </p> <p>Throughout the application I am working on one of the requirements was to have tooltips everywhere. However the customer wanted the ability to see a "Summary" of these tooltips and be able to manage them from a single location.</p> <p>What I ended up doing is creating a new class called FormatToolTip.js</p> <pre><code>function FormatToolTip() { var self = this; amplify.request.define("toolTipListing", "ajax", { url: "resources/prototype/tooltips.json", dataType: "json", type: "GET" }); self.ToolTipId = "ToolTipId"; self.allToolTips = "ToolTips"; self.init = function () { amplify.request({ resourceId: "toolTipListing", success: function (data) { amplify.store(self.allToolTips, data.toolTips); }, error: function () { } }); }; self.buildToolTip = function (helpId) { var toolTipList = amplify.store(self.allToolTips); for (var i = 0; i &lt; toolTipList.length; i++) { var val = toolTipList[i]; if (helpId == val.id) { text = val.text; return text; } } return amplify.store(self.ToolTipId); }; self.setToolTipId = function (toolTipId) { if (toolTipId != undefined || toolTipId != null) { amplify.store(self.ToolTipId, toolTipId); } }; self.init(); } </code></pre> <p>I wanted everything to be based off a class I assign to the element. Here is an example of the format I used. </p> <pre><code>&lt;a class="withToolTip" helpid='1010' href="#" data-placement="right"&gt;&lt;/a&gt; </code></pre> <p>From there it can be initialized. </p> <pre><code> &lt;script type="text/javascript"&gt; $(document).ready(function () { $('.withToolTip').tooltip(); var toolTip; toolTip = new FormatToolTip(); function init(){ $('.withToolTip').each(function(){ var toolTipData; toolTipData = toolTip.buildToolTip($(this).attr('helpid')); $(this).attr('data-original-title',toolTipData); }); } init() }); &lt;/script&gt; </code></pre> <p>To polish off the look and feel I added some CSS and a background image for the element.</p> <pre><code>.withToolTip{ background-image:url("images/help.png"); background-repeat: no-repeat; background-position: center; background-size: 20px; width: 20px; height: 20px; display: inline-block; vertical-align: middle; padding-left: 10px; } </code></pre> <p>I am looking to improve on my code. So suggestions would be awesome. </p>
[]
[ { "body": "<pre><code>function FormatToolTip() {\n \"use strict\";\n\n amplify.request.define(\"listTooltips\", \"ajax\", {\n url: \"resources/prototype/tooltips.json\",\n dataType: \"json\",\n type: \"GET\"\n });\n\n amplify.request({\n resourceId: \"listTooltips\",\n success: function (data) {\n amplify.store('tooltips', data.toolTips);\n }\n });\n\n // Get the tooltip from storage, given it's id\n this.buildToolTip = function (id) {\n var tips = amplify.store('tooltips');\n for (var i = 0, len = tips.length; i &lt; len; i++) {\n var val = tips[i];\n if (id == val.id) {\n return val.text;\n }\n }\n\n // This doesn't appear to be used?\n //return amplify.store(this.ToolTipId);\n };\n\n // Don't think this is used either\n /*\n this.setToolTipId = function (toolTipId) {\n if (toolTipId != undefined || toolTipId != null) {\n amplify.store(this.ToolTipId, toolTipId);\n }\n };\n */\n}\n</code></pre>\n\n<p>Just use a data attribute in your markup: <code>&lt;a href=\"#\" data-tip-id='1010' data-placement=\"right\"&gt;&lt;/a&gt;</code></p>\n\n<p>And initialize like so:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n $(document).ready(function () {\n var tips = $('[data-tip-id]');\n var toolTip = new FormatToolTip();\n\n tips.each(function(){\n var this = $(this);\n var data = toolTip.buildToolTip(this.attr('data-tip-id'));\n this.attr('title',data) // Set the title so .tooltip() works\n .tooltip(); \n });\n });\n&lt;/script&gt;\n</code></pre>\n\n<p><em>*</em> Untested</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-15T05:52:55.320", "Id": "26194", "ParentId": "19458", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T13:59:29.707", "Id": "19458", "Score": "3", "Tags": [ "javascript", "jquery", "css", "twitter-bootstrap" ], "Title": "Improving Tooltips with json data" }
19458
<p>As a learning exercise, I'm developing my own PHP framework. I'm looking for a way to "load views" (kinda like CodeIgniter does it), without polluting my general scope. </p> <p>I came up with the following, basic, example: <pre><code>$data['test'] = 'Hello world'; $str = load_view($data, true); echo $str; function load_view($data, $store = false) { extract($data); ob_start(); include('view.php'); if($store) return ob_get_clean(); else ob_end_flush(); } // End of file </code></pre> <p>view.php<br> <code>&lt;p&gt;&lt;?php echo $test; ?&gt;&lt;/p&gt;</code></p> <p>I could also use <code>load_view($data)</code>, which would output the contents of view.php immediately. </p> <p>Edit: I'm mostly worried about performance. As Peter pointed out, I'm aware that the function should be a class method that's seperate from the logic. </p>
[]
[ { "body": "<p>No this is an ugly way to do it.</p>\n\n<h2>extract() (PHP4 stuff in 2012/2013?)</h2>\n\n<p>The problem with exract() is that it's creating variables ionto the global hyperspace (oh God, why) where can exist (in localy also!) any other variable and can have name collisions and can overwrite the old values. Beside this you are losing the control over your code and it will be hard to maintain (debug, fix also) and to extend.</p>\n\n<h2>load_view()</h2>\n\n<p>Not always returns a value: in PHP this is okay but in general programming it's a bad habit. I do one thing in a case and in another one i do a complete different stuff in same function? And why am i in a function? How about a non-static class method where i know everything in my small environment?</p>\n\n<p><strong>Here is a small example of an idea:</strong></p>\n\n<h2>View class</h2>\n\n<pre><code>&lt;?php\nclass View {\n\n private $_file;\n public $Data;\n\n public function __construct($viewFile, array $data) {\n $this-&gt;_file = $viewFile();\n $this-&gt;Data = $data;\n }\n\n public function Render()\n {\n require $this-&gt;_file;\n }\n\n}\n</code></pre>\n\n<h2>Usage</h2>\n\n<p>In the view file:</p>\n\n<pre><code>&lt;ul&gt;\n&lt;?php\nforeach ($this-&gt;Data[\"rows\"] as $object) {\n echo \"&lt;li&gt;\";\n echo $object-&gt;Name;\n echo \"&lt;/li&gt;\";}\n?&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>The output buffer handling is never part of the view it self. There have to be some kind of ViewEngine which can handle this thing. One thing one responsibility.</p>\n\n<p>The problem with the example is that is's missing a whole lat infrastucture! In my MVC expiriment i have Controller, ControllerBuilder, ActionInvoker, abstract ActionResult, ViewResult a lot of other stuff what is necessary to get thing done. In my default IView implementation i have a Model \"property\" beside the ViewData, i can map a lot helper like Html or Url and any other and just then comes the others: RenderPartial(), RenderSection(), Section(), SectionStart(), SectionEnd(), Layout(); these are pointing to my current IViewEngine implementation which is handling all these stuff.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T15:24:18.883", "Id": "31164", "Score": "0", "body": "Honestly, I don't see how your example is better. Yes, you have put it in a class, which I would do as well, but didn't for the sake of keeping things simple.\n\nYour method also doesn't provide a way to return the output of the view to a string, it merely echoes it when calling the Render method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T15:45:31.673", "Id": "31165", "Score": "0", "body": "Also, I feel like it's very unclean to use stuff like $this->Data[\"rows\"] inside a view file. $this has no logical context there in my opinion, it would make much more sense to use $rows (that's why I used the extract function). Unless that's a huge memory hog/is bad for performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T17:54:26.010", "Id": "31170", "Score": "0", "body": "Made an edit to my answear to explain my thoughts." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T00:40:46.610", "Id": "31175", "Score": "1", "body": "@PeterKiss extract only imports into the scope it's used. In this case, he's using it inside a function so it is not importing the variables into the global scope." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T07:04:22.287", "Id": "31182", "Score": "0", "body": "Still loosing the control over the variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T09:26:30.173", "Id": "31188", "Score": "3", "body": "-1 . what control? How is the use of [extract](http://es.php.net/manual/en/function.extract.php) php4? Note that extract has a number of flags. I think taking a simple method and then saying the problem is it doesn't look like _your_ MVC class structure isn't helpful. forcing `$this->Data['x']` instead of `$x` only means more verbose view files, it doesn't offer benefits over the use of extract where extract is used in not-global-scope." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T18:55:55.113", "Id": "31210", "Score": "0", "body": "If someone will look into the view and will see a variable called $rows, he/she will not know where does it come from. Out from nowhere?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T14:24:32.420", "Id": "19462", "ParentId": "19460", "Score": "-2" } }, { "body": "<p>I don't see any huge problem with what you have - specifically the use of extract(). I doubt you'll notice any difference in either memory use or execution time. The caveats you should be aware of are:</p>\n\n<ol>\n<li><p>What happens if your $data array contains a key \"store\"? It will overwrite your $store argument.</p></li>\n<li><p>Although it would be unusual for view files to initialize variables, it's possible they could. In such cases, you'll have variable name collisions.</p></li>\n</ol>\n\n<p>A big advantage I see in passing the rendered view back as a string is that you can use views inside other views or layouts. Second, if you wish to test your controllers, you can assert things about the returned view. You might consider simply removing the second argument and always return a value - would make one less variable (to get collided with) and would leave you with one return type.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T09:33:47.127", "Id": "31189", "Score": "0", "body": "+1. as a simplistic method the code is fine - there's no value in the store argument though - just use `$foo = load_view($bar);` or `echo load_view($bar)` as appropriate. it's also exactly how [CakePHP](https://github.com/cakephp/cakephp/blob/master/lib/Cake/View/View.php#L910) does it. Should point at the warnings for [extract](http://es.php.net/manual/en/function.extract.php) though - it can be dangerous if used on untrusted data without using e.g. `EXTR_SKIP`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T01:00:52.480", "Id": "19475", "ParentId": "19460", "Score": "2" } }, { "body": "<p>I agree that its a better pattern to wrap your view logic in a class.</p>\n\n<p>Here is some code I whipped together tonight - It represents the simplest class I could devise that contains the minimum logic that I require in a view:</p>\n\n<ul>\n<li><p>Includes - Ability to include other views</p></li>\n<li><p>Captures - Ability to easily capture content within your view</p></li>\n<li><p>Layouts - Ability to inject data into a re-usable layout template</p></li>\n<li><p>Fetching - Ability to fetch view output instead of sending it to output buffer</p></li>\n<li><p>data - Ability to access the resulting data once the view is finished</p></li>\n</ul>\n\n<p>[edit] Refactored per conversation in comments regarding passing $data by reference.</p>\n\n<p><strong>View.php</strong></p>\n\n<pre><code>&lt;?php\n/**\n * Simple view class that supports includes, capturing, and layouts, as well\n * as retrieving rendered view content and resulting data.\n *\n * *NOTE* When a view uses a layout, the output of the view is ignored, as\n * as the view is expected to use capture() to send data to the layout.\n *\n * @author David Farrell &lt;DavidPFarrell@gmail.com&gt;\n */\nclass View implements ArrayAccess\n{\n /**\n * View file to include\n * @var string\n */\n private $file;\n\n /**\n * View data\n * @var array\n */\n private $data;\n\n /**\n * Layout to include (optional)\n * @var string\n */\n private $layout;\n\n /**\n * Constructor\n *\n * @param string $file file to include\n */\n public function __construct($file)\n {\n $this-&gt;file = $file;\n }\n\n /**\n * render Renders the view using the given data\n *\n * @param array $data\n * @return void\n */\n public function render($data)\n {\n $this-&gt;data = $data;\n $this-&gt;layout = null;\n\n ob_start();\n\n include ($this-&gt;file);\n\n // If we did not set a layout\n if (null === $this-&gt;layout)\n {\n // flush view output\n ob_end_flush();\n }\n // We set a layout\n else\n {\n // Ignore view output\n ob_end_clean();\n\n // Include the layout\n $this-&gt;include_file($this-&gt;layout);\n }\n }\n\n /**\n * fetch Fetches the view result intead of sending it to the output buffer\n *\n * @param array $data\n * @return string The rendered view content\n */\n public function fetch($data)\n {\n ob_start();\n $this-&gt;render($data);\n return ob_get_clean();\n }\n\n /**\n * get_data Returns the view data\n *\n * @return array\n */\n public function get_data()\n {\n return $this-&gt;data;\n }\n\n /**\n * include_file Used by view to include sub-views\n *\n * @param string $file\n * @return void\n */\n protected function include_file($file)\n {\n $v = new View($file);\n $v-&gt;render($this-&gt;data);\n $this-&gt;data = $v-&gt;get_data();\n }\n\n /**\n * set_layout Used by view to indicate the use of a layout.\n *\n * If a layout is selected, the normal output of the view wil be\n * discarded. The only way to send data to the layout is via\n * capture()\n *\n * @param string $file\n * @return void\n */\n protected function set_layout($file)\n {\n $this-&gt;layout = $file;\n }\n\n /**\n * capture Used by view to capture output.\n *\n * When a view is using a layout (via set_layout()), the only way to pass\n * data to the layout is via capture(), but the view can use capture()\n * to capture text any time, for any reason, even if the view is not using\n * a layout\n *\n * @return void\n */\n protected function capture()\n {\n ob_start();\n }\n\n /**\n * end_capture Used by view to signal end of a capture().\n *\n * The content of the capture is stored under $name\n *\n * @param string $name\n * @return void\n */\n protected function end_capture($name)\n {\n $this-&gt;data[$name] = ob_get_clean();\n }\n\n /* ArrayAccess methods */\n public function offsetExists($offset) { return isset($this-&gt;data[$offset]); }\n public function offsetGet($offset) { return $this-&gt;data[$offset]; }\n public function offsetSet($offset, $value) { $this-&gt;data[$offset] = $value; }\n public function offsetUnset($offset) { unset($this-&gt;data[$offset]); }\n\n}\n</code></pre>\n\n<p><strong>run.php</strong></p>\n\n<pre><code>&lt;?php\nrequire \"View.php\";\n\n$v = new View('view_main_simple.php');\n$fetch = $v-&gt;fetch(array('message' =&gt; 'Hello, world'));\nprint(\"Fetch result: {$fetch}\\n\");\n\n$v = new View('view_main_complex.php');\n$v-&gt;render(array('one' =&gt; 1, 'two' =&gt; 2, 'rows' =&gt; array('a','b','c')));\n\n$data = $v-&gt;get_data();\n\nprint(\"\\n\");\nvar_export($data);\n</code></pre>\n\n<p><strong>view_main_simple.php</strong></p>\n\n<pre><code>The message is: &lt;?php echo $this['message'] ?&gt;&lt;br/&gt;\n</code></pre>\n\n<p><strong>view_main_complex.php</strong></p>\n\n<pre><code>&lt;?php $this-&gt;set_layout('view_layout.php') ?&gt;\n&lt;?php $this-&gt;capture() ?&gt;\n one=&lt;?php echo $this['one'] ?&gt;&lt;br/&gt;\n &lt;?php $this-&gt;include_file('view_include.php') ?&gt;\n three=&lt;?php echo $this['three'] ?&gt;&lt;br/&gt;\n&lt;?php $this-&gt;end_capture('body') ?&gt;\n</code></pre>\n\n<p><strong>view_include.php</strong></p>\n\n<pre><code>two=&lt;?php echo $this['two'] ?&gt;&lt;br/&gt;\n&lt;?php $this['three'] = 3 ?&gt;\n&lt;ul&gt;\n &lt;?php foreach($this['rows'] as $row) { ?&gt;\n &lt;li&gt;&lt;?php echo $row ?&gt;&lt;/li&gt;\n &lt;?php } ?&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p><strong>view_layout.php</strong></p>\n\n<pre><code>&lt;html&gt;\n&lt;body&gt;\n&lt;pre&gt;\n&lt;?php echo $this['body'] ?&gt;\n&lt;/pre&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p><strong>Program Output</strong></p>\n\n<pre><code>Fetch result: The message is: Hello, world&lt;br/&gt;\n\n&lt;html&gt;\n&lt;body&gt;\n&lt;pre&gt;\n one=1&lt;br/&gt;\n two=2&lt;br/&gt;\n&lt;ul&gt;\n &lt;li&gt;a&lt;/li&gt;\n &lt;li&gt;b&lt;/li&gt;\n &lt;li&gt;c&lt;/li&gt;\n &lt;/ul&gt;\n three=3&lt;br/&gt;\n&lt;/pre&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n\narray (\n 'one' =&gt; 1,\n 'two' =&gt; 2,\n 'rows' =&gt; \n array (\n 0 =&gt; 'a',\n 1 =&gt; 'b',\n 2 =&gt; 'c',\n ),\n 'three' =&gt; 3,\n 'body' =&gt; ' one=1&lt;br/&gt;\n two=2&lt;br/&gt;\n&lt;ul&gt;\n &lt;li&gt;a&lt;/li&gt;\n &lt;li&gt;b&lt;/li&gt;\n &lt;li&gt;c&lt;/li&gt;\n &lt;/ul&gt;\n three=3&lt;br/&gt;\n',\n)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T18:57:14.380", "Id": "31211", "Score": "0", "body": "Do not use passing by reference: http://schlueters.de/blog/archives/125-Do-not-use-PHP-references.html ## Ha-ha my answer is similar to yours but i have -1 point. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T19:27:03.497", "Id": "31216", "Score": "0", "body": "Greetings @PeterKiss! You'll notice that the public functions render() and fetch() do NOT accept references, meaning that they act on a copy of the passed in $data - I then use references internally so that modifications to *MY* $data can be maintained across includes and layouts - I then offer that (possibly) modified $data back to the caller via getData(). So I never alter the user's personal $data, but do (carefully) manage references within my own scope for the benefit of the view (and the user, if they choose) - So I'll take my +1 back now please :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T19:55:48.613", "Id": "31219", "Score": "0", "body": "There is no need to do that hack. If you assign $data to $this->data in render then the do_render doesn't need any parameter. And why is there render and do_render? do_render is private you still calling it as public: (new View($file))->do_render($this->data);" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T20:27:29.827", "Id": "31222", "Score": "0", "body": "@PeterKiss - Your statement isn't fully correct as it doesn't address my need to allow includes to modify $data - But You are right in that I don't need to pass $data around by reference - I already had all the tools I needed, namely the getData() function (now renamed to get_data() for consistency. I have refactored the class to no longer pass $data by reference, merged do_render() into render(), and now reassign my local $data based on the result of the included view." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T07:37:59.217", "Id": "19480", "ParentId": "19460", "Score": "6" } }, { "body": "<p>One thing to note is that in MVC proper, views get their own data from the model. The view should be passed a model and call methods on it to access enterprise data. This makes the common extract($data); method redundant. </p>\n\n<p>A simplistic view API may be:</p>\n\n<p>$view = new View($model);\necho $view->render();</p>\n\n<p>If you enter templates into the equation then you could use $view = new View($model, $template); but the important thing to note is that the View does not get fed data by the controller in MVC. And although many web \"MVC\" frameworks take this approach, this is technically not MVC but PAC.</p>\n\n<p>I don't have enough rep to post images but see the image of MVC on the wikipedia article. You'll see the controller never interacts with the view.</p>\n\n<p>For more information on the MVC architecture see: <a href=\"http://st-www.cs.illinois.edu/users/smarch/st-docs/mvc.html\" rel=\"nofollow\">http://st-www.cs.illinois.edu/users/smarch/st-docs/mvc.html</a> , and <a href=\"http://www.itu.dk/courses/VOP/E2005/VOP2005E/8_mvc_krasner_and_pope.pdf\" rel=\"nofollow\">http://www.itu.dk/courses/VOP/E2005/VOP2005E/8_mvc_krasner_and_pope.pdf</a> </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T11:38:51.667", "Id": "19487", "ParentId": "19460", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T14:12:33.480", "Id": "19460", "Score": "9", "Tags": [ "php" ], "Title": "Is this a proper way of \"loading\" views in PHP?" }
19460
<p>I found a code on my computer that i wrote a while ago. It is based on an exercise from O'Reilly book <em><a href="http://shop.oreilly.com/product/9780596153823.do" rel="noreferrer">Programming the Semantic Web</a></em>. There is a class, that stores <a href="http://en.wikipedia.org/wiki/Resource_Description_Framework" rel="noreferrer">RDF triples</a>, that is data in the form subject-predicate-object:</p> <pre><code>class SimpleGraph: def __init__(self): self._spo = {} self._pos = {} self._osp = {} def add(self, (s, p, o)): # implementation details pass def remove(self, (s, p, o)): # implementation details pass </code></pre> <p>Variables <code>_spo</code>, <code>_pos</code>, <code>_osp</code> are different permutations of subject, predicate, object for performance reasons, and the underlying data structure is dictionary of dictionaries of sets like <code>{'subject': {'predicate': set([object])}}</code> or <code>{'object': {'subject': set([predicate])}}</code>. The class also has a method to yield triples that match the query in a form of a tuple. If one element of a tuple is None, it acts as a wildcard.</p> <pre><code>def triples(self, (s, p, o)): # check which terms are present try: if s != None: if p != None: # s p o if o != None: if o in self._spo[s][p]: yield (s, p, o) # s p _ else: for ro in self._spo[s][p]: yield (s, p, ro) else: # s _ o if o != None: for rp in self._osp[o][s]: yield (s, rp, o) # s _ _ else: for rp, oset in self._spo[s].items(): for ro in oset: yield (s, rp, ro) else: if p != None: # _ p o if o != None: for rs in self._pos[p][o]: yield (rs, p, o) # _ p _ else: for ro, sset in self._pos[p].items(): for rs in sset: yield (rs, p, ro) else: # _ _ o if o != None: for rs, pset in self._osp[o].items(): for rp in pset: yield (rs, rp, o) # _ _ _ else: for rs, pset in self._spo.items(): for rp, oset in pset.items(): for ro in oset: yield (rs, rp, ro) except KeyError: pass </code></pre> <p>You see, this code is huge, and i feel it could be more terse and elegant. I suspect the possible use of dicts here, where tuple (s, p, o) is matched with a certain key in this dict, and then the yield is done. But i have no idea how to implement it.</p> <p>How can i simplify this huge if-else structure?</p>
[]
[ { "body": "<p>You could gain some simplicity by breaking the task into two parts.</p>\n\n<p>Firstly, inspect the <code>None</code>ness of the parameters to figure out which dictionary to look into. Store the results in local variables. So something like:</p>\n\n<pre><code>if (should use _spo):\n data = self._spo\n order = [0,1,2]\nelif (should use _pos):\n data = self._pos\n order = [1,2,0]\nelse:\n ...\n</code></pre>\n\n<p>Secondly, use <code>order</code> and <code>data</code> to actually lookup the data.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T17:46:08.033", "Id": "19498", "ParentId": "19470", "Score": "3" } }, { "body": "<ul>\n<li><p>Set <code>args = (int(s != None), int(p != None), int(o != None))</code> [or <code>args = ''.join(map(str, (int(s != None), int(p != None), int(o != None))))</code>]</p>\n\n<p>Now <code>args</code> will be <code>(1, 0, 1)</code> [or <code>'101'</code>] if p is None and the other two aren't.</p></li>\n<li><p>Also, instead of using for loops you can use generator expressions to make the code more concise.</p></li>\n</ul>\n\n<hr>\n\n<pre><code>def triples(self, (s, p, o)):\n try:\n args = (int(s != None), int(p != None), int(o != None))\n if args == (1, 1, 1):\n #if o in self._spo[s][p]: #See sindikat's comment below\n # yield (s, p, o)\n return iter([(s, p, o)] if o in self._spo[s][p] else [])\n if args == (1, 1, 0):\n return ((s, p, ro) for ro in self._spo[s][p])\n if args == (1, 0, 1):\n return ((s, rp, o) for rp in self._osp[o][s])\n if args == (1, 0, 0):\n return ((s, rp, ro) for rp, oset in self._spo[s].items() for ro in oset)\n if args == (0, 1, 1):\n return ((rs, p, o) for rs in self._pos[p][o])\n if args == (0, 1, 0):\n return ((rs, p, ro) for ro, sset in self._pos[p].items() for rs in sset)\n if args == (0, 0, 1):\n return ((rs, rp, o) for rs, pset in self._osp[o].items() for rp in pset)\n if args == (0, 0, 0):\n return ((rs, rp, ro) for rs, pset in self._spo.items() for rp, oset in pset.items() for ro in oset)\n except KeyError:\n pass\n</code></pre>\n\n<p>Combining this with Winston's suggestion you get the following definition</p>\n\n<pre><code>def triples(self, (s, p, o)):\n try:\n args = (int(s != None), int(p != None), int(o != None))\n\n if args in [(1, 1, 1), (1, 1, 0), (1, 0, 0), (0, 0, 0)]:\n lookat = self._spo\n a1 = s; a2 = p; a3 = o;\n invperm = [0, 1, 2]\n if args in [(0, 1, 1), (0, 1, 0)]:\n lookat = self._pos\n a1 = p; a2 = o; a3 = s;\n invperm = [2, 0, 1]\n if args in [(1, 0, 1), (0, 0, 1)]:\n lookat = self._osp\n a1 = o; a2 = s; a3 = p;\n invperm = [1, 2, 0]\n\n permute = lambda x, p: (x[p[0]], x[p[1]], x[p[2]])\n\n if sum(args) == 3:\n #if a3 in lookat[a1][a2]: #See sindikat's comment below\n # yield permute((a1, a2, a3), invperm)\n return iter([permute((a1, a2, a3), invperm)] if a3 in lookat[a1][a2] else [])\n if sum(args) == 2:\n return (permute((a1, a2, ra3), invperm) for ra3 in lookat[a1][a2])\n if sum(args) == 1:\n return (permute((a1, ra2, ra3), invperm) for ra2, a3set in lookat[a1].items() for ra3 in a3set)\n if sum(args) == 0:\n return (permute((a1, a2, a3), invperm) for ra1, a2set in lookat.items() for ra2, a3set in a2set.items() for ra3 in a3set)\n except KeyError:\n pass\n</code></pre>\n\n<p>Although this is slightly longer, it is easier to maintain in the sense that if you feel that the dictionary to look at should be changed (for better performance) for some combination of input, then the modification is easily accomplished with the second definition.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-08T15:37:13.527", "Id": "32431", "Score": "1", "body": "using `yield` and `return` in a function in Python 2.7 throws `SyntaxError: 'return' with argument inside generator`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T03:13:43.603", "Id": "32491", "Score": "0", "body": "@sindikat Good catch. Edited to provide a workaround." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T12:17:16.160", "Id": "19527", "ParentId": "19470", "Score": "4" } } ]
{ "AcceptedAnswerId": "19527", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T19:00:27.527", "Id": "19470", "Score": "6", "Tags": [ "python", "hash-map" ], "Title": "Refactor deeply nested if-else" }
19470
<p>I have the following interface:</p> <pre><code>public interface ILogger { void Log(string message, string title, StatusType type, DateTime timestamp); IAsyncResult LogAsync(string message, string title, StatusType type, DateTime timestamp, AsyncCallback callback); void EndLogAsync(IAsyncResult result); } </code></pre> <p>Implemented as a file-based logger...</p> <pre><code>... public FileInfo LogFileInfo { get; internal set; } public void Log(string message, string title, StatusType type, DateTime timestamp) { lock (syncObj) { CheckLogFileSize(); //rotates LogFileInfo through numbered log files using (var stream = LogFileInfo.AppendText()) { stream.WriteLine(GetFormattedString(message, title, type, timestamp)); stream.Flush(); } } } public IAsyncResult LogAsync(string message, string title, StatusType type, DateTime timestamp, AsyncCallback callback) { var action = new Action&lt;string, string, StatusType, DateTime&gt;(Log); return action.BeginInvoke(message, title, type, timestamp, callback, action); } public void EndLogAsync(IAsyncResult result) { ((Action)result.AsyncState).EndInvoke(result); } </code></pre> <p>Notice the AsyncState parameter of BeginInvoke; I pass the delegate to its own invocation, so that I can reference it again on the flip side to end the invocation using the same delegate reference I called BeginInvoke on.</p> <p>The questions:</p> <ul> <li>Is it even necessary to keep the actual invoked delegate reference around, or can I simply new up another reference to that method in the EndLogAsync method?</li> <li>Is this an acceptable use of the AsyncState, given that I have no other use for it?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T05:54:42.430", "Id": "31181", "Score": "3", "body": "Is there any chance you're writing on .NET 4.5? And why not use existing logging solutions (NLog, log4net)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T14:37:24.940", "Id": "32633", "Score": "0", "body": "I think the implementation as it stands is the \"most correct\" using delegates/BeginInvoke/EndInvoke. Let it ride." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T14:29:44.930", "Id": "32699", "Score": "0", "body": "I really think that `LogAsync` should return a `Task` and therefore not accept a callback delegate. The APIs that consist `Begin*`/`End*` method pairs are ancient. By using `TPL` you can also let the implementers of `ILogger` interface use the new `async` features in .NET 4.5 more easily." } ]
[ { "body": "<p>To answer your question:</p>\n\n<ul>\n<li>you can access the delegate instance by reading <code>((AsyncResult)asyncResult).AsyncDelegate</code> property (see <code>Executing a Callback Method When an Asynchronous Call Completes</code> section of <a href=\"http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx\" rel=\"nofollow\">Calling Synchronous Methods Asynchronously</a>). But it will be easier to cache the instance of the delegate in a readonly field and use it in both methods.</li>\n<li>yes, you can use AsyncState however you want, and sometimes people use it for passing the delegate being invoked</li>\n</ul>\n\n<p>Note that you're using a separate thread (on a threadpool) each time you write something to log, so there will be contention between multiple threads if you write to log quickly enough. I would recommend using existing logging frameworks like <a href=\"http://nuget.org/packages/nlog\" rel=\"nofollow\">NLog</a> or <a href=\"http://nuget.org/packages/log4net\" rel=\"nofollow\">log4net</a> to avoid inventing a wheel.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T06:15:39.627", "Id": "19478", "ParentId": "19474", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T00:16:50.673", "Id": "19474", "Score": "2", "Tags": [ "c#", "asynchronous", "delegates" ], "Title": "Putting called delegate into AsyncState parameter - Pros/cons?" }
19474
<p>I am trying to remove files based on an array of prefixes, from files present in <code>sourceDirectory</code>. I am using <code>prefixFileFilter</code> to get the list of files with the prefixes. After that I am removing these from the original list.</p> <p>Is there any better approach?</p> <pre><code>package sriram; import java.io.File; import java.util.Arrays; import java.util.List; import org.apache.commons.io.filefilter.PrefixFileFilter; public class FileFilterExample { public static void main(String[] args) { excludeFiles(); } private static List&lt;String&gt; excludeFiles() { String[] filesToBeExcluded = { "sri", "agnew" }; File sourceDirectory = new File( "C:\\Users\\sriram\\workspace1\\sample\\src"); String[] fileNames = sourceDirectory.list(new PrefixFileFilter( filesToBeExcluded)); List&lt;String&gt; listOfFiles = Arrays.asList(fileNames); List&lt;String&gt; totalFiles = Arrays.asList(sourceDirectory.list()); totalFiles.removeAll(listOfFiles); return totalFiles; } } </code></pre>
[]
[ { "body": "<p>you can use java.io.FilenameFilter like:</p>\n\n<pre><code> final List&lt;String&gt; excludedFiles = Arrays.asList(filesToBeExcluded);\n File[] totalFiles = sourceDirectory.listFiles(new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name) {\n return !excludedFiles.contains(name);\n }\n });\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T07:40:07.980", "Id": "19481", "ParentId": "19476", "Score": "5" } }, { "body": "<p>Java 7 have had new features in <strong>nio2</strong> : <em>Files</em> et <em>Paths</em>, it manage also <em>Charset</em> problems.</p>\n\n<p>Here he sample of <em>DirectoryStream.Filter</em></p>\n\n<pre><code>static void newDirectoryStreamFilter(final Path file1, final Object filter1) {\n System.out.println(sepFin + \"\\nFiles.newDirectoryStreamFilter(\"\n + file1.getFileName() + \"), filtre: \" + filter1 + sepDeb);\n try {\n final DirectoryStream.Filter&lt;Path&gt; filter = new DirectoryStream.Filter&lt;Path&gt;() {\n @Override\n public boolean accept(final Path file1) throws IOException {\n for (String s : filesToBeExcluded)\n if (file1.startsWith(s)) return false;\n return true;\n }\n };\n try {\n for (final Path path : Files.newDirectoryStream(file1, filter)) {\n System.out.format(\"%10d %s\\n\", Files.size(path),\n path.toAbsolutePath());\n }\n } catch (final Exception e) {\n System.err.println(e.getMessage());\n }\n } catch (final Exception e) {\n System.err.println(e.getMessage());\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T08:48:27.660", "Id": "19485", "ParentId": "19476", "Score": "1" } }, { "body": "<p>As you are already using commons.io, you could use the <a href=\"http://commons.apache.org/io/api-release/org/apache/commons/io/filefilter/NotFileFilter.html\" rel=\"nofollow\">NotFileFilter</a>.</p>\n\n<p>and you will get:</p>\n\n<pre><code>private static List&lt;String&gt; getFileNamesWithoutExcludedPrefixes(File directory, String[] filesToBeExcluded) {\n return Arrays.asList(directory.list(new NotFileFilter(new PrefixFileFilter(filesToBeExcluded))));\n}\n</code></pre>\n\n<p>(Argument checking could be added) </p>\n\n<p>In your source:</p>\n\n<pre><code>totalFiles.removeAll(listOfFiles);\n</code></pre>\n\n<p>this can not work, because <code>Arrays.asList()</code> creates an immutable list.</p>\n\n<p>You could change the line that creates the list to:</p>\n\n<pre><code>new ArrayList&lt;String&gt;(...);\n</code></pre>\n\n<p>if you need mutability.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T14:48:33.120", "Id": "19492", "ParentId": "19476", "Score": "0" } } ]
{ "AcceptedAnswerId": "19481", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T03:06:49.913", "Id": "19476", "Score": "2", "Tags": [ "java" ], "Title": "File-exclusion based on an array of prefixes" }
19476
<p>There is my SSCCE to generate a value of discrete random variable. </p> <p><code>values</code> is set of value the RV can take and <code>procents</code> is equivalent to discrete pdf.</p> <p>Can you anticipate any issue with this snippet? </p> <pre><code>import java.util.Random; public class RandomTest { public static void main (String[] args) throws Exception { RandomTest rt = new RandomTest(); int[] values = {0, 1, 2}; int[] procents = {30, 60, 10}; for (int i=0; i &lt; 10; i++) { System.out.print(rt.discreteRV(values, procents) + " "); } } public int discreteRV (int[] values, int[] procents) throws Exception { if (values == null || procents == null) throw new Exception("Input parameters are null"); if (values.length != procents.length) throw new Exception("Input parameters length mismatch"); int sumProcents = 0; for (int i=0; i &lt; procents.length; i++) { if (procents[i] &lt; 0) throw new Exception("Negative procents are not allowed"); sumProcents += procents[i]; } if (sumProcents != 100) throw new Exception("Sum of procents is not 100"); int rand = new Random().nextInt(100); int left = 0, right = 0; for (int i=0; i &lt; procents.length; i++) { right += procents[i]; if (rand &gt;= left &amp;&amp; rand &lt; right) return values[i]; left = right; } throw new Exception(""); } } </code></pre>
[]
[ { "body": "<p>In general, this looks ok, i.e. it works.<br>\nI will put some notes on the lines of your method and will provide my suggestion after this. </p>\n\n<p>Spelling: procent is not an English word. Well, the compiler does not care, but the next programmer probably will.</p>\n\n<pre><code>public int discreteRV(final int[] values, final int[] procents) throws Exception {\n</code></pre>\n\n<p>To throw a exception of type <code>Exception</code> does not provide any help. The purpose of exceptions is to communicate errors.\nNoone knows the type of error from <code>Exception</code> and can do anything about it. They should be avoided in throw statements.</p>\n\n<pre><code> if (values == null || procents == null)\n throw new Exception(\"Input parameters are null\");\n</code></pre>\n\n<p>While checking your contract is a good idea, you do not gain anything here.<br>\nJava will throw a Nullpointer error with nearly the exact same message anyway if you try to access them.<br>\nAs long as there are no plans to do any special things, I would not waste lines on this.</p>\n\n<pre><code> if (values.length != procents.length)\n throw new Exception(\"Input parameters length mismatch\");\n</code></pre>\n\n<p>I would throw a runtime exception. <code>IllegalArgumentException</code> looks suitable here.</p>\n\n<pre><code> int sumProcents = 0;\n for (final int procent : procents) {\n if (procent &lt; 0)\n throw new Exception(\"Negative procents are not allowed\");\n sumProcents += procent;\n }\n</code></pre>\n\n<p>For exception: same as above.<br>\nFor check: This is not valid for all input.<br>\nConsider (and/or try:) <code>final int[] procents = { 1234567890, 1234567890, 1825831616 };</code><br>\nIf you want to check the input, check for both sides.</p>\n\n<pre><code> if (sumProcents != 100)\n throw new Exception(\"Sum of procents is not 100\");\n</code></pre>\n\n<p>For exception: same as above.</p>\n\n<pre><code> final int rand = new Random().nextInt(100);\n</code></pre>\n\n<p>If you use this method frequently, make it static (and/or even ThreadLocalRandom)</p>\n\n<pre><code> int left = 0, right = 0;\n for (int i = 0; i &lt; procents.length; i++) {\n right += procents[i];\n if (rand &gt;= left &amp;&amp; rand &lt; right)\n return values[i];\n left = right;\n }\n</code></pre>\n\n<p>The left check is not needed.<br>\nIf you check for something in between, support your readers:<br>\nInstead of <code>rand &gt;= left &amp;&amp; rand &lt; right</code> try to read <code>left &lt;= rand &amp;&amp; rand &lt; right</code></p>\n\n<pre><code> throw new Exception(\"\");\n</code></pre>\n\n<p>For exception: same as above. A <code>IllegalStateException</code> looks suitable here.</p>\n\n<pre><code>}\n</code></pre>\n\n<hr>\n\n<p>Suggestion:</p>\n\n<pre><code>public int discreteRV(final int[] values, final int[] percentages) {\n if (values.length != percentages.length)\n throw new IllegalArgumentException(\"values.length != percentages.length\");\n\n int sumPercentages = 0;\n for (int i = 0; i &lt; percentages.length; ++i) {\n if (percentages[i] &lt; 0)\n throw new IllegalArgumentException(\"Negative percentages are not allowed: percentages[\" + i + \"] = \" + percentages[i]);\n sumPercentages += percentages[i];\n if (sumPercentages &gt; 100)\n throw new IllegalArgumentException(\"Sum &gt; 100\");\n }\n\n if (sumPercentages != 100)\n throw new IllegalArgumentException(\"Sum of percentages is not 100\");\n\n final int randomIntUpTo100 = random.nextInt(100);\n int threshold = 0;\n for (int i = 0; i &lt; percentages.length; i++) {\n threshold += percentages[i];\n if (randomIntUpTo100 &lt; threshold)\n return values[i];\n }\n throw new IllegalStateException(\"No value found. rand:\" + randomIntUpTo100);\n}\n</code></pre>\n\n<p>More ideas:<br>\nThe arguments (arrays) could be replaced by an Object. This could make the handling easier. Depends on the use case.<br>\nThe two loops could be combined into one loop. You will loose the check for sum == 100 then.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T14:34:52.500", "Id": "19491", "ParentId": "19477", "Score": "1" } } ]
{ "AcceptedAnswerId": "19491", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T06:00:09.297", "Id": "19477", "Score": "2", "Tags": [ "java", "random", "generator" ], "Title": "Discrete random variable generator" }
19477
<p>I form DOM nodes as strings and append them to DOM tree like below using jQuery.</p> <pre><code>var dom = '&lt;div&gt;&lt;div style="display: inline-block"&gt;first name&lt;/div&gt;' '&lt;div style="display: inline-block"&gt;last name&lt;/div&gt;&lt;/div&gt;'; $("#contacts").append(dom); </code></pre> <p>The above code is a small sample. In most of my cases <code>dom</code> will hold big strings. </p> <p>When I recently read about JS performance tutorials, I saw this <a href="https://developers.google.com/speed/articles/optimizing-javascript" rel="nofollow">post</a>. It mentioned that this way of string concatenation is not a good practice. It mentioned the use of <code>.join()</code> instead of concatenation. That seems like an old post, so which one is efficient in these days?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T07:38:50.913", "Id": "31469", "Score": "0", "body": "this used to be the case, but these days they are saying concatenation is faster than join now." } ]
[ { "body": "<p>Strings are <a href=\"https://stackoverflow.com/questions/51185/are-javascript-strings-immutable-do-i-need-a-string-builder-in-javascript\">immutable</a>. It means that when you allocate memory while creating a string, you are not able to reallocate it.\nSo, this code:</p>\n\n<pre><code>var a = 'a';\na = a + 'bc';\n</code></pre>\n\n<p>Will allocate a new block of memory for 'a' variable, instead of reusing already allocated.</p>\n\n<p>When you do something like <code>'a' + 'b' + 'c' + 'd'</code> each concatenation allocates a new block of memory for every temporary string.</p>\n\n<p>When you use something like this:</p>\n\n<pre><code>var a = 'a';\na = [a, 'b', 'c'].join('');\n</code></pre>\n\n<p><code>join</code> function calculates memory for result string and allocates it only once for a complete string. </p>\n\n<p>As it is shown in the post that you mentioned, it is easier to handle and to avoid memory leaks in JS interpreter (it seems that IE6 and IE7 just not handle garbage collection for the first variant correctly).</p>\n\n<p>If you are interested for the speed of string concatenation for different browsers you can try and view it <a href=\"http://jsperf.com/string-concatenation\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>UPD: Not advocating <code>join</code>, just trying to explain why it was assumed as an optimized variant. As seen at jsPerf tests new browsers optimize string concatenation, so it is faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T12:43:32.187", "Id": "31192", "Score": "3", "body": "+1 for the updated note about how `join` isn't necessarily the best way to go with new browsers. Just ran the jsPerf test for Chrome 23.0.1271.95 and `join` was actually the slowest option." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T12:51:30.873", "Id": "31193", "Score": "1", "body": "Likewise in Firefox 12, join is quite a bit slower than any of the other options." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T17:44:57.297", "Id": "31208", "Score": "0", "body": "I do think there is some notion of size that needs to be considered, though. If one were to required to build a very large string incrementally over wildly varying code paths, at some point, pushing to a dynamic array (with reasonable growth rate implementation, which I assume most js. imps. have) and joining is always going to be faster than always conjoining. Suppose you have a string that's 10K characters long, and you want to create a new string appending 50 strings (10 characters each) to it. One way creates one 10K+500 characters at once, the other creates fifty 10K+ strings." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T08:07:39.093", "Id": "19483", "ParentId": "19479", "Score": "13" } }, { "body": "<p>Considering this <a href=\"http://jsperf.com/string-concatenation/32\">jsperf</a>, I would stick to</p>\n\n<pre><code>var a = \"asd\" + \"Foo\" + \"bAr\";\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T15:54:37.697", "Id": "31198", "Score": "0", "body": "The referenced test uses static strings which allows the JS engine to optimize the direct concatenation essentially into a NoOp. I tried to fix this to get results that are a bit more realistic: http://jsperf.com/string-concatenation/34 (Now Array.join wins on Firefox)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T08:23:03.830", "Id": "19484", "ParentId": "19479", "Score": "6" } }, { "body": "<p>Since it appears that you're working with the DOM you might want to think about using HTML fragments rather than strings. </p>\n\n<p>Here is one article on the subject:\n<a href=\"http://ejohn.org/blog/dom-documentfragments/\" rel=\"nofollow noreferrer\">http://ejohn.org/blog/dom-documentfragments/</a></p>\n\n<p>For your example, try using something like </p>\n\n<pre><code>$(\"&lt;div /&gt;\").css(\"display\",\"inline-block\").html(\"first Name\");\n</code></pre>\n\n<p>Another related question on using fragments vs. strings:\n<a href=\"https://stackoverflow.com/questions/2217409/jquery-best-practice-for-creating-complex-html-fragments\">https://stackoverflow.com/questions/2217409/jquery-best-practice-for-creating-complex-html-fragments</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T03:57:24.093", "Id": "19650", "ParentId": "19479", "Score": "1" } } ]
{ "AcceptedAnswerId": "19483", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T06:57:02.563", "Id": "19479", "Score": "10", "Tags": [ "javascript", "jquery", "performance", "html", "dom" ], "Title": "Efficient string concatenations with DOM" }
19479
<p>Can someone have a look at my script and maybe find something which can be optimized, as there shall be later 100 of it running.</p> <p>First of all this script shall be triggered once per day to receive data from a website into a sheet called "<em>getdata</em>". Some fields of "<em>getdata</em>" are transferred to "<em>blindcopy</em>" in a certain order. After that the found data shall be put into a sheet called "<em>monitoring</em>" by deleting first row of this sheet and filling the data from "<em>blindcopy</em>" to the row after the last row of "<em>monitoring</em>". These data is referenced to other sheets and finally to the sheet "<em>Output</em>". In the sheet "<em>Output</em>" some cells are colored depending on their relative difference to other cells (first set color of all text in E7:E10 red and if any cell in this range is bigger than its corresponding cell in column D then its text color is set to green).</p> <p>To not overflow the importXML command to the website on the beginning of the script the given URL is set to a cell and from there it is deleted at the end of the script again. This is because I do not want to call the importxml command everytime when I or others view the "<em>Output</em>" sheet, where none of the data is displayed coming directly via importxml, but it would be called, even if the data will not be displayed because the displayed data on "<em>Output</em>" is referencing to sheets where the importxml commands are executed (I hope I could explain this properly).</p> <p>OK, the script is working fine no problems with that. But as I want to use this script in 100 different spreadsheets triggered on different times of the day once every day I think I might run into "exceeding CPU time" error. And before that I want to make sure that I have stripped the script down to the minimum (like I changed the getValue to getValue*<em>s</em>*).</p> <p>It would be fine if someone could have a look into it, as there might be something to improve.</p> <pre><code>function myFunction() { // Open spreadsheet var docid = "some_long_strange_id_following_the_key=_in_the_URL_of_the_spreadsheet" var doc = SpreadsheetApp.openById(docid); var getsheet = doc.getSheetByName("getdata"); // Get url from C1 and insert to multiple-referenced cell C4 var cellreference = getsheet.getRange("C1"); var url = cellreference.getValue(); var cellreference = getsheet.getRange("C4"); cellreference.setValue(url); // Transferring data from "blindcopy" to "monitoring" var getsheet = doc.getSheetByName("monitoring"); getsheet.deleteRow(1) var sheetFrom = doc.getSheetByName("blindcopy"); var sheetTo = doc.getSheetByName("monitoring"); var lastRow = sheetFrom.getLastRow(); var cell = sheetFrom.getRange('A1').offset(lastRow, 0); var rowTo = sheetTo.getLastRow() + 1; for( var i = 1; i &lt; 33; i++) { sheetTo.getRange(rowTo, i).setValues( sheetFrom.getRange(lastRow, i).getValues()); } // Compare values1 to values2 for the coloring var s = doc.getSheetByName('Output'); var values1Rule1 = s.getRange('E7:H10').getValues(); var values2Rule1 = s.getRange('D7:D10').getValues(); var matchList = []; for (var row in values1Rule1) { for (var col in values1Rule1) { for (var row2 in values2Rule1) { if (values1Rule1[row][col] &gt;= values2Rule1[row][0]) matchList.push(s.getRange('E7').offset(row, col, 1, 1).getA1Notation()); }}} // Turn values1 red first s.getRange('E7:H10').setFontColor('RED'); // Then only turn matches green for (var m in matchList) s.getRange(matchList[m]).setFontColor('GREEN'); // delete C4 in "getdata" to avoid too much traffic to URL by importxml due to many lookups of "Output" var getsheet = doc.getSheetByName("getdata"); var blubb = "blockxmlimport"; var cellreference = getsheet.getRange("C4"); cellreference.setValue(blubb); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T12:52:48.107", "Id": "31194", "Score": "0", "body": "How long does it take to run now and does it take up lots of resouces?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T22:16:27.103", "Id": "31227", "Score": "0", "body": "How can I see how much resources it takes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T22:57:18.697", "Id": "31230", "Score": "0", "body": "Script runs round about 10 seconds" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T02:35:35.753", "Id": "66609", "Score": "0", "body": "`for (var row in values1Rule1) {\n for (var col in values1Rule1) {\n for (var row2 in values2Rule1) {` looks fishy" } ]
[ { "body": "<p>From my research, the slowest part of your script is by far <code>SpreadsheetApp.openById(docid)</code>, there is nothing much you can do about that. I am not sure how this script will behave once you have a 100 instances of it running, but my prediction is that it will be bad..</p>\n\n<p>Furthermore from a once over:</p>\n\n<ul>\n<li>You never use <code>cell</code> in <code>var cell = sheetFrom.getRange('A1').offset(lastRow, 0);</code></li>\n<li>You never use <code>row2</code> in <code>for (var row2 in values2Rule1) {</code>, I dont think you need it</li>\n<li>You only have to declare <code>cellreference</code> and <code>getsheet</code> once</li>\n<li>You should consider lowerCamelCasing: <code>getsheet</code> -> <code>getSheet</code>, <code>cellreference</code> -> <code>cellRefeference</code></li>\n<li><p><code>getSheet</code> is a terrible name, you should name the variable of the sheet:<br></p>\n\n<pre><code>var monitoringSheet = doc.getSheetByName(\"monitoring\");\n</code></pre></li>\n<li><p>You call <code>doc.getSheetByName(\"monitoring\")</code> twice, you could simply:<br></p>\n\n<pre><code>var toSheet = monitoringSheet; \n</code></pre></li>\n<li><p>Instead of reading one cell value and then assigning it to another, you could simply use <code>copyTo</code>:<br></p>\n\n<pre><code>var dataSheet = doc.getSheetByName(\"getdata\");\n// Get url from C1 and insert to multiple-referenced cell C4\nvar c1 = getsheet.getRange(\"C1\"),\nvar c4 = getsheet.getRange(\"C4\");\nc1.copyTo(c4);\n</code></pre></li>\n<li><p>At the end you already had a reference to C4, so you could simply:<br></p>\n\n<pre><code>c4.setValue( 'blockxmlimport' );\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T14:44:31.663", "Id": "40962", "ParentId": "19486", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T02:51:13.357", "Id": "19486", "Score": "3", "Tags": [ "javascript", "optimization", "beginner" ], "Title": "Complex spreadsheet script optimization" }
19486
<p>My aim is to avoid using threadpool threads for CPU bound work, thus avoiding a situation where IIS stops responding to new requests.</p> <p><strong>Can you see any problems with the code below?</strong> Is this a safe/clean approach? Can you offer any improvements?</p> <pre><code> private static ConcurrentQueue&lt;Job&gt; Jobs = new ConcurrentQueue&lt;Job&gt;(); static int threadCount = 0; private void QueueJob(Job job) { bool startQueue=false; lock(Jobs) { if (threadCount == 0) { Interlocked.Increment(ref threadCount); startQueue = true; } } Jobs.Enqueue(job); if (startQueue) { var t= new Thread(new ThreadStart(ConsumeQueue)); t.Start(); } } private void ConsumeQueue() { while (true) { lock (Jobs) { if (!Jobs.Any()) { Interlocked.Decrement(ref threadCount); return; } } Job j; var jobToDo = Jobs.TryDequeue(out j); if (jobToDo) { DoCPUBoundWork(j); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T14:40:53.183", "Id": "31196", "Score": "2", "body": "Er, `ConcurrentQueue<T>` is already thread-safe, I don't think you need to do any locking to access it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T18:59:02.950", "Id": "31212", "Score": "0", "body": "@JesseC.Slicer: you would likely need to lock if you need some guarantee of state between two consecutive invocations of expressions {X,Y} when that state dependency is relevant between the two invocations. I'm not sure if that is really needed here, though. For instance, what is `ResizeJobs`? I don't think I could say whether or not any of the locks needed without knowing what `ResizeJobs` is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T19:10:44.060", "Id": "31214", "Score": "0", "body": "@Tom: what is ResizeJobs?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T19:35:57.563", "Id": "31217", "Score": "0", "body": "@JayC code corrected - `ResizeJobs` should be `Jobs`!" } ]
[ { "body": "<p>From my experience ASP.NET is using threadpool threads only for requests.\nWhen creating a new thread inside a request thread will usually* not cause your application pool to run out of resources.</p>\n\n<p>*I say usually as there are cases when a new thread created from inside a request is causing apppool to use another threadpool thread. e.g. <code>System.Threading.ThreadPool.QueueUserWorkItem</code> </p>\n\n<p>What could still go wrong in your code is the following:</p>\n\n<ol>\n<li>you call <strong>QueueJob</strong> from a request thread ( R1 )</li>\n<li>a new thread running <strong>ConsumeQueue</strong> is started T1</li>\n<li>R1 waits untill all it's subthreads are finished ( waits T1 to finish)</li>\n<li>if T1 takes a lot of time, than R1 is blocked for a while.</li>\n</ol>\n\n<p>So you have 1 request hanging for the entire runtime of T1 maybe throwing request timeout at some point.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T19:36:58.380", "Id": "31218", "Score": "0", "body": "Thought that 3 wouldn't happen..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T15:55:00.920", "Id": "19495", "ParentId": "19489", "Score": "1" } }, { "body": "<p>Hmm any reason your not using the TPL with the TaskPoolScheduler? I would use a Task instance from the TaskPoolScheduler to perform the work on your job.</p>\n\n<p>In light of my comment: Creating a Task with TaskCreationOptions.LongRunning effective achieves the same thing. As in, it bypasses the Threadpool. </p>\n\n<p>To expand on Almaz answer:</p>\n\n<pre><code> private Task consumer;\n private ConcurrentQueue&lt;Job&gt; jobs = new ConcurrentQueue&lt;Job&gt;();\n\n private void QueueJob(Job job)\n {\n EnsureConsumer();\n jobs.Enqueue(job);\n } \n\n private void EnsureConsumer() {\n if (consumer == null || consumer.IsCompleted || consumer.IsFaulted)\n {\n lock (consumer)\n {\n if (consumer == null || consumer.IsCompleted || consumer.IsFaulted)\n {\n consumer = Task.Factory.StartNew(() =&gt; DoCPUBoundWork(), TaskCreationOptions.LongRunning);\n }\n }\n }\n }\n\n private void DoCPUBoundWork() {\n Job j = null;\n while( jobs.TryDequeue(out j)) {\n\n //do your work\n }\n }\n</code></pre>\n\n<p>This effectively ensures that there is one thread consuming your queue. When the task runs, it simply tries to work its way through the queue and stops when there is no work, only to start up again when needed.</p>\n\n<p>If you dont need that, you can also create your task in the constructor of your class, and never let your task stop by simply having it spin. You can then stop your Task using an TaskCancellationToken.</p>\n\n<p>Also note that I did not make the collection or Task instance static. This is because you will want to utilize the Dispose method to stop your long running task, if any. If you really need your job queue to be a single instance, either use an DI container to force a single instance in your appdomain, or use a singleton.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T23:32:59.627", "Id": "31231", "Score": "1", "body": "Thankyou, how does this compare with almaz's suggestion? (which is what I am going with at the moment)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T07:51:31.180", "Id": "31319", "Score": "0", "body": "The same actually. Although you can expand on his anwer by saving the Task in a private var and checking at each invocation of the QueueJob method if the task is still running. Ill edit my answer with an example." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T17:08:27.793", "Id": "19497", "ParentId": "19489", "Score": "1" } }, { "body": "<p>I would do something like that:</p>\n\n<pre><code>private void QueueJob(Job job)\n{\n Task.Factory.StartNew(() =&gt; DoCPUBoundWork(job), TaskCreationOptions.LongRunning);\n}\n</code></pre>\n\n<p><strong>Update:</strong>\nI did miss the point of having just a single thread that does the heavy work... You're right about using <code>BlockingCollection</code>, this is the best structure to be used here:</p>\n\n<pre><code>public class Program\n{\n private readonly BlockingCollection&lt;Job&gt; _jobs = new BlockingCollection&lt;Job&gt;();\n\n public Program()\n {\n //You can add CancellationToken in case you may want to stop queue processing externally\n Task.Factory.StartNew(ConsumeQueue, TaskCreationOptions.LongRunning);\n }\n\n private void QueueJob(Job job)\n {\n _jobs.Add(job);\n }\n\n private void ConsumeQueue()\n {\n while (true)\n {\n DoCPUBoundWork(_jobs.Take());\n }\n }\n}\n</code></pre>\n\n<p>This code is simple because it doesn't shut down the worker thread in case when there are no tasks. If you do need this functionality you'll need to add some more thread management code:</p>\n\n<pre><code>private readonly BlockingCollection&lt;Job&gt; _jobs = new BlockingCollection&lt;Job&gt;();\nprivate readonly object _syncLock = new object();\nprivate volatile Task _task;\n\nprivate void QueueJob(Job job)\n{\n _jobs.Add(job);\n if (_task != null)\n return;\n\n lock (_syncLock)\n {\n if (_task != null)\n return;\n\n _task = Task.Factory.StartNew(ConsumeQueue);\n }\n\n}\n\nprivate bool TryDequeueOtherwiseShutdown(out Job job)\n{\n if (_jobs.TryTake(out job, TimeSpan.FromSeconds(10)))\n return true;\n\n lock (_syncLock)\n {\n var task = _task;\n _task = null; //to signal that we're close to shutdown - in order to avoid racing conditions\n\n if (!_jobs.TryTake(out job))\n return false;\n\n _task = task; //cancelling shutdown, going back to work\n return true;\n }\n}\n\nprivate void ConsumeQueue()\n{\n Job job;\n while (TryDequeueOtherwiseShutdown(out job))\n {\n DoCPUBoundWork(job);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T23:41:26.560", "Id": "31233", "Score": "0", "body": "This looks like the best option really. I am calling `Task.Factory.StartNew(() => DoCPUBoundWork(job), TaskCreationOptions.LongRunning);` from an `AsyncController` method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T16:17:00.420", "Id": "31280", "Score": "0", "body": "Note this behaves differently than the original code. Using TaskCreationOptions.LongRunning creates a new thread, so this code will spawn one thread per job. If you have a lot of jobs, this will spawn a lot of threads. The original code would spawn just one thread." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T17:50:15.550", "Id": "31478", "Score": "0", "body": "Yes, I have realised that this isn't actually what I want. I am going with a `BlockingCollection<Action>` but would be interested to know if there is a one liner like the above - but that queues jobs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T22:21:50.810", "Id": "31487", "Score": "0", "body": "@Tom I updated the answer" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T22:14:08.770", "Id": "19505", "ParentId": "19489", "Score": "1" } }, { "body": "<p>I do think there's a race condition which might mean that some jobs never get executed.\nGiven:</p>\n\n<pre><code>private void QueueJob(Job job)\n{\n bool startQueue=false;\n lock(Jobs)\n {\n if (threadCount == 0)\n {\n Interlocked.Increment(ref threadCount);\n startQueue = true;\n }\n }\n Jobs.Enqueue(job);\n if (startQueue)\n {\n var t= new Thread(new ThreadStart(ConsumeQueue)); \n t.Start();\n }\n}\n</code></pre>\n\n<p>Suppose the following:</p>\n\n<ul>\n<li>R1,R2: requests to enqueue a job </li>\n<li>T1, T2: current job executor </li>\n<li><p><code>Jobs</code> has no jobs enqueued.</p>\n\n<ol>\n<li>R1 executes <code>Foo.QueueJob(job1) : lock(Jobs){}</code> until the end of the lock block and determines there's a thread executing but is preemptively switched just after. Because there's a thread running, <code>startQueue</code> is never set to <code>true</code></li>\n<li>T1: Finishes it's job, finds there's no jobs remaining, decrements the thread count and returns, killing T1.</li>\n<li>(other threads execute, we get back to R1)</li>\n<li>R1: enqueues a job</li>\n<li>R1: sees <code>startQueue == false</code> so does not start a new thread to perform the job. job1 stuck in queue, R1 finishes, and job1 doesn't get done.</li>\n<li>... until... some time passes. If the process dies/gets recycled at this time, job1 never gets executed. </li>\n<li>Some R2 executes <code>Foo.QueueJob(job2) : lock(Jobs){}</code>. It sees that there are no threads so set flag to start thread.</li>\n<li>R2 enqueues job2 and starts a new thread (T2) again. There should only be one thread created as if there were an R3 that executed just after R2 executed the lock block it would just enqueue another job3 and go on.</li>\n<li>T2: starts, finally executes job1 (and any other jobs, including job2)</li>\n</ol></li>\n</ul>\n\n<p>I think the simplest solution from what you have is to lock Jobs until both the new job is enqueued and the new thread is started, but that's just wrapping more code. Supposing it were written this way, however, I think we avoid the race condition, and it's much simpler:</p>\n\n<pre><code>private void QueueJob(Job job)\n{\n\n Jobs.Enqueue(job);\n lock(Jobs)\n {\n if (threadCount == 0)\n {\n Interlocked.Increment(ref threadCount);\n var t= new Thread(new ThreadStart(ConsumeQueue)); \n t.Start();\n }\n }\n\n}\n</code></pre>\n\n<p>But of course, strictly speaking, we don't need to start the thread while we have a lock on <code>Jobs</code>, we just need to know <em>that the current request needs to start it</em>. However, I don't like flags polluting the local scope. Maybe this is better?</p>\n\n<pre><code>private bool shouldStartNewQueueConsumer()\n{\n bool startConsumer = false;\n lock(Jobs)\n {\n if (threadCount == 0)\n {\n Interlocked.Increment(ref threadCount);\n startConsumer = true;\n }\n }\n return startConsumer;\n}\n\nprivate void QueueJob(Job job)\n{\n Jobs.Enqueue(job);\n if(shouldStartNewQueueConsumer()){\n var t= new Thread(new ThreadStart(ConsumeQueue)); \n t.Start(); \n }\n}\n</code></pre>\n\n<p>Other issues: </p>\n\n<p>Another issue would be if <code>DoCPUBoundWork</code> throws an exception, the thread would die, but no new threads would get started, and a heap of jobs would build up.</p>\n\n<p>I have doubts about <code>threadCount==0</code>, etc, but as all operations relating to threadCount occur only within the context of a locked <code>Jobs</code> object, I guess we're ok, for now. :-/\nBut once you desire to have more than one thread to process your job Queue, you'll probably want to maintain the set of threads in it's own synchronized collection, and your threadCount variable seems less utilizable in that case, anyway.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T23:36:34.003", "Id": "31232", "Score": "0", "body": "Thankyou, yes I agree this looks safe. How do you think this compares with almaz's suggestion - given that we are talking about trying to sensibly manage a particularly heavy request. What I have currently is an `AsyncController` which calls `Task.Factory.StartNew(() => DoCPUBoundWork(job), TaskCreationOptions.LongRunning);` . Does this seem like a better alternative?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T03:13:03.837", "Id": "31247", "Score": "0", "body": "It looks like something worth investigating, although I don't know enough about the default factory and default scheduler to know if it fits your situation. There's an interesting example of creating factory with an instance of a derived TaskScheduler class i on http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.aspx which would limit the number of concurrent tasks and I suspect that might work better for you, but I suppose there's no point in trying that until you know what the default TaskFactory does." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T22:21:14.350", "Id": "19506", "ParentId": "19489", "Score": "1" } }, { "body": "<p>I think a much easier solution is to just increse the number of threads available in the thread pool by calling <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.threadpool.setmaxthreads.aspx\" rel=\"nofollow\"><code>ThreadPool.SetMaxThreads()</code></a>.</p>\n\n<p>Also, if you have this many threads, then it means that:</p>\n\n<ol>\n<li>either you're not going to get any performance improvements from parallelization, because all your cores are busy</li>\n<li>or most of your threads are blocked, which means a better approach would be to actually solve the problem by using asynchronous waiting (possibly with the help of C# 5 <code>async</code>-<code>await</code>), instead of working around the problem.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T02:48:13.390", "Id": "31245", "Score": "0", "body": "The idea of this is to move CPU bound work out of the threadpool. The only reason I have potentially lots of threads is from concurrent requests. I am not trying to parallelise the work, rather to serialise it onto a single thread, at least that is the intention of the code above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T02:50:23.010", "Id": "31246", "Score": "0", "body": "I am not working around an existing problem, I am trying to write this code in such a way as to avoid tying up threadpool threads, which I know to be a common anti-pattern." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T20:03:27.023", "Id": "31298", "Score": "0", "body": "How are you going to start and work for that work? If you're going to do it synchronously, you're not going to save any ThreadPool threads." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T01:26:25.620", "Id": "19514", "ParentId": "19489", "Score": "2" } }, { "body": "<p>If you're reasonably sure there will be some work to do, you might as well start up the thread when the app starts and leave it waiting for work. This approach greatly simplifies all the queuing and dequeueing logic, at the slight cost that you have to call <code>Start()</code> just once at startup, and <code>Stop()</code> just once at shutdown. Calling them from you <code>Global.Application_Start()</code> and <code>Global.Application_End()</code> methods should suffice. </p>\n\n<pre><code>private static BlockingCollection&lt;Job&gt; Jobs = new BlockingCollection&lt;Job&gt;(new ConcurrentQueue&lt;Job&gt;());\nprivate static Thread workerThread;\nprivate static CancellationTokenSource cancelSource = new CancellationTokenSource();\n\npublic static void Start()\n{\n workerThread = new Thread(ConsumeQueue);\n workerThread.Start();\n}\n\npublic void Stop()\n{\n cancelSource.Cancel();\n workerThread.Join();\n workerThread = null;\n}\n\nprivate void QueueJob(Job job)\n{\n Jobs.Add(job);\n}\n\nprivate void ConsumeQueue()\n{\n while (true)\n {\n try\n {\n Job j = Jobs.Take(cancelSource.Token);\n\n //if we're shutting down, bail out immediately\n if (cancelSource.Token.IsCancellationRequested)\n {\n return;\n }\n DoCPUBoundWork(j);\n }\n catch (OperationCancelledException)\n {\n return;\n }\n catch (Exception ex)\n {\n //Do something sensible here\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T15:48:52.920", "Id": "31473", "Score": "0", "body": "(as it is) we can end up spinning in the loop forever, after `Take` thows `OperationCancelledException`. Do something sensible = `break`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T17:37:21.887", "Id": "31476", "Score": "0", "body": "This code (as is) ends up spinning! I think that this happens after `Stop` is called from `Application_End` after an app pool recycle, `Take` will then throw and we go into an endless loop. 'Do something sensible' = break;" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T15:20:55.457", "Id": "31507", "Score": "0", "body": "@Tom - sorry about that, you're right. I modified the code above to watch for OperationCancelledException and return" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T16:33:00.903", "Id": "19536", "ParentId": "19489", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T13:27:18.730", "Id": "19489", "Score": "4", "Tags": [ "c#", ".net", "multithreading", "asp.net", "thread-safety" ], "Title": "Strategy for avoiding threadpool starvation while performing cpu bound jobs in a queued fashion" }
19489
<p>I am building an application that opens Wireshark services (Wireshark has several services) in order to to different things on Wireshark files like edit, change format, statistics, etc. Each option usually uses a different service, so I want to build my classes with inheritance.</p> <p>I was wondering if what I want to do is appropriate.</p> <p>Main class <code>WiresharkServices</code> with the following members and methods:</p> <pre><code>public class WiresharkProcesses { protected string _filePath; //the file path who send to Wiresahrk process protected string _capinfos; protected string _dumpcap; protected string _editcap; protected string _mergecap; protected string _rawshark; protected string _text2pcap; protected string _tshark; protected string _wireshark; public void initializeServices() { if (Directory.Exists(@"C:\Program Files (x86)\Wireshark")) { _capinfos = @"C:\Program Files (x86)\Wireshark\_capinfos.exe"; _dumpcap = @"C:\Program Files (x86)\Wireshark\_dumpcap.exe"; _editcap = @"C:\Program Files (x86)\Wireshark\editcap.exe"; _mergecap = @"C:\Program Files (x86)\Wireshark\_mergecap.exe"; _rawshark = @"C:\Program Files (x86)\Wireshark\_rawshark.exe"; _text2pcap = @"C:\Program Files (x86)\Wireshark\_text2pcap.exe"; _tshark = @"C:\Program Files (x86)\Wireshark\_tshark.exe"; _wireshark = @"C:\Program Files (x86)\Wireshark\_wireshark.exe"; } else if (Directory.Exists(@"C:\Program Files\Wireshark")) { _capinfos = @"C:\Program File)\Wireshark\_capinfos.exe"; _dumpcap = @"C:\Program Files\Wireshark\_dumpcap.exe"; _editcap = @"C:\Program Files\Wireshark\editcap.exe"; _mergecap = @"C:\Program Files\Wireshark\_mergecap.exe"; _rawshark = @"C:\Program Files\Wireshark\_rawshark.exe"; _text2pcap = @"C:\Program Files\Wireshark\_text2pcap.exe"; _tshark = @"C:\Program Files\Wireshark\_tshark.exe"; _wireshark = @"C:\Program Files\Wireshark\_wireshark.exe"; } } } </code></pre> <p>When the application is running, I am of course checking if Wireshark is installed on the machine. If not, I throw an exception:</p> <pre><code>WiresharkServices wservices = new WiresharkServices(); wservices .initializeServices(); </code></pre> <p>and in each class its own methods.</p> <p>Child class example which receives a file path to convert it to another Wireshark format:</p> <pre><code>public class Editcap : WiresharkProcesses { private string _newFileName; public void startProcess(string filePath) { FileInfo file = new FileInfo(filePath); _newFileName = file.FullName.Replace(file.Extension, "_new") + ".pcap"; ProcessStartInfo editcapProcess = new ProcessStartInfo(string.Format("\"{0}\"", _editcap)) { Arguments = string.Format("{2}{0}{2} -F libpcap {2}{1}{2}", file.FullName, _newFileName, "\""), WindowStyle = ProcessWindowStyle.Hidden, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, UseShellExecute = false, ErrorDialog = false }; using (Process editcap = Process.Start(editcapProcess)) { editcap.WaitForExit(); } } public string getNewFileName() { return _newFileName; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T15:56:45.913", "Id": "31199", "Score": "0", "body": "You mention that you want to use inheritance but I see no evidence of it. Also, these fields should be properties. You can detect the 32-bit vs the 64-bit once and then build the file paths from that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T15:58:40.373", "Id": "31200", "Score": "0", "body": "this is the class that all the other classes should inherite, i am checking if Wireshak installed on the machine once the form load." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T16:25:06.933", "Id": "31201", "Score": "2", "body": "It's often said that \"Inheritance breaks encapsulation\" and in this case, that's certainly true. While I can see what you're trying to achieve, it's probably worth looking into using composition rather than inhertiance. From an OOP perspective composition should amost always be favoured. Can you give us an example of a child class that uses this parent?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T16:29:31.207", "Id": "31202", "Score": "0", "body": "child class added" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T16:59:26.633", "Id": "31205", "Score": "0", "body": "I do not see many benefits in using inheritance and I am convinced that composition is the way to go." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T17:02:58.440", "Id": "31206", "Score": "0", "body": "what do you mean composition ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T17:34:22.430", "Id": "31207", "Score": "2", "body": "http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/" } ]
[ { "body": "<p>The only thing you are getting out of this inheritance is which directory should be used to access the executable. And you are only using that to define a number of (what should be constant) strings. The fact that you have an error in your value for <code>_capinfos</code> in the seconds case should be an indication that this is not the best way to perform this action.</p>\n\n<p>To accomplish the task of initializing the strings, I would instead do something like this.</p>\n\n<pre><code>public void initializeCommands(String path) {\n _capinfos = path + \"_capinfos.exe\";\n _dumpcap = path + \"_dumpcap.exe\";\n _editcap = path + \"editcap.exe\";\n _mergecap = path + \"_mergecap.exe\";\n _rawshark = path + \"_rawshark.exe\";\n _text2pcap = path + \"_text2pcap.exe\";\n _tshark = path + \"_tshark.exe\";\n _wireshark = path + \"_wireshark.exe\";\n}\n</code></pre>\n\n<p>You can wrap this in something that determines the path or even support non-standard paths.</p>\n\n<p>But what this really comes down to is that you are using inheritance just so you have easy access to some constants you might want to use. You are not defining any methods that would specify actual code used between multiple classes that execute Wireshark processes. If <code>Editcap</code> were passed in the path to the executable, it would no longer have a need to the parent class. If the coupling is this loose, inheritance is generally not the best idea.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T19:12:28.280", "Id": "31215", "Score": "1", "body": "It would take me too long to rewrite the original code in a way that I consider proper. The biggest problem I see is code repetition, which can be avoided with dictionaries, or you name it. I do have a concern about thread-safety, and everything can be accomplished with static methods, so no actual state is required. As far as improving your answer, you should use a better way to join paths as described here: http://stackoverflow.com/questions/961704/how-do-i-join-two-paths-in-c" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T18:45:38.580", "Id": "19499", "ParentId": "19493", "Score": "3" } }, { "body": "<p>This should be a little better, but not perfect. Note that wrote this without having Visual Studio in front of me.</p>\n\n<p>Notice that the WiresharkProcesses class is static, so you cannot inherit from it and you cannot instantiate it. It is like a namespace with a bunch of functions except that the static constructor does some work. This is not perfect. I will gladly accept some suggestions from the community. You could open up some private readonly fields or expose them as properties at least. Notice that repeated access to the properties will cause repeated string concatenation, but it is a very fast operation. Another alternative would be to use auto-properties like <code>public static string CapInfosExePath { get; private set;}</code> instead of the protected fields. Either way, inheritance is not required. The <code>EditCap</code> class has too much boiler-plate code. Frankly, you only need one or two classes altogether, perhaps make them <code>partial</code> and split them into two separate files (just a thought).</p>\n\n<pre><code>using System.IO;\n\n// TODO: also add namespace around this\npublic static class WiresharkProcesses\n{\n // TODO: actually use proper library for this.\n // http://stackoverflow.com/questions/1085584/how-do-i-programmatically-retrieve-the-actual-path-to-the-program-files-folder?lq=1\n // Note that a spanish Windows version will have \"C:\\Archivos de programa\\\" instead\n private static readonly string ProgramFiles64Path = @\"C:\\Program Files\";\n private static readonly string ThirtyTwoBitSuffix = @\" (x86)\";\n private static readonly string ProgramFiles32Path = Path.Join(ProgramFiles64Path, ThirtyTwoBitSuffix);\n private static readonly string WiresharkDirName = @\"Wireshark\";\n private static bool Is64Bit = true;\n private static string ProgramFilesPath = null;\n private static readonly string WiresharkDirectoryPath = null;\n\n // Static constructor runs only once\n public static WiresharkProcesses()\n {\n if (Directory.Exists(ProgramFiles64Path))\n {\n Is64Bit = true;\n ProgramFilesPath = ProgramFiles64Path;\n }\n else if (Directory.Exists(ProgramFiles32Path))\n {\n Is64Bit = false;\n ProgramFilesPath = ProgramFiles32Path;\n }\n else\n {\n throw new AppropriateException(\"WTF!\");\n }\n\n WiresharkDirectoryPath = Path.Combine(ProgramFilesPath, WiresharkDirName);\n }\n\n private static string GetFullPath(string exeName)\n {\n return Path.Combine(WiresharkDirectoryPath, exeName);\n }\n\n public static string CapInfosExePath\n {\n get\n {\n // Perhaps this arg should be a variable as well.\n return GetFullPath(\"_capinfos.exe\");\n }\n }\n\n ...\n\n public static string WiresharkExePath\n {\n get\n {\n // Perhaps this arg should be a variable as well.\n return GetFullPath(\"_wireshark.exe\");\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T01:22:33.720", "Id": "19595", "ParentId": "19493", "Score": "2" } } ]
{ "AcceptedAnswerId": "19499", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T15:39:26.677", "Id": "19493", "Score": "1", "Tags": [ "c#", "error-handling" ], "Title": "Performing various Wireshark services" }
19493
<p>I am learning PHP OOP. I am familiar with PHP, and limited use of OOP, but not writing OOP. I have a small successful website that uses large associative arrays but is now suffering performance problems because the arrays soak up memory (My teamarray contains 16k teams of the data below, plus more). I am rewriting the code to take advantage of OOP and hopefully achieve greater performance as a result. (A quick trial reduced memory use by 16x).</p> <p>I have this class:</p> <pre><code>class team { private $teamid; private $name; private $urlname; private $mascot; private $city; private $stateid; private $jv; private $color1; private $color2; private $address; private $zip; private $lat; private $lng; function __construct($teamid) { global $my_db; $row = $my_db-&gt;query("SELECT * FROM `team` WHERE `teamid` = $teamid;")-&gt;fetchRow(MDB2_FETCHMODE_ASSOC); $this-&gt;set_teamid = $row['teamid']; $this-&gt;set_name = $row['name']; $this-&gt;set_urlname = $row['urlname']; $this-&gt;set_mascot = $row['mascot']; $this-&gt;set_city = $row['city']; $this-&gt;set_stateid = $row['stateid']; $this-&gt;set_jv = $row['jv']; $this-&gt;set_color1 = $row['color1']; $this-&gt;set_color2 = $row['color2']; $this-&gt;set_address = $row['address']; $this-&gt;set_zip = $row['zip']; $this-&gt;set_lat = $row['lat']; $this-&gt;set_lng = $row['lng']; } public function get_teamid() { return $this-&gt;teamid; } private function set_teamid($new) { $this-&gt;teamid = $new; } public function get_name() { return $this-&gt;name; } private function set_name($new) { $this-&gt;name = $new; } public function get_urlname() { return $this-&gt;urlname; } private function set_urlname($new) { $this-&gt;urlname = $new; } public function get_mascot() { return $this-&gt;mascot; } private function set_mascot($new) { $this-&gt;mascot = $new; } public function get_city() { return $this-&gt;city; } private function set_city($new) { $this-&gt;city = $new; } public function get_stateid() { return $this-&gt;stateid; } private function set_stateid($new) { $this-&gt;stateid = $new; } public function get_jv() { return $this-&gt;jv; } private function set_jv($new) { $this-&gt;jv = $new; } private public function get_color1() { return $this-&gt;color1; } private function set_color1($new) { $this-&gt;color1 = $new; } public function get_color2() { return $this-&gt;color2; } private function set_color2($new) { $this-&gt;color2 = $new; } public function get_address() { return $this-&gt;address; } private function set_address($new) { $this-&gt;address = $new; } public function get_zip() { return $this-&gt;zip; } private function set_zip($new) { $this-&gt;zip = $new; } public function get_lat() { return $this-&gt;lat; } private function set_lat($new) { $this-&gt;lat = $new; } public function get_lng() { return $this-&gt;lng; } private function set_lng($new) { $this-&gt;lng = $new; } </code></pre> <p>}</p> <p>The team is just an object container storing all static data, so I have the <code>set_</code> functions at private.</p> <p>The team can be added (not sure if it should be extended? probably the team_class class would be a better choice for going into the game) into a game class (not yet written, where two teams compete, time, date, location, scores, etc), and also (probably extended) into a team_class class (also not yet written) where they get properties about the season they are competing in (sport, year, level, etc).</p> <p>Can it be improved? Are there any glaring problems?</p> <p>Since $stateid is just an ID reference to the state, should I store the state name as part of the object? Is it better to compare stateid or state?</p> <p>Do I need to store the $teamid?</p> <p>Is there a better way to handle the colorsX? These are just 2 hex code color strings.</p> <p>Can I declare all the private properties like:</p> <pre><code>private $teamid, $name, ....; </code></pre> <p>I'm thinking I would store all the object handlers (perhaps up to a hundred, maybe thousands) in an array for working with them. Is there a better way?</p> <pre><code>$teamarray[$teamid] = new team($teamid); $teamarray[$teamid]-&gt;get_name(); </code></pre> <p>Finally, is there an good, easy "fiddle" supports databases?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T19:38:29.457", "Id": "31295", "Score": "0", "body": "Q: Are you just now moving your 16k records into a database? i.e. was it all in memory or a text file or something else previously? Q: Where does `$teamid` come from in the statement `$teamarray[$teamid] = new team($teamid);` i.e. do you have another query/text tile that gets all teamid's then loops over loading the data? SQLite is probably the easiest 'fiddle' database : http://www.sqlite.org/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T19:46:08.280", "Id": "31296", "Score": "0", "body": "No, I've been using MySQL from the beginning. What I previously was doing was getting ALL 16k teams and stuffing them into an array. I did this for all the \"configuration\" data from the database. A single page load was therefore using ~128M of memory, which is the main reason to go to OOP and only get what I need, when I need it. $teamid comes from the \"controller\" basically saying \"I need information about this teamid.\"" } ]
[ { "body": "<p>Okay, here's a preliminary tidying up of the code, with comments: </p>\n\n<pre><code>&lt;?php\n\nclass team {\n # You can stream line the private fields\n private $teamid, $name, $urlname, $mascot, $city, $stateid, $jv;\n $color1, $color2, $address, $zip, $lat, $lng;\n\n # Avoid `global $my_db`, perhaps direct injection \n # of the db class into the constructor?\n function __construct($teamid) {\n global $my_db;\n\n # $teamid is not safe in this query it would seem...perhaps consider prepared statements? \n $row = $my_db-&gt;query(\"SELECT * FROM `team` WHERE `teamid` = $teamid;\")-&gt;fetchRow(MDB2_FETCHMODE_ASSOC);\n\n # Let's clarify this...you're using functions as such:\n # $this-&gt;set_teamid($row['teamid']); \n # We're not doing any variable checking, so why not \n # just set the variable directly and get rid of a \n # bunch of functions and function calls?\n $this-&gt;teamid = $row['teamid'];\n $this-&gt;name = $row['name'];\n $this-&gt;urlname = $row['urlname'];\n $this-&gt;mascot = $row['mascot'];\n $this-&gt;city = $row['city'];\n $this-&gt;stateid = $row['stateid'];\n $this-&gt;jv = $row['jv'];\n $this-&gt;color1 = $row['color1'];\n $this-&gt;color2 = $row['color2'];\n $this-&gt;address = $row['address'];\n $this-&gt;zip = $row['zip'];\n $this-&gt;lat = $row['lat'];\n $this-&gt;lng = $row['lng'];\n } \n\n\n # Below, we will remove all the set_* functions \n # and concatenate all the get_* functions into 1 \n # switch function\n public function get($varname){\n switch($varname){\n case 'teamid' : $return = $this-&gt;teamid; break;\n case 'name' : $return = $this-&gt;name; break;\n case 'urlname' : $return = $this-&gt;urlname; break;\n case 'mascot' : $return = $this-&gt;mascot; break;\n case 'city' : $return = $this-&gt;city; break;\n case 'stateid' : $return = $this-&gt;stateid; break;\n case 'jv' : $return = $this-&gt;jv; break;\n case 'color1' : $return = $this-&gt;color1; break;\n case 'color2' : $return = $this-&gt;color2; break;\n case 'address' : $return = $this-&gt;address; break;\n case 'zip' : $return = $this-&gt;zip; break;\n case 'lat' : $return = $this-&gt;lat; break;\n case 'lng' : $return = $this-&gt;lng; break;\n default : $return = \"Error in get().\"; break;\n }\n\n return $return;\n }\n\n # Replaced\n #public function get_teamid() {\n # return $this-&gt;teamid;\n #} \n\n # Removed\n #private function set_teamid($new) {\n # $this-&gt;teamid = $new;\n #}\n\n # Replaced\n #public function get_name() {\n # return $this-&gt;name;\n #}\n\n #Removed\n #private function set_name($new) {\n # $this-&gt;name = $new;\n #}\n\n # Replaced\n #public function get_urlname() {\n # return $this-&gt;urlname;\n #}\n\n # Removed\n #private function set_urlname($new) {\n # $this-&gt;urlname = $new;\n #}\n\n # Replaced\n #public function get_mascot() {\n # return $this-&gt;mascot;\n #}\n\n # Removed\n #private function set_mascot($new) {\n # $this-&gt;mascot = $new;\n #}\n\n # Replaced\n #public function get_city() {\n # return $this-&gt;city;\n #}\n\n # Removed\n #private function set_city($new) {\n # $this-&gt;city = $new;\n #}\n\n # Replaced\n #public function get_stateid() {\n # return $this-&gt;stateid;\n #}\n\n # Removed\n #private function set_stateid($new) {\n # $this-&gt;stateid = $new;\n #}\n\n # Replaced\n #public function get_jv() {\n # return $this-&gt;jv;\n #}\n\n # Removed\n #private function set_jv($new) {\n # $this-&gt;jv = $new;\n #}\n\n # Replaced\n #public function get_color1() {\n # return $this-&gt;color1;\n #}\n\n # Removed\n #private function set_color1($new) {\n # $this-&gt;color1 = $new;\n #}\n\n # Replaced\n #public function get_color2() {\n # return $this-&gt;color2;\n #}\n\n # Removed\n #private function set_color2($new) {\n # $this-&gt;color2 = $new;\n #}\n\n # Replaced\n #public function get_address() {\n # return $this-&gt;address;\n #}\n\n # Removed\n #private function set_address($new) {\n # $this-&gt;address = $new;\n #}\n\n # Replaced\n #public function get_zip() {\n # return $this-&gt;zip;\n #}\n\n # Removed\n #private function set_zip($new) {\n # $this-&gt;zip = $new;\n #}\n\n # Replaced\n #public function get_lat() {\n # return $this-&gt;lat;\n #}\n\n # Removed\n #private function set_lat($new) {\n # $this-&gt;lat = $new;\n #}\n\n # Replaced\n #public function get_lng() {\n # return $this-&gt;lng;\n #}\n\n # Removed\n #private function set_lng($new) {\n # $this-&gt;lng = $new;\n #}\n}\n\n?&gt;\n</code></pre>\n\n<p>And here it is without comments: </p>\n\n<pre><code>&lt;?php\n\nclass team {\n private $teamid, $name, $urlname, $mascot, $city, $stateid, $jv;\n $color1, $color2, $address, $zip, $lat, $lng;\n\n function __construct($teamid) {\n global $my_db;\n $row = $my_db-&gt;query(\"SELECT * FROM `team` WHERE `teamid` = $teamid;\")-&gt;fetchRow(MDB2_FETCHMODE_ASSOC);\n\n $this-&gt;teamid = $row['teamid'];\n $this-&gt;name = $row['name'];\n $this-&gt;urlname = $row['urlname'];\n $this-&gt;mascot = $row['mascot'];\n $this-&gt;city = $row['city'];\n $this-&gt;stateid = $row['stateid'];\n $this-&gt;jv = $row['jv'];\n $this-&gt;color1 = $row['color1'];\n $this-&gt;color2 = $row['color2'];\n $this-&gt;address = $row['address'];\n $this-&gt;zip = $row['zip'];\n $this-&gt;lat = $row['lat'];\n $this-&gt;lng = $row['lng'];\n } \n\n public function get($varname){\n switch($varname){\n case 'teamid' : $return = $this-&gt;teamid; break;\n case 'name' : $return = $this-&gt;name; break;\n case 'urlname' : $return = $this-&gt;urlname; break;\n case 'mascot' : $return = $this-&gt;mascot; break;\n case 'city' : $return = $this-&gt;city; break;\n case 'stateid' : $return = $this-&gt;stateid; break;\n case 'jv' : $return = $this-&gt;jv; break;\n case 'color1' : $return = $this-&gt;color1; break;\n case 'color2' : $return = $this-&gt;color2; break;\n case 'address' : $return = $this-&gt;address; break;\n case 'zip' : $return = $this-&gt;zip; break;\n case 'lat' : $return = $this-&gt;lat; break;\n case 'lng' : $return = $this-&gt;lng; break;\n default : $return = \"Error in get().\"; break;\n }\n\n return $return;\n }\n}\n\n?&gt;\n</code></pre>\n\n<p>Again - the glaring issue is that SQL query...can easily be injected if you're not doing any checking in query() itself - and even if this is say, an intranet site, don't hedge on that for safety and laziness. Protect the database at all costs. </p>\n\n<p><em><strong>Now for your questions:</em></strong></p>\n\n<p><strong>Can it be improved? Are there any glaring problems?</strong></p>\n\n<p><em>See above notes about SQL</em></p>\n\n<p><strong>Since $stateid is just an ID reference to the state, should I store the state name as part of the object? Is it better to compare stateid or state?</strong></p>\n\n<p><em>Feel free to store it, or not. Doesn't matter either way. If you require it for your software, then keep it obviously.</em></p>\n\n<p><strong>Do I need to store the $teamid?</strong></p>\n\n<p><em>Again, you don't need to if your software doesn't require it, but down the line, it might become a reference in some piece of software or other.</em></p>\n\n<p><strong>Is there a better way to handle the colorsX? These are just 2 hex code color strings.</strong></p>\n\n<p><em>Perhaps an array - ie: <code>$colors[1]; $colors[2];</code>? Or you can leave them as is.</em></p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Edited for idiom:</p>\n\n<pre><code>&lt;?php\n\nclass team {\n private $row;\n\n function __construct($teamid) {\n global $my_db;\n $this-&gt;row = $my_db-&gt;query(\"SELECT * FROM `team` WHERE `teamid` = $teamid;\")-&gt;fetchRow(MDB2_FETCHMODE_ASSOC);\n }\n\n public function get($item){\n return $this-&gt;row[$item] ? $this-&gt;row[$item] : NULL;\n }\n}\n\n# Usage: \n$t = new team(14);\necho $t-&gt;get('city');\n\n?&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T16:54:37.823", "Id": "31204", "Score": "0", "body": "Thanks for the tips. What does this mean? How would I do this? _perhaps direct injection of the db class into the constructor?_" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T18:12:33.770", "Id": "31209", "Score": "1", "body": "@MECU - rather than trying to explain it here, I'll just link to http://net.tutsplus.com/tutorials/php/dependency-injection-huh/ :) one of the best and simplest explanations I've found. Basically, instead of adding a `global $db` - you just pass the `$db` object to the class as you would the `$teamid`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T00:07:21.647", "Id": "31234", "Score": "0", "body": "-1 for the getter pattern, which seems far from idiomatic - If you're going to get via a function like this, then why not just store $row directly and make get() check $this->row for the value and throw an error (or return null) if it doesn't exist? If you want to avoid having a bunch of setter/getter methods, you can implement ArrayAccess and then access the data as `$myTeam['name']`; If you want the data to be read-only then have the set* methods throw an Exception if called. Just the same, your IDE can generate your getter methods for you and then you can manage incremental changes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T00:24:06.547", "Id": "31235", "Score": "0", "body": "@DavidFarrell using array access where it's not necessary doesn't seem like the best advice - what's wrong with [__get](http://php.net/manual/en/language.oop5.overloading.php#object.get) ? I agree about the null-benefit `team::get()` method in the answer though" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T01:02:45.360", "Id": "31236", "Score": "0", "body": "@AD7six - When I use an array as backing-store, I use ArrayAccess for magic methods. When using magic methods on properties, I use _get - I basically do this to ensure 1-to-1 conformance to acceptable key values i.e. array keys can contain characters that php variables names cannot. It can also come down to preference on accessing, i.e. `$myTeam['key']` vs `$myTeam->key` - Also if using a variable for `key` I tend to prefer `$myTeam[$key]` over `$myTeam->$key`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T03:38:53.840", "Id": "31248", "Score": "0", "body": "@DavidFarrell: Edited for idiom. See edit implementing your first comment. Perhaps a +1 is in order? It does seem far more concise, uses far less variables, and fails silently (null)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T19:00:24.727", "Id": "31294", "Score": "0", "body": "@jsanc623, after re-reading original question, I get the impression that object properties are desired over an array (seems like OP mentioned memory benefits of such) - but you fixed the idiom and you're also the only one who's taken time to answer all of the OP's questions, so +1 for all that!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T16:40:15.617", "Id": "19496", "ParentId": "19494", "Score": "3" } }, { "body": "<p>Use oop to describe your domain, provide encapsulation, make code testable, etc. <strong>Oop does not inherently make code run more efficiently</strong>. An object with 13 properties uses just as much memory (if not slightly more) than an array with 13 keys.</p>\n\n<p>My approach to oop is to describe the problem domain first. Worrying about the database at this point will only complicate things.</p>\n\n<p>Obviously, I don't understand your problem domain but, for discussion purposes, let's say I have these things: Team, Season, Competition</p>\n\n<p>Now, thinking about an api or how these things interact with each other you might have something like this to register teams for a season:</p>\n\n<pre><code>$fireBalls = new Team();\n$fireBalls-&gt;setName('Fire Balls');\n\n$springSeason = new Season();\n$springSeason-&gt;setName('spring');\n$sprintSeason-&gt;setYear(2013);\n$springSeason-&gt;registerTeam($fireBalls);\n</code></pre>\n\n<p>To set up a game perhaps:</p>\n\n<pre><code>$game1 = new Game();\n$game1-&gt;setTime(new DateTime('2012-03-01 15:00:00'));\n$game1-&gt;setTeams($fireBalls, $dragons); //these two teams already created/fetched\n</code></pre>\n\n<p>There is much omitted here but the point is to understand how your objects relate to one another and what kind of behavior is needed. Spend some time writing this all out on a whiteboard or paper. Talk it over with others who understand the domain. Make sure it properly describes the domain before writing a single line of actual code. Note that a model is not simply Entities with a bunch of setters/getters. The model should contain actual behavior (such as registerTeam) which usually does more than just set 1 internal value. Behavior modifies the state of the model by performing calculations, checking validity, etc.</p>\n\n<p>Once you are ready to persist some of this data, I highly recommend that you use an existing persistence library such as Doctrine, Propel, etc. Some of these work differently from one another but the idea is that they capture the state of your Model by mapping your Objects to your Relational Database and re-create your Objects from the Relational Database when you need them again.</p>\n\n<p>Regarding some of your specific questions:</p>\n\n<p><em><strong>Are there any glaring problems?</em></strong>\nI'm not a huge fan of sticking persistence stuff into my Entities but, this is personal preference. However, if you want to use this pattern (called Active Record btw), the db object should be injected as others have already stated. Also, with passing an id to the constructor, how would one go about creating a new Entity?</p>\n\n<p>All of your setters are private. Is the team class considered read only?</p>\n\n<p><em><strong>Since $stateid is just an ID reference to the state, should I store the state name as part of the object?</em></strong>\nIt depends on whether you consider State to be a simple property of team or whether it is actually part of some related entity such as Address or Location.</p>\n\n<p><em><strong>Do I need to store the $teamid?</em></strong>\nIf you use a ORM, let it worry about that.</p>\n\n<p><em><strong>Is there a better way to handle the colorsX?</em></strong>\nHandle it vertically instead of horizontally. i.e.</p>\n\n<pre><code>$team-&gt;addColor(1, 'red');\n$team-&gt;addColor(2, 'green');\n</code></pre>\n\n<p><em><strong>I'm thinking I would store all the object handlers (perhaps up to a hundred, maybe thousands) in an array for working with them. Is there a better way?</em></strong>\nThis sounds like the source of your original problem! Large arrays can chew up alot of memory. It does not matter if it's an array of arrays or an array of objects. A Relational Database is much better for the job. There are many to choose from, postgresql, mysql, sqlite, oracle, etc</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T03:50:25.657", "Id": "19518", "ParentId": "19494", "Score": "1" } } ]
{ "AcceptedAnswerId": "19496", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T15:49:25.457", "Id": "19494", "Score": "2", "Tags": [ "php", "object-oriented" ], "Title": "Best Practice: Learning PHP OOP" }
19494
<p>I currently have a method in my repository that will run SQL and map the reader to objects:</p> <pre><code>protected IEnumerable&lt;T&gt; Query&lt;T, TFactory&gt;(string sql, List&lt;IDbDataParameter&gt; parameters = null) where TFactory : IFactory&lt;T&gt; { List&lt;T&gt; list = new List&lt;T&gt;(); var factory = Activator.CreateInstance&lt;TFactory&gt;(); var connection = (Db == null) ? Connection : Db.Connection; using (var manager = new DbCommandManager(connection, sql)) { if (parameters != null) foreach (var parameter in parameters) manager.AddParameter(parameter); using (var reader = manager.GetReader()) { while(reader.Read()) list.Add(factory.CreateTFromReader(reader)); } } return list; } </code></pre> <p>To use the following you simply do:</p> <pre><code>public IEnumerable&lt;Code&gt; GetCodeWType(string CodeType, string Code) { var sql = @"Select CODE_TYPE, CODE, DESCRIPTION From Codes Where (CODE_TYPE = :1) AND (CODE = :2)"; var parameters = new List&lt;IDbDataParameter&gt;(); parameters.Add(DbFactory.GetParameter(":1", CodeType, DbType.String)); parameters.Add(DbFactory.GetParameter(":2", Code, DbType.String)); return this.Query&lt;Code, CodeFactory&gt;(sql, parameters); } </code></pre> <p>I would love to hear thoughts and feedback on how I can improve.</p>
[]
[ { "body": "<p>As of code itself it is quite good, the only thing to note is that you can add a <code>new()</code> constraint on <code>TFactory</code> and just use <code>var factory = new TFactory();</code>.</p>\n\n<p>But as with all self-written DB access frameworks I would suggest to switch to mature ORM frameworks like Entity Framework or NHibernate (if you haven't worked with them previously Entity Framework would probably be easier for you). They have a well-developed environment, proper unit-of-work management, good querying and tuning capabilities.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T21:31:53.700", "Id": "19503", "ParentId": "19500", "Score": "1" } }, { "body": "<p>It looks ok for me so, just a couple of suggestions:</p>\n\n<p>First: given it is a protected method and not a private, it can be called be derived classes which probably could not be in the same assembly (this is true only if the class is public) then, you shouldn´t use optional parameters, they force you to <strong>recompile all</strong> when you change them.</p>\n\n<p>Instead, use an overloaded method as follow:</p>\n\n<pre><code>protected List&lt;T&gt; Query&lt;T, TFactory&gt;(string query) where TFactory : IFactory&lt;T&gt;\n{\n return Query&lt;T, TFactoty&gt;(query, Enumerable.Empty&lt;IDbDataParameter&gt;());\n}\n\nprotected List&lt;T&gt; Query&lt;T, TFactory&gt;(string query, IEnumerable&lt;IDbDataParameter&gt; parameters) \n where TFactory : IFactory&lt;T&gt;\n{\n</code></pre>\n\n<p>It also help you to remove the checking for nulls.</p>\n\n<p>Second, if you return an IEnumerable, the callers will have less features. The rule is you you should require the most generic and return the most specific implementation so, if you have a list you could return a List&lt;>, IList&lt;> or a Collection. Then, callers have more options.</p>\n\n<p>My attempts is this one:</p>\n\n<pre><code>protected List&lt;T&gt; Query&lt;T, TFactory&gt;(string query) where TFactory : IFactory&lt;T&gt;\n{\n return Query&lt;T, TFactoty&gt;(query, Enumerable.Empty&lt;IDbDataParameter&gt;());\n}\n\nprotected List&lt;T&gt; Query&lt;T, TFactory&gt;(string query, IEnumerable&lt;IDbDataParameter&gt; parameters) \n where TFactory : IFactory&lt;T&gt;\n{\n var collection = new List&lt;T&gt;();\n\n var factory = Activator.CreateInstance&lt;TFactory&gt;();\n var connection = (Db == null) ? Connection : Db.Connection; // this line looks rare for me\n\n using (var manager = new DbCommandManager(connection, sql))\n {\n foreach (var parameter in parameters)\n manager.AddParameter(parameter);\n\n using (var reader = manager.GetReader())\n {\n while (reader.Read())\n list.Add(factory.CreateTFromReader(reader));\n }\n }\n\n return list;\n}\n</code></pre>\n\n<p><strong>Update:</strong></p>\n\n<p>One more thing about optional parameters, when you call the Query method with one argument, you really are passing two: the query and a null in 'parameters'. You have never pass nulls (or at least you have to try) because if you pass nulls then, you need to check for null values. </p>\n\n<p>One more thing about the protected modifier, privates methods can trust that their parameter won´t be null but protected methods cannot do it. This is because private members will be called by other methods in the same class but protected method can be called by other methods in other classes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T22:53:16.540", "Id": "31229", "Score": "0", "body": "+1 I would say that is a very general rule to return the most specific. As with most things it always depends..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T01:22:57.937", "Id": "31237", "Score": "0", "body": "yes, they are just guides." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T02:17:40.943", "Id": "31244", "Score": "0", "body": "Thanks for all the good feedback. I am going to make said adjustments. The var connection line allows the user to either pass an open connection, or a wrapper object that contains a connection and transaction. I can post that class tomorrow so you can see it. Db would eventually turn into a unit of work." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T22:33:20.670", "Id": "19508", "ParentId": "19500", "Score": "2" } } ]
{ "AcceptedAnswerId": "19508", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T19:57:13.713", "Id": "19500", "Score": "3", "Tags": [ "c#", "asp.net" ], "Title": "Running SQL and mapping the reader to objects" }
19500
<p>I've written a Time class that records the time of day and performs simple timing operations (add 2 times, convert a time object to an integer and back again,etc.) following the prompts in How to Think Like a Computer Scientist: Learning with Python. </p> <pre><code>class Time(object): """Attributes: hours, minutes, seconds""" def __init__(self,hours,minutes,seconds): self.hours =hours self.minutes=minutes self.seconds=seconds def print_time(self): """prints time object as a string""" print "%.2d:%.2d:%.2d" % (self.hours, self.minutes, self.seconds) def _str_(self): """returns time object as a string""" return "%.2d:%.2d:%.2d" % (self.hours, self.minutes, self.seconds) def name(self,name): """names an instance""" self.name=name return self.name def after(t1,t2): """checks to see which of two time objects is later""" if t1.convert_to_seconds()&lt;t2.convert_to_seconds(): return "%s is later" %(t2.name) elif t1.convert_to_seconds&gt;t2.convert_to_seconds: return "%s is later" %(t1.name) else: return "these events occur simultaneously" def convert_to_seconds(self): """converts Time object to an integer(# of seconds)""" minutes=self.hours*60+self.minutes seconds=minutes*60+self.seconds return seconds def make_time(self,seconds): """converts from an integer to a Time object""" self.hours=seconds/3600 seconds=seconds-self.hours*3600 self.minutes=seconds/60 seconds=seconds-self.minutes*60 self.seconds=seconds def increment_time(self, seconds): """Modifier adding a given # of seconds to a time object which has been converted to an integer(seconds); permanently alters object""" sum=self.convert_to_seconds()+seconds self.make_time(sum) return self._str_() def add_time(self, addedTime): """adds 2 Time objects represented as seconds; does not permanently modify either object""" import copy end_time=copy.deepcopy(self) seconds=self.convert_to_seconds()+addedTime.convert_to_seconds() end_time.make_time(seconds) return end_time._str_() </code></pre> <p>Usage examples:</p> <pre><code>breakfast=Time(8,30,7) dinner=Time(19,0,0) smokebreak=Time(19,0,0) interval=(4,30,0) print dinner.after(smokebreak) print breakfast.add_time(interval) print breakfast.increment_time(3600) </code></pre> <p>The Time Class example in the text I'm following does not use an <strong>init</strong> method, but passes straight into creating a time object and assigning attributes. Is there any advantage to including an <strong>init</strong> function, as I have done? Removing the <strong>init</strong> method seems to make it easier to adopt a terser and more functional style. Is including a method to name instances bad form, as I suspect? Would it be better write a functional-style version of add_time without importing deepcopy? I would appreciate any advice on best practices in Python 2.x OOP.</p>
[]
[ { "body": "<p>It is perfectly fine to implement an <code>__init__</code> method in this case. I think the only thing you should note is, by the way it's defined, the <code>Time</code> class forces the programmer to give values for <code>hours</code>, <code>minutes</code> and <code>seconds</code> to define a <code>Time</code> object. So, with that constraint in mind, it's really up to you as to whether this is an advantage or disadvantage. Do you want to force the programmer (most likely yourself) to enter these values here? Or should you allow him to first construct an object and then define them later? This is your decision; I don't think Pythoneers will try to sway you one way or another.</p>\n\n<p>Alternatives are (1) as you've already implied: removal or (2) giving these variables default values.</p>\n\n<p>For example:</p>\n\n<pre><code>def __init__(self,hours=None,minutes=None,seconds=None):\n self.hours =hours\n self.minutes=minutes\n self.seconds=seconds\n</code></pre>\n\n<p>With the above you are giving the user the option to define these later or now with no penalty either way. Just keep the following simple philosophy of Python in mind:</p>\n\n<blockquote>\n <p>Easier to ask for forgiveness than permission</p>\n</blockquote>\n\n<p>(From the <a href=\"http://docs.python.org/2/glossary.html\" rel=\"nofollow\">Python Glossary</a>)</p>\n\n<p>I don't really see a point in naming instances. Do you have a rationale for that? Also, if you choose to name them, I think that returning said name after setting is an unexpected behavior and gives the <code>name</code> function more responsibility than it needs.</p>\n\n<p>In your <code>add_time</code> method, I would suggest constructing a new <code>Time</code> object using the values of the <code>self</code> object and then returning that with the incrementation. And, in general, <code>import</code> statements occur at the top of the Python module, unless it is a really special case.</p>\n\n<p>Overall, everything looks pretty good. I hope this was somewhat helpful, if you have any questions be sure to comment.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T14:26:56.947", "Id": "31506", "Score": "0", "body": "Thanks for your comments. The `name` method is of little utility - I thought that naming instances might be useful in print debugging (tracking objects passed between methods), and I also used the `name` method in the `after` method. Perhaps using `_str_` would be a better choice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T05:01:25.423", "Id": "19520", "ParentId": "19502", "Score": "3" } }, { "body": "<p>Two small issues:</p>\n\n<ol>\n<li>Why is <code>Time.make_time</code> an instance method? I shouldn't have to have a Time object to make one. Consider making it a <a href=\"http://docs.python.org/2/library/functions.html#staticmethod\" rel=\"nofollow\">static method</a>.</li>\n<li>You seem to be using underscore_naming everywhere except <code>def add_time(self, addedTime):</code></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T04:54:10.303", "Id": "19603", "ParentId": "19502", "Score": "1" } }, { "body": "<p>mjgpy3's answer is very good, though here are a few nit-picks of my own:</p>\n\n<p>1) Conventions are a good thing to adhere to, and the best guide I have found for python is <a href=\"http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html/\" rel=\"nofollow noreferrer\">here</a>. It is far more important to learn the concepts of a language, however, so if you feel this is too much at once, focus on learning the hard stuff before you get to the syntactical sugar.</p>\n\n<p>2) your <code>print_time</code> and <code>_str_</code> functions do nearly the same thing: perhapes it would be better to combine them together? Perhaps like this:</p>\n\n<pre><code>def _str_(self):\n \"\"\"Returns the object as a string\"\"\"\n return '{}:{}:{}'.format(self.hours, self.minutes, self.seconds)\n</code></pre>\n\n<p>2a) As well, the % formatter is commonly used less compared to the .format() option. You could use either, but be sure of the <a href=\"https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format/\">limitations</a> of both.</p>\n\n<p>Apart from those small nit-picks, your code seems fine to me</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T19:34:32.930", "Id": "19637", "ParentId": "19502", "Score": "1" } } ]
{ "AcceptedAnswerId": "19520", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T21:02:52.100", "Id": "19502", "Score": "3", "Tags": [ "python", "object-oriented" ], "Title": "Python Time Class definition and methods, use of __init__" }
19502
<p>I have written two programs to find out a loopy path in a directed graphs.</p> <p>The first version is a pure functional recursive solution, but its complexity is exponential. The second version following it achieves a linear complexity, but it doesn't look perfect either.</p> <pre><code> def GetACycle(start: String, maps: Map[String, List[String]]): List[String] = { def explore(node: String, visits: List[String], steps: Int): List[String] = { println(List.fill(steps)("\t").mkString + node) if (visits.contains(node)) (visits.+:(node)).reverse else { if (maps(node).isEmpty) Nil else { val id = maps(node).indexWhere(x =&gt; !explore(x, visits.+:(node), steps + 1).isEmpty) if (id.!=(-1)) explore(maps(node)(id), visits.+:(node), steps + 1) else Nil } } } explore(start, List(), 0) } </code></pre> <p>The second version uses mutable variables, the "visits" and "path", though it achieves a linear complexity in terms of number of visited nodes. </p> <p>Would it be possible to achieve such a linear complexity in this situation while using a pure functional recursion without any mutable variables?</p> <pre><code> def GetACycle2(start: String, maps: Map[String, List[String]]): List[String] = { val nodes = maps.:\(Set[String]())((item, set) =&gt; item._2.:\(set)(((i, set) =&gt; set.+(i))).+(item._1)) val pairs = nodes.toList.zip(List.fill(nodes.size)(false)) var visits = pairs.toMap var path = List[String]() def explore(node: String, steps: Int): Boolean = { println(List.fill(steps)("\t").mkString + node) path = path.+:(node) if (visits(node)) { visits = visits.updated(node, true); true } else { visits = visits.updated(node, true) if (maps(node).isEmpty) false else { maps(node).exists( x =&gt; explore(x, steps+1)) } } } explore(start, 0) path </code></pre> <p>}</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T14:03:29.360", "Id": "31265", "Score": "0", "body": "`path = path.+:(node)` is very bad. Add values to the front of a list, and reverse it when you are finished." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T14:40:16.567", "Id": "31270", "Score": "0", "body": "Landei, you're right about it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-22T00:41:45.160", "Id": "230286", "Score": "0", "body": "I just posted a more FP immutable answer on a related StackOverflow thread: http://stackoverflow.com/a/36144158/501113" } ]
[ { "body": "<p>Here is a solution in OCaml (I don't know Scala).</p>\n\n<pre><code>module M = Map.Make(String)\n\nlet rec loopy (graph: string list M.t) (node: string) (path_from_start: string list) (visited: string list M.t) =\n if M.mem node visited then\n (true, visited, path_from_start, M.find node visited)\n else\n let rec explore visited = function\n | [] -&gt; (false, visited, [], [])\n | h :: t -&gt;\n match loopy graph h (h::path_from_start) visited with\n | (true, _, _, _) as ans -&gt; ans\n | (false, visited, _, _) -&gt; explore visited t\n in\n explore (M.add node path_from_start visited) (M.find node graph)\n\nlet get_a_cycle (graph: string list M.t) (start: string) =\n match loopy graph start [start] (M.add start [start] M.empty) with\n | false, _, _, _ -&gt; None\n | true, _, l1, l2 -&gt; Some (List.rev_append l1 l2)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T08:27:19.440", "Id": "19524", "ParentId": "19504", "Score": "1" } }, { "body": "<p>What about something like this (Please excuse my style/form - As with the other poster, I'm not very familiar with coding in Scala either):</p>\n\n<pre><code>def GetACycle(start: String, maps: Map[String, List[String]]): List[String] = {\n\n//entry function\ndef explore(node: String): List[String] = {\n explore_r(node, List(), List())\n}\n\n//main recursive\ndef explore_r(node: String, visited: List[String], path: List[String]): List[String] = {\n println(node)\n if (!maps.contains(node)) return Nil\n if (visited.contains(node)) return path++List(node)\n val branches = maps(node)\n for (nextnode &lt;- branches){\n val loop = explore_r(nextnode, visited++List(node), path++List(node))\n if (loop != Nil) return loop\n }\n Nil\n}\nexplore(start)\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T20:44:18.127", "Id": "31348", "Score": "0", "body": "The key is using the RETURN to jump out of the recursion earlier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T04:18:43.503", "Id": "31368", "Score": "1", "body": "@Qi Qi Glad I could help! To acknowledge Landei's comment to the original question, my solution should also be edited to prepend elements to the lists." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T04:08:40.547", "Id": "19562", "ParentId": "19504", "Score": "2" } }, { "body": "<p>The key is to using \"return\" keyword. Here is the improved version based on @Thomash and @tandem5 suggestions.</p>\n\n<pre><code> def GetACycle_perfect(start: String, maps: Map[String, List[String]]): List[String] = {\n\ndef explore(node: String, visits: List[String], steps: Int): List[String] = {\n println(List.fill(steps)(\"\\t\").mkString + node)\n if (visits.contains(node)) (visits.+:(node)).reverse\n else {\n if (maps(node).isEmpty) Nil\n else {\n maps(node).foreach(v =&gt; {\n val loop = explore(v, visits.+:(node), steps + 1) \n if (!loop.isEmpty) return loop\n })\n Nil\n }\n }\n}\nexplore(start, List(), 0)\n</code></pre>\n\n<p>}</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T20:47:24.497", "Id": "19590", "ParentId": "19504", "Score": "0" } }, { "body": "<p>I had a similar problem lately. The thing that bothers me in the above solution is, that the function explore is <em>not</em> tail recursive! This solution works of course for small trees, but if you have a large tree or - as in my case - a generated tree, you would have to come up with a solution with tail recursion. So, I wouldn't say that my solution is \"perfect\", but I think it would be worth a while (I also added a small main function so that others might test the code). The trick here is to use stacks (for backtracking) and an <strong>exception</strong> for the result (which might look a bit awkward - but isn't a loop kind of an exception?)</p>\n\n<pre><code>import scala.annotation.tailrec\nimport scala.collection.mutable.ArrayStack\n\nobject CheckCycle {\n def GetACycle(start: String, maps: Map[String, List[String]]): List[String] = {\n // the loop is returned in an exception\n case class ResultException(val loop: List[String]) extends Exception\n val visited = ArrayStack[String]()\n val branchesStack = ArrayStack[Iterator[String]]()\n\n def explore(node: String): List[String] = {\n try {\n // the \"normal\" result is Nil\n explore_tr(List(node).iterator)\n }\n catch {\n // the exceptional result is a loop\n case ResultException(loop) =&gt; loop\n }\n }\n\n @tailrec\n def explore_tr(branches: Iterator[String]): List[String] = {\n if (branches.hasNext) {\n val node = branches.next\n if (visited.contains(node)) {\n visited.push(node)\n // we found the loop\n throw new ResultException(visited.toList.reverse)\n }\n else\n maps.get(node) match {\n case None =&gt;\n // go to siblings\n if (branches.hasNext) \n explore_tr(branches)\n else {\n // track back\n if (!branchesStack.isEmpty) {\n visited.pop\n explore_tr(branchesStack.pop)\n }\n else Nil // we're done\n }\n case Some(children) =&gt;\n // go deeper\n visited.push(node)\n branchesStack.push(branches)\n explore_tr(children.iterator)\n }\n }\n else Nil\n }\n\n explore(start)\n }\n\n def main(args: Array[String]) {\n def maps = Map(\n \"1\" -&gt; List(\"2\", \"3\"),\n \"2\" -&gt; List(\"4\"),\n \"3\" -&gt; List(\"4\", \"5\"),\n \"4\" -&gt; List(\"6\", \"1\"))\n println(GetACycle(\"1\", maps))\n }\n}\n</code></pre>\n\n<p>Cheers Michael</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T07:03:00.190", "Id": "21409", "ParentId": "19504", "Score": "0" } } ]
{ "AcceptedAnswerId": "19562", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T21:49:59.810", "Id": "19504", "Score": "1", "Tags": [ "algorithm", "scala" ], "Title": "How to break this curse by a pure functional recursive function?" }
19504
<p>I am new to JavaScript development, so I'm seeking help in guidelines on how I can better organize my code in a better way. This is what I have for a small app I am working on:</p> <pre><code>var app = app || {}; app.p = function(){ ... }; app.q = function(){ ... }; app.r = function(){ ... }; app.init = function(){ ... }; app.onload = function(){ if (window.applicationCache) { window.applicationCache.addEventListener('updateready', function() { // do stuff }); } }; window.addEventListener('load', app.onload); window.addEventListener('online',app.p); Zepto(function($){ app.init(); app.p(); $('#aaaa').change(function(){ app.q(); app.r(); }); }); </code></pre> <ol> <li><p>Is it good enough that I am splitting my functions and then adding them to a single global object? Any better way?</p></li> <li><p>I am using some native <code>window.addEventListener()</code> calls. Is it ok to keep native code, even when you have a library loaded on the page, just for the performance gain? Or does it depend on the size of codebase? Is it ok for small enough and probably moving in a large one?</p></li> <li><p>How the whole execution begins, like Zepto kickstarts <code>init()</code> function on document ready event and then I take it from there, is this how I should be doing it or is there a better way?</p></li> </ol> <p>Any other suggestions welcome!</p>
[]
[ { "body": "<h1>Namespacing</h1>\n\n<blockquote>\n <p>1) Is it good enough that I am splitting my functions and then adding them to a single global object? Any better way?</p>\n</blockquote>\n\n<p>Yes, it's a good and <a href=\"https://stackoverflow.com/a/881556/1888292\">popular</a> approach. It's simple and it works. </p>\n\n<p>You might consider using closures to create <code>app.p</code>, <code>app.q</code> and <code>app.r</code>. I think this is referred to as using IIFEs (immediately invoked function expressions) [<a href=\"http://benalman.com/news/2010/11/immediately-invoked-function-expression/\" rel=\"nofollow noreferrer\">details</a>]. Right now, <code>app.p</code>, <code>app.q</code> and <code>app.r</code> have no persistent private scope. The only private scope they will have is whatever happens within the function, itself. If they needed to keep track of something, they will need to use a variable in the global scope because it is the only scope outside of the function. Using an 'IIFE' would allow there to be some persistent and private state for each function:</p>\n\n<pre><code>app.p = (function() {\n var someCounter = 0;\n return function(){ \n someCounter++;\n // do stuff\n }\n})();\n</code></pre>\n\n<p>Now, <code>app.p</code> can access the <code>someCounter</code> variable but nothing else can. <a href=\"http://snook.ca/archives/javascript/no-love-for-module-pattern\" rel=\"nofollow noreferrer\">Some people don't care for this</a>, but I'm a fan. </p>\n\n<p>For larger projects, the <code>var app = app || {};</code> might become unwieldy. Something I've been working with a bit that allows a little more flexibility is at the bottom of this page:</p>\n\n<p><a href=\"http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/\" rel=\"nofollow noreferrer\">http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/</a></p>\n\n<pre><code>function namespace(namespaceString) {\n var parts = namespaceString.split('.'),\n parent = window,\n currentPart = ''; \n\n for(var i = 0, length = parts.length; i &lt; length; i++) {\n currentPart = parts[i];\n parent[currentPart] = parent[currentPart] || {};\n parent = parent[currentPart];\n }\n\n return parent;\n}\n</code></pre>\n\n<p>Using this approach, to define something in a namespace (modified from the same page):</p>\n\n<pre><code>// using an immediately invoked function expression (IIFE)\n// keeps things private to the function and prevents spillage\n// of variables into this outer scope\n(function() {\n // retrieve what exists or make a new definition\n var examples = namespace('io.examples');\n\n // add something to it (another IIFE)\n examples.log = (function() {\n // can have private variables\n var numMsgs = 0,\n // for this, the api is an invokable function: api(), but\n // we will also add more functions to it: api.subFunction()\n // these will all have access to the numMsgs private variable\n api = function() {\n numMsgs++;\n console.log.apply(console, arguments);\n };\n api.getMsgCount = function() {\n return numMsgs;\n }\n // returning api sets io.examples.log to the api function\n return api;\n })();\n})();\n</code></pre>\n\n<p>And, to use something from a namespace:</p>\n\n<pre><code>// retrieve what exists (we already made something, \n// so it will not create an empty place-holder)\nvar log = namespace('io.examples.log');\n\n// the api was a function, so we can call it\n// or access the sub-function we attached to it\nlog('hello');\nvar numSoFar = log.getMsgCount();\n</code></pre>\n\n<p>A related topic is AMDs (asynchronous module definitions) and dependency-injection (which is rather a sub-set of what AMDs set out to do, I think). Some options are <a href=\"http://requirejs.org/\" rel=\"nofollow noreferrer\">requireJS</a>, <a href=\"http://yepnopejs.com/\" rel=\"nofollow noreferrer\">yepnope</a>, and <a href=\"http://angularjs.org/\" rel=\"nofollow noreferrer\">angularjs</a> (which entails committing the project to the angularjs framework). I'm sure there are a lot of others, I just don't know them. </p>\n\n<h1>native addEventListener</h1>\n\n<blockquote>\n <p>2) I am using some native window.addEventListener() calls...</p>\n</blockquote>\n\n<p>Historically, when I avoid using a library it's because I don't want to either load it. That being said, <a href=\"http://jsperf.com/jquery-on-vs-native/2\" rel=\"nofollow noreferrer\">the performance difference</a> is impressive. Most things I write are driven from UI events, which are generally rare (how often are you clicking?), and the performance difference between the two doesn't matter. I would say it doesn't even matter if the code base is large. Seems like the main thing would be whether you are handling events that occur super-frequently or not.</p>\n\n<p>It's also worth noting that creating a dependency on a library can hinder the reusability of whatever you're writing.</p>\n\n<h1>init process</h1>\n\n<blockquote>\n <p>3) How the whole execution begins, like Zepto kickstarts init() function</p>\n</blockquote>\n\n<p>If you're using native event listeners, then you don't have a choice, it can't go in the Zepto init. If you're using the Zepto init process, I would just put it in the <code>Zepto(...)</code> if a) nothing else needs a reference to it and b) you don't need it before then, anyway.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-23T03:49:23.477", "Id": "31768", "Score": "0", "body": "Thanks a lot for your answer, I got to learn a bunch of things I didn't know about :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T12:13:01.433", "Id": "19579", "ParentId": "19507", "Score": "10" } } ]
{ "AcceptedAnswerId": "19579", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T22:26:56.433", "Id": "19507", "Score": "9", "Tags": [ "javascript", "beginner" ], "Title": "Structure JavaScript code" }
19507
<p>I have this prime factor generator for some number <code>n</code>. It returns list of all prime factors. In other words, product of the list equals <code>n</code>.</p> <pre><code>def prime_factors_generate(n): a = [] prime_list = sorted(primes()) pindex = 0 p = prime_list[pindex] num = n while p != num: if num % p == 0: a.append(p) num //= p else: pindex += 1 p = prime_list[pindex] return a </code></pre> <p>The <code>primes()</code> function uses the <a href="http://plus.maths.org/content/os/issue50/features/havil/index" rel="nofollow noreferrer">Sundaram Sieve</a> from <a href="https://stackoverflow.com/a/2073279/596361">here</a> and returns a <em>set</em> of all primes below some limit, by default 10<sup>6</sup>.</p> <p>How can I make this code functional? I want to get rid of the <code>while</code>-loop, list appending and mutated state.</p>
[]
[ { "body": "<p>The implementation of sundaram's sieve that you've mentioned returns primes in sorted order. So, <code>sorted()</code> is not needed.</p>\n\n<p>Also, it is best to define <code>prime_list = primes()</code> outside the definition of <code>prime_factors_generate</code> (This will reduce calls to primes()). You can argue that that will make the code less functional but that would be nitpicking [Even the definition of primes() isn't functional]</p>\n\n<hr>\n\n<p>EDIT: As pointed out in a comment by mteckert, my earlier solution will not provide the desired result. This EDIT will work though (It'll return [2, 2, 2, 3] instead of [2, 3] for prime_factors_generate(24))</p>\n\n<pre><code>def max_pow(n, x):\n if n%x == 0:\n return max_pow(n/x, x)+1\n else:\n return 0\n\ndef prime_factors_generate(n): #Variables added just for convenience. Can be removed.\n prime_list = primes()\n nested_ans = map(lambda x: [x]*max_pow(n, x), prime_list)\n ans = [item for sublist in nested_ans for item in sublist]\n return ans\n</code></pre>\n\n<p>One liners (if you're interested in them) for max_pow and prime_factors generator:</p>\n\n<pre><code>max_pow = lambda n, x: max_pow(n/x, x)+1 if n%x==0 else 0\nprime_factors_generate = lambda n: [item for sublist in map(lambda x: [x]*max_pow(n, x), primes()) for item in sublist]\n</code></pre>\n\n<p>End of EDIT. I'm leaving my earlier solution intact (which returns [2, 3] for prime_factors_generate(24)).</p>\n\n<hr>\n\n<p>This should work:</p>\n\n<pre><code>def prime_factors_generate(n): #Variables added just for convenience. Can be removed.\n prime_list = primes()\n prime_factors = filter(lambda x: n % x == 0, prime_list)\n return prime_factors\n</code></pre>\n\n<p>Or if you're into one liners:</p>\n\n<pre><code>prime_factors_generate = lambda n: filter(lambda x: n % x == 0, primes())\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T06:19:20.710", "Id": "31252", "Score": "0", "body": "Your code finds prime factors, but since the problem requires that the \"product of the list equals `n`,\" a full prime factorization is necessary. For example, `f(100)` should return `[2, 2, 5, 5]` and not `[2, 5]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T07:07:44.917", "Id": "31254", "Score": "0", "body": "Yeah. sorry about this. Will edit shortly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T09:46:22.260", "Id": "31259", "Score": "0", "body": "Yeah, just found list comprehensions in http://docs.python.org/2/howto/functional.html Will modify codes appropriately." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T13:57:20.437", "Id": "31263", "Score": "0", "body": "@mteckert This is a comment on your solution - not enough reputation to comment directly. 1) Although primes need not be computed to get the correct answer, computing them and running over them alone will be faster. 2) If given the input p^q where p is a large prime, each recursive call will run from 2 to p. This can be avoided by using an auxiliary function that takes the number to start checking from as input, i.e., instead of `(x for x in range(2, ceil(sqrt(n))+1) if n%x == 0)` you can use `(x for x in range(s, ceil(sqrt(n))+1) if n%x == 0)` where s is an input to the aux. function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T00:58:34.110", "Id": "31307", "Score": "0", "body": "While there are many ways to optimize the code the focus is on making it more functional, not more performant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T05:18:33.793", "Id": "31315", "Score": "0", "body": "@mteckert I understand. But I feel that your implementation changes the identity of the original code, in the sense that the underlying algo. has changed. Instead of checking from 2 to 1st factor, then from 1st factor to 2nd..., you're doing 2 to 1st, 2 to 2nd... Kind of similar to implementing merge-sort in FP when asked to implement some other sorting algo. Just wanted to point out that this is not unavoidable in this case. Introducing an aux. function to your code won't make it any less functional and will implement the original algo. Just my opinion though." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T05:56:47.910", "Id": "19521", "ParentId": "19509", "Score": "2" } }, { "body": "<p>There are a few things you can do to make your code more functional. First note that it isn't necessary to have a list of primes beforehand. As you eliminate factors from the bottom up, there cannot be a composite \"false positive\" since its prime factors will have been accounted for already. </p>\n\n<p>Here is a more functional version of your code:</p>\n\n<pre><code>from math import ceil, sqrt\n\ndef factor(n):\n if n &lt;= 1: return []\n prime = next((x for x in range(2, ceil(sqrt(n))+1) if n%x == 0), n)\n return [prime] + factor(n//prime)\n</code></pre>\n\n<p><strong>Generator expression</strong></p>\n\n<p>This is a <a href=\"http://docs.python.org/3.3/tutorial/classes.html#generator-expressions\" rel=\"nofollow\">generator expression</a>, which is a <a href=\"http://docs.python.org/3.3/tutorial/classes.html#generators\" rel=\"nofollow\">generator</a> version of <a href=\"http://docs.python.org/3.3/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow\">list comprehensions</a>:</p>\n\n<pre><code>(x for x in range(2, ceil(sqrt(n))+1) if n%x == 0)\n</code></pre>\n\n<p>Note that in Python 2.7.3, <code>ceil</code> returns a <code>float</code> and <code>range</code> accepts <code>ints</code>.</p>\n\n<p>Basically, for every number from 2 to <code>ceil(sqrt(n))</code>, it generates all numbers for which <code>n%x == 0</code> is true. The call to <code>next</code> gets the first such number. If there are no valid numbers left in the expression, <code>next</code> returns <code>n</code>.</p>\n\n<p><strong>Recursion</strong></p>\n\n<p>This is a <a href=\"http://en.wikipedia.org/wiki/Recursion_%28computer_science%29\" rel=\"nofollow\">recursive</a> call, that appends to our list the results of nested calls:</p>\n\n<pre><code>return [prime] + factor(n//prime)\n</code></pre>\n\n<p>For example, consider <code>factor(100)</code>. Note that this is just a simplification of the call stack.</p>\n\n<p>The first prime will be 2, so:</p>\n\n<pre><code>return [2] + factor(100//2)\n</code></pre>\n\n<p>Then when the first recursive call is to this point, we have:</p>\n\n<pre><code>return [2] + [2] + factor(50//2)\nreturn [2] + [2] + [5] + factor(25//5)\nreturn [2] + [2] + [5] + [5] + factor(5//5)\n</code></pre>\n\n<p>When <code>factor</code> is called with an argument of <code>1</code>, it breaks the recursion and returns an empty list, at <code>if n &lt;= 1: return []</code>. This is called a <a href=\"http://en.wikipedia.org/wiki/Base_case\" rel=\"nofollow\">base case</a>, a construct vital to functional programming and mathematics in general. So finally, we have:</p>\n\n<pre><code>return [2] + [2] + [5] + [5] + []\n[2, 2, 5, 5]\n</code></pre>\n\n<p><strong>Generator version</strong></p>\n\n<p>We can create a generator version of this ourselves like this: </p>\n\n<pre><code>from math import ceil, sqrt\n\ndef factorgen(n):\n if n &lt;= 1: return\n prime = next((x for x in range(2, ceil(sqrt(n))+1) if n%x == 0), n)\n yield prime\n yield from factorgen(n//prime)\n</code></pre>\n\n<p>The keyword <code>yield</code> freezes the state of the generator, until <code>next</code> is called to grab a value. The <code>yield from</code> is just syntactic sugar for</p>\n\n<pre><code>for p in factorgen(n//prime):\n yield p\n</code></pre>\n\n<p>which was introduced in <a href=\"http://docs.python.org/3/whatsnew/3.3.html\" rel=\"nofollow\">Python 3.3</a>.</p>\n\n<p>With this version, we can use a for loop, convert to a list, call <code>next</code>, etc. Generators provide <a href=\"http://en.wikipedia.org/wiki/Lazy_evaluation\" rel=\"nofollow\">lazy evaluation</a>, another important tool in a functional programmer's arsenal. This allows you to create the \"idea\" for a sequence of values without having to bring it into existence all at once, so to speak.</p>\n\n<p>Though I didn't use it here, I can't resist mentioning a very nice Python library named <a href=\"http://docs.python.org/3.3/library/itertools.html\" rel=\"nofollow\"><code>itertools</code></a>, which can help you immensely with functional-style programming.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T07:09:21.173", "Id": "19523", "ParentId": "19509", "Score": "2" } } ]
{ "AcceptedAnswerId": "19523", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T22:46:03.297", "Id": "19509", "Score": "1", "Tags": [ "python", "algorithm", "functional-programming", "primes" ], "Title": "Functional prime factor generator" }
19509
<p>I have a function for finding factors of a number in Python</p> <pre><code>def factors(n, one=True, itself=False): def factors_functional(): # factors below sqrt(n) a = filter(lambda x: n % x == 0, xrange(2, int(n**0.5)+1)) result = a + map(lambda x: n / x, reversed(a)) return result </code></pre> <p><code>factors(28)</code> gives <code>[2, 4, 7, 14]</code>. Now i want this function to also include 1 in the beginning of a list, if <code>one</code> is true, and 28 in the end, if <code>itself</code> is true.</p> <pre><code>([1] if one else []) + a + map(lambda x: n / x, reversed(a)) + ([n] if itself else []) </code></pre> <p>This is "clever" but inelegant.</p> <pre><code>if one: result = [1] + result if itself: result = result + [n] </code></pre> <p>This is straight-forward but verbose.</p> <p>Is it possible to implement optional one and itself in the output with the most concise yet readable code possible? Or maybe the whole idea should be done some other way - like the function <code>factors</code> can be written differently and still add optional 1 and itself?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T03:46:51.630", "Id": "31249", "Score": "0", "body": "The straight forward way isn't that verbose. I don't see a different way to do it the doesn't sacrifice readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T04:34:05.523", "Id": "31250", "Score": "0", "body": "You may think it is verbose but it is self explanatory and can easily be commented out without messing around with the core code." } ]
[ { "body": "<p>What about this?</p>\n\n<pre><code>[1] * one + result + [n] * itself\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T05:37:14.763", "Id": "31316", "Score": "1", "body": "I was thinking `[1]*int(one) + result + [n]*int(itself)`, scrolled down and saw this beauty. Didn't know this could be done. +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T04:47:22.787", "Id": "31370", "Score": "0", "body": "interesting... but please don't actually do this. \"Programs must be written for people to read and only incidentally for machines to execute.\" This takes me way longer to read than the 4-liner." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T12:37:44.743", "Id": "19528", "ParentId": "19510", "Score": "5" } } ]
{ "AcceptedAnswerId": "19528", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T23:15:37.983", "Id": "19510", "Score": "3", "Tags": [ "python", "functional-programming" ], "Title": "Function to find factors of a number, optionally including 1 and the number itself" }
19510
<p>I am creating a commercial API for the first time for responsive webpages/web applications (mobile devices).</p> <p>I am new and, sadly, working alone as well as new to Javascript (long complicated story).</p> <p>I was just wondering if someone from the industry could offer their professional opinion on the following format of a "get" call:</p> <pre><code>var getSample = function(params) { //Returns Object return $.ajax({ url: URL + 'downloadQuadrat.php', type: 'GET', data: { 'projectID': params.pid, 'quadratID': params.qid }, dataType: dataType }); } </code></pre> <p>Function call:</p> <pre><code>var printList = function(lid,options,get) { var list = $("ul#"+lid); var promise = get(options); promise.promise().then( function(response) { var items = response; list.empty(); $.each(items, function(item,details) { var ul = $('&lt;ul/&gt;'); ul.attr('id', lid+'_'+details.ID); var li = $('&lt;li/&gt;') .text(details.ID) .appendTo(list); ul.appendTo(list); $.each(details,function(key,value) { var li = $('&lt;li/&gt;') .text(key+': '+value) .appendTo(ul); }); }); } ); } </code></pre> <p>Any input or guidance will be hugely appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T01:22:58.527", "Id": "31238", "Score": "0", "body": "Is `getSample` supposed to be getting or setting? It seems to do both." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T01:30:16.450", "Id": "31239", "Score": "0", "body": "getSample is supposed to retrieve a sample from the database, save it as an object, and add it to array. When you call the function, it returns the JSON object, so essentially it's just a \"get\".\n\nA \"setSample\" will add/update to the database" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T01:31:48.440", "Id": "31240", "Score": "0", "body": "So, getSample is not a part of the API? Is it an example of an implementation? Because you have problems with the function returning a JSON array that doesn’t exist (yet)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T02:17:26.687", "Id": "31243", "Score": "0", "body": "I've updated the code, with the new \"promise\" structure. Is it correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T09:37:45.073", "Id": "31257", "Score": "1", "body": "Have you tested either of the above code blocks? Do they work as you intended? If not, this seems like more of a question for Stack Overflow (\"how do I do this\") rather than Code Review (\"is this the best way to do this\"). I can't figure out what the second code block should do (your `get` function is undefined and `.promise()` with no params is used for monitoring animations. With your `$.ajax()` example, it seems to me you need to at least look at using the `.done()` chained method for a start." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T20:15:50.497", "Id": "31345", "Score": "0", "body": "Yep, they've always worked. I was directed from there to here actually :) My main goal is to form a healthy JS habit before I start on the rest of the API" } ]
[ { "body": "<p>From what I understand, you are building an abstraction layer and making your own functions for your API. Here's what you need:</p>\n\n<ol>\n<li><p>A Namespace </p>\n\n<p>Sounds very C++-ish but yes, you do need namespaces in JS. This prevents you from polluting the global namespace and have a central go-to object for your functions. For example, jQuery uses <code>jQuery</code> and the <code>$</code> namespaces for a central collection of their functions. Notice <code>$</code> in <code>$.each()</code>, <code>$</code> is actually the namespace (a function actually).</p></li>\n<li><p>Module that code</p>\n\n<p>Another way to prevent code pollution and collision is to wrap your code in a scope, usually called a \"closure\". This is just a geeky way of calling a function scope that persists because of something returned that still has reference to that scope. Normally, it's called a module (as in a modular piece of code). A simple way of building a module is to use an \"immediate function\" or a function that immediately executes. A more detailed explanation how it works is <a href=\"https://stackoverflow.com/a/10226918/575527\">explained here</a></p></li>\n<li><p>Extensibility</p>\n\n<p>With modular, namespaced code, usually developers forget to open their modules to extensibility. Because module pattern is like putting a cage around their code, developers forget to actually provide a way to make their module extendable. </p>\n\n<p>You should provide a way (like provide a function) that allows (limited) access to your module and allow it to attach custom functions <em>from the outside</em>. An example is how jQuery allows plugins to be made.</p></li>\n</ol>\n\n<p>Here's a short way to make a module, and have your custom functions</p>\n\n<pre><code>(function(namespace){\n\n namespace.get = function(params){\n ...\n }\n\n}(window.myNamespace = window.myNamespace || {}));\n\nmyNamespace.get(params);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T20:42:52.003", "Id": "31486", "Score": "0", "body": "thank you for that. I am actually from a C background, it's the web side of things (and JS etiquette) I struggle with. I will certainly refer to your comment when structuring my API" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T12:04:19.027", "Id": "19632", "ParentId": "19511", "Score": "3" } } ]
{ "AcceptedAnswerId": "19632", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T00:50:51.903", "Id": "19511", "Score": "2", "Tags": [ "javascript", "jquery", "api" ], "Title": "Creating JavaScript API for first time; request review" }
19511
<p>I am looking for advice on making the following code shorter. Any help is appreciated.</p> <pre><code>public String determineWinner(String winner) { winner = ""; if (playChoice.equals(compChoice)) winner = "The result is a tie."; else if (compChoice.equals("R")) if (playChoice.equals("S") || playChoice.equals("s")) winner = "Computer wins because Rock beats Scissors."; else winner = "Player wins because Paper beats Rock"; else if (compChoice.equals("S")) if (playChoice.equals("P") || playChoice.equals("p")) winner = "Computer wins because Scissors beats Paper."; else winner = "Player wins because Rock beats Scissors"; else if (playChoice.equals("R") || playChoice.equals("r")) winner = "Computer wins because Paper beats Rock."; else winner = "Player wins because Scissors beats Paper."; return winner; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T13:59:38.693", "Id": "31264", "Score": "1", "body": "A very simple improvement would be using `String.equalsIgnoreCase()` in order to avoid checking twice for uppper and lower case." } ]
[ { "body": "<p>You code looks unclear from point of view of parameter usage and ignoring case difference is case of \"The result is a tie.\", so ...</p>\n\n<p>Try this :).</p>\n\n<pre><code>public class testik {\n // No throws clause here\n public static void main(String[] args) {\n // Paper &lt; Rock &lt; Scissors &lt; Paper\n System.out.println(\"Comp:S vs User:R = \" + determineWinnerOtherWay(\"S\",\"R\")); //user win\n System.out.println(\"Comp:S vs User:P = \" + determineWinnerOtherWay(\"S\",\"P\")); // com win\n\n System.out.println(\"Comp:P vs User:R = \" + determineWinnerOtherWay(\"P\",\"R\")); //com win\n System.out.println(\"Comp:P vs User:S = \" + determineWinnerOtherWay(\"P\",\"S\")); // user win\n\n System.out.println(\"Comp:R vs User:S = \" + determineWinnerOtherWay(\"R\",\"S\")); //com win\n System.out.println(\"Comp:R vs User:P = \" + determineWinnerOtherWay(\"R\",\"P\")); // user win\n }\n\n public static String code2Title(String code){\n if (\"R\".equals(code)) {\n return \"Rock\";\n } else if (\"P\".equals(code)) {\n return \"Paper\";\n } else {\n return \"Scissors\";\n }\n }\n\n public static String determineWinnerOtherWay(String compChoice, String playChoice) {\n String winner = \"\";\n String playerChoiceN = playChoice.toUpperCase();\n if (playChoice.equals(compChoice))\n winner = \"The result is a tie.\";\n int diff = compChoice.charAt(0) - playerChoiceN.charAt(0);\n if ( diff == 1 || diff == 2 || diff ==-3) {\n winner = \"User win bacause:\"+code2Title(playerChoiceN)+\" wins \" + code2Title(compChoice);\n } else {\n winner = \"Computer wins because:\"+code2Title(compChoice)+\" wins \" + code2Title(playerChoiceN);\n }\n return winner;\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T23:16:22.987", "Id": "31303", "Score": "0", "body": "A better choice, instead of `compChoice.charAt(0) - playerChoiceN.charAt(0)` (which is sort of hacky), would be to create a custom implementation of [Comparator](http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T04:13:04.620", "Id": "31313", "Score": "0", "body": "just tried to be close to task \"making the following code shorter.\" :) but I agree with you." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T04:38:23.090", "Id": "19519", "ParentId": "19513", "Score": "2" } }, { "body": "<p>I've written this in C#, but it should translate to Java easily.</p>\n\n<p>I made <code>determineWinner()</code> call itself, reversing the order of player1 &amp; player2. This eliminates fully half of the 'if else` maze.</p>\n\n<pre><code>// these are class level variables.\nstring winnerNotice = @\"{0} wins. {1} beats {2}\";\nstring drawNotice = @\"Draw. Both players picked {0}\";\n\n// new structures to help clean up the determineWinner() method\npublic class Player { \n public string Name;\n public choices choice;\n}\n\npublic enum choices\n{\n Paper = 1 , Scissors = 2 , Rock = 4\n}\n\n public String determineWinner( Player player1, Player player2 ) {\n\n //tie\n if ( player1.choice == player2.choice ) \n return string.Format( drawNotice ,player1.choice );\n\n // paper covers rock\n if ( player1.choice == choices.Paper &amp;&amp; player2.choice == choices.Rock) \n return string.Format(winnerNotice,player1.Name,player1.choice,player2.choice);\n\n // rock beats scissors beats paper\n if ( player1.choice &gt; player2.choice ) \n return string.Format( winnerNotice ,player1.Name ,player1.choice ,player2.choice );\n\n // player 1 did not win, did player 2 win?\n determineWinner(player2, player1);\n }\n }\n\n\n\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T15:22:58.417", "Id": "19533", "ParentId": "19513", "Score": "1" } }, { "body": "<p>Consider: </p>\n\n<pre><code>paper = 2\nscissors = 3\nrock = 5\n</code></pre>\n\n<p>Then your function could look like:</p>\n\n<pre><code>public int determineWinner(int player1, int player2)\n{\n if(player1 != player2)\n if(player1 + player2 == 7)\n return Math.min(player1, player2);\n else\n return Math.max(player1, player2);\n else\n return 0;\n}\n</code></pre>\n\n<p>Then the implementation is up to you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T16:58:33.463", "Id": "19539", "ParentId": "19513", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T01:25:36.490", "Id": "19513", "Score": "3", "Tags": [ "java", "game", "rock-paper-scissors" ], "Title": "Making my Rock, Paper, Scissors game shorter" }
19513
<p>When I have a place with limited space, where I entry a text that can be few letters or huge amount of text because it's dynamic, I'm using this code to make the text fit the specific space.</p> <pre><code>#region TextSizing string textSizing = databaseTable.Description; using (System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(IntPtr.Zero)) { size = g.MeasureString(textSizing, new System.Drawing.Font("Arial", 14)).Width; } if (size &lt; 1500) lblText.Text = textSizing; else lblText.Text = textSizing.Length &gt; 135 ? textSizing.Remove(135) + "..." : textSizing; #endregion </code></pre> <p>A friend of mine suggested that I should use cache to store the Font and the Graphics, I didn't understand it very well, but keep thinking about it... <strong>How can I make this code (that is usually in a loop) faster and efficiently ?</strong></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T12:02:18.610", "Id": "31261", "Score": "0", "body": "Not sure how to put a good title for this question, so **please** feel free to change it so it can be fit more the Q&A format. thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T13:25:32.327", "Id": "31262", "Score": "2", "body": "You should use the unicode character ellipsis `…`, and not three dots. You might also be interested in https://gist.github.com/4250125" } ]
[ { "body": "<p>Cache the instance of <code>Graphics</code> and <code>Font</code> objects so that you don't need to create them each time you measure the length of string. I've created a small test to see which part takes most of the time:</p>\n\n<pre><code>private static void Main()\n{\n Stopwatch stopwatch = Stopwatch.StartNew();\n\n stopwatch.Restart();\n for (int i = 0; i &lt; 1000000; i++)\n {\n using (System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(IntPtr.Zero))\n {\n var size = g.MeasureString(\"asdasdf\", new System.Drawing.Font(\"Arial\", 14)).Width;\n }\n }\n Console.WriteLine(\"Current solution - create a new Graphics per measure: {0} milliseconds\", stopwatch.ElapsedMilliseconds);\n\n stopwatch.Restart();\n using (System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(IntPtr.Zero))\n {\n for (int i = 0; i &lt; 1000000; i++)\n {\n var size = g.MeasureString(\"asdasdf\", new System.Drawing.Font(\"Arial\", 14)).Width;\n }\n }\n Console.WriteLine(\"Measure the string with Graphics cached: {0} milliseconds\", stopwatch.ElapsedMilliseconds);\n\n stopwatch.Restart();\n using (System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(IntPtr.Zero))\n using (var font = new System.Drawing.Font(\"Arial\", 14))\n {\n for (int i = 0; i &lt; 1000000; i++)\n {\n var size = g.MeasureString(\"asdasdf\", font).Width;\n }\n }\n Console.WriteLine(\"Measure the string with Graphics and font cached: {0} milliseconds\", stopwatch.ElapsedMilliseconds);\n}\n</code></pre>\n\n<p>Results on my computer are:</p>\n\n<pre><code>Current solution - create a new Graphics per measure: 26864 milliseconds\nMeasure the string with Graphics cached: 6588 milliseconds\nMeasure the string with Graphics and font cached: 803 milliseconds\n</code></pre>\n\n<p>So by caching <code>Graphics</code> you'll reduce the time consumption by 75%, and by caching both <code>Font</code> and <code>Graphics</code> you get a nice 33.5X performance boost :).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T16:33:16.337", "Id": "31281", "Score": "0", "body": "Thank you very much for your hard work. This help me more than I expected =)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T16:37:36.483", "Id": "31282", "Score": "0", "body": "Now I just need to figure out a way to do this as a method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T17:17:29.937", "Id": "31284", "Score": "1", "body": "@MichelAyres see updated answer for better results :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T16:09:42.000", "Id": "19535", "ParentId": "19526", "Score": "10" } } ]
{ "AcceptedAnswerId": "19535", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T12:01:37.283", "Id": "19526", "Score": "2", "Tags": [ "c#", "performance" ], "Title": "How can I make this code (that is usually in a loop) faster and efficiently?" }
19526
<p>I have made a class for generating html form elements:</p> <pre><code>class input { public $tag = 'input', $type = 'text', $customClass, $name; public function __construct(array $cfg){ if ( isset($cfg['name']) ){ if ( isset($cfg['tag']){ $this-&gt;tag = strtolower($cfg['tag']); } if ( $this-&gt;tag === 'input' &amp;&amp; isset($cfg['type']){ $this-&gt;type = $cfg['type']; } if ( isset($cfg['customClass']){ $this-&gt;customClass= $cfg['customClass']; } //etc... } } } </code></pre> <p>I would like to be able to set a custom default config for all my fields - without changing the class. For example I want all the fields in a given script to have 'myClass' as customClass. For me, the solution would be to make these default values static, and make a function to change them like this:</p> <pre><code>class input { static $tag = 'input', $type = 'text', $customClass, $name; public static function setDefault(array $cfg){ if ( isset($cfg['tag']) ){ self::tag = strtolower($cfg['tag']); } if ( isset($cfg['type']) ){ self::type = $cfg['type']; } if ( isset($cfg['customClass']) ){ self::customClass= $cfg['customClass']; } //etc... } public function __construct(array $cfg){ if ( isset($cfg['name']) ){ $this-&gt;tag = isset($cfg['tag']) ? strtolower($cfg['tag']) : self::tag; $this-&gt;type = isset($cfg['type']) ? strtolower($cfg['type']) : self::type; $this-&gt;customClass = isset($cfg['customClass']) ? $cfg['customClass'] : self::customClass; //etc... } } } </code></pre> <p>The problem is that I read everywhere - and particulary here - that static are evil. What other solution would be suitable in the present case? Or can someone tell me "yeah, that's the perfect case to use statics!"? :)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T14:13:08.240", "Id": "31266", "Score": "0", "body": "some further information on how the class is used / in which context / which other components you do have regarding configuration etc... would be helpful. AFAIK there are many very clean solutions. However they highly depend on the available infrastructure and use-cases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T14:16:50.953", "Id": "31268", "Score": "0", "body": "I'm using a custom MVC framework, but I'd like this class to work as stand-alone, although I plan to use it with another class generating form from database table structure." } ]
[ { "body": "<p>You could either a <a href=\"https://stackoverflow.com/questions/3394853/builder-pattern-vs-config-object\">configuration object or a builder</a> for this. As you probably can see yourself, using static gets complicated quite fast.</p>\n\n<p><strong>Using a builder</strong>:</p>\n\n<p>\n\n<pre><code>class InputBuilder\n{\n private $_defaults = array(\n 'tag' =&gt; null,\n 'type' =&gt; null,\n );\n\n private $_current;\n\n public function __construct(array $defaults = null)\n {\n foreach ($defaults as $key =&gt; $value) {\n if (array_key_exists($this-&gt;_defaults[$key])) {\n $this-&gt;_defaults[$key] = $value;\n }\n }\n\n $this-&gt;reset();\n }\n\n public function reset()\n {\n $this-&gt;_current = array();\n foreach ($this-&gt;_defaults as $key =&gt; $value) {\n $this-&gt;_current[$key] = $value;\n } \n }\n\n public function setTag($tag)\n {\n if (!is_string($tag)) {\n throw new InvalidArgumentException('...');\n }\n $this-&gt;_current['tag'] = $tag;\n }\n\n public function setType($type)\n {\n if (!is_string($type)) {\n throw new InvalidArgumentException('...');\n }\n $this-&gt;_current['type'] = $type; \n }\n\n public function getInput()\n {\n return new Input($this-&gt;_current);\n }\n}\n</code></pre>\n\n<p>Usage would be:</p>\n\n<pre><code>$builder-&gt;setType('text')\n -&gt;build(); // tag: input, type: text\n$builder-&gt;setType('password')\n -&gt;build(); // tag: input, type: password\n$builder-&gt;reset(); // reset everything to defaults\n$builder-&gt;setTag('textarea') // tag: textarea: type: text\n -&gt;build();\n</code></pre>\n\n<p>The builder pattern is extremely strong if you want to build the object programmatically. (SQL) Query-builder are a very common use case for this.</p>\n\n<p><strong>Using a configuration object</strong>:</p>\n\n<pre><code>class InputConfiguration\n{\n private $_init = array(\n 'tag' =&gt; null,\n 'type' =&gt; null,\n );\n\n private $_current;\n\n public function __construct(array $defaults = null)\n {\n foreach ($defaults as $key =&gt; $value) {\n if (array_key_exists($this-&gt;_defaults[$key])) {\n $this-&gt;_defaults[$key] = $value;\n }\n }\n }\n\n public function configure(Input $element)\n {\n $config = $this-&gt;_init['tag'];\n\n if (null !== $config['tag'] &amp;&amp; null !== $element-&gt;getTag()) {\n $element-&gt;setTag($config['tag']);\n }\n\n if (null !== $config['type'] &amp;&amp; null !== $element-&gt;getType()) {\n $element-&gt;setType($config['type']);\n }\n }\n}\n\nclass Input \n{\n public function construct(InputConfiguration $config = null)\n {\n if (null !== $config) {\n $config-&gt;configure($this);\n }\n }\n\n // ...\n}\n</code></pre>\n\n<p>Usage would be: </p>\n\n<pre><code>$configuration = new InputConfiguration(\n 'tag' =&gt; 'input', \n 'type' =&gt; 'text',\n);\n\n$newObject = new Input($configuration); // has defaults applied\n\n$newObject2 = new Input(); // we don't want to use defaults\n$configuration-&gt;configure($newObject2); // or decide to apply them later on\n</code></pre>\n\n<p>The configuration object decouples the configuration from your object. Furthermore it makes one configuration reusable and optional.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T18:34:12.040", "Id": "31292", "Score": "0", "body": "Thanks, that looks like a good implementation. What I prefered in mine is there was only one class - so 1 file included but that's detail. Yes, I think a builder would be the solution for me. Still, why do you say \"using static gets complicated quite fast\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T20:25:07.070", "Id": "31299", "Score": "0", "body": "because you maintain almost the same information twice within the class + the class is responsible for knowing two thinks: the defaults and the current data. Look at your code above - in my opinion it's already overly complicated ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T15:30:11.703", "Id": "19534", "ParentId": "19529", "Score": "1" } } ]
{ "AcceptedAnswerId": "19534", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T13:17:59.040", "Id": "19529", "Score": "1", "Tags": [ "object-oriented", "php5", "static" ], "Title": "Using static for class default properties" }
19529
<p>As an example, suppose I had a large amount of data about a set of Restaurants for a large set of Dates in a database that I need to analyze / output to the user.</p> <p>I have a custom class that holds the data for each restaurant for each date:</p> <pre><code>Public Class DateData Public Property Var1 As Double = 0 Public Property Var2 As Double = 0 Public Property Var3 As Double = 0 Public Property Var4 As Double = 0 Public Sub Sub1() .... End Sub ... etc .... End Class </code></pre> <p>And since I am getting this data for each date (and since date-order does matter for my calculations), I have the following class set up too (where most of the work / calculation is done):</p> <pre><code>Public Class RestaurantData Inherits SortedDictionary(Of Date, DateData) Public Property Name As String Public Property RestaurantLevelData1 As Double = 0 Public Property RestaurantLevelData2 As Double = 0 Public Sub New(ByVal strName As String, ByVal DatesList As List(Of Date)) _Name = strName For Each daDate As Date In DatesList Me.Add(daDate) Next End Sub Public Overloads Sub Add(ByVal daDate As Date) MyBase.Add(daDate, New DateData) End Sub Public Sub Sub1() For i As Integer = 0 To Me.Keys.Count - 1 Dim daDate As Date = Me.Keys(i) Me(daDate).Sub1() .... etc .... Next End Sub ... etc .... End Class </code></pre> <p>And, finally, since this is for a large amount of restaurants, I have a class which holds this <code>Dictionary</code> on a restaurant levele:</p> <pre><code>Public Class RestaurantsDict Inherits Dictionary(Of String, RestaurantData) Public Overloads Sub Add(ByVal strName As String, ByVal Dates As List(Of Date)) MyBase.Add(strName, New RestaurantData(strName, Dates)) End Sub End Class </code></pre> <p>I have 2 main questions:</p> <ol> <li><p>Is this a good way to set this up? My original code consisted of dozens of</p> <pre><code>Dictionary(Of String, SortedDictionary(Of Date, Double)) </code></pre> <p>But I am a fairly novice programmer and would love to know if there is a more efficient architecture for what I am trying to achieve.</p></li> <li><p>The way I am currently setting this up is very hard to debug. For example, the <code>Count</code> property of my <code>RestaurantData</code> throws an exception of type <code>System.TypeLoadException</code>.</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T14:38:28.177", "Id": "31269", "Score": "0", "body": "Why do you need a `SortedDictionary`? Other options are: just to sort incoming data by dates and store in array or list; use `SortedList`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T14:51:34.173", "Id": "31273", "Score": "0", "body": "@almaz, Thanks for the comment and answer. Just to understand how you would suggest doing this, you would simply use a dictionary and have a separate SortedList(Of Date) that I oculd use to hold the keys in a sorted fashion?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T15:45:46.703", "Id": "31278", "Score": "2", "body": "`SortedList<TKey, TValue>` is pretty much the same as `SortedDictionary<TKey, TValue>`, the difference is in internal data structures, memory consumption and performance of addition/searching" } ]
[ { "body": "<p>Inheriting from collections is rarely a good practice. In your case it's better to have a private collection (<code>SortedDictionary</code> in your case), and populate it as needed (in other words it's better to use delegation than inheritance here). </p>\n\n<p>The reason why inheriting is not so good here is that your class will expose a lot of functionality that users of <code>RestaurantData</code> aren't actually interested in.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T14:50:02.450", "Id": "31271", "Score": "0", "body": "Thanks for the response - Just to understand (since this is all fairly new to me), you are suggesting my initial approach of just having a series of `Dictionary(Of...)` in my code rather than creating custom objects? My logic for going this way was that it allowed me to create extra `Add` events and constructors for these specific classes... As a larger-scale question, when do you decide to delegate rather than inherit? Thanks!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T14:54:02.350", "Id": "31274", "Score": "2", "body": "@JohnBustos: No, you will have one private `SortedDictionary` inside your `RestaurantData` class and will potentially have public methods in that class similar to those in `SortedDictionary`. It is possible that you will want to implement `IDictionary` or `IEnumerable` (e.g., so that you can use Linq on `RestaurantData`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T15:37:49.987", "Id": "31277", "Score": "0", "body": "Aaaaaah, @Brian... Ok, that's **beginning** to make sense to me and my thick skull... So I would still have those 3 different classes, just not inherit the `Dictionary` / `SortedDictionary`. Another question - the way I have it programmed now allows me to write my code along the lines of `MyRestaurantDict(\"RestName\")(#Date#).Var1` - How could I get the same functionality / ease of referencing without inheriting the dictionary classes? Could you (or someone) just point me in the right direction as to how my class definitions could look? Thanks!!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T15:53:43.147", "Id": "31279", "Score": "0", "body": "@JohnBustos You would have to create a new method `GetDateData(Date)` in `RestaurantData` that will return required DateData object" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T14:41:46.360", "Id": "19532", "ParentId": "19530", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T13:33:56.460", "Id": "19530", "Score": "2", "Tags": [ ".net", "object-oriented", "vb.net" ], "Title": "Inherit SortedDictionary" }
19530
<p>I came across a situation where I'd like to improve my code, but don't really have a clue about what I could do... It's for a game I'm making, I want to get a perimeter surrounding a unit, but I don't want tiles inside the perimeter. I'm pretty sure there is a better way to do this. (@x and @y are the unit's coordinates)</p> <pre><code>r = 4 radius = [] for x in @x-r..@x+r for y in @y-r..@y+r radius.push([x, y]) if $game_map.passable?(x, y) end end radius.delete_if {|a| radius.include?([a[0] + 1, a[1]]) &amp;&amp; radius.include?([a[0] - 1, a[1]]) &amp;&amp; radius.include?([a[0], a[1] + 1]) &amp;&amp; radius.include?([a[0], a[1] - 1]) } </code></pre> <p>There are some things that I simplified here to focus on the problem, like the local variable 'r' that would not be constantly 4. What matters is how to handle radius so it gives the same result without having to add the coordinates that will be removed.</p> <p>Performance is important as this function is called frequently by many units.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T14:55:23.023", "Id": "31275", "Score": "0", "body": "Please a give some assert test (or a couple) in the form \"If I have this @x, @y and r, I want this value in radius\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T15:02:24.403", "Id": "31276", "Score": "0", "body": "The thing is that the perimeter is irregular, I need at least two couples of coordinates by row and by column. r is there as a limit, a range. If the perimeter was a rectangle, then I could easily add something in my loop like: next if ! ([@x-r, @x+r].include?(x) || [@y-r, @y+r].include?(y))" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T22:04:35.983", "Id": "31438", "Score": "0", "body": "Is this for a homework problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T22:24:37.287", "Id": "31439", "Score": "0", "body": "Also, have you seen any performance penalty with the current approach?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T10:18:41.790", "Id": "31495", "Score": "0", "body": "No, it's for a personal project. And well, it's not particularly good since the program adds useless values and then evaluates them all. I wonder if there would be some kind of algorithm which can simply add the necessary values so I don't have to use delete_if. Also, as you may have noticed, with my current solution I need to get all the values I normally wouldn't want in order to make the evaluations. This function is quite frequently, so improving this part of the code will make a difference." } ]
[ { "body": "<blockquote>\n<p>Better late than never - Anon</p>\n<p>first make it work, then make it right, and, finally, make it fast. -\nKernighan &amp; Johnson</p>\n<p>Rules of optimization:\n(1) Don't.\n(2) (for experts only) Don't yet.\n(3) Profile before optimizing</p>\n</blockquote>\n<h1>First make it work, then make it right</h1>\n<p>There's a bug. If <code>$game_map#passable?</code> always returns true, the\ncoordinates returned by this code are in this pattern:</p>\n<pre><code>XXXXXXXXX\nX-X-X-X-X\nXX-X-X-XX\nX-X-X-X-X\nXX-X-X-XX\nX-X-X-X-X\nXX-X-X-XX\nX-X-X-X-X\nXXXXXXXXX\n</code></pre>\n<p>Based on your description, you are (or were) looking for this pattern:</p>\n<pre><code>XXXXXXXXX\nXXXXXXXXX\nXXXXXXXXX\nXXX---XXX\nXXX---XXX\nXXX---XXX\nXXXXXXXXX\nXXXXXXXXX\nXXXXXXXXX\n</code></pre>\n<p>The trouble is here:</p>\n<pre><code> radius.delete_if {|a|\n radius.include?([a[0] + 1, a[1]]) &amp;&amp;\n radius.include?([a[0] - 1, a[1]]) &amp;&amp;\n radius.include?([a[0], a[1] + 1]) &amp;&amp;\n radius.include?([a[0], a[1] - 1])\n }\n radius\n</code></pre>\n<p>One fix is to replace those lines with:</p>\n<pre><code> radius.reject do |x, y|\n x.between?(@x - 1, @x + 1) &amp;&amp; y.between?(@y - 1, @y + 1)\n end\n</code></pre>\n<h1>and finally, make it fast</h1>\n<p>With the above fix, the code works, so let's benchmark it. 10,000\niterations of it take 0.600 seconds on my box.</p>\n<p>We can do better. Instead of adding coordinates just to remove them\nlater, how about not adding them in the first place?</p>\n<pre><code> r = 4\n radius = []\n for x in @x-r..@x+r\n for y in @y-r..@y+r\n next if x.between?(@x - 1, @x + 1) &amp;&amp; y.between?(@y - 1, @y + 1)\n radius.push([x, y]) if $game_map.passable?(x, y)\n end\n end\n radius\n</code></pre>\n<p>This is simpler, but is it faster? Just a bit. 10,000 iterations now\ntake 0.500 seconds instead of 0.600. More important, though, it's\nsimpler.</p>\n<p>There doesn't seem to be much room for optimization here, which leads\nto these questions:</p>\n<ul>\n<li>Is the program fast enough?</li>\n<li>If not, <em>which part of the program is the bottleneck</em>?</li>\n</ul>\n<p>You can't answer those questions without profiling. That's why the\nfirst code you write should be clear and correct. Then, only if it isn't\nfast enough, profile to learn where it's too slow, and optimize that\npart. Repeat until it's fast enough, then stop.</p>\n<p>The reason to optimize later rather than earlier is because\noptimization has a cost. It increases the complexity of the code,\noften leading to code that's harder to read and maintain. It's no\ngood to pay that cost unless you're getting actual benefit from it.</p>\n<h1>An OOP issue</h1>\n<p>This code should probably be in GameMap:</p>\n<pre><code>class GameMap\n ...\n\n def passable_coords_near(x, y)\n r = 4\n radius = []\n for x in (x - r)..(x + r)\n for y in (y - r)..(y + r)\n next if x.between?(x - 1, x + 1) &amp;&amp; y.between?(y - 1, y + 1)\n radius.push([x, y]) if passable?(x, y)\n end\n end\n radius\n end\n\n ...\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T13:47:41.553", "Id": "38827", "ParentId": "19531", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T14:13:09.980", "Id": "19531", "Score": "3", "Tags": [ "performance", "ruby" ], "Title": "Irregular perimeter in Ruby code" }
19531
<p>I need help refactoring this method. It is way too long.</p> <pre><code> def report_total(feed_event, advisor) count = 0 advisor.activity_feed_events.each do |lead| if lead == SignupFeedEvent count += 1 else if lead.is_a?(feed_event) if lead.event_date &gt; (Time.now - 7.days) count += 1 end end end end count end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T17:14:16.907", "Id": "31283", "Score": "0", "body": "Is this in a Rails app? Are the different types of `FeedEvent` in a single table (i.e. are you using STI)? A little context would be helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T17:22:37.633", "Id": "31287", "Score": "0", "body": "Yes, it's a Rails app." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T17:23:29.707", "Id": "31288", "Score": "0", "body": "ActivityFeedEvent is the parent class and all the others (ex: SignupFeedEvent) inherit from this parent." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T17:27:59.443", "Id": "31289", "Score": "0", "body": "And are they all in the same table in your database (with a `type` column)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T17:29:11.107", "Id": "31290", "Score": "0", "body": "@andy h Yup, thats correct!" } ]
[ { "body": "<p>You could use scopes to do this at the database level, which would (potentially) be much faster than returning then iterating over all <code>ActivityFeedEvent</code>s.</p>\n\n<pre><code># ActivityFeedEvent\nscope :by_type, -&gt;(type){ where(type: type.to_s) }\nscope :recent, -&gt;{ where(\"event_date &gt; ?\", Time.now - 7.days) }\n\n# wherever report_total is\ndef report_total(feed_event_type, advisor)\n advisor.activity_feed_events.by_type(SignupFeedEvent).count +\n advisor.activity_feed_events.recent.by_type(feed_event_type).count\nend\n</code></pre>\n\n<p>Note that you need a lambda for the <code>recent</code> scope despite it not taking args, because otherwise the Time.now will only be evaluated once (when the server starts).</p>\n\n<p>Or, perhaps even more neatly, you could do it the other way round:</p>\n\n<pre><code># ActivityFeedEvent\nscope :for, -&gt;(advisor){ where(advisor_id: advisor.id) }\nscope :recent, -&gt;{ where(\"event_date &gt; ?\", Time.now - 7.days) }\n\n# wherever report_total is\ndef report_total(feed_event_type, advisor)\n SignupFeedEvent.for(advisor).count + feed_event_type.for(advisor).count\nend\n</code></pre>\n\n<p>Depending on your models you may need a more descriptive name than <code>for</code> for this one, <code>belonging_to</code> or <code>for_advisor</code> are candidates.</p>\n\n<p>Also note that some people prefer to write scopes as class methods instead of using lambdas</p>\n\n<pre><code># ActivityFeedEvent\ndef self.for(advisor)\n where(advisor_id: advisor.id)\nend\n\ndef self.recent\n where(\"event_date &gt; ?\", Time.now - 7.days)\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T17:46:21.367", "Id": "19541", "ParentId": "19538", "Score": "3" } }, { "body": "<p>Andy's solution with scopes is the one, so just to complement it, a refactor of your method using <code>sum</code> (although what you really need is <code>count</code>, see other answers):</p>\n\n<pre><code>def report_total(feed_event, advisor)\n advisor.activity_feed_events.sum do |lead|\n if lead == SignupFeedEvent ||\n (lead.is_a?(feed_event) &amp;&amp; lead.event_date &gt; (Time.now - 7.days))\n 1\n else\n 0\n end\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T21:59:58.020", "Id": "31437", "Score": "0", "body": "You could pull the boolean logic into a predicate method that takes `lead` as an argument." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T22:55:46.987", "Id": "31440", "Score": "0", "body": "yeah, something like `lead.reportable?`. But I wanted to focus on the refactoring of the same OP code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T19:35:11.290", "Id": "19547", "ParentId": "19538", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T16:56:05.130", "Id": "19538", "Score": "2", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Simple: Need help refactoring this awkward looking method" }
19538
<p>I have a mammoth SQL statement, however it's taking a long time to load (27 secs on the server). I think the issue lies with the IN statements towards the bottom (the IN statement is repeated too, can this be stored so it only does it once?) (taking it out shaves 23 seconds, anything under 10 will be brilliant) but i'm unsure, is there any better ways of writing this?</p> <p>Thanks in advance!</p> <p>Dave</p> <pre><code>DECLARE @site INT = 4 DECLARE @langid INT = 9 DECLARE @checkID INT = 0 DECLARE @minstockQTY INT = 0 DECLARE @branchCount INT = (SELECT COUNT(*) FROM Branch WHERE ApplicationID = @site) if @site = 4 BEGIN SET @checkID = 4 end select p.*, stuff((select ',' + cast(BrandID as nvarchar(max)) from Product_Brand_Mapping d where d.ProductCode = p.ProductCode AND d.ApplicationID = @site for xml path('')) , 1, 1, '') as BrandIDs, stuff((select '|' + cast(Name as nvarchar(max)) from Brands e where e.ID IN (SELECT BrandID FROM Product_Brand_Mapping f WHERE f.ProductCode = p.ProductCode AND f.ApplicationID = @site) for xml path('')), 1, 1, '') as BrandNames, stuff((select ',' + cast(DepartmentID as nvarchar(max)) from Product_Department_Mapping e where e.ProductCode = p.ProductCode and e.ApplicationID = @site for xml path('')), 1, 1, '') as DepartmentIDs, stuff((select ',' + cast(DepartmentID as nvarchar(max)) + '|' + cast(DisplayOrder as nvarchar(max)) from Product_Department_DisplayOrder e where e.ProductCode = p.ProductCode and e.ApplicationID = @site for xml path('')), 1, 1, '') as DisplayOrders, stuff((select '|' + cast(Size as nvarchar(max)) from Products e where e.ProductCode = p.ProductCode and e.Sell &gt; 0 AND e.Department &gt; 0 AND e.ApplicationID = @site AND e.Published = 1 AND e.PrimaryPLU IN (select SKU FROM Stock WHERE BranchID IN (1,2,11,12,32,31,13,14,15,0,96) AND ApplicationID = @site GROUP BY SKU HAVING(SUM(CASE WHEN Stock &lt; 0 AND BranchID = 31 THEN Stock WHEN BranchID = 31 THEN Stock END)) - p.MinStockQty &gt; 0) for xml path('')), 1, 1, '') as Sizes, stuff((select '|' + cast(Colour as nvarchar(max)) from Products e where e.ProductCode = p.ProductCode and e.Sell &gt; 0 AND e.Department &gt; 0 AND e.ApplicationID = @site AND e.Published = 1 AND e.PrimaryPLU IN (select SKU FROM Stock WHERE BranchID IN (1,2,11,12,32,31,13,14,15,0,96) AND ApplicationID = @checkID GROUP BY SKU HAVING(SUM(CASE WHEN Stock &lt; 0 AND BranchID = 31 THEN Stock WHEN BranchID NOT IN (31) THEN Stock END)) - p.MinStockQty &gt; 0) for xml path('')), 1, 1, '') as Colours, (select MAX(pr.Sell) from Products pr where pr.ProductCode = p.ProductCode AND pr.ApplicationID = @site) as SellTo, (select MAX(pr.WholeSale) from Products pr where pr.ProductCode = p.ProductCode AND pr.ApplicationID = @site) as WasTo, (select MAX(Department) from Products pr where pr.ProductCode = p.ProductCode AND pr.ApplicationID = @site) as Department from ProductDescription p WHERE p.ApplicationID = @site AND p.LanguageID = @langid AND p.Published = 1 AND p.Deleted = 0 AND p.ProductCode IN (SELECT Distinct pr.ProductCode FROM Products pr WHERE pr.Sell &gt; 0 AND pr.Department &gt; 0 AND pr.ApplicationID = @site AND pr.Published = 1) AND ((SELECT SUM(st.Stock) FROM Stock st WHERE st.ApplicationID = 4 AND st.SKU IN (SELECT DISTINCT pr.PrimaryPLU FROM Products pr WHERE p.ProductCode = pr.ProductCode AND pr.ApplicationID = @site) AND st.BranchID IN (1,2,11,12,32,13,14,15,0,96)) + ISNULL((SELECT SUM(st.Stock) FROM Stock st WHERE st.ApplicationID = 4 AND st.SKU IN (SELECT DISTINCT pr.PrimaryPLU FROM Products pr WHERE p.ProductCode = pr.ProductCode AND pr.ApplicationID = @site) AND st.BranchID = 31 AND st.Stock &lt; 0), 0)) - p.MinStockQty &gt; 0 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T18:08:32.740", "Id": "31291", "Score": "2", "body": "Please include execution plan" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T18:36:18.293", "Id": "31293", "Score": "0", "body": "Also please describe your data structures, mainly what are the primary keys for tables involved in the query" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T23:12:09.527", "Id": "31302", "Score": "2", "body": "I have a feeling that, if we knew a little more about your relationships (entity, not personal), we might be able to figure our what bits and pieces could be simplified. Some of your `CASE` statements have unnecessary conditions..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T13:15:43.847", "Id": "39041", "Score": "0", "body": "If you want to get a really good and efficient answer, it would help the most if you provided the community with all the pieces to get up and running with the query. If the data is not confidential, could you generate `CREATE TABLE` and `INSERT` statements for all of the relevant tables as [pasties](http://pastie.org/) and link them in your post. If it is confidential, then manufacture some fake data that shows the problem. Ideally, provide a [SQLFiddle](http://www.sqlfiddle.com/) with your query running and showing results, and you will get lots of help." } ]
[ { "body": "<p>Subquery should not be used.Please prefer a join with Table\\view</p>\n\n<pre><code>Select * from ProductDescription pinner join Product PR on P.ProductCode=PR.ProductCode on AND pr.Department &gt; 0 \n AND pr.ApplicationID = @site \n AND pr.Published = 1 Left join Stock st on PR.SKU=pr.PrimaryPLU WHERE p.ApplicationID = @site \n AND p.LanguageID = @langid \n AND p.Published = 1 \n AND p.Deleted = 0\n</code></pre>\n\n<p>This is not complete sql but might help you to refactor you code </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T08:53:05.700", "Id": "19770", "ParentId": "19542", "Score": "1" } }, { "body": "<p>Use the Display Estimated Execution plan and Show Execution Plan on the Query Analyzer menu.</p>\n\n<p>Pay special attention to the 'Percentage of Overall Query' numbers. You can make significant improvements by focusing on any single step that is taking the most time.</p>\n\n<p>Number one no brainier to look for is Table Scan of any large table. Table Scan of small ( less than 100 rows or so ) is perfectly ok.</p>\n\n<p>You can hover highlight the connecting lines between the steps to show the amount of data that is being transferred in each filtering step. This can give you a clue as to what could be optimized. The more data that is being moved around and joined with other large amounts of data means a slower query. </p>\n\n<p>Be aware of the kinds of join strategy being selected by the engine. The lack of appropriate indexes can force the engine to pick a very slow join strategy. As you add indexes, monitor the choices made by the engine each time you redo the execution plan. Watch for table scan to disappear and index seeks to show up. Watch for join strategies to change and perhaps the overall data flow to be rearranged in a more efficient way once appropriate indexes are added. Also once you develop a baseline for the approximately correct plan for this type of data pull, you will have an easier time if performance problems come up in the future.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-17T18:30:01.483", "Id": "29893", "ParentId": "19542", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T18:01:51.440", "Id": "19542", "Score": "5", "Tags": [ "sql", "sql-server" ], "Title": "SQL Query Tuning" }
19542
<p>I just started learning how to write code in Java. I want to turn the code to OOP with fewer methods, using classes like Sudoku rather than <code>int[][]</code> puzzle.</p> <pre><code>import java.util.Random; //Generates a Sudoku puzzle through brute-force public class SudokuPuzzle { public int[][] puzzle = new int[9][9]; // Generated puzzle. public int[][] solved_puzzle = new int[9][9]; // The solved puzzle. private int[][] _tmp_grid = new int[9][9]; // For the solver private Random rand = new Random(); private short solution_count; // Should be 1 /** * Constructor generates a new puzzle, and its solution */ public SudokuPuzzle() { generateSolvedPuzzle(0); generatePuzzle(); } /** * Finds a solved puzzle through depth-first search */ private boolean generateSolvedPuzzle(int cur_cell) { if (cur_cell &gt; 80) return true; int col = cur_cell % 9; int row = cur_cell / 9; // create a sequence of the integers {1,...,9} of random order int [] numbers = new int[9]; for (int i=0; i &lt; 9; i++) numbers[i] = 1+i; shuffle_array(numbers); for (int i=0; i &lt; 9; i++) { int n = numbers[i]; // for the next number in the array // if number is acceptable by Sudoku rules if (!existsInColumn(solved_puzzle, n, col) &amp;&amp; !existsInRow(solved_puzzle, n, row) &amp;&amp; !existsInSubGrid(solved_puzzle, n, row, col)) { // attempt to fill in the next cell with the current cell set to number solved_puzzle[row][col] = n; if (generateSolvedPuzzle(cur_cell + 1)) return true; solved_puzzle[row][col] = 0; // didn't work, reset cell and try the next number in sequence } } return false; // unreachable (since search is exhaustive and a solved puzzle must exist) } /** * Solves the Sudoku puzzle through depth-first, exhaustive search, and store the number of * solutions in solution_count. Currently, we want to use this only to detect if two solutions * exist. Hence, we stop the search as soon as two solutions have been found. * * */ private boolean _solvePuzzle(int cur_cell) { if (cur_cell &gt; 80) { solution_count++; if (solution_count &gt; 1) // two solutions detected. notify caller to abort search return true; return false; } int col = cur_cell % 9; int row = cur_cell / 9; if (_tmp_grid[row][col] == 0) // if cell is unfilled { for (int n=1; n &lt;= 9; n++) // for each number { // if number is acceptable by Sudoku rules if (!existsInColumn(_tmp_grid, n, col) &amp;&amp; !existsInRow(_tmp_grid, n, row) &amp;&amp; !existsInSubGrid(_tmp_grid, n, row, col)) { // attempt to fill in the next cell with the current cell set to number _tmp_grid[row][col] = n; if (_solvePuzzle(cur_cell + 1)) // notified of two solutions being detected return true; // notify caller to abort search _tmp_grid[row][col] = 0; // try with other numbers } } } else if (_solvePuzzle(cur_cell + 1)) // notified of two solutions being detected return true; // notify caller to abort search return false; } private void shuffle_array(int array[]) { // swap the first size elements with other elements from the whole array for (int i = 0; i &lt; array.length; i++) { // find an index j (i&lt;j&lt;=array_length) to swap with the element i int j = i + rand.nextInt(array.length - i); int t = array[j]; array[j] = array[i]; array[i] = t; } } /** * Returns whether a given number exists in a given column. * * @param col column to check. * @param number number to check. * @return true iff number exists in row. */ private boolean existsInColumn(int[][] puzzle, int number, int col) { for (int row = 0; row &lt; 9; row++) if (puzzle[row][col] == number) return true; return false; } /** * Returns whether a given number exists in a given row. * * @param row row to check. * @param number number to check. * @return true iff number exists in row. */ private boolean existsInRow(int[][] puzzle, int number, int row) { for (int col = 0; col &lt; 9; col++) if (puzzle[row][col] == number) return true; return false; } /** * Returns whether if the 3x3 sub-grid which includes (row, col) contains a * cell with the given number. * * @param row a row in the sub-grid. * @param col a col in the sub-grid. * @param number number to check. * @return true iff sub-grid contains number. */ private boolean existsInSubGrid(int[][] puzzle, int number, int row, int col) { int sub_grid_start_row = (row / 3)*3; int sub_grid_start_col = (col / 3)*3; for (int _row = sub_grid_start_row; _row &lt; sub_grid_start_row + 3; _row++) for (int _col = sub_grid_start_col; _col &lt; sub_grid_start_col + 3; _col++) if (puzzle[_row][_col] == number) return true; return false; } /** * Generates a Sudoku puzzle from a solved puzzle by setting up to 64 cells to 0. * (We cannot set more than 64 cells to 0. See http://www.math.ie/McGuire_V1.pdf) */ private void generatePuzzle() { // copy solved_puzzle to puzzle for (int row = 0; row &lt; 9; row++) for (int col = 0; col &lt; 9; col++) puzzle[row][col] = solved_puzzle[row][col]; // create a sequence of the integers {0,...,80} of random order int [] cell_sequence = new int[81]; for (int i=0; i &lt; 81; i++) cell_sequence[i] = i; shuffle_array(cell_sequence); // attempt to set each cell in the sequence to 0 int count_set_to_zero = 0; for (int i=0; i &lt; 81 &amp;&amp; count_set_to_zero &lt; 64; i++) { int cur_cell = cell_sequence[i]; int col = cur_cell % 9; int row = cur_cell / 9; int sav = puzzle[row][col]; puzzle[row][col] = 0; solution_count = 0; // copy puzzle to _tmp_grid for the solver to work on for (int r = 0; r &lt; 9; r++) for (int c = 0; c &lt; 9; c++) _tmp_grid[r][c] = puzzle[r][c]; if (_solvePuzzle(0)) // Puzzle allows more than 1 solution puzzle[row][col] = sav; // Revert to original puzzle else count_set_to_zero++; } } public void showSolution() { for (int row = 0; row &lt; 9; row++) { System.out.print(" "); for (int col = 0; col &lt; 9; col++) System.out.print(" " + solved_puzzle[row][col]); System.out.println(); } } public void show() { for (int row = 0; row &lt; 9; row++) { System.out.print(" "); for (int col = 0; col &lt; 9; col++) System.out.print(" " + puzzle[row][col]); System.out.println(); } } public static void main(String[] args) { SudokuPuzzle sudoku_puzzle = new SudokuPuzzle(); System.out.println("Puzzle:"); sudoku_puzzle.show(); System.out.println(); System.out.println("Solution:"); sudoku_puzzle.showSolution(); } </code></pre>
[]
[ { "body": "<p>Try to think of different components with different responsibilities, like: </p>\n\n<ul>\n<li>SudokuTable, with basic functionality to store/change the table values</li>\n<li>SudokuGenerator</li>\n<li>SudokuSolver</li>\n<li>SudokuVisualizer</li>\n<li>MatrixUtils</li>\n</ul>\n\n<p>as a later exercise, look at the components you defined and try to imagine possible subclasses for each one, e.g., ConsoleSudokuVisualizer, SwingSudokuVisualizer, RandomSudokuGenerator, FileBasedSudokuGenerator. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T19:18:54.067", "Id": "19545", "ParentId": "19544", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T18:11:46.487", "Id": "19544", "Score": "6", "Tags": [ "java", "sudoku" ], "Title": "Change Sudoku code to OOP" }
19544
<p>I've just started to practice coding in OOP and just wanted to ask if my code's pattern is correct. I need your comments or suggestions so I can improve it.</p> <p><strong>sample_class.php:</strong></p> <pre><code>&lt;?php $host = 'localhost'; $db = 'sample_db'; $user = 'sample_user'; $pass = 'sample_password'; $conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass); $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $conn-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); Class MySearchClass { public function __construct(PDO $conn) { $this-&gt;pdo=$conn; } public function search_name($keyword){ $query = "SELECT * FROM table WHERE name = '$keyword'"; $result = $this-&gt;pdo-&gt;prepare($query); $result -&gt;execute(); return $result; } public function view_all(){ $query = "SELECT * FROM table"; $result = $this-&gt;pdo-&gt;prepare($query); $result -&gt;execute(); return $result; } } </code></pre> <p><strong>search_form.php:</strong></p> <pre><code>&lt;?php include('sample_class.php'); $search= new MySeachClass($database_connection); if (isset($_POST['submit'])){ $keyword = $_POST['keyword']; $go_search = $search-&gt;search_name($keyword); $data = $go_search-&gt;fetchAll(PDO::FETCH_ASSOC); foreach($data as $row){ echo $row['name']; echo other rows.... } }else{ $view = $search-&gt;view_all(); $data = $view-&gt;fetchAll(PDO::FETCH_ASSOC); foreach($data as $row){ echo $row['name']; echo other rows.... } } &lt;form action="" method="POST"&gt; &lt;input type="text" name="keyword"&gt; &lt;input type="submit" name="search"&gt; &lt;/form&gt; </code></pre>
[]
[ { "body": "<p>Here's a recommendation to bind parameters correctly. This sort of thing is used to prevent against SQL injection attacks.</p>\n\n<pre><code>$query = \"SELECT * FROM table WHERE name = :keyword\"; \n$statement = $this-&gt;pdo-&gt;prepare($query);\n$statement-&gt;bindParam(':keyword', $keyword, PDO::PARAM_STR);\n$result $statement-&gt;execute(); \n</code></pre>\n\n<p>Read more about <a href=\"http://php.net/manual/en/pdostatement.bindparam.php\">PDOStatement#bindParam</a> here</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T20:18:00.370", "Id": "19552", "ParentId": "19551", "Score": "5" } }, { "body": "<p>The caller of <code>MySearchClass</code> methods should not know that there is a PDO access layer to database - the caller should not know about database at all! The class might internally query cache first or return hardcoded values - but return ready to use php collections (arrays)!</p>\n\n<p>So I suggest moving all the <code>fetchAll</code> calls into <code>MySearchClass</code> methods.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T20:36:59.893", "Id": "19553", "ParentId": "19551", "Score": "3" } }, { "body": "<p>If you're on PHP 5.2.0 you should also use <a href=\"http://www.php.net/manual/en/function.filter-input-array.php\" rel=\"nofollow\">filter_input_array</a> or <a href=\"http://www.php.net/manual/en/function.filter-input.php\" rel=\"nofollow\">filter_input()</a> rather than $_POST as this allows you to sanitize the string before it goes anywhere else.</p>\n\n<p>For example:</p>\n\n<pre><code>$post_copy = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$keyword = filter_input(INPUT_POST, 'keyword', FILTER_SANITIZE_SPECIAL_CHARS);\n</code></pre>\n\n<p>Using the filter_input_array can also allow you to specify what items you expect in the $_POST as items and apply a filter on them. This basically means if someone sends junk to you in the $_POST it will also be filtered out. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-17T18:11:24.247", "Id": "51013", "ParentId": "19551", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T20:11:43.380", "Id": "19551", "Score": "3", "Tags": [ "php", "object-oriented", "search", "form" ], "Title": "Search form sample pattern" }
19551
<p>I want to determine which separator is used in a csv file. CSV.foreach will return something like this:</p> <pre><code>["something1;something2;something3"] </code></pre> <p>The code beneath does the trick, but something better must exist. I find it annoying to have the need for sep_count. Do you know of a method that returns the most frequent of the characters from SEPERATORS?</p> <pre><code>SEPERATORS = [";", ","] CSV.foreach(@file, @config) do |header| sep_count = 0 SEPERATORS.each do |seperator| if header.first.scan(/#{seperator}/).count &gt; sep_count @config[:col_sep] = seperator sep_count = header.first.scan(/#{seperator}/).count end end break end </code></pre> <p>EDIT:</p> <p>Based on your awesome answers I got the 1-liner that I asked for:</p> <pre><code>@config[:col_sep] = %w(; ,).sort_by { |separator| File.open(@file).first(1).join.count(separator) }.last </code></pre> <p>I have also come up with this piece of code that determines both col_sep and row_sep:</p> <pre><code>first_line = "" File.open(@file) do |file| file.each_char do |char| first_line &lt;&lt; char if "\r\n".include?(char) @config[:row_sep] = first_line.scan(/\n$|\r$/).first break end end end @config[:col_sep] = %w(; ,).sort_by { |separator| first_line.count(separator) }.last </code></pre> <p>By using the full code we ensure that it is always the first line that gets used, and we also set the row_sep. Feel free to comment if you think anything could be improved further.</p>
[]
[ { "body": "<p>maybe this?</p>\n\n<pre><code>SEPERATORS = [\";\", \",\"]\n\nCSV.foreach(@file, @config) do |header|\n sep_counts = Hash.new(0)\n header.each_char {|c| sep_counts[c] += 1 if SEPERATORS.include? c }\n @config[:col_sep] = sep_counts.sort { |a,b| a[1] &lt;=&gt; b[1] }.first.first\n break\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T08:21:51.483", "Id": "31321", "Score": "0", "body": "Thanks. I have put in a first in line 3, then it works.\n\n CSV.foreach(@file, @config) do |header|\n sep_counts = Hash.new(0)\n header.first.each_char { |c| sep_counts[c] += 1 if SEPERATORS.include? c }\n @config[:col_sep] = sep_counts.sort { |a,b| a[1] <=> b[1] }.first.first\n break\n end\n\nFunny thing though. CSV.foreach on a comma seperated CSV file returns:\n\n [\"something1\", \"something2\", \"something3\"]" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T22:16:17.757", "Id": "19558", "ParentId": "19555", "Score": "2" } }, { "body": "<p>You can get the most common separator in <code>header</code> with a one-liner like this:</p>\n\n<pre><code>most_common = SEPARATORS.sort_by{|separator| header.count(separator)}.last\n</code></pre>\n\n<p>But as you have noticed <code>CSV.foreach</code> attempts to split up the rows, assuming by default that the separator is a comma.</p>\n\n<p>You probably need to determine the separator in a preprocessing step before actually doing the CSV processing.</p>\n\n<p>You could just do something like</p>\n\n<pre><code>contents = File.read(@file)\n@config[:col_sep] = %w(; ,).sort_by{|separator| contents.count(separator)}.last\n\nCSV.parse(contents, @config) do |row|\n ...\nend\n\n# or use the returned array of arrays\nrows = CSV.parse(contents, @config)\n</code></pre>\n\n<p>This might be quite slow if your file is large because you have to read the whole thing into memory. In that case you might want to just look at the first line of the file, and guess the separator from that. To do this, assuming <code>\\n</code> is your line separator:</p>\n\n<pre><code>first_line = File.open(@file) do |file|\n file.first\nend\n</code></pre>\n\n<p>Note that you should use the block form to ensure that the file gets closed.</p>\n\n<p>If you need to be line-separator agnostic, I don't think there's a built-in way to do so (although you can change the line separator, that assumes you know it in advance). You might try something like</p>\n\n<pre><code>first_line = \"\"\nFile.open(@file) do |file|\n file.each_char do |char|\n break if \"\\r\\n\".include?(char)\n first_line &lt;&lt; char\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T15:51:30.540", "Id": "31331", "Score": "0", "body": "That is just awesome. It works. Thanks. Only issue is that the search for separators is carried out in the entire file. This means that a file with many ,'s in sentences could have more ,'s than ;'s. But all our 53 tests passes, so all seem fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T22:15:58.057", "Id": "31357", "Score": "0", "body": "@Christoffer: `File.open('path_to_file.csv').first(10).join` results in a string containing the first 10 lines. Should speed things up without affecting your test results." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T11:58:20.500", "Id": "31389", "Score": "0", "body": "Awesome line. I can see it assumes that \\n is the line break. Some files uses \\r. Is it possible to put in an argument that makes it stop at the first \\r or \\n?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T13:39:00.103", "Id": "31392", "Score": "0", "body": "@Christoffer: I've updated my answer with a possible approach." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T08:30:33.333", "Id": "19566", "ParentId": "19555", "Score": "5" } }, { "body": "<p>I came up with this:</p>\n\n<pre><code># Guess CSV column separator, based on counts. Tested in Ruby 1.9.3\ndef guess_columns_separator(string)\n separators = %W(; , \\t)\n counts = separators.inject({}){ |hash, separator| hash[string.count(separator)] = separator; hash }\n counts[counts.keys.max]\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-01T10:53:25.273", "Id": "32061", "ParentId": "19555", "Score": "0" } } ]
{ "AcceptedAnswerId": "19566", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-12T20:46:02.120", "Id": "19555", "Score": "3", "Tags": [ "ruby" ], "Title": "Look through a string and return the most frequent character (Ruby)" }
19555
<p>I have a controller. It functions as follows:</p> <p>A user imports a file and decides whether the files contents contain new entries to be placed into a database, or existing entries entries to be updated.</p> <p>The user clicks on the import button and is sent to the controller below. If there are any warnings or errors, the validation results screen is shown - to help the users correct their data.</p> <p>If the file doesn't contain any errors or warnings, the validation screen will be skipped and their file contents will be inserted/updated into the database.</p> <p>This is clearly far too much logic for a controller as I have read that the controller is simply meant to decide which view to send the data to. I am having a rather difficult time determining how to extract out the data.</p> <p>I am looking for suggestions on what my next step should be. Thank you to anyone who takes time to help me.</p> <pre><code>public ActionResult ValidationResultsScreen(HttpPostedFileBase file, DatabaseAccessMode databaseAccess) { try { var fileLocation = Path.Combine(Path.GetTempPath(), string.Join(Guid.NewGuid().ToString(), file.FileName)); Session["TempFileLocation"] = fileLocation; Session["DatabaseAccessMode"] = databaseAccess; file.SaveAs(fileLocation); var importer= new Importer(_connectionString, _logManager, databaseAccess,Server.MapPath("..\\bin")); var parsedValues= importer.ParseFile(fileLocation); var failedValues = ParsedValues.Where(x =&gt; x.ParsedState != ParsedState.Success); if (failedValues.Any())//if there were any warnings or errors display the validation results screen { return View(processedValues); } //else import the file to the database var transactionResults = importer.UploadToDatabase(parsedValues); var failedDBTransactions= RetrieveFailedResults(transactionResults); return failedDBTransactions.Any() ? View("DatabaseImportErrorScreen", failedDBTransactions) : View("DatabaseImportResults", transactionResults); } catch (Exception exception) { ViewBag.ExceptionMessage = exception.Message; return View("DefaultErrorScreen"); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T00:19:41.283", "Id": "31304", "Score": "1", "body": "If you're uncomfortable with the method size, just refactor as much of the logic as you can into another class, perhaps your repository class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T00:23:04.887", "Id": "31305", "Score": "0", "body": "Hello Robert, that is exactly what I want to do, hence the question. I am unsure how to extract the logic out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T00:56:08.760", "Id": "31306", "Score": "0", "body": "Why do you use var every time you create a variable? That makes it more difficult to tell what that variable contains. For example, what type is parsedValues?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T01:12:07.183", "Id": "31308", "Score": "0", "body": "@BobHorn It can be a problem here, but it's usually less of a problem in practice, because of the IDE." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T01:53:55.663", "Id": "31309", "Score": "0", "body": "@BobHorn I don't understand why knowing the type of parsedValues is necessary... All the information that is necessary from that object is available here. It contains a state (Success) and it is required by UploadToDatabase." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T02:58:03.773", "Id": "31310", "Score": "3", "body": "It's not necessary; it's nice. It's a readability thing. IMO, beautiful code isn't filled with vars. It would be nice to see it and instantly know what it is, without having to look somewhere else or hover over it. Beautiful code should read like a book." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T04:50:01.467", "Id": "31314", "Score": "1", "body": "I really would like to know why you are attempting to use the session in your controller. Or are we upgrading old code to mvc and this hasn't been handled yet?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T18:29:17.883", "Id": "31336", "Score": "0", "body": "@JayC I would like to lie and say that I'm upgrading old code, however that is not the case. I am pretty fresh to MVC (~1 month so far spent on it). I'm reading MVC4 in action in my spare time but I'm still only 1/3 of the way through. I simply am using the easiest to understand methods, with my current knowledge of controllers I am unable to determine the best practices." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T18:30:28.220", "Id": "31337", "Score": "0", "body": "@BobHorn I also hold code readability at a high standard, in my opinion not worrying about what types variables are makes code much less cluttered as well as better aligned." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T20:27:43.460", "Id": "31347", "Score": "0", "body": "@JayC could you please give a little insight as to what I am doing wrong with using the session? Is my use of Session[\"xxx\"] your problem, or is using a session in general what you believe is what I am doing wrong?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-23T03:05:00.207", "Id": "88928", "Score": "0", "body": "@SamuelDavis Have you unit tested this code? By writing tests first, this can help you to factor out unnecessary code." } ]
[ { "body": "<p>Maybe something like this? (commentary included):</p>\n\n<pre><code>//Do file locations really need to be saved in the session? I would hope not.\nprotected string TempFileLocation {get; set;}\n//This assumes DatabaseAccessMode is an class of some kind.\nprotected DatabaseAccessMode DatabaseAccess {get;set;}\n\n//place wherever your private methods go...\nprivate WhateverTypeORInterfaceParsedValuesIs GetParsedValues(HttpPostedFileBase file)\n{\n TempFileLocation = Path.Combine(Path.GetTempPath(), \n string.Join(Guid.NewGuid().ToString(), \n file.FileName));\n\n file.SaveAs(TempFileLocation);\n var importer= new Importer(_connectionString, \n _logManager, \n DatabaseAccess ,Server.MapPath(\"..\\\\bin\"));\n var parsedValues= importer.ParseFile(TempFileLocation);\n\n return parsedValues;\n}\n\n//and of course, your new Action\npublic ActionResult ValidationResultsScreen(HttpPostedFileBase file, DatabaseAccessMode databaseAccess)\n{\n try\n {\n //save it for later. \n //(we still need to figure out a proper lifetime\n // for your Database Access mode)\n DatabaseAccess = databaseAccess; \n\n //grab parsed values.\n var parsedValues = GetParsedValues(file)\n\n //if there were any warnings or errors display the validation results screen\n if (parsedValues.Where(x =&gt; x.ParsedState != ParsedState.Success).Any())\n {\n return View(processedValues); // what are the processedValues???\n } \n else\n { \n //import the file to the database\n var transactionResults = importer.UploadToDatabase(parsedValues);\n var failedDBTransactions= RetrieveFailedResults(transactionResults);\n\n return failedDBTransactions.Any() \n ? View(\"DatabaseImportErrorScreen\", failedDBTransactions) \n : View(\"DatabaseImportResults\", transactionResults);\n }\n }\n catch (Exception exception)\n {\n ViewBag.ExceptionMessage = exception.Message;\n return View(\"DefaultErrorScreen\");\n }\n}\n</code></pre>\n\n<p>However, you may have noticed I removed the utilization of a Session object</p>\n\n<p>I could see some value to having a Database access mode in session. Even so, using a session to cache data can cause a multitude of problems if you don't have a session timeout page or ways to refill your session on session timeout. Also, using the session directly might introduce race issues. </p>\n\n<p>One attempt to still use the session while avoiding race issues might be the following:</p>\n\n<pre><code>private DatabaseAccessMode _DataAccess;\nprotected DatabaseAccessMode DatabaseAccess\n{\n get{\n //save the first non-null value retrieved and use that every time. \n _DataAccess = _DataAccess \n ?? (DatabaseAccessMode) HttpContext.Current.Session[\"DatabaseAccessMode\"]\n return _DataAccess ;\n }\n set{\n _DataAccess = value;\n HttpContext.Current.Session[\"DatabaseAccessMode\"] = value;\n }\n}\n</code></pre>\n\n<p>but if you have a whole set of these values, and changing any one of them might invalidate all the others, it would probably be best to isolate that logic somewhere else.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T19:46:51.917", "Id": "31342", "Score": "0", "body": "Thank you for your answer, how would you suggest persisting \"protected string TempFileLocation {get; set;}\" though? The value would be lost as soon as the controller is next called" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T20:21:17.760", "Id": "31346", "Score": "0", "body": "And could you possibly provide a little insight as to why the session is such a bad place to persist data? It seems to me that this is the entire point of the session..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T02:55:22.707", "Id": "31421", "Score": "0", "body": "The more state you introduce into your application via session, and the more pages you have to visit to set appropriate session variables, the harder your application is to debug and the easier it is to introduce bugs. I especially don't like direct use of the Session object because, if I were required to change something relating to that session object, I'd first have to scan all the files to determine where that session variable is used, and then reverse engineer the use cases possibly affecting or effected by that variable. Not fun. Hiding session access makes that job easier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T20:21:16.560", "Id": "31485", "Score": "0", "body": "Ahh yes that makes sense. Yes I would never want to get into that situation. Thank you so much for the help :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T05:42:14.837", "Id": "19563", "ParentId": "19559", "Score": "1" } }, { "body": "<p>Based on your case your controller seems to be mixing multiple things at the same time. The total context is not clear but it seems this is a controller method in a controller that does more than this, correct?</p>\n\n<p>In general I would suggest to see it different. An import is an object, so create a seperate controller for it: ImportsController. That can be a very standard controller:</p>\n\n<p><strong>Add:</strong> User add a new file, controller just sends it to Import model -> save. The model saves it in a temp file or whatever it needs to do. You can implement validation here already but you can also say: \"A upload and saved file is ok. That is a correct creation of an import.\"</p>\n\n<p>Pseudo code:</p>\n\n<pre><code>if(dataIncoming) {\n this-&gt;Import-&gt;save(data)\n //handle file save errors, no data received etc. All coming back from model which should take care of the validation.\n //redirect to edit\n}\n</code></pre>\n\n<p><strong>Edit:</strong> Next step is to review the import. Here you can ask the model to validate.</p>\n\n<p>Pseudo code:</p>\n\n<pre><code>ON SAVE (if this is requested without a save/submit action just show data and validation results)\nthis-&gt;Import-&gt;parseFile(data) //validate\n\n//show parse file issues to user if any\nreturn View(processedValues);\n\nif(no errors in parsefile) {\n //try database save\n Import-&gt;saveInDatabase\n //show validation errors if needed\n\n //if all ok you can redirect (or have user interaction) to delete\n}\n</code></pre>\n\n<p><strong>View:</strong> Always shows you the data of the import</p>\n\n<p><strong>Delete:</strong> Can be used to remove a wrong import upload (user uploaded file twice) or when import is done. You can validate this.</p>\n\n<p>Here you can implement also a soft delete for example.</p>\n\n<p>Pseudo code:</p>\n\n<pre><code>Import-&gt;delete\n</code></pre>\n\n<p>So as you see I would move all that file, tmpfile and other parts to the model by seeing an import as a standalone object. That makes it possible to have all encapsulated and also well testable. A controller method doing all steps is much harder to test. For example you would need to catch all different views rendered etc. I prefer to split it up.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T19:51:44.183", "Id": "31343", "Score": "0", "body": "Hello, I was instructed to not show a \"file successfully validated\" screen as it would just be an extra annoying button to click. If I were not told this, I would definitely do this in two steps (and originally tried to until told otherwise). Also I still have the same problem of persisting the file location across two controller calls. Due to these problems, my code can't really be changed to your suggestion unfortunately." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T10:02:10.140", "Id": "31380", "Score": "1", "body": "There is no need to show that screen. If no errors you can just redirect to the next method. Most important what I explained it to see an Import as a separate object. If you handle saving the tmp file in your Import model instance your file location issue is also taken care of." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T10:13:39.427", "Id": "19575", "ParentId": "19559", "Score": "2" } } ]
{ "AcceptedAnswerId": "19563", "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T00:17:34.900", "Id": "19559", "Score": "0", "Tags": [ "c#", "mvc", "controller", "asp.net-mvc-4" ], "Title": "How could I make my controller a little less hideous?" }
19559
<p>I have a process that runs as 32-bits regardless of the architecture. In it, I want to be able to spawn a process from the 64-bit program files menu (e.g. <code>c:\program files</code> instead of <code>c:\program files (x86)\</code>). </p> <p>I tried using <code>System.Environment.GetFolderPath</code>, but for a 32 bit process, both <code>SpecialFolders.ProgramFiles</code> and <code>SpecialFolders.ProgramFilesX86</code> returned the x86 folder. Ditto trying to use <code>System.Environment.ExpandEnvironmentVariables("%programfiles%")</code>.</p> <p>Instead I put together this mess:</p> <pre><code>Path.Combine(System.Environment.ExpandEnvironmentVariables("%systemdrive%") + @"\", @"Program Files\..."); </code></pre> <p>The Path.Combine seems pretty useless since I've already put every '\' in there, so I simplified it to:</p> <pre><code>System.Environment.ExpandEnvironmentVariables("%systemdrive%") + @"\Program Files\..."; </code></pre> <p>In my environment(s), the program files folder is always on the system drive, but the system drive has varying drive letters. Is there any better way to write this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T03:48:03.297", "Id": "31311", "Score": "0", "body": "Is there a reason why iy needs to be in `\\Program Files\\\\` instead of `\\Program Files (x86)\\\\`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T17:33:04.983", "Id": "31333", "Score": "0", "body": "@JamesKhoury, I'm trying to launch an app that's installed separately from mine. It only installs to `Program Files`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T23:38:32.697", "Id": "31360", "Score": "1", "body": "I'd suggest a look at http://stackoverflow.com/questions/3916713/how-can-i-get-another-applications-installation-path-programmatically ... I've not tried it but the answers seem to suggest searching the registry for it. Specifically: `HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths`" } ]
[ { "body": "<p>In the end, I made a slight simplification and ended up with:</p>\n\n<pre><code>System.Environment.ExpandEnvironmentVariables(\"%systemdrive%\\Program Files\\...\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T20:28:02.087", "Id": "19624", "ParentId": "19560", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T00:45:31.547", "Id": "19560", "Score": "7", "Tags": [ "c#", ".net" ], "Title": "Create path to file under 64-bit %programfiles% from 32-bit process" }
19560
<p>I have two functions to split string to array of strings. Input string is: (1Letter E|V|R) + 8 number, last component of string (1Letter + V) + 8 or less numbers.</p> <p>I'v got two functions advised to use, both of them are working properly. But I can't decide which one is better to use.</p> <p>1st:</p> <pre><code>- (NSArray *) componentSaparetedByLength:(NSUInteger) length{ NSMutableArray *array = [NSMutableArray new]; NSRange range = NSMakeRange(0, length); NSString *subString = nil; while (range.location + range.length &lt;= self.length) { subString = [self substringWithRange:range]; [array addObject:subString]; //Edit range.location = range.length + range.location; //Edit range.length = length; } if(range.location&lt;self.length){ subString = [self substringFromIndex:range.location]; [array addObject:subString]; } return array; } </code></pre> <p>2nd:</p> <pre><code>NSMutableArray *brokenString=[NSMutableArray new]; int start=0; for (; start&lt;mainString.length-9; start+=9) { [brokenString addObject:[mainString substringWithRange:NSMakeRange(start, 9)]]; } [brokenString addObject:[mainString substringFromIndex:start]]; NSLog(@"-&gt;%@",brokenString); </code></pre>
[]
[ { "body": "<p>I would favor the first category approach, as it takes benefit of a great Objective-C feature: extend existing classes with new methods. </p>\n\n<p>On the other hand probably both ways will fail if it comes to more advanced characters, like <a href=\"http://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B10000_to_U.2B10FFFF\" rel=\"nofollow\">surrogate pairs</a>, base characters plus <a href=\"http://en.wikipedia.org/wiki/Combining_character\" rel=\"nofollow\">combining marks</a>, <a href=\"http://en.wikipedia.org/wiki/Hangul\" rel=\"nofollow\">Hangul jamo</a>, and <a href=\"http://rishida.net/scripts/indic-overview/#consonantclusters\" rel=\"nofollow\">Indic consonant clusters</a>.</p>\n\n<p>So here is my Category implementation:</p>\n\n<pre><code>@interface NSString (Split)\n-(NSArray *)arrayBySplittingWithMaximumSize:(NSUInteger)size;\n@end\n\n@implementation NSString (Split)\n\n-(NSArray *)arrayBySplittingWithMaximumSize:(NSUInteger)size\n{\n NSMutableArray *letterArray = [NSMutableArray array];\n [self enumerateSubstringsInRange:NSMakeRange(0, [self length])\n options:(NSStringEnumerationByComposedCharacterSequences)\n usingBlock:^(NSString *substring,\n NSRange substringRange,\n NSRange enclosingRange,\n BOOL *stop) {\n [letterArray addObject:substring];\n }];\n\n\n NSMutableArray *array = [NSMutableArray array];\n [letterArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {\n if (idx%size == 0) {\n [array addObject: [NSMutableString stringWithCapacity:size]];\n }\n NSMutableString *string = [array objectAtIndex:[array count]-1];\n [string appendString:obj];\n\n }];\n\n return array;\n}\n</code></pre>\n\n<p>use it like:</p>\n\n<pre><code>NSArray *arraysWith9Letters = [letters arraysBySplittingWithMaximumSize:9];\n</code></pre>\n\n<p>This approach could be easily extended to split by words, sentences, lines too</p>\n\n<pre><code>@interface NSString (Split)\n-(NSArray *)arrayBySplittingWithMaximumSize:(NSUInteger)size\n options:(NSStringEnumerationOptions) option;\n@end\n\n@implementation NSString (Split)\n\n-(NSArray *)arrayBySplittingWithMaximumSize:(NSUInteger)size\n options:(NSStringEnumerationOptions) option\n{\n NSMutableArray *letterArray = [NSMutableArray array];\n [self enumerateSubstringsInRange:NSMakeRange(0, [self length])\n options:(option)\n usingBlock:^(NSString *substring,\n NSRange substringRange,\n NSRange enclosingRange,\n BOOL *stop) {\n [letterArray addObject:substring];\n }];\n\n\n NSMutableArray *array = [NSMutableArray array];\n [letterArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {\n if (idx%size == 0) {\n [array addObject: [NSMutableString stringWithCapacity:size]];\n }\n NSMutableString *string = [array objectAtIndex:[array count]-1];\n [string appendString:obj];\n\n }];\n\n return array;\n}\n</code></pre>\n\n<p>Now use it like</p>\n\n<pre><code>NSString *letters = @\"ABCDEFकट्रತ್ಯÖäüℝijgrvਉਤਸੁਕsasas\";\nNSArray *arraysWith9Letters = [letters arraysBySplittingWithMaximumSize:9 options:NSStringEnumerationByComposedCharacterSequences] ;\nNSLog(@\"%@\", arraysWith9Letters);\n\nNSString *lorem = @\"Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam\";\nNSArray *loremArray = [lorem arraysBySplittingWithMaximumSize:9 options:NSStringEnumerationByWords];\nNSLog(@\"%@\", loremArray);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T06:56:06.543", "Id": "31373", "Score": "0", "body": "Thank you for your opinion and your implementation, I will consider accepting after a day, just maybe another answer might occur :). That's a great code you'v written here but for wider usage. But is it worth it to implement it, if i know that i will never get different strings only E|V|R + 8numbers?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T11:22:12.923", "Id": "31388", "Score": "0", "body": "a category makes it dead simple to re-use code. when it is so simple to write code, that can be used in different situation, why not?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-23T07:07:34.170", "Id": "33392", "Score": "0", "body": "@vikingosegundo: your method is just awesome. OP's two method cant compete with your block based. I have a doubt between 1 and 2 w.r.t. memory and complexity. How can we find the complexity of both the methods?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-23T19:02:42.850", "Id": "33416", "Score": "0", "body": "@AnoopVaidya — are you talking of BigO?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-23T19:04:15.460", "Id": "33417", "Score": "0", "body": "@vikingosegundo : Yes" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-23T19:10:55.890", "Id": "33418", "Score": "0", "body": "@AnoopVaidya — all solutions are linear, actually mine is O(2n), but in BigO constant values dont count, so it is O(n)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-23T19:13:12.290", "Id": "33419", "Score": "0", "body": "And what about memory usage...as Ist one is calling a lot memory, that will push the stack..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-23T19:15:04.740", "Id": "33420", "Score": "0", "body": "I didnt test it. feel free to do so and report back." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T15:31:35.523", "Id": "72575", "Score": "0", "body": "Tested and works elegantly +1" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T19:12:15.957", "Id": "19586", "ParentId": "19567", "Score": "2" } } ]
{ "AcceptedAnswerId": "19586", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T08:46:56.210", "Id": "19567", "Score": "3", "Tags": [ "objective-c", "cocoa" ], "Title": "Spliting string to array by number" }
19567
<p>My purpouse is to select every character which is surrounded by <code>{</code> and <code>}</code>, this is easily achievable using this regexp <code>{\w*}</code>.</p> <p>I've developed an extenstion method for strings:</p> <pre><code> public static IEnumerable&lt;string&gt; ObtainTokens(this string originalString) { Regex expression = new Regex(@"{\w*}"); foreach (Match element in expression.Matches(originalString)) { //Exclude the brackets from the returned valued yield return Regex.Replace(element.Value, @"{*}*", ""); } } </code></pre> <p>Is there a way to get rid of of <code>Regex.Replace</code>? Returning the values as IEnumerable is a good choice?</p>
[]
[ { "body": "<p>Modify your regexp: <code>{(\\w*)}</code> and then replace:</p>\n\n<pre><code>yield return Regex.Replace(element.Value, @\"{*}*\", \"\");\n</code></pre>\n\n<p>with</p>\n\n<pre><code>yield return element.Groups[1].Value;\n</code></pre>\n\n<p>ps: full code is avaialbe <a href=\"https://gist.github.com/4275479\" rel=\"nofollow\">here</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T09:54:23.670", "Id": "31322", "Score": "0", "body": "By applying your suggestion on the test string `{THIS} is a {TEST}` the response is an `IEnumerable<string>` containing two empty string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T10:16:24.593", "Id": "31325", "Score": "1", "body": "regex has beed updated to capture groups: `{(\\w*)}`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T09:48:37.410", "Id": "19570", "ParentId": "19569", "Score": "4" } } ]
{ "AcceptedAnswerId": "19570", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T09:34:45.633", "Id": "19569", "Score": "1", "Tags": [ "c#", "regex" ], "Title": "RegExp selecting strings surrounded by brackets" }
19569
<p>I've got dictionary of lists of tuples. Each tuple has timestamp as first element and values in others. Timestamps could be different for other keys:</p> <pre><code>dict = { 'p2': [(1355150022, 3.82), (1355150088, 4.24), (1355150154, 3.94), (1355150216, 3.87), (1355150287, 6.66)], 'p1': [(1355150040, 7.9), (1355150110, 8.03), (1355150172, 8.41), (1355150234, 7.77)], 'p3': [(1355150021, 1.82), (1355150082, 2.24), (1355150153, 3.33), (1355150217, 7.77), (1355150286, 6.66)], } </code></pre> <p>I want this convert to list of lists:</p> <pre><code>ret = [ ['time', 'p1', 'p2', 'p3'], [1355149980, '', 3.82, 1.82], [1355150040, 7.9, 4.24, 2.24], [1355150100, 8.03, 3.94, 3.33], [1355150160, 8.41, 3.87, 7.77], [1355150220, 7.77, '', ''], [1355150280, '', 6.66, 6.66] ] </code></pre> <p>I'm making conversion with that dirty definition:</p> <pre><code>def convert_parameters_dict(dict): tmp = {} for p in dict.keys(): for l in dict[p]: t = l[0] - l[0] % 60 try: tmp[t][p] = l[1] except KeyError: tmp[t] = {} tmp[t][p] = l[1] ret = [] ret.append([ "time" ] + sorted(dict.keys())) for t, d in sorted(tmp.iteritems()): l = [] for p in sorted(dict.keys()): try: l.append(d[p]) except KeyError: l.append('') ret.append([t] + l) return ret </code></pre> <p>Maybe there is some much prettier way?</p>
[]
[ { "body": "<p>Have a look at <a href=\"http://pandas.pydata.org/\"><code>pandas</code></a>:</p>\n\n<pre><code>import pandas as pd\n\nd = {\n 'p2': [(1355150022, 3.82), (1355150088, 4.24), (1355150154, 3.94), (1355150216, 3.87), (1355150287, 6.66)],\n 'p1': [(1355150040, 7.9), (1355150110, 8.03), (1355150172, 8.41), (1355150234, 7.77)],\n 'p3': [(1355150021, 1.82), (1355150082, 2.24), (1355150153, 3.33), (1355150217, 7.77), (1355150286, 6.66)],\n} \n\nret = pd.DataFrame({k:pd.Series({a-a%60:b for a,b in v}) for k,v in d.iteritems()})\n</code></pre>\n\n<p>returns</p>\n\n<pre><code> p1 p2 p3\n1355149980 NaN 3.82 1.82\n1355150040 7.90 4.24 2.24\n1355150100 8.03 3.94 3.33\n1355150160 8.41 3.87 7.77\n1355150220 7.77 NaN NaN\n1355150280 NaN 6.66 6.66\n</code></pre>\n\n<p>It is not a list of lists, but using pandas you can do much more with this data (such as convert the unix timestamps to datetime objects with a single command).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T07:56:17.853", "Id": "31323", "Score": "0", "body": "Wow, now that is slick!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T07:55:33.260", "Id": "19573", "ParentId": "19572", "Score": "7" } }, { "body": "<p>How about...</p>\n\n<pre><code>times = sorted(set(int(y[0] / 60) for x in d.values() for y in x))\ntable = [['time'] + sorted(d.keys())]\nfor time in times:\n table.append([time * 60])\n for heading in table[0][1:]:\n for v in d[heading]:\n if int(v[0] / 60) == time:\n table[-1].append(v[1])\n break\n else:\n table[-1].append('')\nfor row in table:\n print row\n</code></pre>\n\n<p>Or, less readable but probably faster if the dictionary is long (because it only loops through each list in the dictionary once):</p>\n\n<pre><code>times = sorted(set(int(v2[0] / 60) for v in d.values() for v2 in v))\nempty_row = [''] * len(d)\ntable = ([['time'] + sorted(d.keys())] + \n [[time * 60] + empty_row for time in times])\nfor n, key in enumerate(table[0][1:]):\n for v in d[key]:\n if int(v[0] / 60) in times:\n table[times.index(v[0] / 60) + 1][n + 1] = v[1]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T09:28:07.727", "Id": "31324", "Score": "0", "body": "Thank you all. Stuart, I'll use your second solution. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T08:47:45.800", "Id": "19574", "ParentId": "19572", "Score": "1" } } ]
{ "AcceptedAnswerId": "19574", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T07:50:28.937", "Id": "19572", "Score": "6", "Tags": [ "python", "hash-map" ], "Title": "Convert dictionary of lists of tuples to list of lists/tuples in python" }
19572
<p>My company's web application projects are heavily based on user controls. One common case is like we want to reuse the UI visual elements but note the packaged original logic .</p> <p>I have read some very smelly code in some user controls code behinde. </p> <pre><code>if(WebConfig.CurrentProject == "xxx") { //do xxx's logic ddlPostalCode.DataSouce= this.addressManager.getUSAPostal(); } else { //do yyy's logic ddlPostalCode.DataSouce= this.addressManager.getUKPostal(); } //Or use configuration if(config.enableAlpha) { //Do alpha's logic ddlPostalCode.DataSouce= this.addressManager.getAlphaPostalCode(); } </code></pre> <p>And these logics normally involving manipulating server controls .</p> <p>So I am thinking, if we just want to reuse the visual element and parts of its logic. Why don't we make the server and its event handler public ? </p> <pre><code>//In xxx.ascx.cs public EventHandler AddressControl_Init; protected override void OnInit(EventArgs e) { if(this.AddressControl_Init!= null) { this.AddressControl_Init(sender, e); } else { //Default logic. } } //In xxx.ascx.designer.cs public public global::XYZ.Controls.Basic.XYZDropDownList ddlPostalCode; //In the code behinde of the page using this address ascx. //HostingPage.aspx.cs protected override void OnPreInit(EventArgs e) { this.AddressControl.AddressControl_Init += new EventHandler(USAAddressControl_Init); } void USAAddressControl_Init(object sender, EventArgs e) { //Now i can use any business manager class here to populate the source data. this.AddressControl.ddlPostalCode.DataSource = Anymanager.GetMarsCode(); this.AddressControl.ddlPostalCode.DataBind(); } </code></pre> <p>This is a very simple example, but it also can be a very flexsiable solution. It decouple the logic behinde the user control. Let the user, the page to deside the control's logic. </p> <p>Is there any better elegent ways to solve my problem? </p>
[]
[ { "body": "<blockquote>\n <p>Is there any better elegent ways to solve my problem?</p>\n</blockquote>\n\n<p>You are going down a horrible path messing with all these user controls. ASP.NET MVC is much better for dealing with reusable visual parts, and everything happens on the request level so you don't have to worry about horrible event ordering.</p>\n\n<p>Can't use MVC? Forget the complex events of user controls entirely. Put no code in user controls. If you need the data from a textbox in a control for example, pull it directly from the post variables (wrap this in a class if you need to)</p>\n\n<p>Make your goal to deal with requests in a SINGLE, centralized point. It's the MVC way, it's the MVP way, it's the MVVM way.</p>\n\n<p>Need ajax? scrap ajax controls and hit a web service; throw away the ajax toolkit.</p>\n\n<p>I actually wish I had an old crufty webforms app that I could re-work this on. I would completely bail on the failure that is <a href=\"http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.100%29.aspx\" rel=\"nofollow\">asp.net lifecycle</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T16:18:37.507", "Id": "19613", "ParentId": "19576", "Score": "3" } }, { "body": "<p>It looks like all you need is to access your controls in usercontrol directly in HostingPage.aspx.cs. You can make them public. Just find the declaration and change it to public. Then you can access them directly in Init method of HostingPage, you don't need event for that. </p>\n\n<p>Nicer solution would be to create public properties in your usercontrol and use them to pass data from HostingPage to usercontrol and then do your binding bind there.</p>\n\n<p>I don't think using usercontrols is bad, they can be very powerful tool. I suggest you to define interfaces and then access usercontrols trough them. In this case you can also load them dinamically with no problem.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T01:43:11.430", "Id": "19648", "ParentId": "19576", "Score": "2" } } ]
{ "AcceptedAnswerId": "19613", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T10:17:45.357", "Id": "19576", "Score": "4", "Tags": [ "c#", "asp.net" ], "Title": "Reusable user control (ascx) design for multiple web application" }
19576
<p>I have this code:</p> <pre><code>Tabzilla.fillZGContacts = function(){ if (!Tabzilla.panel.id) return; $.ajax({ url: 'zgcontacts.json', success: function(d){ // "Type","Name","Link","Contact","Location","Icon" Tabzilla.zgContacts = d; var countries = []; d.rows.forEach(function(row){ if (row[0] == 'Country') countries.push( {link:row[2], contact:row[3], country: row[4]} ); }); //alphabetically countries.sort(sortByKey('country')); //adding link countryTemplate = function (country){ s = '&lt;a title="'+country.country+'" class="chapters_link" href="' +country.link+'" target="_blank"&gt;' +'&lt;div class="chapters c_'+country.country.toLowerCase()+'"&gt;' +'&lt;span class="flag-margin"&gt;'+country.country+'&lt;/span&gt;&lt;/div&gt;&lt;/a&gt;' return s; } var byletter = {}; //count countries starting from each letter countries.forEach(function(c){ var firstletter = c.country.toLowerCase().charAt(0); if (byletter[firstletter]) byletter[firstletter]++; else byletter[firstletter]=1; }); console.log(byletter); //prepare containers var panel = $("#"+Tabzilla.panel.id); var $cols = []; $cols.push(panel.find(".c_COL4")); $cols.push(panel.find(".c_COL3")); $cols.push(panel.find(".c_COL2")); $cols.push(panel.find(".c_COL1")); var columns = $cols.length; var targetlen = countries.length/columns; var FirstLetter = countries[0].country.toLowerCase().charAt(0); var cc = []; //fill containers. this loop is buggy. should be reviewed. countries.forEach(function(c){ var newFirstLetter = c.country.toLowerCase().charAt(0); if (FirstLetter != newFirstLetter) { var l1 = cc.length; var l2 = l1 + byletter[newFirstLetter]; //condition maybe shd be changed.. if (Math.abs(l2-targetlen) &gt;= Math.abs(l1-targetlen)){ var $col; if ($cols.length&gt;0) $col = $cols.pop(); cc.forEach(function(c){ $col.append(countryTemplate(c)); }); cc=[]; //does not work :( //could generate another template with first letter raised $col.find('span').first().addClass("first-letter"); } cc.push(c); } else cc.push(c); FirstLetter = newFirstLetter; }); }, }); } </code></pre> <p>The zgcontacts.json file can be found <a href="https://gist.github.com/4275805" rel="nofollow">here</a>.</p> <p>Any pointers in optimizing this is much appreciated. For example, this loop:</p> <pre><code>countries.forEach(function(c) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T13:54:41.517", "Id": "31329", "Score": "0", "body": "Does not belong here, because the code does not work. `var $col; if ($cols.length>0) $col = $cols.pop(); cc.forEach(function(c){ $col.append(countryTemplate(c)); });` This part cannot work, $col is undefined." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T23:30:34.077", "Id": "31359", "Score": "0", "body": "@ANeves yes it is. `$cols` is defined further up as `var $cols = [];` and `$col` is declared `var $col;` and then defined `$col = $cols.pop();`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T09:48:48.900", "Id": "31376", "Score": "0", "body": "@JamesKhoury thanks for correcting. But (1.) if `cols.length == 0`? $col is undefined, and one cannot do `$col.append`; unless this never happens, in which case the `if` is vestigial code and only serves to trick or confuse the reader. Also, (2.) what about that `//does not work :(` comment in the code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T13:38:27.120", "Id": "31391", "Score": "0", "body": "@ANeves shall i move this to stackoverflow, but i am unsure if it is possible?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T15:07:23.130", "Id": "31397", "Score": "0", "body": "@khinester if the code does work, it should stay here. If it does not, it should be moved. (I think only admins can move it.) This is just my opinion, though, and JamesKhoury disagrees." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T16:13:10.470", "Id": "31400", "Score": "0", "body": "earlier i made a post on stackoverflow and was told it is better here ;(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T04:42:37.820", "Id": "31491", "Score": "0", "body": "@khinester You have to descide if this works or not. If it does then Code review can help you write it better. Otherwise take it to StackOverflow with the problem and someone will help you fix it. (Not improve it)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T01:37:52.690", "Id": "68215", "Score": "1", "body": "... but please, if/when it comes back, make sure the formatting is more readable (indenting, braces, etc... ) See @JamesKhoury answer." } ]
[ { "body": "<p>Use braces <code>{</code> in all your if blocks. It makes it easier to read.</p>\n\n<pre><code>if (byletter[firstletter]){\n byletter[firstletter]++;\n}else{\n byletter[firstletter]=1;\n}\n</code></pre>\n\n<p>You have <code>for</code> loops like : <code>countries.forEach(function(c){</code> which are also hard to read. I'd only use this if you have a function you want to apply. </p>\n\n<pre><code>for(var countryindex = 0; countryindex &lt; countries.length; countryindex++)\n{\n var c = countries[countryindex];\n // ...\n}\n</code></pre>\n\n<p>Use descriptive variable names. </p>\n\n<pre><code>if (FirstLetter != newFirstLetter)\n{\n var l1 = cc.length;\n var l2 = l1 + byletter[newFirstLetter];\n</code></pre>\n\n<p>What is <code>l1</code> &amp; <code>l2</code> ? What is <code>c</code> or <code>cc</code>? </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T02:05:06.683", "Id": "68225", "Score": "0", "body": "@konijn javascript has `for` and `for .. in` I think they are much more readable and debuggable than `[].forEach(`. When would you favour it over the more traditional for loops?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T00:40:47.907", "Id": "40499", "ParentId": "19577", "Score": "5" } }, { "body": "<p>The location of your <code>countryTemplate</code> function breaks the flow of your code, you should put it at the very end. Also I would encourage you to use some templating routine, you could use this one:</p>\n\n<pre><code>function fillTemplate( s )\n{ //Replace ~ in s with further provided arguments\n for( var i = 1 ; i &lt; arguments.length ; i++ )\n s = s.replace( \"~\" , arguments[i] );\n return s;\n} \n</code></pre>\n\n<p>Then your countryTemplate could be :</p>\n\n<pre><code> countryTemplate = function (country)\n {\n var template = '&lt;a title=\"~\" class=\"chapters_link\" href=\"~\" target=\"_blank\"&gt;' +\n '&lt;div class=\"chapters c_~\"&gt;' +\n '&lt;span class=\"flag-margin\"&gt;~&lt;/span&gt;' +\n '&lt;/div&gt;' +\n '&lt;/a&gt;';\n return fillTemplate( template , country.country\n , country.link\n , country.country.toLowerCase()\n , country.country\n\n }\n</code></pre>\n\n<p>This could be DRY'er of course, since I repeat <code>country.country</code> a number of times, I leave the final code to you.</p>\n\n<p>Furthermore, there is no reason not to merge the extraction of the countries and the calculation of <code>byletter</code>, it will save you a 'forEach` call:</p>\n\n<pre><code> var countries = [],\n byletter = {};\n\n d.rows.forEach(function(row){\n if (row[0] == 'Country'){\n var country = { link:row[2], contact:row[3], country: row[4] };\n var firstletter = row[4].toLowerCase().charAt(0);\n countries.push( country );\n byletter[firstletter] = ( byletter[firstletter] || 0 ) + 1;\n }\n });\n</code></pre>\n\n<p>Finally, your <em>buggy loop</em> is very badly written, I cannot tell what you are trying to achieve with that code. Maybe you should comment each section with what it is supposed to do and indeed follow the suggestions of James Khoury.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T01:41:42.423", "Id": "40502", "ParentId": "19577", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T11:16:02.433", "Id": "19577", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Optimise JavaScript loop" }
19577
<p>I am studying graphs and I am trying to make a library in C# for myself and anyone else interested, that is didactic and simple, so I can remember how to solve common problems.</p> <p>I would like to improve it.<br> How can I improve, for example, the <code>DFS</code>, complete the <code>Prim's algorithm</code> and implement the Kruskal's and Dijkstra's algorithms ? </p> <p>Create an interface that can be derived for representing different kinds of graphs, like Undirect and Direct Graph, for example.</p> <pre><code>public interface IGraph { void InsertDirectEdge(int edgeAKey, int edgeBKey,int weight = 0); void IsertNewVertex(int vertexKey); bool ExistKey(int vertexKey); Vertex InitializeDFS(int vertexKeyToFind); bool MakeItBipartite(); Vertex DFS(Vertex root, int vertexKeyToFind); void FindNumberOfConnectedComponents(); void BFS(int startVertexKey); Vertex InitialiazeBFS(int vertexKeyToFind); bool IsVisited(Vertex v); Vertex MarkVertexAsVisited(Vertex v); Vertex GetFirstElementOfTheList(int findKey); void InsertUndirectedEdge(int vertexAKey, int vertexBKey, int Weight = 0); GraphDirect PrimAlgorithm(); Vertex FindByKey(int vertexKey); } </code></pre> <p>Created a direct graph, with a <code>Dictionary&lt;int,Vertex&gt;</code> to represent a <code>Graph Adjacency List</code>, where the <code>key</code> is an integer.</p> <pre><code> public class GraphDirect : IGraph { private Dictionary&lt;int,Vertex&gt; Vertices { get; set; } //For use on the DFS to "break" the recursion. private bool finished; public GraphDirect() { Vertices = new Dictionary&lt;int, Vertex&gt;(); } //Initialize all vertices with Unvisited value. private void InitializeVertices() { foreach(int key in this.Vertices.Keys) { this.Vertices[key].Status = State.UnVisited; } } } </code></pre> <p>This part is used for Depth-First-Search and probably should be changed to be more elegant and efficient. It should execute in linear time <code>O(|E|)</code>, where <code>E</code> is the total number of edges. To call <code>DFS</code> in this case you start calling <code>InitializeDFS(TheKeyYouWantToFind)</code>.</p> <pre><code>public Vertex InitializeDFS(int vertexKeyToFind) { if (this.Vertices.Count == 0) return null; InitializeVertices(); finished = false; return this.DFS(Vertices.First().Value, vertexKeyToFind); } private void ProccessVertex(int vertexBeenProcessed, int vertexKeyToFind) { if (vertexBeenProcessed == vertexKeyToFind) finished = true; else finished = false; } public Vertex DFS(Vertex root, int vertexKeyToFind) { Console.WriteLine("Root = {0}", root.Key); ProccessVertex(root.Key, vertexKeyToFind); if (finished) return root; this.Vertices[root.Key].Status = State.Visited; while (root.Next != null) { if (Vertices[root.Next.Key].Status == State.UnVisited) { root.Next.Status = State.Processed; Console.WriteLine("Root.Next = {0}", root.Key); DFS(Vertices[root.Next.Key], vertexKeyToFind); } root = root.Next; } if (!finished) return null; else return root; } </code></pre> <p>This part is to check if the graph is bipartite or not.</p> <pre><code>void InitializeVerticesColors() { foreach(Vertex v in this.Vertices.Values) { v.Color = Color.Uncolored; } } //If is bipartite public bool MakeItBipartite() { InitializeVerticesColors(); InitializeVertices(); return this.BFS2Colors(this.Vertices.First().Key); } private bool BFS2Colors(int startVertexKey) { if (this.Vertices.Count == 0) return true; int white = 0; Queue&lt;Vertex&gt; Q = new Queue&lt;Vertex&gt;(); Console.WriteLine("Starting at: {0}", this.Vertices[startVertexKey].Key); this.Vertices[startVertexKey].Color = Color.White; Console.WriteLine("White"); this.GetFirstElementOfTheList(startVertexKey).Status = State.Visited; Q.Enqueue(this.GetFirstElementOfTheList(startVertexKey)); while (Q.Count != 0) { white = (this.Vertices[Q.Peek().Key].Color == Color.White) ? 1 : 0; List&lt;Vertex&gt; children = GetChildrenOfVertex(Q.Dequeue()); foreach (Vertex v in children) { if (this.Vertices[v.Key].Status == State.UnVisited) { Console.WriteLine("Passed to {0}", v.Key); if (white == 1) this.Vertices[v.Key].Color = Color.Black; else this.Vertices[v.Key].Color = Color.White; if (this.Vertices[v.Key].Color == Color.White) Console.WriteLine("Child color white"); else if (this.Vertices[v.Key].Color == Color.Black) Console.WriteLine("Child Color Black"); this.Vertices[v.Key].Status = State.Visited; Q.Enqueue(this.Vertices[v.Key]); } } } return true; } </code></pre> <p>This part if for checking the number of Connected Components of a Graph.</p> <pre><code> public void FindNumberOfConnectedComponents() { int c = 0; InitializeVertices(); foreach (Vertex v in this.Vertices.Values) { if (v.Status == State.UnVisited) { //Counting the number of components c++; Console.WriteLine("Component number {0}", c); this.BFS(v.Key); } } } </code></pre> <p>This is to do a Breath-First-Search (BFS) looking for a key.</p> <pre><code>public void BFS(int startVertexKey) { if (this.Vertices.Count == 0) return; Queue&lt;Vertex&gt; Q = new Queue&lt;Vertex&gt;(); Console.WriteLine("Starting at: {0}", this.Vertices[startVertexKey].Key); this.GetFirstElementOfTheList(startVertexKey).Status = State.Visited; Q.Enqueue(this.GetFirstElementOfTheList(startVertexKey)); while (Q.Count != 0) { List&lt;Vertex&gt; children = GetChildrenOfVertex(Q.Dequeue()); foreach (Vertex v in children) { if (this.Vertices[v.Key].Status == State.UnVisited) { Console.WriteLine("Passed to {0}", v.Key); this.Vertices[v.Key].Status = State.Visited; Q.Enqueue(this.Vertices[v.Key]); } } } } private List&lt;Vertex&gt; GetChildrenOfVertex(Vertex headVertex) { List&lt;Vertex&gt; vertexes = new List&lt;Vertex&gt;(); Vertex v = headVertex.Next; while (v != null) { vertexes.Add(v); v = v.Next; } return vertexes; } public Vertex InitialiazeBFS(int vertexKeyToFind) { InitializeVertices(); return BFS(this.Vertices.First().Key,vertexKeyToFind); } private Vertex BFS(int startVertexKey, int vertexKeyToFind) { if (this.Vertices.Count == 0) return null; //Starting from the first element Queue&lt;Vertex&gt; Q = new Queue&lt;Vertex&gt;(); Console.WriteLine("Starting at: {0}", this.Vertices[startVertexKey].Key); this.GetFirstElementOfTheList(startVertexKey).Status = State.Visited; Q.Enqueue(this.GetFirstElementOfTheList(startVertexKey)); while (Q.Count != 0) { List&lt;Vertex&gt; children = GetChildrenOfVertex(Q.Dequeue()); foreach (Vertex v in children) { if (this.Vertices[v.Key].Status == State.UnVisited) { Console.WriteLine("Passed to {0}", v.Key); if (v.Key == vertexKeyToFind) return v; this.Vertices[v.Key].Status = State.Visited; Q.Enqueue(this.Vertices[v.Key]); } } } return null; } public bool IsVisited(Vertex v) { if (v == null) return false; return this.Vertices[v.Key].Status == State.Visited; } public Vertex MarkVertexAsVisited(Vertex v) { if (v == null) return null; this.Vertices[v.Key].Status = State.Visited; return this.Vertices[v.Key]; } public Vertex GetFirstElementOfTheList(int findKey) { if (this.Vertices.ContainsKey(findKey)) return this.Vertices[findKey]; return null; } public bool ExistKey(int vertexKey) { if (this.FindByKey(vertexKey) == null) return false; else return true; } </code></pre> <p>These are operations used to insert new <code>vertices</code>, <code>undirect edges</code> and <code>direct edges</code>. Also find an element on the graph by it's <code>key</code>, return <code>null</code> if it doesn't exist on the graph.</p> <pre><code>public void IsertNewVertex(int vertexKey) { if (!this.ExistKey(vertexKey)) { this.Vertices.Add(vertexKey, new Vertex(vertexKey)); } } public void InsertUndirectedEdge(int vertexAKey, int vertexBKey, int Weight = 0) { this.InsertDirectEdge(vertexAKey, vertexBKey, Weight); this.InsertDirectEdge(vertexBKey, vertexAKey, Weight); } public void InsertDirectEdge(int vertexAKey, int vertexBKey, int weightEdge = 0) { //Create the vertex A on the vertex list if (!this.ExistKey(vertexAKey)) { this.IsertNewVertex(vertexAKey); } //Create the vertex B on the vertex list if (!this.ExistKey(vertexBKey)) { this.IsertNewVertex(vertexBKey); } //Add the vertex B on the vertex A position on the Dictionary, as the second element of the list Vertex vertexB = new Vertex(vertexBKey); vertexB.Weight = weightEdge; vertexB.Next = this.Vertices[vertexAKey].Next; this.Vertices[vertexAKey].Next = vertexB; } public Vertex FindByKey(int vertexKey) { if (this.Vertices.ContainsKey(vertexKey)) return this.Vertices[vertexKey]; return null; } </code></pre> <p>This is a Prim's algorithm used to find the minimum spanning tree of a Graph using Greedy algorithm, and it is still <strong>incomplete</strong>.</p> <pre><code>public GraphDirect PrimAlgorithm() { if (this.Vertices.First().Value == null) return null; GraphDirect SpanningTree = new GraphDirect(); Vertex v = this.Vertices.First().Value; v.SpanningTreeVertex = true; Console.WriteLine("v.key = {0}",v.Key); SpanningTree.IsertNewVertex(v.Key); Queue&lt;Vertex&gt; Q = new Queue&lt;Vertex&gt;(); Q.Enqueue(v); int min = int.MaxValue; Vertex minVertex = null; while (Q.Count != 0) { Vertex parent = Q.Dequeue(); List&lt;Vertex&gt; children = GetChildrenOfVertex(parent); foreach (Vertex vet in children) { if (vet.Status == State.UnVisited &amp;&amp; vet.Weight &lt; min) { min = vet.Weight; minVertex = vet; } } //TODO: minVertex.Status = State.Visited; SpanningTree.InsertUndirectedEdge(parent.Key, minVertex.Key, min); } return SpanningTree; } </code></pre> <p>Created the states of the graph for <code>DFS</code>, and Colors for checking if a graph is <code>bipartite</code> or not, also the <code>Vertex</code> is represented bellow, where the <code>Key</code> is the integer that uniquely identify it, and attached to the class you can add any attributes like <code>Value</code> for example.</p> <pre><code>public enum State { Visited = 0, UnVisited = 1, Processed = 2 } public enum Color { White = 0, Black = 1, Uncolored = 2 } public class Vertex { public int Key; public int Value; public State Status = State.UnVisited; public Vertex Next; public Color Color = Color.Uncolored; public bool SpanningTreeVertex = false; public int Weight = 0; public Vertex(int key) { this.Key = key; this.Value = 0; } public Vertex(int key, int value) { this.Key = key; this.Value = value; } } </code></pre> <p>An example showing how to use the <code>GraphDirect</code> class on a Console Application:</p> <pre><code>public class Start { public static void Main(){ GraphDirect gDirect = new GraphDirect(); gDirect.InsertDirectEdge(2, 7, 2); gDirect.InsertDirectEdge(7, 4, 4); gDirect.InsertDirectEdge(4, 6, 5); gDirect.InsertDirectEdge(8, 3, 5); gDirect.InsertDirectEdge(6, 2, 4); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T22:30:32.887", "Id": "31410", "Score": "0", "body": "“I think that it is not quite correct.” What do you mean? Why do you think it's not correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T16:34:08.940", "Id": "31475", "Score": "0", "body": "Hi @svick, is because I would like to remove the \"finished\" property and add the properties for each edge \"back edge\" to be closer to the wikipedia pseudocode.\nhttp://en.wikipedia.org/wiki/Depth-first_search#Pseudocode" } ]
[ { "body": "<p>You have put too many responsibilities in a single interface and class. Your <code>IGraph</code> interface knows not only about graph itself, but also about all the possible methods of traversing this graph. It breaks <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">Single-responsibility principle</a>, <a href=\"http://en.wikipedia.org/wiki/Open/closed_principle\" rel=\"nofollow\">Open/closed principle</a> (as you'll have to edit <code>Graph</code> if you want to add more search methods) and <a href=\"http://en.wikipedia.org/wiki/Interface_segregation_principle\" rel=\"nofollow\">Interface segregation principle</a>.</p>\n\n<p>What you should do is refactor your interface and implementation so that:</p>\n\n<ul>\n<li>There is an interface <code>IGraph</code> that describes all necessary methods and properties of a graph, i.e. ability to get adjacent vertices of a certain vertex, and methods of mutating a graph if needed (I would start with immutable graph first). Also I would add a generic parameter that defines the type of vertices. It <em>should not</em> include any functionality related to methods of traversing the graph, that is no BFS/DFS/Bipartite etc.</li>\n<li><code>Graph</code> class should not contain any data related to searching, that is no <code>Visited</code> states, no colors, etc.</li>\n<li>Define a new class for each method of working with graph, e.g. <code>BreadthFirstSearch</code> class, <code>DepthFirstSearch</code> class, etc. Each of those should work with <code>IGraph</code> and store information required for their processing, e.g. all those vertex visited states, etc. If there is some common functionality (like visited states) you may introduce a base class that all others will inherit from.</li>\n</ul>\n\n<p>That will make your code decoupled, different graph traversal methods would be independent from others, and code would be much easier to read and understand.</p>\n\n<p>Example of <code>Graph</code> and <code>BreadthFirstSearch</code> implementation:</p>\n\n<pre><code>public interface IGraph&lt;TVertex&gt;\n{\n bool Contains(TVertex vertex);\n IEnumerable&lt;TVertex&gt; GetAdjacent(TVertex vertex);\n}\n\npublic class Graph&lt;TVertex&gt; : IGraph&lt;TVertex&gt;\n{\n private readonly Dictionary&lt;TVertex, List&lt;TVertex&gt;&gt; _edges;\n\n public Graph(params Tuple&lt;TVertex, TVertex&gt;[] directEdges)\n {\n _edges = directEdges\n .GroupBy(tuple =&gt; tuple.Item1, tuple =&gt; tuple.Item2)\n .ToDictionary(g =&gt; g.Key, g =&gt; g.ToList());\n\n //Adding vertices that are used as a target to the list of available vertices\n foreach (var missingVertex in directEdges\n .Where(tuple =&gt; !_edges.ContainsKey(tuple.Item2))\n .Select(tuple =&gt; tuple.Item2))\n {\n _edges[missingVertex] = new List&lt;TVertex&gt;();\n }\n }\n\n public bool Contains(TVertex vertex)\n {\n return _edges.ContainsKey(vertex);\n }\n\n public IEnumerable&lt;TVertex&gt; GetAdjacent(TVertex vertex)\n {\n List&lt;TVertex&gt; adjacentVertices;\n return _edges.TryGetValue(vertex, out adjacentVertices) ? adjacentVertices : Enumerable.Empty&lt;TVertex&gt;();\n }\n}\n\npublic class BreadthFirstSearch&lt;TVertex&gt;\n{\n private readonly IGraph&lt;TVertex&gt; _graph;\n\n public BreadthFirstSearch(IGraph&lt;TVertex&gt; graph)\n {\n _graph = graph;\n }\n\n public IEnumerable&lt;TVertex&gt; GetAllReachableVertices(TVertex startingVertex)\n {\n HashSet&lt;TVertex&gt; visited = new HashSet&lt;TVertex&gt; { startingVertex };\n Queue&lt;TVertex&gt; horizon = new Queue&lt;TVertex&gt; { startingVertex };\n\n while (horizon.Count &gt; 0)\n {\n var nextVertexToExpand = horizon.Dequeue();\n yield return nextVertexToExpand;\n\n foreach (var vertex in _graph.GetAdjacent(nextVertexToExpand).Where(vertex =&gt; !visited.Contains(vertex)))\n {\n visited.Add(vertex);\n horizon.Enqueue(vertex);\n }\n }\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>public class Program\n{\n public static void Main()\n {\n var graph = new Graph&lt;int&gt;(\n Tuple.Create(2, 7),\n Tuple.Create(7, 4),\n Tuple.Create(4, 6),\n Tuple.Create(8, 3),\n Tuple.Create(6, 2));\n\n var breadthFirstSearch = new BreadthFirstSearch&lt;int&gt;(graph);\n\n foreach (var vertex in breadthFirstSearch.GetAllReachableVertices(4))\n {\n Console.WriteLine(\"Next vertex is {0}\", vertex);\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T20:55:41.307", "Id": "31587", "Score": "1", "body": "Good review! I would suggest `Contains` (or `ContainsVertex`) instead of `IsPresent` as more expressive names. And it isn't necessary to explicitly put `startingVertex` in an array to add it to the HashSet and Queue, you could just do: `var visited = new HashSet<TVertex>{ startingVertex };`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-11-04T15:43:17.677", "Id": "341027", "Score": "0", "body": "I agree about \"too many responsibilities in a single interface and class\" :+1: One suggestion I have to this answer is to make `GetAllReachableVertices` an extension method. That way, it becomes easier to discover where you can still maintain the separation." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T18:29:50.457", "Id": "19751", "ParentId": "19580", "Score": "4" } } ]
{ "AcceptedAnswerId": "19751", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T13:37:58.430", "Id": "19580", "Score": "7", "Tags": [ "c#", "algorithm", "breadth-first-search" ], "Title": "Improve Graph Adjacency List Implementation and Operations" }
19580
<pre><code>['content', 'answers', 'comments'].each do |t| break if results.length &gt;= MAX_RESULTS Question.search_tank('', :conditions =&gt; conditions.merge(t =&gt; "#{search_term}"), :page =&gt; 1, :per_page =&gt; 5).each do |q| next if matched_qs.include? q.id matched_qs &lt;&lt; q.id r = {:title =&gt; q.content, :value =&gt; app_question_url(q.app, q.id)} if t == 'content' r[:label] = highlight_matched(search_regex, q.content) r[:label] &lt;&lt; "&lt;span class='search-type'&gt;Question&lt;/span&gt;" else r[:label] = q.content end if t == 'answers' r[:label] = "&lt;span class='search-type snippet'&gt;Answer&lt;/span&gt;" + [r[:label], get_snippet(search_regex, q.answers)].compact.join('&lt;br /&gt;') end if t == 'comments' r[:label] = "&lt;span class='search-type snippet'&gt;Comment&lt;/span&gt;" + [r[:type], r[:label], get_snippet(search_regex, q.answers.map(&amp;:comments).flatten)].compact.join('&lt;br /&gt;') end results &lt;&lt; r break if results.length &gt;= MAX_RESULTS end </code></pre> <p>I would like to refactor that part which generates r[:label]</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T18:34:04.933", "Id": "31338", "Score": "0", "body": "is there a `results = []` before the loop? are you missing an `end` at the end? is this a helper?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T23:56:36.460", "Id": "31361", "Score": "0", "body": "Yes there is ``results = []`` before the loop and yes i miss ``end`` No this is no helper but ``search#new`` action which render json ``results.to_json`` https://gist.github.com/6738554e438c741fba45" } ]
[ { "body": "<p>This needs some tweaking, but I hope it helps you identify the main issues to address in your code (IMHO):</p>\n\n<pre><code>objects = [:content, :answers, :comments].flat_map do |type|\n questions = Question.search_tank('', {\n :page =&gt; 1, \n :per_page =&gt; 5,\n :conditions =&gt; conditions.merge(type =&gt; search_term), \n })\n questions.map { |q| [q, type] }\nend.uniq_by(&amp;:first).take(MAX_RESULTS)\n\nresults = objects.map do |q, type| \n label = case type\n when :content\n highlight_matched(search_regex, q.content) + \n content_tag(:span, \"Question\", :class =&gt; \"search-type\")\n when :answers\n content_tag(:span, \"Answer\", :class =&gt; 'search-type snippet'&gt;) + \n [q.content, get_snippet(search_regex, q.answers)].compact.join(tag(:br))\n when :comments\n comments = get_snippet(search_regex, q.answers.flat_map(&amp;:comments))] \n content_tag(:span, \"Comment\", :class =&gt; 'search-type snippet'&gt;) +\n [t, q.content, comments].compact.join(tag(:br))\n end\n {:title =&gt; q.content, :value =&gt; app_question_url(q.app, q.id), :label =&gt; label}\nend\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>Avoid stateful variables whenever possible (that's it, don't update inplace), work with expressions. </li>\n<li>Use Rails helpers (content_tag, tag, ...).</li>\n<li>Use symbols for key-like values, not strings.</li>\n<li><code>\"#{something}</code>\" -> <code>something.to_s</code></li>\n<li>map + flatten = flat_map. Even though you should able to write <code>q.answer_commments</code> in Rails 3.1 will the correct model settings.</li>\n<li>Use <code>case</code>, not a chain of <code>if</code>/<code>elsif</code> if the condition is on the same value.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T10:11:40.637", "Id": "31385", "Score": "0", "body": "And since this is no helper I can use ``content_tag``" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T10:22:00.130", "Id": "31386", "Score": "1", "body": "can or can't? it does not matter if it's not a helper, you can always use helpers just with an `include` of the desired module." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T10:31:53.980", "Id": "31387", "Score": "0", "body": "Hmm, Of course I can`t :), thx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T12:23:10.323", "Id": "31390", "Score": "0", "body": "``\"#{content_tag(:span, \"Answer\", :class: 'search-type snippet')}\" +\n [q.content, get_snippet(search_regex, q.answers)].compact.join(tag(:br))`` I dont know why I have to use ``#{}`` here ``to_s`` not working and i see html tags <br/> http://i.imgur.com/81mst.png" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T18:53:24.760", "Id": "19585", "ParentId": "19582", "Score": "2" } } ]
{ "AcceptedAnswerId": "19585", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T16:35:55.190", "Id": "19582", "Score": "2", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "How to refactor this complicated html generator in Ruby?" }
19582
<p>I'm wanting to throw an error when reference keys are missing, however instead of failing through a integrity check, I want to list out the missing keys. I've created the below which works. However I'm hoping there is a way to optimise it and reduce the number of lines of code.</p> <pre><code>DECLARE @NonRefKeys INT SELECT @NonRefKeys = SUM(1) FROM staging.Sale sa WHERE NOT EXISTS ( SELECT cu.Customer_Shipping_ID FROM staging.Customer cu WHERE LTRIM(RTRIM(sa.Customer_Shipping_ID)) = LTRIM(RTRIM(cu.Customer_Shipping_ID))) IF @NonRefKeys IS NOT NULL BEGIN IF OBJECT_ID('tempdb..#Missing_Ref') IS NOT NULL DROP TABLE #Missing_Ref; SELECT sa.Customer_Shipping_ID AS ID INTO #Missing_Ref FROM staging.Sale sa WHERE NOT EXISTS ( SELECT cu.Customer_Shipping_ID FROM staging.Customer cu WHERE LTRIM(RTRIM(sa.Customer_Shipping_ID)) = LTRIM(RTRIM(cu.Customer_Shipping_ID))) DECLARE @Current_ID VARCHAR(50); DECLARE @Missing_ID VARCHAR(MAX) = ''; DECLARE @Output_Error VARCHAR(MAX); DECLARE id_cursor CURSOR FOR SELECT ID FROM #Missing_Ref; OPEN id_cursor FETCH NEXT FROM id_cursor INTO @Current_ID </code></pre>
[]
[ { "body": "<p>I'm not sure I completely understand your logic, but since this is a stored procedure the temp table isn't visible outside it so you don't need to check if it exists (unless you have other code in the same procedure that might have created it already).</p>\n\n<p>And the most obvious way to reduce the number of lines is not to count the number of IDs and then get them, but to just get them and use <code>@@ROWCOUNT</code> to see how many you got:</p>\n\n<pre><code>-- get missing IDs\nSELECT sa.Customer_Shipping_ID AS ID\nINTO #Missing_Ref\nFROM staging.Sale sa\nWHERE NOT EXISTS (\n SELECT cu.Customer_Shipping_ID\n FROM staging.Customer cu\n WHERE LTRIM(RTRIM(sa.Customer_Shipping_ID)) = LTRIM(RTRIM(cu.Customer_Shipping_ID)))\n\n-- only continue if we got at least 1 missing ID\nif @@rowcount &gt; 0\nbegin\n\n DECLARE @Current_ID VARCHAR(50);\n DECLARE @Missing_ID VARCHAR(MAX) = '';\n DECLARE @Output_Error VARCHAR(MAX);\n\n DECLARE id_cursor CURSOR FOR\n SELECT ID\n FROM #Missing_Ref;\n\n -- rest of cursor here (presumably)\nend\n</code></pre>\n\n<p>BTW, the title of your question seems to have nothing to do with the actual code, which is concerned with finding a set of rows that may or may not exist.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-13T22:41:11.823", "Id": "21681", "ParentId": "19583", "Score": "5" } }, { "body": "<p>Regarding your question, I would suggest that you use <code>RAISERROR()</code> for this. </p>\n\n<p>See this example:</p>\n\n<pre><code>IF(@id IS NULL) BEGIN\n RAISERROR('@id is null, which shouldn't be',16,1);\nEND\n</code></pre>\n\n<p>The first part is the error message which will be thrown as msg. 50.000 to the user/application. The 16 is the severity. The severity can be from 1 to 21. >18 can just be thrown by the SA with the <code>WITH LOG</code> option. Severity under 16 won't be read and won't cause an abort. They are just warnings. Severity 16 will cause an abort of the current (sub)procedure. Severity 18 will cause an abort of the whole procedure stack. Unless if they are catches in a try catch.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-20T14:08:07.970", "Id": "94183", "ParentId": "19583", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T16:38:31.317", "Id": "19583", "Score": "2", "Tags": [ "sql", "sql-server", "error-handling" ], "Title": "Throwing a custom error in a stored procedure" }
19583
<p>This reads a list of points from a file with a certain format:</p> <blockquote> <pre><code>&lt;number of points&gt; x1 y1 x2 y2 </code></pre> </blockquote> <p>How I can make it better?</p> <pre><code>from collections import namedtuple Point = namedtuple('Point ', ['x', 'y']) def read(): ins = open("PATH_TO_FILE", "r") array = [] first = True expected_length = 0 for line in ins: if first: expected_length = int(line.rstrip('\n')) first = False else: parsed = line.rstrip('\n').split () array.append(Point(int(parsed[0]), int(parsed[1]))) if expected_length != len(array): raise NameError("error on read") return array </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T03:25:21.697", "Id": "31365", "Score": "0", "body": "If you're dealing with points you might want to use a library like Shapely, which will give you a nice Point object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T09:46:38.313", "Id": "31375", "Score": "0", "body": "@monkut, thx I'll see." } ]
[ { "body": "<p>You don't need all that <code>expected_length</code> and <code>first=True</code> stuff. You can treat a file as an iterator, and it will return objects until it quits, so you can just use the <code>.next()</code> method and throw item away, or save it to a variable if you wish. In that sense, it's best to write two functions-- one to deal with the file, and another to deal with a single line as provided by the file object. </p>\n\n<pre><code>def lineparse(line):\n ''' Parses a single line. '''\n # your code goes here\n\ndef fileparse(filepath):\n f = open(filepath, \"r\")\n n = int(f.next()) # this also advances your iterator by one line\n while True: \n yield lineparse(f.next())\n f.close()\n\ndata = list(fileparse(filepath))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T03:54:29.167", "Id": "31366", "Score": "0", "body": "`expected_length` is a check that the supposed length of the array equals the amount of data, you can't just ignore it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T04:08:18.050", "Id": "31367", "Score": "0", "body": "Ah ignore me, I've just noticed you use `n =` to get the expected length. Still a bit confusing that you say you don't need `expected_length` though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T23:26:20.563", "Id": "19594", "ParentId": "19588", "Score": "3" } }, { "body": "<p>Not that big a change but you don't need to worry about stripping out <code>\\n</code>s as the <code>split</code> and <code>int</code> functions will take care of that. Secondly, as already pointed out, you can grab the first line by just calling <code>.next()</code> then use a loop for the remaining lines.</p>\n\n<pre><code>def read():\n ins = open(\"FILE\", \"r\")\n array = []\n expected_length = int(ins.next())\n for line in ins:\n parsed = line.split()\n array.append(Point(int(parsed[0]), int(parsed[1])))\n if expected_length != len(array):\n raise NameError('error on read')\n ins.close()\n return array\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T04:10:47.597", "Id": "19600", "ParentId": "19588", "Score": "3" } }, { "body": "<p>Another improvement is to use <code>open</code> as a context manager so that you don't have to remember to <code>.close()</code> the file object even if there are errors while reading.</p>\n\n<pre><code>def read():\n with open(\"FILE\", \"r\") as f:\n array = []\n expected_length = int(f.next())\n for line in f:\n parsed = map(int, line.split())\n array.append(Point(*parsed))\n if expected_length != len(array):\n raise NameError('error on read')\n return array\n</code></pre>\n\n<p>See <a href=\"http://docs.python.org/2/library/stdtypes.html#file.close\" rel=\"nofollow\">http://docs.python.org/2/library/stdtypes.html#file.close</a> for more details.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T04:28:24.557", "Id": "19602", "ParentId": "19588", "Score": "4" } } ]
{ "AcceptedAnswerId": "19602", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T19:52:28.513", "Id": "19588", "Score": "3", "Tags": [ "python", "file" ], "Title": "Reading data from file" }
19588
<p>After experimenting with different design approaches for the past two years, I've created a library for managing and processing dynamic content to be displayed on a single HTML view. This library is <a href="https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md" rel="nofollow">PSR-0</a>, PSR-1 and PSR-2 compliant. I'm quite happy with this design but want to make sure it can stand excessive use.</p> <p>It's simple enough until you start dealing with nested data. To give a quick summary, each single piece of content on a page can be dynamically changed depending on its associated GET parameter. This is what I've called a <strong>Slot</strong>.</p> <p>For exmaple, on a page, I might have a Slot for a headline, which would be bound to Get parameter <code>h</code>, so <code>?h=3</code> would show a different headline to <code>?h=2</code>. I've called each item of content in a slot a <strong>Card</strong>. The card value of a slot it retrieved through the following method.</p> <pre><code>&lt;?php $page = new Page($data); $headline = $page-&gt;get('headline'); ?&gt; &lt;h1&gt;&lt;?=$headline?&gt;&lt;/h1&gt; </code></pre> <p>However, a slot may contain another slot, where for example, a headline could have the content <code>"Welcome back, {username} from {location}"</code> and each tag name is processed and existing Slot objects with those names are injected into its parent object.</p> <ol> <li>Should I instead try and create a reference to those slots instead of injecting them?</li> <li>Would this consume a lot of memory if someone tried to nest them multiple times, or if there are many nested slots or if a slot holds 10 000 possible cards?</li> <li>Below is the main class <code>Page</code>, where the slots are injected in the constructor. Followed by the <code>Slot</code> class, should this be done at instantiation and/or should I have a method for updating the configuration?</li> </ol> <p>If you need more scope, the repository is currently on <a href="https://github.com/archfizz/slotmachine/tree/6b68ef67e6e56f822a56a906dd24995e931b33ec" rel="nofollow">GitHub</a>. <em>Update: the library has since been renamed on Github from Kamereon to SlotMachine. Also, a new version (renamed as Slots) will be rewritten using PhpSpec to drive the design and test the class, and will be using Symfony Translation for string interpolation.</em></p> <p>Page.php</p> <pre><code>&lt;?php namespace Kamereon; use Symfony\Component\HttpFoundation\Request; /** * The base for a new dynamic landing page. Each dynamic placeholder is called a slot * where a slot will hold many cards for one to be displayed depending on a set of * given parameters. * * @author Adam */ class Page { /** * The Symfony HttpFoundation Request object. */ protected $request; /** * Raw configuration data. */ protected $config = array(); /** * Collection of Slot objects. */ protected $slots = array(); /** * Loads the config data and creates new Slot instances. * * @param array $config */ public function __construct(array $config) { $this-&gt;request = Request::createFromGlobals(); $this-&gt;config = $config; // created new instances for each slot foreach ($config['slots'] as $slotName =&gt; $slotData) { $this-&gt;slots[$slotName] = new Slot($slotName, $slotData); } // inject nested slots foreach ($config['slots'] as $slotName =&gt; $slotData) { if (isset($slotData['nestedWith']) &amp;&amp; count($slotData['nestedWith']) &gt; 0) { foreach ($slotData['nestedWith'] as $nestedSlotName) { $this-&gt;slots[$slotName]-&gt;addNestedSlot($this-&gt;slots[$nestedSlotName]); } } } } /** * Get the configuration array. * * @return array */ public function getConfig() { return $this-&gt;config; } /** * Get a Slot object from the slot collection by its key. * * @param string $slot * @return Slot */ public function getSlot($slot) { return $this-&gt;slots[$slot]; } /** * Get the card value for a slot. * * @param string $slotName * @param string $default * @return string */ public function get($slotName, $default = '0') { $slot = $this-&gt;slots[$slotName]; try { $card = $slot-&gt;getCard($this-&gt;request-&gt;get($slot-&gt;getKeyBind(), $default)); } catch (\Exception $e){ $card = ''; } if ($slot-&gt;getHasNestedSlots()) { foreach ($slot-&gt;getNestedSlots() as $nestedSlot) { try { $nestedCards[$nestedSlot-&gt;getName()] = $nestedSlot-&gt;getCard( $this-&gt;request-&gt;get($nestedSlot-&gt;getKeyBind(), $default) ); } catch (\Exception $e){ $nestedCards[$nestedSlot-&gt;getName()] = ''; } } foreach ($nestedCards as $cardName =&gt; $cardValue) { $card = str_replace( sprintf('{%s}', $cardName), $cardValue, $card ); } } return $card; } /** * Override the request instance by injecting your own. * * @param Request $request */ public function setRequest(Request $request) { $this-&gt;request = $request; } /** * Get the request instance. * * @return Request */ public function getRequest() { return $this-&gt;request; } } </code></pre> <p>Slot.php</p> <pre><code>&lt;?php namespace Kamereon; /** * A placeholder for variable content on a page, which a value will be assigned * to it as a Card instance * * @author Adam */ class Slot { /** * The name of the slot */ protected $name; /** * The key name that is bound to the slot * A key can be shared with another slot */ protected $keyBind; /** * An array of the names of nested slots */ protected $nestedSlotNames = array(); /** * The collection array of nested Slot objects */ protected $nestedSlots = array(); /** * A list of cards for each one will be displayed on the page */ protected $cards = array(); /** * Create new slot with name, key binding and its cards * and if the slot has nested slots, assign only the names of * those slots. * * @param string $name * @param array $data */ public function __construct($name, array $data) { $this-&gt;name = $name; $this-&gt;keyBind = $data['keyBind']; $this-&gt;cards = $data['cards']; if (isset($data['nestedWith'])) { $this-&gt;nestedSlotNames = $data['nestedWith']; } } /** * Get the name of the slot * * @return string */ public function getName() { return $this-&gt;name; } /** * Add a slot to the nested slots collection * * @param Slot $slot */ public function addNestedSlot(Slot $slot) { $this-&gt;nestedSlots[$slot-&gt;getName()] = $slot; } /** * Get all nested slots * * @return array */ public function getNestedSlots() { return $this-&gt;nestedSlots; } /** * Get specific nested slot * * @return Slot */ public function getNestedSlotByName($name) { return $this-&gt;nestedSlots[$name]; } /** * Get a value of a card by its index / array key. * Throws an InvalidArgumentException if the key does not exist. * * @return string */ public function getCard($index) { if (array_key_exists($index, $this-&gt;cards)) { return $this-&gt;cards[$index]; } throw new \InvalidArgumentException(sprintf( 'Card with index "%s" for slot "%s" does not exist', $index, $this-&gt;name)); } /** * Get the binded key * * @return string */ public function getKeyBind() { return $this-&gt;keyBind; } /** * Check if a slot contains other slots nested within * * @return boolean */ public function getHasNestedSlots() { return count($this-&gt;nestedSlots) &gt; 0; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-25T04:39:34.083", "Id": "159065", "Score": "0", "body": "I have rolled back your Rev 4. If you would like a review of your new code, please ask a follow-up question. (See [this Meta post](http://meta.codereview.stackexchange.com/q/1763/9357))." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-25T11:16:02.563", "Id": "159095", "Score": "0", "body": "@200_success I've had a look at the meta post but I'm not asking for further feedback on my question (I've already accepted an answer). I just wanted to address 3 issues with my edit: 1. My grammar, 2. the dead link, 3. The mismatch in class names between here and github. Other than that the original code has been left as is" } ]
[ { "body": "<p>I'm going to try hard to answer your questions. I'm a little confused by how you're doing this. It seems like you're trying to generate a complicated request from <code>$_GET</code> and instead of just loading up what you need, you've created a complicated structure that loads things up and then unpacks them later. I think you could more easily load things up into an array instead of nesting things, but it's always hard to figure out what people are really trying to do. If you can provide a more clear problem case, you might get better responses.</p>\n\n<ol>\n<li><p>I would inject the request, first of all, instead of using a static method. Next, I wouldn't have that new operator in the constructor. I would inject an array of Slots and just assign that:</p>\n\n<pre><code>$this-&gt;slots = $slots; __construct(Request $request, $slots){} \n</code></pre></li>\n<li><p>When you start talking about 10,000 cards, I start to wonder more about what you're doing. It doesn't seem particularly intensive, but you may end up having to up your memory allocation if you're using large objects. I'll defer to someone else on this. I usually wait until I hit upper limits before I think about resources. Not my area.</p></li>\n<li><p>You actually aren't injecting it properly. Also, you're building your request object twice. I wouldn't use a set method. I would stick with dependency injection. I don't really know what you mean by configuration, but anything your class needs should be passed into your constructor, not set later. It's less confusing that way and it guarantees you have everything you need for your object.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T09:57:49.847", "Id": "31377", "Score": "0", "body": "Thanks Stephane, that's pretty helpful. Good point about the request object, but I'd wanted a default object to be instantiated instead of the user explicitly injecting one. How to do this correctly? Also I originally had an array instead of nested objects and it worked well, but found it much harder to worker nested values, and could only be nested once. Plus it was more difficult to write tests for. Just realised I'm missing the configuration array from my post, I'll add it to the question, with a more realistic sample." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T17:50:16.493", "Id": "31433", "Score": "0", "body": "I've just made a [commit](https://github.com/archfizz/Kamereon/commit/ee93376f2967f750f50db9312252a08b607a7ad8) that allows an optional Request object to be passed, or default to creating one from PHP globals." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T04:10:21.337", "Id": "19599", "ParentId": "19591", "Score": "3" } }, { "body": "<p>I must criticize your tests. They are not part of your question here, but available in your github repo.</p>\n\n<p>Your SlotTest does not test slots. It does test the page. Why?</p>\n\n<pre><code>class SlotTest extends \\PHPUnit_Framework_TestCase\n{\n protected $page;\n protected function setUp()\n {\n require __DIR__.'/../fixtures/config.php';\n $this-&gt;page = new Page($kamereon);\n }\n</code></pre>\n\n<p>Reading the tests, I do not really see how a single slot is to be used. I only see how multiple slots inside a page are used. Also, I only see tests for several GET methods. If I want to verify that the results that are coming out are correct, I somehow have to read the config fixture file - a secondary source of information.</p>\n\n<p>This situation actually is bad. I want to be able to read the tests, and actually CHANGE some input values in a certain test method to see whether or not it changes the output and breaks the test. If I cannot see the input, I cannot play with the values.</p>\n\n<p>One final improvement: If you include files, they can actually return a value. You do not need to define a global variable that will transfer the config values.</p>\n\n<pre><code>// don't use this\n$kamereon = array(...);\n\n// use this\nreturn array(...);\n\n// Fetching values then is like this:\n$kamereon = include('config.php');\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T23:39:28.693", "Id": "31441", "Score": "0", "body": "Thanks for the suggestions. I'm relatively new to writing tests, so if you know of good resources for unit testing best practices that be great. SlotTest and PageTest could be combined into one file, and still cover both Slot and Page, but were you expecting that SlotTest cover the usage of a Slot by itself?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T23:42:08.053", "Id": "31442", "Score": "0", "body": "Also, good idea regarding return the included file. I've done it like this because the configuration could potentially be in xml, yaml, json, from a database, etc" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T23:13:19.610", "Id": "19642", "ParentId": "19591", "Score": "1" } } ]
{ "AcceptedAnswerId": "19599", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:34:55.137", "Id": "19591", "Score": "2", "Tags": [ "php", "object-oriented", "dependency-injection" ], "Title": "Nesting multiple objects vs referencing them for a slot machine" }
19591
<blockquote> <p>The following is a new question based on answers from here: <a href="https://codereview.stackexchange.com/q/7531/3163">Small PHP MVC Template</a> </p> </blockquote> <p>I have written a small MVC template library that I would like some critiques on.</p> <p>The library is <a href="https://github.com/maniator/SmallFry/tree/7bcd7a0e992e8d5a78ff12a83a3b33d69f230863" rel="nofollow noreferrer">located here</a></p> <p>If you are looking for where to start, check out the files in the <a href="https://github.com/maniator/SmallFry/tree/7bcd7a0e992e8d5a78ff12a83a3b33d69f230863/lib" rel="nofollow noreferrer"><code>lib</code></a> directory.</p> <p>I would really love to hear your critiques on:</p> <ul> <li>Code quality</li> <li>Code clarity</li> <li>How to improve</li> <li>Anything else that needs clarification expansion etc </li> </ul> <p>I'm more interested in what I'm doing wrong than right.<br> The README is not complete and there is <strong>a lot</strong> more functionality than what is documented, if you have any questions, please ask me.</p> <p>Any opinions on the actual usefulness of the library are welcome.</p> <hr> <p>Code examples (all of the code is equal, just on my last question I was asked for some snippets):</p> <p><a href="https://github.com/maniator/SmallFry/blob/7bcd7a0e992e8d5a78ff12a83a3b33d69f230863/lib/Bootstrap.php" rel="nofollow noreferrer"><code>Bootstrap.php</code></a>:</p> <pre><code>&lt;?php /** * The main library for the framework */ namespace SmallFry\lib; class_alias('SmallFry\lib\MySQL_Interface', 'SmallFry\lib\MySQL'); // MySQL class to be deprecated /** * Description of Bootstrap * * @author nlubin */ Class Bootstrap { /** * * @var SessionManager */ private $_session; /** * * @var stdClass */ private $_path; /** * * @var AppController */ private $_controller; /** * * @var Template */ private $_template; /** * * @var Config */ private $CONFIG; /** * @param Config $CONFIG */ function __construct(Config $CONFIG) { $this-&gt;CONFIG = $CONFIG; $this-&gt;CONFIG-&gt;set('page_title', $this-&gt;CONFIG-&gt;get('DEFAULT_TITLE')); $this-&gt;CONFIG-&gt;set('template', $this-&gt;CONFIG-&gt;get('DEFAULT_TEMPLATE')); $this-&gt;_session = new SessionManager($this-&gt;CONFIG-&gt;get('APP_NAME')); $this-&gt;_path = $this-&gt;readPath(); $this-&gt;_controller = $this-&gt;loadController(); $this-&gt;_template = new Template($this-&gt;_path, $this-&gt;_session, $this-&gt;_controller, $this-&gt;CONFIG); //has destructor that controls it $this-&gt;_controller-&gt;displayPage($this-&gt;_path-&gt;args); //run the page for the controller $this-&gt;_template-&gt;renderTemplate($this-&gt;_path-&gt;args); //only render template after all is said and done } /** * @return \stdClass */ private function readPath(){ $default_controller = $this-&gt;CONFIG-&gt;get('DEFAULT_CONTROLLER'); $index = str_replace("/", "", \SmallFry\Config\INDEX); //use strtok to remove the query string from the end fo the request $request_uri = !isset($_SERVER["REQUEST_URI"]) ? "/" : strtok($_SERVER["REQUEST_URI"],'?');; $request_uri = str_replace("/" . $index , "/", $request_uri); $path = $request_uri ?: '/'.$default_controller; $path = str_replace("//", "/", $path); $path_info = explode("/",$path); $page = isset($path_info[2]) ? $path_info[2] : "index"; list($page, $temp) = explode('.', $page) + array("index", null); $model = $path_info[1] ?: $default_controller; $obj = (object) array( 'path_info' =&gt; $path_info, 'page' =&gt; $page, 'args' =&gt; array_slice($path_info, 3), 'route_args' =&gt; array_slice($path_info, 2), //if is a route, ignore page 'model' =&gt; $model ); return $obj; } /** * @return AppController */ private function loadController(){ $this-&gt;CONFIG-&gt;set('page', $this-&gt;_path-&gt;page); //LOAD CONTROLLER $modFolders = array('images', 'js', 'css'); //load controller if(strlen($this-&gt;_path-&gt;model) == 0) $this-&gt;_path-&gt;model = $this-&gt;CONFIG-&gt;get('DEFAULT_CONTROLLER'); //find if is in modFolders: $folderIntersect = array_intersect($this-&gt;_path-&gt;path_info, $modFolders); if(count($folderIntersect) == 0){ //load it only if it is not in one of those folders $controllerName = "{$this-&gt;_path-&gt;model}Controller"; $app_controller = $this-&gt;create_controller($controllerName); if(!$app_controller) { $route = $this-&gt;CONFIG-&gt;getRoute($this-&gt;_path-&gt;model); if($route) { //try to find route $this-&gt;_path-&gt;page = $route-&gt;page; $this-&gt;CONFIG-&gt;set('page', $route-&gt;page); //reset the page name $this-&gt;_path-&gt;args = count($route-&gt;args) ? $route-&gt;args : $this-&gt;_path-&gt;route_args; $app_controller = $this-&gt;create_controller($route-&gt;controller); if(!$app_controller) { //show nothing header("HTTP/1.1 404 Not Found"); exit; } } else { //show nothing header("HTTP/1.1 404 Not Found"); exit; } } return $app_controller; } else { //fake mod-rewrite $this-&gt;rewrite($this-&gt;_path-&gt;path_info, $folderIntersect); } //END LOAD CONTROLLER } /** * @param string $controllerName * @return AppController */ private function create_controller($controllerName) { $useOldVersion = !$this-&gt;CONFIG-&gt;get('DB_NEW'); $mySQLClass = "SmallFry\lib\MySQL_PDO"; if($useOldVersion) { $mySQLClass = "SmallFry\lib\MySQL_Improved"; } //DB CONN $firstHandle = null; $secondHandle = null; //Primary db connection $database_info = $this-&gt;CONFIG-&gt;get('DB_INFO'); if($database_info) { $firstHandle = new $mySQLClass($database_info['host'], $database_info['login'], $database_info['password'], $database_info['database'], $this-&gt;CONFIG-&gt;get('DEBUG_QUERIES')); } else { exit("DO NOT HAVE DB INFO SET"); } //Secondary db connection $database_info = $this-&gt;CONFIG-&gt;get('SECONDARY_DB_INFO'); if($database_info) { $secondHandle = new $mySQLClass($database_info['host'], $database_info['login'], $database_info['password'], $database_info['database'], $this-&gt;CONFIG-&gt;get('DEBUG_QUERIES')); } //END DB CONN $nameSpacedController = "SmallFry\\Controller\\$controllerName"; if (class_exists($nameSpacedController) &amp;&amp; is_subclass_of($nameSpacedController, __NAMESPACE__.'\AppController')) { $app_controller = new $nameSpacedController($this-&gt;_session, $this-&gt;CONFIG, $firstHandle, $secondHandle); } else { return false; } return $app_controller; } /** * @param array $path_info * @param array $folderIntersect */ private function rewrite(array $path_info, array $folderIntersect){ $find_path = array_keys($folderIntersect); $find_length = count($find_path) - 1; $file_name = implode(DIRECTORY_SEPARATOR,array_slice($path_info, $find_path[$find_length])); $file = \SmallFry\Config\DOCROOT."webroot".DIRECTORY_SEPARATOR.$file_name; if(is_file($file)){ //if the file is a real file header("Last-Modified: " . date("D, d M Y H:i:s", getlastmod())); include \SmallFry\Config\BASEROOT.DIRECTORY_SEPARATOR.'functions'.DIRECTORY_SEPARATOR.'mime_type.php'; // needed for setups without `mime_content_type` header('Content-type: ' . mime_content_type($file)); readfile($file); } else { header("HTTP/1.1 404 Not Found"); } exit; } } </code></pre> <p><a href="https://github.com/maniator/SmallFry/blob/7bcd7a0e992e8d5a78ff12a83a3b33d69f230863/lib/AppController.php" rel="nofollow noreferrer"><code>AppController.php</code></a>:</p> <pre><code>&lt;?php namespace SmallFry\lib; /** * Description of AppController * * @author nlubin */ class AppController { private $pageOn; protected $name = __CLASS__; protected $helpers = array(); protected $validate = array(); protected $posts = array(); protected $session; protected $validator; protected $template; protected $CONFIG; /** * * @param SessionManager $SESSION * @param Config $CONFIG * @param MySQL_Interface $firstHandle * @param MySQL_Interface $secondHandle */ public function __construct(SessionManager $SESSION, Config $CONFIG, MySQL_Interface $firstHandle, MySQL_Interface $secondHandle = null) { $this-&gt;CONFIG = $CONFIG; $this-&gt;pageOn = $this-&gt;CONFIG-&gt;get('page'); $this-&gt;session = $SESSION; $model_name = isset($this-&gt;modelName) ? $this-&gt;modelName : $this-&gt;name; /* Build the AppModel */ $this-&gt;$model_name = &amp;AppModelFactory::buildModel($model_name, $CONFIG, $firstHandle, $secondHandle); /* Get all posts */ $this-&gt;posts = $this-&gt;$model_name-&gt;getPosts(); $this-&gt;CONFIG-&gt;set('view', strtolower($model_name)); if(!$this-&gt;session-&gt;get(strtolower($model_name))){ $this-&gt;session-&gt;set(strtolower($model_name), array()); } } private function getPublicMethods(){ $methods = array(); $r = new \ReflectionObject($this); $r_methods = $r-&gt;getMethods(\ReflectionMethod::IS_PUBLIC); $notAllowedMethods = array("__construct", "init", "__destruct"); //list of methods that CANNOT be a view and are `keywords` foreach($r_methods as $method){ if($method-&gt;class !== 'SmallFry\lib\AppController' &amp;&amp; !in_array($method-&gt;name, $notAllowedMethods)){ //get only public methods from extended class $methods[] = $method-&gt;name; } } return $methods; } /** * * @param Template $TEMPLATE */ public function setTemplate(Template $TEMPLATE){ $this-&gt;template = $TEMPLATE; $this-&gt;setHelpers(); } /** * Function to run before the constructor's view function */ public function init(){} //function to run right after constructor /** * Show the current page in the browser * * @param array $args * @return string */ public function displayPage($args) { $this-&gt;CONFIG-&gt;set('method', $this-&gt;pageOn); $public_methods = $this-&gt;getPublicMethods(); if(in_array($this-&gt;pageOn, $public_methods)) { call_user_func_array(array($this, $this-&gt;pageOn), $args); } else { if(!in_array($this-&gt;pageOn, $public_methods)) { header("HTTP/1.1 404 Not Found"); } else { $this-&gt;CONFIG-&gt;set('method', '../missingfunction'); //don't even allow trying the page return($this-&gt;getErrorPage($this-&gt;CONFIG-&gt;get('view')."/{$this-&gt;pageOn} does not exist.")); } exit; } } /** * * @return string */ function index() {} /** * * @param string $msg * @return string */ protected function getErrorPage($msg = null) { $err = '&lt;div class="error errors"&gt;%s&lt;/div&gt;'; return sprintf($err, $msg); } protected function setHelpers(){ $helpers = array(); foreach($this-&gt;helpers as $helper){ $help = "{$helper}Helper"; $nameSpacedHelper = "SmallFry\\helper\\$help"; if(class_exists($nameSpacedHelper) &amp;&amp; is_subclass_of($nameSpacedHelper, 'SmallFry\\helper\\Helper')){ $this-&gt;$helper = new $nameSpacedHelper(); $helpers[$helper] = $this-&gt;$helper; } } $this-&gt;template-&gt;set('helpers', (object) $helpers); } protected function logout(){ session_destroy(); header('Location: '.WEBROOT.'index.php'); exit; } /** * * @param array $validate * @param array $values * @param boolean $exit * @return boolean */ protected function validateForm($validate = null, $values = null, $exit = true){ $this-&gt;validator = new FormValidator(); //create new validator if($validate == null){ $validate = $this-&gt;validate; } foreach($validate as $field =&gt; $rules){ foreach($rules as $validate=&gt;$message){ $this-&gt;validator-&gt;addValidation($field, $validate, $message); } } return $this-&gt;doValidate($values, $exit); } protected function doValidate($values = null, $exit = true){ if(!(!isset($_POST) || count($_POST) == 0)){ //some form was submitted if(!$this-&gt;validator-&gt;ValidateForm($values)){ $error = ''; $error_hash = $this-&gt;validator-&gt;GetErrors(); foreach($error_hash as $inpname =&gt; $inp_err) { $error .= $inp_err.PHP_EOL; } return $this-&gt;makeError($error, $exit); } } return true; } protected function makeError($str, $exit = true){ $return = $this-&gt;getErrorPage(nl2br($str)); if($exit) exit($return); return $return; } protected function killPage(){ //Throw a 404 for the page header("HTTP/1.1 404 Not Found"); exit; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T23:59:53.853", "Id": "31363", "Score": "0", "body": "Saw this on /r/php...you should read the fig standards wrt things like keyword case, prefixing underscores on properties, brace placement, using \"exit\", etc. At the least please try to maintain consistency with whitespace and formatting inside your own project. (sorry, wasn't trying to sound mean)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T14:13:02.573", "Id": "31395", "Score": "0", "body": "@ChadRetz the spacing got messed up somehow when I committed.... That was not my fault :-\\ It does not look like that on my computer. Can you expand on your other comments? Just for a backstory, I had started out using [this](http://anantgarg.com/2009/03/13/write-your-own-php-mvc-framework-part-1/) and then I expanded from there." } ]
[ { "body": "<p>A few things: </p>\n\n<p>Firstly, It's not MVC. In MVC, controllers do not feed the view data. This is a common misconception but the architecture you're using here is closer to PAC. See <a href=\"http://www.garfieldtech.com/blog/mvc-vs-pac\">http://www.garfieldtech.com/blog/mvc-vs-pac</a> and <a href=\"http://r.je/views-are-not-templates.html\">http://r.je/views-are-not-templates.html</a> for more info (Full disclosure: I wrote the second article.)</p>\n\n<p>Secondly, your models aren't models they're simple data access and barely even that. They should at least abstract SQL away. You have domain logic, presentation logic and application logic all in the controller. In MVC the model should store application state (and have access to domain state), the controller should respond to user actions and the view should fetch the data from the model. See <a href=\"http://blog.astrumfutura.com/2008/12/the-m-in-mvc-why-models-are-misunderstood-and-unappreciated/\">http://blog.astrumfutura.com/2008/12/the-m-in-mvc-why-models-are-misunderstood-and-unappreciated/</a> for a description of the model in MVC.</p>\n\n<p>Thirdly, forcing models, views and controllers to extend from specific base classes heavily limits flexibility. Your controllers, views and models should implement interfaces instead of extending base classes. Although from experience, I have found that controllers and models don't even need to do that.</p>\n\n<p>Finally, you should always favour Dependency injection rather than constructing objects arbitrarily throughout the code. See <a href=\"http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/\">http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/</a> (and the rest of his very excellent site) for more information. </p>\n\n<p>Sorry to sound very critical, but it's important to get the fundamental architecture correct before asking people to critique code clarity and quality. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T22:07:58.650", "Id": "31351", "Score": "0", "body": "My classes are using Dependency Injection. Is there anything you can add on how I can improve my code? (forget the naming conventions, those can be changed)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T22:11:24.330", "Id": "31352", "Score": "0", "body": "Occasionally you are, however things like : public final function addUseModel($usingModel) {\n $this->$usingModel = &AppModelFactory::buildModel($usingModel, $this->CONFIG, $this->firstHandle, $this->secondHandle);\n } are not DI. In DI you would pass in the fully constructed object instead of having a factory build it. The reason for this is flexibility: The appmodel (as you're calling it) should be agnostic about where its dependencies come from." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T22:12:19.963", "Id": "31353", "Score": "0", "body": "That buildModel function is only for when a model **uses** another model (or models). That way I can do: `$this->ModelA->ModelB->getSomething();` (also side note: full code blocks do not show up well in comments like that, using pastebin or another bin site might fix that)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T22:13:39.250", "Id": "31354", "Score": "0", "body": "How would I allow for a Model to use other models except for using that function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T22:14:23.757", "Id": "31355", "Score": "0", "body": "I'd argue that's bad practice in itself. See: http://misko.hevery.com/code-reviewers-guide/flaw-digging-into-collaborators/ any models which have a dependency on other models should define them as constructor (or method) arguments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T22:15:21.937", "Id": "31356", "Score": "0", "body": "Ok.. but then how would I handle table joins etc without doing that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T22:19:46.347", "Id": "31358", "Score": "0", "body": "That's a a different issue but it's rooted in not having a proper model. See the article by Padraic Brady I linked to http://blog.astrumfutura.com/2008/12/the-m-in-mvc-why-models-are-misunderstood-and-unappreciated/ The model would encapsulate all data access. This can work by any means but it usually boils down to DataMapper vs ActiveRecord. There's a lot of information around on this topic but the key difference is that DataMapper is preferred because it doesn't do table joins. Making assumptions that all data comes from the same source leads to problems. Neither ORM is a MVC model, however." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T14:13:44.183", "Id": "31396", "Score": "0", "body": "Just for a backstory: I had started out using [this](http://anantgarg.com/2009/03/13/write-your-own-php-mvc-framework-part-1/) and then I expanded from there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-16T14:20:38.703", "Id": "31472", "Score": "0", "body": "Yes, it is a common misunderstanding. You could argue that if everyone is calling it \"MVC\" that it is MVC because the definition has changed. However, this architecture is only called MVC by PHP/web developers. That's not a problem in itself but the original architecture was created by clever academics that had very carefully considered what they were trying to achieve. The common PAC like architecture used on the web loses a lot of the advantages MVC offers but information on original MVC pattern is lost by people incorrectly labelling other architectures." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T22:06:39.850", "Id": "19593", "ParentId": "19592", "Score": "8" } }, { "body": "<p>There is plenty of stuff to criticize in your approach, and it boils down to the usual stuff:</p>\n\n<ol>\n<li>Your classes do too much different stuff</li>\n<li>Your classes do not implement proper dependency injection.</li>\n<li>But if they do, they have very weird dependencies that will fit a certain use case, but not all.</li>\n</ol>\n\n<p>Some details:</p>\n\n<pre><code> $this-&gt;CONFIG-&gt;set('page_title', $this-&gt;CONFIG-&gt;get('DEFAULT_TITLE'));\n $this-&gt;CONFIG-&gt;set('template', $this-&gt;CONFIG-&gt;get('DEFAULT_TEMPLATE'));\n</code></pre>\n\n<p>I find it weird that the bootstrap class actually changes the configuration. Configuration to me is a read-only value storage. It gets written in the config object only once in the life cycle of the application request: When it's read from it's permanent storage.</p>\n\n<p>The AppController for some weird reason has dependencies on a session manager, a configuration object, and TWO database connections. None of them should be the business of a controller. The controllers task is to be the combining layer between the incoming request on the input side, a number of models that act upon the data in the request as the processing step, and passing data back to the response as the output. </p>\n\n<p>Analyzing the input data from the request usually is done by helping objects that represent HTML forms to do validation (none of the controllers business). The models usually make use of some database access or session, but this also is not for the controller to know. Preparing a response means to push some values into the answer, which might actually be rendered by a template, but this also is not really the business of the controller.</p>\n\n<p>When I look at your AppController class, I see that it offers a whole lot of methods that have nothing to do with controller tasks, but with implementation details of a concrete application. I see methods like <code>displayPage</code>, <code>validateForm</code>, <code>logout</code>, that shouldn't be there. I especially wonder why <code>logout()</code> does not use the <code>SessionManager</code> to terminate the session.</p>\n\n<p>It was mentioned before, but I want to underline that if you force all the application classes to be extended from your frameworks classes, you make it hard for others to use your framework. For example the <code>Helpers</code> - for some reason they have to be extended from your mother helper class. A much better approach would be to only force the implementation of an interface, and offer an abstract helper class that already has a basic implementation that can be extended if there is no need to build from scratch.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T20:30:51.230", "Id": "31894", "Score": "0", "body": "Wow I did not realize \"logout\" was still there. That is from a very old version of the code when The SessionManager did not exist." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T22:35:26.570", "Id": "19640", "ParentId": "19592", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T21:38:10.270", "Id": "19592", "Score": "3", "Tags": [ "php", "object-oriented", "mvc", "library" ], "Title": "Small MVC for PHP" }
19592
<p>I was looking for a way to start elevated (i.e. administrator permissions) and/or invisible processes via batch in Windows. It turns out that this is kind of impossible with batch only, so I googled some vbs stuff and hacked it all together into a neat command line power utility.</p> <p>The interface is as follows: </p> <pre><code>exec [/action: elevate, open, read, print] [/display: hide, show] exe [arguments] </code></pre> <p><code>/action</code> defaults to <code>open</code>. <code>/display</code> defaults to <code>show</code>. <code>exe</code> is the path to an executeable, could be a script, image, whatever as well. <code>arguments</code> are applied to the <code>exe</code>.</p> <p>Example: This starts a background node.js deamon with admin rights. </p> <pre><code>exec /action:elevate /display:hide node myDeamon.js </code></pre> <p>Everything works just fine, but I'm pretty sure that it's not perfect yet, as I basically have no idea about VBScript. I'd like to hear your opinions or ideas!</p> <pre class="lang-vb prettyprint-override"><code>Set objShell = CreateObject("Shell.Application") intOffset = 0 ' get action strAction = "open" If (WScript.Arguments.Named.Exists("action")) Then intOffset = intOffset + 1 Select Case WScript.Arguments.Named.Item("action") Case "elevate" strAction = "runas" Case "open" strAction = "open" Case "read" strAction = "read" Case "print" strAction = "print" Case Else strAction = "open" End Select End If ' get display mode intMode = 1 If (WScript.Arguments.Named.Exists("display")) Then intOffset = intOffset + 1 Select Case WScript.Arguments.Named.Item("display") Case "0" intMode = 0 Case "false" intMode = 0 Case "hide" intMode = 0 Case "hidden" intMode = 0 Case Else intMode = 1 End Select End If ' get application to execute strApplication = WScript.Arguments(intOffset) ' get arguments strArguments = "" For i = intOffset+1 To WScript.Arguments.Count-1 strArguments = strArguments &amp; WScript.Arguments(i) Next ' execute application If (WScript.Arguments.Count &gt;= 1) Then objShell.ShellExecute strApplication, strArguments, "", strAction, intMode Else WScript.Quit End If </code></pre> <p><a href="https://gist.github.com/4281665" rel="nofollow">Gist</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T09:18:15.553", "Id": "31374", "Score": "1", "body": "silvinci, please include the relevant code directly in your question as required by the [faq]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T01:46:18.260", "Id": "31412", "Score": "0", "body": "Done. Just thought it would be too lengthy." } ]
[ { "body": "<p>The number one improvement you can make is to include <a href=\"http://msdn.microsoft.com/en-us/library/bw9t3484%28v=vs.84%29.aspx\" rel=\"nofollow\"><code>Option Explicit</code></a> as the first line of your script and explicitly declare your variables using <code>Dim</code>. This will save you a lot of heartache in the future (e.g., if you make a typo in a variable name, it becomes a runtime error, instead of just silently creating a new variable).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T12:09:03.830", "Id": "37025", "Score": "0", "body": "This sounds pretty reasonable. Thanks. Do I have to `Dim` in `For` statements?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T19:24:05.260", "Id": "37052", "Score": "0", "body": "If you have a statement `For i = 1 To 10`, then you must declare `i` with `Dim i`, if that's what you're asking." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T08:04:57.447", "Id": "24001", "ParentId": "19596", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T02:01:09.067", "Id": "19596", "Score": "4", "Tags": [ "optimization", "vbscript" ], "Title": "Power utility for starting processes" }
19596
<p>Developing some industrial WinForms application for some industrial setting, I wanted to provide users of our software with a convenient way to back up the database the software uses (to send it to developer for investigation of any issues that might arise, or just to keep it at hand in case something goes wrong).</p> <p>The assumptions (more or less checked to be true in our environment):</p> <ol> <li>The GUI of software works on some server, accesing the DB over an SQL connection</li> <li>The user of the GUI is the person most likely to report the problems; he is an enginier, not an IT guy</li> <li>We store no confidential data - anyone with the right to use the database is ok to read it all (not so ok with writing it all over)</li> <li>The database server administrator is not readily available (there is no dedicated database administrator; most of the time the thing just works, and when it does not, someone comes to fix the problem - and that "someone", having a rather wide area of responsibility, would like to have less things to care about, not more)</li> <li>Some computers this is to work on might be a part of domain, some not; SMB shares might exist, someone might know and/or periodically change the password, network names, all sort of stuff.</li> </ol> <p>The solution:</p> <p>The solution I came up with is to back up the database onto the same computer the GUI is running on, over the same SQL connection GUI accesses the database through. Restoring is still manual.</p> <p>The following is the SQL part. So, what do you say about it?</p> <pre><code>CREATE PROCEDURE get_backup @make bit = 1, @download bit = 1, @delete bit = 1 AS BEGIN SET NOCOUNT ON; DECLARE @count int, @part int, @sql nvarchar(max) DECLARE @files table (n int, pathname nvarchar(2000), path nvarchar(2000), quoted_pathname nvarchar(2000), quoted_name nvarchar(200)) IF @make = 1 BEGIN DECLARE @size int SET @size = (SELECT SUM(total_pages)/128.0 AS megabytes FROM sys.allocation_units) SET @count = (@size + 1000) / 1000 SET @sql = 'BACKUP DATABASE ' + QUOTENAME(DB_NAME()) + ' TO ' SET @part = 1 WHILE @part &lt;= @count BEGIN SET @sql = @sql + 'DISK = ''' + REPLACE(DB_NAME(), '''' ,'''''') + '-part' + RIGHT('0000' + CAST(@part AS nvarchar(4)), 4) + '.tmp-bak''' IF @part &lt; @count SET @sql = @sql + ', ' SET @part = @part + 1 END SET @sql = @sql + ' WITH FORMAT, COPY_ONLY, STATS = 1' EXEC(@sql) END INSERT INTO @files SELECT TOP 1 WITH TIES family_sequence_number, physical_device_name, REVERSE(RIGHT(REVERSE(physical_device_name), (LEN(physical_device_name) - CHARINDEX('\', REVERSE(physical_device_name), 1)) + 1)), '''' + REPLACE(physical_device_name, '''' ,'''''') + '''', '''' + REPLACE(REPLACE(REVERSE(LEFT(REVERSE(physical_device_name), CHARINDEX('\', REVERSE(physical_device_name), 1) - 1)), '.tmp-bak', '.bak'), '''' ,'''''') + '''' FROM msdb.dbo.backupmediafamily WHERE physical_device_name LIKE '%.tmp-bak' ORDER BY media_set_id DESC IF @count IS NULL SET @count = (SELECT COUNT(*) FROM @files) IF @count &lt;&gt; (SELECT COUNT(*) FROM @files) RAISERROR('Count mismatch', 16, 0) IF @download = 1 BEGIN PRINT CAST(@count AS nvarchar(4)) + ' files per backup.' SET @sql = ''; SET @part = 1 WHILE @part &lt;= @count BEGIN SET @sql = @sql + (SELECT 'SELECT ' + quoted_name + ' AS name, BulkColumn AS data FROM OPENROWSET (BULK ' + quoted_pathname + ', SINGLE_BLOB) AS a' FROM @files WHERE n = @part) IF @part &lt; @count SET @sql = @sql + ' UNION ' SET @part = @part + 1 END EXEC(@sql) END IF @delete = 1 BEGIN DECLARE @path nvarchar(2000) SET @path = (SELECT TOP 1 path from @files) EXECUTE xp_delete_file 0, @path, 'tmp-bak', '2080-01-01', 0 END END </code></pre> <hr> <p>Inspired by </p> <ul> <li><a href="http://www.codeproject.com/Articles/33963/Transferring-backup-files-from-a-remote-SQL-Server" rel="nofollow">Transferring backup files from a remote SQL Server instance to a local machine without network shares, FTP, HTTP</a> </li> <li><a href="http://www.mssqltips.com/sqlservertip/1643/using-openrowset-to-read-large-files-into-sql-server/" rel="nofollow">Using OPENROWSET to read large files into SQL Server</a> </li> <li><a href="http://sqlblog.com/blogs/andy_leonard/archive/2009/03/11/xp-delete-file.aspx" rel="nofollow">xp_delete_file</a>.</li> </ul>
[]
[ { "body": "<p>Leaving aside your general design, here are some comments - in no particular order - purely about the code itself:</p>\n\n<ul>\n<li>There are no comments anywhere. This makes the code very difficult to read. You should have enough comments in the code so that someone can read through them quickly and get an immediate understanding of <em>what</em> the code does. The code itself explains <em>how</em> it does it.</li>\n<li>Your parameter and variable naming is somewhat vague: 'make', 'count', 'size' etc. are all general terms and more precise naming would be clearer and make the code more readable, e.g. <code>@make_backup</code>, <code>@number_of_files</code> and <code>@backup_file_size</code>.</li>\n<li>You're using dynamic SQL heavily but you don't have any easy way to debug it. Dynamic SQL is notoriously error-prone (although often unavoidable), so if you use it then make sure you have an easy way to troubleshoot. I always add a <code>@debug</code> parameter and put lots of <code>if @debug = 0x1 print @sql</code> statements in the code. It can also be useful to add an <code>@execute</code> parameter to control whether or not the dynamic SQL code should be executed or just generated.</li>\n<li>Your code is full of implicit data type conversions: your string variables are <code>nvarchar</code> but your string literals are <code>varchar</code>, and your bit literals are actually integers. <code>nvarchar</code> literals are preceded with <code>N</code> ie. <code>N'literal'</code> and bits are either <code>0x0</code> or <code>0x1</code>. In this specific procedure it will probably make no difference, but when writing queries against large tables conversions can cause noticeable performance problems.</li>\n<li>The condition <code>IF @count IS NULL</code> would be better written as <code>IF @make = 0x0</code> because the only way <code>@count</code> will be <code>NULL</code> is if the make section wasn't executed. Relying on default behaviour - in this case that an uninitialized variable is <code>NULL</code> - is difficult to read and maintain and breaks easily when you modify what appears to be an unrelated piece of the code.</li>\n<li><code>xp_delete_file</code> is an undocumented stored procedure. In other words it may change behaviour or vanish completely in the next service pack (even if it's been around for a long time already). Relying on undocumented features always has some risk - even for 'well-known' undocumented features - and I wouldn't ship any code that relies on them.</li>\n<li>You have a 'magic string' in your code: <code>2080-01-01</code>. There's no comment to explain it, so you're assuming that the next person to maintain this code will understand it immediately. In fact, this often leads to code that everyone is afraid to change. And ironically the maintenance developer struggling to understand it will possibly be you, because you just forgot why you put it there.</li>\n<li>In general, whenever you embed a literal value of any kind in your code (<code>tmp-bak</code> is another example), consider whether or not it should be either declared (and commented!) as a variable as the start of your procedure, or put into a 'configuration' or 'constants' table where it can be more easily maintained and documented. This depends mainly on the scope of the value and how often it's used, of course.</li>\n</ul>\n\n<p>As a general observation, I find this a very strange way of making a backup. Since you're writing a .NET application, I would use <a href=\"http://msdn.microsoft.com/en-us/library/ms162169.aspx\">SMO</a> to do the whole thing 'natively' in .NET code. TSQL is a very poor language for working with files and anything else outside the database, so you would probably find that SMO is easier. But as always, you know your own situation and requirements best so there may be good reasons for trying to do this all in TSQL.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-19T17:44:42.060", "Id": "22895", "ParentId": "19598", "Score": "6" } } ]
{ "AcceptedAnswerId": "22895", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T04:00:59.057", "Id": "19598", "Score": "4", "Tags": [ "sql", "sql-server" ], "Title": "Backup a database over an SQL connection" }
19598
<p>I have code that is accessed by multiple threads. If by any chance it has a problem, all accessing threads will wait for recovery. By default, the first thread that fails, will have to recover and all others will have to wait. When the process is complete, everyone leaves the method.</p> <pre><code>[TestMethod] public void RecoveryConcurrentTest() { Task task = Task.Factory.StartNew(() =&gt; { ManualResetEvent r1 = new ManualResetEvent(false); var t1 = new Thread((obj) =&gt; { AutoRecover(); r1.Set(); }); ManualResetEvent r2 = new ManualResetEvent(false); var t2 = new Thread((obj) =&gt; { AutoRecover(); r2.Set(); }); ManualResetEvent r3 = new ManualResetEvent(false); var t3 = new Thread((obj) =&gt; { AutoRecover(); r3.Set(); }); ManualResetEvent r4 = new ManualResetEvent(false); var t4 = new Thread((obj) =&gt; { AutoRecover(); r4.Set(); }); t1.Start(); t2.Start(); t3.Start(); t4.Start(); WaitHandle.WaitAll(new WaitHandle[] { r1, r2, r3, r4 }); }); task.Wait(); } private Object _syncRoot = new Object(); private int count; private bool handled; public void AutoRecover() { Trace.WriteLine("thread: " + Thread.CurrentThread.ManagedThreadId); Interlocked.Increment(ref count); Trace.WriteLine("count + 1 = " + count); // not work properly lock (_syncRoot) { Trace.WriteLine("thread: " + Thread.CurrentThread.ManagedThreadId); if (handled) { Trace.WriteLine("handled is true"); } else { Trace.WriteLine("handled is false"); Trace.WriteLine("PROCESSING...."); Thread.Sleep(10000); Trace.WriteLine("PROCESSED...."); handled = true; Trace.WriteLine("handled set true"); } Interlocked.Decrement(ref count); Trace.WriteLine("count - 1 = " + count); if (count == 0) { handled = false; Trace.WriteLine("handled set false"); } } } </code></pre> <p>It works well for my tests, but I believe that there are necessary adjustments and that it can be implemented differently.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T13:55:05.393", "Id": "31393", "Score": "0", "body": "It's not quite clear what do you want us to review... AutoRecover() looks like just a stub, right? Are you asking to review the test method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T15:39:06.893", "Id": "31398", "Score": "0", "body": "I would like to better ways, other ways of dealing with concurrency." } ]
[ { "body": "<p>There is no sense in creating a task and waiting on it straight away. The following code is almost identical to your test method (almost - because tasks are created on a thread pool here):</p>\n\n<pre><code>[TestMethod]\npublic void RecoveryConcurrentTest()\n{\n var tasks = Enumerable.Range(0, 10).Select(i =&gt; Task.Factory.StartNew(AutoRecover)).ToArray();\n\n Task.WaitAll(tasks);\n}\n</code></pre>\n\n<p>Note that it doesn't actually test the fact that <code>AutoRecover</code> allows only one thread at a time, it just ensures that nothing fails when multiple threads call this method. There is no way in current design to detect it.</p>\n\n<p>What I would suggest is to expose the fact of long process inside of <code>AutoRecover</code> by returning a <code>Task</code> that any thread can wait on:</p>\n\n<pre><code>[TestMethod]\npublic void RecoveryConcurrentTest()\n{\n var tasks = Enumerable.Range(0, 10).Select(i =&gt; AutoRecoverAsync()).ToArray();\n\n Task.WaitAll(tasks);\n}\n\nprivate volatile Task _recoveryTask;\nprivate readonly object _syncRoot = new object();\n\nprivate async Task DoActualRecover()\n{\n Trace.WriteLine(\"PROCESSING....\");\n await Task.Delay(10000);\n Trace.WriteLine(\"PROCESSED....\");\n _recoveryTask = null;\n}\n\npublic Task AutoRecoverAsync()\n{\n var recoveryTask = _recoveryTask;\n if (recoveryTask != null)\n return recoveryTask;\n\n lock (_syncRoot)\n {\n recoveryTask = _recoveryTask;\n if (recoveryTask != null)\n return recoveryTask;\n\n return _recoveryTask = DoActualRecover();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-03T12:03:27.937", "Id": "32142", "Score": "0", "body": "Is a good approach. I thought of using semaphores, it may also be a good option." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-26T14:40:46.053", "Id": "142435", "Score": "0", "body": "It's much better performance for that issue, much better." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-15T21:42:14.140", "Id": "19639", "ParentId": "19607", "Score": "1" } } ]
{ "AcceptedAnswerId": "19639", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T10:42:59.907", "Id": "19607", "Score": "0", "Tags": [ "c#", "multithreading", "concurrency" ], "Title": "Simplifying and optimize a concurrent access" }
19607
<p>I wrote this <a href="http://plus.maths.org/content/os/issue50/features/havil/index" rel="nofollow">Sundaram's sieve</a> in <a href="http://coffeescript.org/" rel="nofollow">Coffeescript</a> to quickly generate prime numbers up to <code>limit</code>:</p> <pre><code>sieve_sundaram = (limit) -&gt; numbers = (n for n in [3...limit+1] by 2) half = limit / 2 start = 4 for step in [3...limit+1] by 2 for i in [start...half] by step numbers[i-1] = 0 start += 2 * (step + 1) if start &gt; half result = (n for n in numbers when n &gt; 0) result.shift 2 return result </code></pre> <p>See equivalent <a href="http://coffeescript.org/#try%3asieve_sundaram%20%3D%20%28limit%29%20-%3E%0A%20%20%20%20numbers%20%3D%20%28n%20for%20n%20in%20%5b3...limit%2B1%5d%20by%202%29%0A%20%20%20%20half%20%3D%20limit%20%2F%202%0A%20%20%20%20start%20%3D%204%0A%0A%20%20%20%20for%20step%20in%20%5b3...limit%2B1%5d%20by%202%0A%20%20%20%20%20%20%20%20for%20i%20in%20%5bstart...half%5d%20by%20step%0A%20%20%20%20%20%20%20%20%20%20%20%20numbers%5bi-1%5d%20%3D%200%0A%20%20%20%20%20%20%20%20start%20%2B%3D%202%20%2a%20%28step%20%2B%201%29%0A%0A%20%20%20%20%20%20%20%20if%20start%20%3E%20half%0A%20%20%20%20%20%20%20%20%20%20%20%20result%20%3D%20%28n%20for%20n%20in%20numbers%20when%20n%20%3E%3D%200%29%0A%20%20%20%20%20%20%20%20%20%20%20%20result.shift%202%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20result" rel="nofollow">Javascript code</a>.</p> <p>Is it possible to rewrite it in <a href="https://en.wikipedia.org/wiki/Functional_programming" rel="nofollow">functional paradigm</a>? I'm concerned mainly with the need to change the <code>numbers</code> array and increment <code>start</code> variable. If external library (like <a href="http://documentcloud.github.com/underscore/" rel="nofollow">underscore.js</a>) is needed, it's acceptable. JavaScript solutions are also acceptable.</p>
[]
[ { "body": "<p><code>result.shift 2</code> probably doesn't do what you think it does. You meant <code>unshift</code>.</p>\n\n<ul>\n<li><code>shift</code> removes the first element of an array (and doesn't take any arguments).</li>\n<li><code>unshift</code> adds new items at the beginning of the array.</li>\n</ul>\n\n<p>As a result, your final array isn't <code>[2,3,5,...]</code> but <code>[5,...]</code></p>\n\n<hr>\n\n<p>Also, I'll point out the bug in the code you have in your \"equivalent Javascript code\" link - it has <code>&gt;=</code> in the <code>result = (n for n in numbers when n &gt;= 0)</code> at the bottom instead of <code>n &gt; 0</code> (which is correct).</p>\n\n<p>You probably guessed that since your code here has that fixed. <code>n &gt;= 0</code> doesn't filter the <code>0</code> elements from the array, <code>n &gt; 0</code> does.</p>\n\n<hr>\n\n<p>And now for the functional ways. <em>(Disclaimer: I don't think my functional rewrite of your code is any prettier - but it's more functional. Maybe someone can make it look more elegant?)</em></p>\n\n<p>I'm no expert on functional programming, but from what I've learned, you generally try to use things like map, reduce, filter.</p>\n\n<ul>\n<li><p><code>[].filter()</code> takes predicate (test function returning boolean) that gets called with all the elements one by one and returns array with values that pass the test. You kind of already used it in the <code>(n for n in numbers when n &gt; 0)</code> - it's the <code>when</code> part.</p></li>\n<li><p><code>[].map()</code> takes a \"transforming\" function that gets called with all the elements one by one and returns array with the transformed values. With CoffeeScript we can cheat again and use list comprehensions: <code>(my_function(x) for x in xs)</code>.</p></li>\n<li><p><code>[].reduce()</code> is probably the least intuitive one - but we'll use it in your sieve :) You give it an initial value (accumulator) and a transforming function and it reduces the array left to right to a single value. The canonical example is summation: <code>the_sum = [1,2,3].reduce(((acc, val) -&gt; acc + val), 0) # the_sum is 6 now</code>.</p></li>\n</ul>\n\n<p>Now, when I hear \"functional paradigm,\" I hear \"loopless way\" and \"immutability.\" Functional programming is about more things, of course.</p>\n\n<p><em>EDIT: oh man, I had <code>limit = 100</code> in the code. Stupid mistake :) Fixed now.</em></p>\n\n<pre><code>sieve_sundaram = (limit) -&gt;\n\n start = 4\n half = limit/2\n\n numbers = (n for n in [3...limit+1] by 2)\n steps = numbers[..] # copy of numbers\n</code></pre>\n\n<p>As you can see, <code>numbers</code> equals <code>steps</code>, at least at the first go. What we'll change will be the loops. Instead of thinking in terms of <code>for ... do ...</code>, we'll think more like <code>result = (... for ...)</code> - transforming the arrays with our <code>map</code>, <code>filter</code>, <code>reduce</code> functions or their CoffeeScript counterparts.</p>\n\n<p>Now, we have to define the transforming function for the <code>reduce()</code>, because we want to do something like <code>steps.reduce(callback,numbers)</code>. You see, with a little bit of imagination you had <code>for step in steps do something</code> in your code.</p>\n\n<p>Now we'll do exactly that - our function for the <code>reduce</code> will get a step at every call, just like your loop did. So that's that.</p>\n\n<p>Next problem we have is rewriting the \"global\" changes you make inside the loop. So we need to do something about the <code>numbers[i-1] = 0</code> and <code>start += 2 * (step + 1)</code> lines. We'll make the changes propagate through the result values.</p>\n\n<p>But how can we make two things propagate through one value? We'll use an array. Remember, <code>numbers</code> is an array and <code>start</code> is a number. Essentially we'll insert the <code>start</code> at the beginning (or the end, wouldn't matter) of the <code>numbers</code> array and at each call of our reduce callback extract it from there - and of course, after the reduce finishes.</p>\n\n<pre><code> callback = (start_and_nums,step) -&gt;\n\n start = start_and_nums[0]\n nums = start_and_nums[1..]\n</code></pre>\n\n<p>So that's the extraction part. Pretty trivial with CoffeeScript.</p>\n\n<p>Next part is little bit trickier. If you're familiar with recursion, you know the <strong>base case</strong> is usually written before the other parts of recursive function. We'll do something similar - check for your <code>if start &gt; half</code> condition before we do anything else.</p>\n\n<p>If it's true, it will simply mean that we don't need to do any of that sieving mumbo jumbo, that we're done and just need to wait till we get through all the elements, because we can't stop the reduce function midway.</p>\n\n<pre><code> if start &gt; half\n result = (n for n in nums when n &gt; 0)\n result.unshift start \n return result \n\n # We can't stop iterating inside the reduce() although we'd like to right now.\n # Also, we slice the first element every time our function gets called,\n # so we'll put it back here for now. We'll deal with it after reduce() finishes.\n # Also, we mustn't forget about the 2!\n</code></pre>\n\n<p>Next portion of the code is reached only if we still have work to do (we didn't get to the <code>return</code> inside the <code>if</code>). It's outdented, but maybe that's hard to see with my comments between the lines.</p>\n\n<p>Now, look at your <code>for i...</code> line. What you really want is <code>i-1</code>, because you use it in the next line (<code>numbers[i-1]</code>). So we'll use map. It should be pretty straightforward:</p>\n\n<pre><code> idxs = (idx-1 for idx in [start...half] by step)\n</code></pre>\n\n<p>OK, we have the <code>i</code>s, now we have to deal with the sieving. If you look at your code and think about it in terms of transforming one array to another, you realize you either change an element to 0 if it was unlucky and its index was in the <code>[start...half] by step</code>, or don't change anything if the index wasn't there. Look how it translates to code:</p>\n\n<pre><code> new_nums = ((if i in idxs then 0 else num) for num,i in nums)\n</code></pre>\n\n<p>We dealt with the sieving, now we need to change the <code>start</code> variable. That's trivial:</p>\n\n<pre><code> new_start = start + 2 * (step + 1)\n</code></pre>\n\n<p>And we need to prepare these new values for the next \"iteration\" - and return them. You can see that instead of deciding whether to finish or loop again right after changing the <code>start</code>, we delegate that to the beginning of the callback.</p>\n\n<p>If we had it here instead of at the beginning, we'd do unnecessary (and potentially harmful) changes to the numbers array, because we can't stop the reduce from getting through all the steps. That's a minor disadvantage of this approach - we do <strong>some</strong> unnecessary work. But <strong>we can limit it</strong> to just finding out if we actually need to do something or can just return immediately.</p>\n\n<pre><code> new_start_and_nums = new_nums[..]\n new_start_and_nums.unshift new_start\n return new_start_and_nums\n</code></pre>\n\n<p>That's the end of our callback function. Now remember, the function works with <code>start_and_nums</code>, but so far we have only the <code>numbers</code>. Let's fix that:</p>\n\n<pre><code> start_and_nums = numbers[..]\n start_and_nums.unshift start\n</code></pre>\n\n<p>And let's finally run the reduce function!</p>\n\n<pre><code> result = (steps.reduce(callback,start_and_nums))\n</code></pre>\n\n<p>We don't really need the start value at the beginning.</p>\n\n<pre><code> result.shift()\n</code></pre>\n\n<p>But we need to put in the 2! The point of doing it here and not in the callback is again that we can't stop reduce from stopping. If we inserted it in there, it would get inserted multiple times.</p>\n\n<pre><code> result.unshift 2\n</code></pre>\n\n<p>Aaaand we're done.</p>\n\n<pre><code> return result\n</code></pre>\n\n<p>By the way, thanks for your question - I see the Sundaram's sieve for the first time. Seems very elegant :)</p>\n\n<p>The final code: either copypaste the snippets above or use <strong><a href=\"https://gist.github.com/Janiczek/4974905\" rel=\"nofollow\">this gist</a></strong> :) But I sincerely hope you at least read through this and not just use the final thing, because of the time I put into writing the explanations... :D</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-18T03:13:57.150", "Id": "22843", "ParentId": "19608", "Score": "3" } } ]
{ "AcceptedAnswerId": "22843", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T11:12:16.283", "Id": "19608", "Score": "3", "Tags": [ "javascript", "functional-programming", "coffeescript", "primes" ], "Title": "Functional Sundaram's sieve" }
19608
<p>I have this code for a website I'm working on. It uses <code>window.scroll</code> events to parallax some items. It's running a bit slow on average machines. Is there any way I could improve it to make it run faster?</p> <pre><code>$(function() { // Tell the DOM that JS is enabled $('html').removeClass('no-js'); // Navigation Waypoints $('.waypoint').waypoint(function(event, d) { var a = $(this); if (d === "up") a = a.prev(); if (!a.length) a = a.end(); $('.active').removeClass('active'); a.addClass('active'); $('a[href=#'+a.attr('id')+']').addClass('active'); }, {offset: '40%'}); // Parallax Effects $(window).scroll(function() { var s = $(window).scrollTop(), b = ($('body').height()/100)*20; $('.container').each(function () { $(this).css('top', Math.round((($(this).closest('.waypoint').offset().top-s)+b)/$(this).attr('data-speed'))); }); $('#home hgroup').css('bottom', '-'+Math.round(s/6)+'px'); }); // FAQs $(document).on('click', '.faqs a', function () { $('.faqs .open').slideToggle().removeClass('open'); $(this).siblings().slideToggle('fast').addClass('open'); return false; }); // Kinetics $('.counter').kinetic({ y: false }); // Smooth Scroll $(document).on('click', 'nav a', function() { var t = $($(this).attr('href')), o = t.offset().top, b = ($('body').height()/100)*10; if($(this).attr('href') === "#home") { $('html, body').animate({scrollTop: o}, 'slow'); } else { $('html, body').animate({scrollTop: o+b}, 'slow'); } return false; }); // Set Margin function setMargin () { var t = $('#about'), o = t.offset().top, c = $('.container'), b = ($('body').height()/100)*20, m = Math.round(parseInt(t.css('margin-top'))), a = Math.round((((o/2)+b)+m)/2); c.css('top', a); } // Calculate Padding function calcPadding() { var p = Math.round(($(window).width()-700)/2); $('.pr').css('padding-right', p); setWidth(); } // Calculate Width function setWidth () { $('.draggable').each(function () { var w = 0; $(this).children().each(function () { w = w + $(this).outerWidth() + parseInt($(this).css('margin-left')) + parseInt($(this).css('margin-right')); }); $(this).css('width', w); }); } // Window Resize $(window).on('resize', calcPadding); // Initialize Functions calcPadding(); setMargin(); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T15:48:28.670", "Id": "31399", "Score": "2", "body": "Except for the idiomatic `i` in `for` cycles, I suggest you avoid one-letter variables. `var a = Math.round((((o/2)+b)+m)/2)` is indeed compact, but not very nice to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T16:21:07.397", "Id": "31401", "Score": "0", "body": "I see your point, it was mainly for speed as I needed to get it done ASAP." } ]
[ { "body": "<p>The <a href=\"http://api.jquery.com/on/#event-performance\">jQuery documentation</a> offers the best advice:</p>\n\n<blockquote>\n <p><strong>Event performance</strong></p>\n \n <p>In most cases, an event such as <code>click</code> occurs infrequently and performance is not a significant concern. However, high frequency events such as <code>mousemove</code> or <code>scroll</code> can fire dozens of times per second, and in those cases it becomes more important to use events judiciously. Performance can be increased by reducing the amount of work done in the handler itself, caching information needed by the handler rather than recalculating it, or by rate-limiting the number of actual page updates using <code>setTimeout</code>.</p>\n</blockquote>\n\n<p>Obviously it would be ideal if you could move the calculations outside the event handler to reach the desired performance, but that may not be possible in this case. So to expand on the rate-limiting approach, there are 2 ways you could go about it:</p>\n\n<ol>\n<li><p>Call event handler after the user has finished scrolling (hasn't scrolled for some set amount of time):</p>\n\n<pre><code>var timer = null;\n$(window).scroll(function () {\n if (timer) {\n clearTimeout(timer);\n }\n\n timer = setTimeout(function() {\n timer = null;\n\n // your event handling logic here\n }, 50);\n});\n</code></pre></li>\n<li><p>Call event handler immediately after scrolling, with a minimum delay between scroll events:</p>\n\n<pre><code>var justExecuted = false;\n$(window).scroll(function() {\n if(justExecuted) {\n return;\n }\n\n // your event handling logic here\n\n justExecuted = true;\n setTimeout(function() {\n justExecuted = false;\n }, 50);\n});\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T12:45:51.297", "Id": "31557", "Score": "0", "body": "Hey man, thanks for the response, unfortunately I am updating the css top position of an element using the distance scrolled from the top as the user scrolls so I can't fire the function after the user has scrolled." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T12:47:11.250", "Id": "31558", "Score": "0", "body": "I don't know if there is a better way of parallaxing my elements tho." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T13:12:51.473", "Id": "31560", "Score": "0", "body": "@SimonSturgess: My recommendation would be the second approach I listed, where you execute your event handling logic immediately after scrolling, with a minimum delay between each scroll event. You only need to try this if caching the values (as in tiffon's answer) isn't fast enough." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T13:24:15.993", "Id": "31561", "Score": "0", "body": "I've tested tiffons code on a slowish machine and it seems to perform pretty well. Thanks so much for your responses. I'm an intermediate jquery user, just need to work improving the quality and performance of the code I write." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T17:33:32.197", "Id": "19617", "ParentId": "19610", "Score": "6" } }, { "body": "<p>I don't know what the \"waypoint\" plugin is, but you might be able to optimize your <code>scroll</code> event handler by caching the jQuery objects, data-speed values, and the results of the <code>.closest('.waypoint')</code> calls:</p>\n\n<pre><code>// Parallax Effects\n$(window).scroll(\n (function() {\n // cache the queries\n var $body = $(document.body),\n $containers = $('.container'),\n $hgroup = $('#home hgroup'),\n speeds = [],\n waypoints = [];\n\n // save the values for data-speed attributes \n // and the waypoints / container relationships\n // based on the index in $containers\n $containers.each( function(idx) {\n var $this = $(this);\n // if the waypoints never change, you could just put\n // the offset().top value in the waypoints array\n waypoints[idx] = $this.closest('.waypoint');\n speeds[idx] = $this.data('speed'); \n });\n\n return function() {\n\n var s = window.scrollY,\n diff = ($body.height() / 100 * 20) - s;\n\n // you don't need the Math.round(...)\n $containers.each(function(idx) {\n $(this).css('top', (waypoints[idx].offset().top + diff ) / speeds[idx]);\n });\n $hgroup.css('bottom', s / -6);\n };\n })()\n);\n</code></pre>\n\n<p>If the results of <code>waypoints[idx].offset().top</code> don't change, you could store those values instead of the result of the <code>.closests('.waypoint')</code> in the <code>waypoints</code> array.</p>\n\n<p>Lastly, I don't think you need the 'px' <code>Math.round()</code> when setting the CSS properties with jQuery.</p>\n\n<p>I haven't tested this as you didn't provide a link to a live page or a jsFiddle, but <em>in theory</em>, it <em>should</em> work.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T12:44:09.377", "Id": "31556", "Score": "0", "body": "hey man thanks for the response. the staging site is up at: staging.lightenink.com I'll have a go at implementing your advice tonight!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T12:50:51.660", "Id": "31559", "Score": "0", "body": "I just implemented your code and result wise is identical, I will try it on a slow machine in a bit to see if the performance has increased. Thanks so much for your help. Will try and get my head around what you did!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-18T13:25:11.937", "Id": "31562", "Score": "0", "body": "This code seems to perform pretty well on slowish machines. Thanks so much for all your help! If you have any other advice on how I can improve the way I write my code it would be greatly appreciated! Thanks guys!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T09:58:47.257", "Id": "19690", "ParentId": "19610", "Score": "2" } } ]
{ "AcceptedAnswerId": "19690", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T14:21:29.170", "Id": "19610", "Score": "6", "Tags": [ "javascript", "performance", "jquery", "parallax" ], "Title": "jQuery parallax site (on scroll)" }
19610
<p>I have a nested <code>for</code>-loop that populates a list with elements:</p> <pre><code>a = [] for i in range(1, limit+1): for j in range(1, limit+1): p = i + j + (i**2 + j**2)**0.5 if p &lt;= limit: a.append(p) </code></pre> <p>I could refactor it into list comprehension:</p> <pre><code>a = [i + j + (i**2 + j**2)**0.5 for i in range(1, limit+1) for j in range(1, limit+1) if i + j + (i**2 + j**2)**0.5 &lt;= limit] </code></pre> <p>But now the same complex expression is in both parts of it, which is unacceptable. Is there any way to create a list in a functional way, but more elegantly?</p> <p>I guess in Lisp I would use recursion with <code>let</code>. How it is done in more functional languages like Clojure, Scala, Haskell?</p> <p>In Racket it's possible to <a href="https://stackoverflow.com/q/14979231/596361">bind expressions</a> inside a <code>for/list</code> comprehension. I've found one solution to my problem:</p> <pre><code>[k for i in range(1, limit+1) for j in range(1, limit+1) for k in [i + j + (i**2 + j**2)**0.5] k &lt;= limit] </code></pre> <p>I'm not sure how pythonic it is.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-19T18:56:55.870", "Id": "31637", "Score": "0", "body": "Just pointing out that you can divide limit by 2 in the range function (since you square the numbers anyway) and you'll still get the full set of results. Also, I would write a `transform` function that handled the math and run a list comprehension over it." } ]
[ { "body": "<p>You can rewrite it with two separate comprehensions. One to generate the values and one to filter them out. You can use <a href=\"http://docs.python.org/2/library/itertools.html#itertools.product\" rel=\"nofollow\"><code>itertools.product</code></a> to get the cartesian product.</p>\n\n<pre><code>a = [x for x in (i + j + (i**2 + j**2)**0.5\n for i, j in itertools.product(range(1, limit+1), repeat=2))\n if x &lt;= limit]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T15:29:31.167", "Id": "19612", "ParentId": "19611", "Score": "3" } }, { "body": "<p>In the general case, Jeff's answer is the way to go : generate then filter.</p>\n\n<p>For your particular example, since the expression is increasing wrt both variables, you should stop as soon as you reach the limit.</p>\n\n<pre><code>def max_value(limit, i) :\n \"\"\"return max positive value one variable can take, knowing the other\"\"\"\n if i &gt;= limit :\n return 0\n return int(limit*(limit-2*i)/(2*(limit-i)))\n\ndef collect_within_limit(limit) :\n return [ i + j + (i**2 + j**2)**0.5\n for i in range(1,max_value(limit,1)+1)\n for j in range(1,max_value(limit,i)+1) ]\n</code></pre>\n\n<p>Now, providing this <code>max_value</code> is error prone and quite ad-hoc. We would want to keep the stopping condition based on the computed value. In your imperative solution, adding <code>break</code> when <code>p&gt;limit</code> would do the job. Let's find a functional equivalent :</p>\n\n<pre><code>import itertools\n\ndef collect_one_slice(limit,i) :\n return itertools.takewhile(lambda x: x &lt;= limit,\n (i + j + (i**2 + j**2)**0.5 for j in range(1,limit)))\n\ndef collect_all(limit) :\n return list(itertools.chain(*(collect_one_slice(limit, i)\n for i in range(1,limit))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-26T18:25:30.887", "Id": "19948", "ParentId": "19611", "Score": "3" } } ]
{ "AcceptedAnswerId": "19948", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-14T14:31:14.840", "Id": "19611", "Score": "5", "Tags": [ "python", "combinatorics" ], "Title": "Finding perimeters of right triangles with integer-length legs, up to a limit" }
19611