body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I am playing with different ways to do database interaction in PHP, and one of the ideas I have been playing with is connecting to the DB in the constructor and disconnecting in the destructor. This is the code from my <code>Database</code> class.</p> <pre><code>function __construct() { $this-&gt;link = mysql_connect($this-&gt;server.':'.$this-&gt;port, $this-&gt;username); if(!$this-&gt;link) die('Could not connect: '.mysql_error()); if(!mysql_select_db($this-&gt;database, $this-&gt;link)) die('Could not select database: '.mysql_error()); } function __destruct() { if(mysql_close($this-&gt;link)) $this-&gt;link = null; } </code></pre> <p>This works well, my only reservation is that if I need to connect several to hit the database several times it will do multiple connections and disconnects. If I do that a lot I can see, maybe, potential problems. Is this a concern or is there a better way to do this? And is my code even up to snuff in general?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-18T07:49:12.973", "Id": "496986", "Score": "0", "body": "Look at the URL number. This is the first question humanity ever asked here!" } ]
[ { "body": "<p>You could use MySQLi (PHP extension) which is class based by default instead of MySQL. It \nis very easy to set up multiple connections. You are, however, required to know the connection you are querying always.</p>\n\n<hr>\n\n<p>Congrats with the first question.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:04:27.663", "Id": "3", "ParentId": "1", "Score": "19" } }, { "body": "<p>From your question I infer that you're thinking of having several instances of the DB class. If so I'd suggest abstracting the connection out to another class and holding a reference to the same connection in each DB instance.</p>\n\n<p>You could then set your connection up as a singleton and thus only connect &amp; disconnect once.</p>\n\n<p>Apologies in advance if I've missed anything here - my PHP is far from fluent.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:14:45.420", "Id": "13", "Score": "0", "body": "Yes. I will have multiple instances of the database class. I just wasn't sure on a good approach to make for abstracting away the connection, or if I even should." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:58:41.740", "Id": "49", "Score": "0", "body": "The thing is I've been stung in the past by using more than one connection when I could've shared the connection so I'd say \"abstract it unless you can think of a very good reason not to\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:10:07.140", "Id": "5", "ParentId": "1", "Score": "18" } }, { "body": "<p>You might also look into the built-in php command mysql_pconnect(). This differs from mysql_connect in that it opens a persistent connection to the DB the first time it is called, and each subsequent time, it checks to see if an existing connection to that database exists and uses that connection instead. You should then remove the mysql_close command from the destructor, as they will persist between page loads.</p>\n\n<p>The php manual page: <a href=\"http://php.net/manual/en/function.mysql-pconnect.php\">http://php.net/manual/en/function.mysql-pconnect.php</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:19:33.573", "Id": "19", "Score": "0", "body": "I read about that, and it sounds very enticing. However, how do you close the connection? in the docs it says the mysql_close() doesn't work. Do you just rely on mysql server to close it when it has been inactive for so long. I'd like to know that once all the work is done that the connection is closed." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:22:54.403", "Id": "23", "Score": "0", "body": "You don't close the connection explicitly. It eventually gets closed by the php internals after a certain time has elapsed without use. This eliminates all of the overhead involved with repeatedly opening and closing connections, and allows individual page requests to be much faster." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:26:33.283", "Id": "28", "Score": "0", "body": "Okay, i'll do some playing with this too. Thanks." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:12:43.930", "Id": "6", "ParentId": "1", "Score": "16" } }, { "body": "<p>use an abstraction library like Pear MDB2 for your database connection. </p>\n\n<p>This abstracts all the connection logic away from your code, so should ever change your database (mysql to SQLite,etc) you won't have to change your code. </p>\n\n<p><a href=\"http://pear.php.net/manual/en/package.database.mdb2.php\">http://pear.php.net/manual/en/package.database.mdb2.php</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:42:57.963", "Id": "38", "Score": "3", "body": "The last stable release was in [2007](http://pear.php.net/package/MDB2)... So either it's good to the point where it doesn't need updating (doubt it, since there's a beta in the works), or it's just plain inactive (more likely) There are tons of better abstraction layers (IMHO) that are more actively developed than this..." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:46:32.370", "Id": "39", "Score": "1", "body": "i haven't used PHP in a while,so please feel free to add it in this thread or create a new response :) my point is that a much better solution is to abstract the connection/query logic away via a library, more so than a specific library." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:32:29.907", "Id": "19", "ParentId": "1", "Score": "13" } }, { "body": "<p>I don't think it makes any difference in regards to connecting to the database within the construction or within a connect method, what i do think you need to change is those die commands.</p>\n\n<p>using die causes the script to halt and send 1 little message to the user, who would think this is rubbish, and never visit your site again :( :(</p>\n\n<p>What you should be doing is catching your errors, and redirecting to a static page where you can show a very nice message to the user, fully apologising for the technical issues your having.</p>\n\n<p>You can also have an box that says, Enter your email address and we will email you when were back on line, you get the idea.</p>\n\n<p>as for the code I would go down the lines of:</p>\n\n<pre><code>class Database\n{\n public function __construct($autoconnect = false)\n {\n //Here you would 'globalize' your config and set it locally as a reference.\n if($autoconnect === true)\n {\n $this-&gt;connect();\n }\n }\n\n public function connect()\n {\n if($this-&gt;connected() === false)\n {\n $result = $this-&gt;driver-&gt;sendCommand(\"connect\");\n if($result === true)\n {\n $this-&gt;setConnectionState(\"active\");\n $this-&gt;setConnectionResource($this-&gt;driver-&gt;sendCommand(\"get_resource\"));\n }else\n {\n throw new DatabaseConnectionError($this-&gt;driver-&gt;sendCommand(\"getDriverError\"));\n }\n }\n }\n}\n</code></pre>\n\n<p>This gives you more functionality in the long run as every action is decidable within your APP, nothing is auto fired on default.</p>\n\n<p>you can simple use try,catch blocks to maintain your error reporting.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T09:29:26.970", "Id": "239", "Score": "0", "body": "+1 for the use of try/catch. Also I have experienced issues with failures thrown in the constructor: you do not have an instance of the object to implement whatever fallback mechanism would make sense, which in my case was using large parts of code present in the class... Without a valid instance, you cannot call instance methods, and I had to make some static methods, which was less than ideal." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T12:33:19.980", "Id": "244", "Score": "0", "body": "Thanks, But I'me struggling to understand you, Can you please rephrase your comment please." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T17:12:59.320", "Id": "251", "Score": "0", "body": "Sure :) Throwing exceptions is fine as long as you add code to try and catch them. Avoid code that throws exceptions in a constructor though, this could lead to some issues that I have experienced: in case of failure, you have no object created, and you might miss that in your catch block, if you want to reuse behaviors defined for this object. I would rather recommend to create the connection in a regular method, e.g. init() or connect(), called on the object after it has been created, not directly in the constructor." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T23:31:15.977", "Id": "41", "ParentId": "1", "Score": "11" } } ]
{ "AcceptedAnswerId": "5", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-19T21:02:47.183", "Id": "1", "Score": "39", "Tags": [ "php", "mysql", "constructor" ], "Title": "Database connection in constructor and destructor" }
1
<p>I'd like suggestions for optimizing this brute force solution to <a href="http://projecteuler.net/index.php?section=problems&amp;id=1">problem 1</a>. The algorithm currently checks every integer between 3 and 1000. I'd like to cut as many unnecessary calls to <code>isMultiple</code> as possible:</p> <pre><code>''' If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' end = 1000 def Solution01(): ''' Solved by brute force #OPTIMIZE ''' sum = 0 for i in range(3, end): if isMultiple(i): sum += i print(sum) def isMultiple(i): return (i % 3 == 0) or (i % 5 == 0) </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:06:48.893", "Id": "3", "Score": "1", "body": "Are you trying to optimize the algorithm or the code itself?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:07:15.663", "Id": "5", "Score": "0", "body": "@JoePhillips: Why not both? ;)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:08:43.633", "Id": "6", "Score": "0", "body": "@JoePhillips: the algorithm. it currently checks every single integer between 3 and 1000." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:09:03.493", "Id": "7", "Score": "0", "body": "@Zolomon: good point, either type of answer would be helpful." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:12:10.890", "Id": "2889", "Score": "0", "body": "Just a note. The detailed explanation for [Richard's Answer](http://codereview.stackexchange.com/questions/2/project-euler-problem-1-in-python/280#280) on Wikipedia may be helpful if you didn't already understand the Math. See [here](http://en.wikipedia.org/wiki/Arithmetic_series#Sum)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-12T16:57:29.667", "Id": "12182", "Score": "0", "body": "[Relevant blog post](http://cowbelljs.blogspot.com/2011/12/projecteuler-001.html)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-13T02:30:06.993", "Id": "12221", "Score": "0", "body": "@TryPyPy, you may want to weigh in here: http://meta.codereview.stackexchange.com/questions/429/online-contest-questions" } ]
[ { "body": "<p>I think the best way to cut out possible checks is something like this:</p>\n\n<pre><code>valid = set([])\n\nfor i in range(3, end, 3):\n valid.add(i)\n\nfor i in range(5, end, 5):\n valid.add(i)\n\ntotal = sum(valid)\n</code></pre>\n\n<p>There's still a bit of redundancy (numbers which are multiples of both 3 and 5 are checked twice) but it's minimal.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:25:31.500", "Id": "25", "Score": "0", "body": "@gddc: nice, I didn't even know you could specify an increment in a range like that." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:26:07.760", "Id": "26", "Score": "0", "body": "That's also what I would do now." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:26:24.727", "Id": "27", "Score": "0", "body": "@calavera - range() is a great function ... the optional step as a 3rd parameter can save tons of iterations." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T22:03:12.310", "Id": "50", "Score": "0", "body": "http://docs.python.org/library/functions.html#range just for good measure" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T19:36:59.043", "Id": "496", "Score": "0", "body": "You could save some memory (if using 2.x) by using the xrange function instead of range, it uses the iterator protocol instead of a full blown list." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T19:38:54.627", "Id": "497", "Score": "2", "body": "Also by using the set.update method you could shed the loop and write someting like: valid.update(xrange(3, end, 3))" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:23:04.670", "Id": "11", "ParentId": "2", "Score": "28" } }, { "body": "<p>g.d.d.c's solution is slightly redundant in that it checks numbers that are multiples of 3 and 5 twice. I was wondering about optimizations to this, so this is slightly longer than a comment, but not really an answer in itself, as it totally relies on g.d.d.c's awesome answer as inspiration.</p>\n\n<p>If you add multiples to the valid list for the multiple \"3\" and then do another pass over the whole list (1-1000) for the multiple \"5\" then you do experience some redundancy.</p>\n\n<p>The order in which you add them:</p>\n\n<pre><code> add 3-multiples first\n add 5 multiples second\n</code></pre>\n\n<p>will matter (albeit slightly) if you want to check if the number exists in the list or not.</p>\n\n<p>That is, if your algorithm is something like</p>\n\n<pre><code>add 3-multiples to the list\n\nadd 5-multiples to the list if they don't collide\n</code></pre>\n\n<p>it will perform slightly worse than</p>\n\n<pre><code>add 5-multiples to the list\n\nadd 3-multiples to the list if they don't collide\n</code></pre>\n\n<p>namely, because there are more 3-multiples than 5-multiples, and so you are doing more \"if they don't collide\" checks.</p>\n\n<p>So, here are some thoughts to keep in mind, in terms of optimization:</p>\n\n<ul>\n<li>It would be best if we could iterate through the list once</li>\n<li>It would be best if we didn't check numbers that weren't multiples of 3 nor 5.</li>\n</ul>\n\n<p>One possible way is to notice the frequency of the multiples. That is, notice that the LCM (least-common multiple) of 3 and 5 is 15: </p>\n\n<pre><code>3 6 9 12 15 18 21 24 27 30\n || ||\n 5 10 15 20 25 30\n</code></pre>\n\n<p>Thus, you should want to, in the optimal case, want to use the frequency representation of multiples of 3 and 5 in the range (1,15) over and over until you reach 1000. (really 1005 which is divided by 15 evenly 67 times).</p>\n\n<p>So, you want, for each iteration of this frequency representation:</p>\n\n<p>the numbers at: 3 5 6 9 10 12 15</p>\n\n<p>Your frequencies occur (I'm sorta making up the vocab for this, so please correct me if there are better math-y words) at starting indexes from <strong>0k + 1 to 67k</strong> (1 to 1005) [technically 66k]</p>\n\n<p>And you want the numbers at positions <em>3, 5, 6, 9, 10, 12, and 15</em> enumerating from the index.</p>\n\n<p>Thus,</p>\n\n<pre><code>for (freq_index = 0; freq_index &lt; 66; ++freq_index) {\n valid.add(15*freq_index + 3);\n valid.add(15*freq_index + 5);\n valid.add(15*freq_index + 6);\n valid.add(15*freq_index + 9);\n valid.add(15*freq_index + 10);\n valid.add(15*freq_index + 12);\n valid.add(15*freq_index + 15); //also the first term of the next indexed range\n}\n</code></pre>\n\n<p>and we have eliminated redundancy</p>\n\n<p>=)</p>\n\n<p><hr>\n<em>Exercise for the astute / determined programmer:</em><br>\nWrite a function that takes three integers as arguments, <em>x y z</em> and, without redundancy, finds all the multiples of <em>x</em> and of <em>y</em> in the range from 1 to <em>z</em>.<br>\n(basically a generalization of what I did above).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T22:44:11.497", "Id": "54", "Score": "0", "body": "I'll have to check the documentation to be sure, but I believe the `set.add()` method uses a binary lookup to determine whether or not the new element exists already. If that's correct then the order you check the multiples of 3's or 5's won't matter - you have an identical number of binary lookups. If you can implement a solution that rules out double-checks for multiples of both you may net an improvement." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T01:14:51.330", "Id": "72", "Score": "1", "body": "@g.d.d.c: Ah, good point. I was thinking more language-agnostically, since the most primitive implementation wouldn't do it efficiently. An interesting aside about the python <code>.add()</code> function from a google: http://indefinitestudies.org/2009/03/11/dont-use-setadd-in-python/" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T16:46:42.527", "Id": "146", "Score": "0", "body": "@sova - Thanks for the link on the union operator. I hadn't ever encountered that and usually my sets are small enough they wouldn't suffer from the performance penalty, but knowing alternatives is always great." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T22:45:48.320", "Id": "169", "Score": "0", "body": "@g.d.d.c also, the solution above does indeed rule out double-checks for multiples of both, it figures out the minimal frequency at which you can repeat the pattern for digits (up to the LCM of the two digits). Each valid multiple of 3, 5, or both, is \"checked\" (actually, not really checked, just added) only once." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T17:57:44.573", "Id": "1741", "Score": "0", "body": "@g.d.d.c python's set is based on a hash table. It is not going to use a binary lookup. Instead it will do a hash table lookup." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T18:29:45.833", "Id": "1744", "Score": "0", "body": "@sova, the conclusion in that blog post is wrong. Its actually measuring the overhead of profiling. Profile .add is more expensive then profiling |=, but .add is actually faster." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T22:23:56.613", "Id": "24", "ParentId": "2", "Score": "8" } }, { "body": "<p>I would do it like this:</p>\n\n<pre><code>total = 0\n\nfor i in range(3, end, 3):\n total += i\n\nfor i in range(5, end, 5):\n if i % 3 != 0: # Only add the number if it hasn't already\n total += i # been added as a multiple of 3\n</code></pre>\n\n<p>The basic approach is the same as g.d.d.c's: iterate all the multiples of 3, then 5. However instead of using a set to remove duplicates, we simply check that the multiples of 5 aren't also multiples of 3. This has the following upsides:</p>\n\n<ol>\n<li>Checking divisibility is less expensive than adding to a set.</li>\n<li>We build the total up incrementally, so we don't need a separate call to sum at the end.</li>\n<li>We got rid of the set, so we only need constant space again.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T15:24:15.257", "Id": "3594", "Score": "0", "body": "do you think it would be faster or slow to allow the repetitive 5's to be added and then substract the 15's? we would lose `end/5` divisibility checks and it costs only `add/15` subtractions" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T04:38:14.877", "Id": "67", "ParentId": "2", "Score": "12" } }, { "body": "<p>I would get rid of the <code>for</code> loops and use <code>sum</code> on generator expressions.</p>\n\n<pre><code>def solution_01(n):\n partialsum = sum(xrange(3, n, 3)) \n return partialsum + sum(x for x in xrange(5, n, 5) if x % 3)\n</code></pre>\n\n<p>Note that we're using <code>xrange</code> instead of <code>range</code> for python 2. I have never seen a case where this isn't faster for a <code>for</code> loop or generator expression. Also consuming a generator expression with <code>sum</code> <em>should</em> be faster than adding them up manually in a <code>for</code> loop.</p>\n\n<p>If you wanted to do it with sets, then there's still no need for <code>for</code> loops</p>\n\n<pre><code>def solution_01(n):\n values = set(range(3, n, 3)) | set(range(5, n, 5))\n return sum(values)\n</code></pre>\n\n<p>Here, we're just passing the multiples to the set constructor, taking the union of the two sets and returning their sum. Here, I'm using <code>range</code> instead of <code>xrange</code>. For some reason, I've seen that it's faster when passing to <code>list</code>. I guess it would be faster for <code>set</code> as well. You would probably want to benchmark though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T06:23:09.830", "Id": "71", "ParentId": "2", "Score": "17" } }, { "body": "<p>Using a generator is also possible :</p>\n\n<pre><code>print sum(n for n in range(1000) if n % 3 == 0 or n % 5 == 0)\n</code></pre>\n\n<p>Note that intent is not really clear here. For shared code, I would prefer something like</p>\n\n<pre><code>def euler001(limit):\n return sum(n for n in range(limit) if n % 3 == 0 or n % 5 == 0)\n\nprint euler001(1000)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T14:37:09.013", "Id": "275", "ParentId": "2", "Score": "8" } }, { "body": "<p>The sum 3+6+9+12+...+999 = 3(1+2+3+...+333) = 3 (n(n+1))/2 for n = 333. And 333 = 1000/3, where \"/\" is integral arithmetic.</p>\n\n<p>Also, note that multiples of 15 are counted twice.</p>\n\n<p>So</p>\n\n<pre><code>def sum_factors_of_n_below_k(k, n):\n m = (k-1) // n\n return n * m * (m+1) // 2\n\ndef solution_01():\n return (sum_factors_of_n_below_k(1000, 3) + \n sum_factors_of_n_below_k(1000, 5) - \n sum_factors_of_n_below_k(1000, 15))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T15:19:22.627", "Id": "3593", "Score": "9", "body": "this is obviously most efficient. i was about to post this as a one liner but i prefer the way you factored it. still, would `sum_multiples_of_n_below_k` be the appropriate name? they are not n's factors, they are its multiples" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-27T15:27:51.710", "Id": "280", "ParentId": "2", "Score": "43" } }, { "body": "<p>Well, this <em>is</em> an answer to a Project Euler question after all, so perhaps the best solution is basically a pencil-paper one.</p>\n\n<pre><code>sum(i for i in range(n + 1)) # sums all numbers from zero to n\n</code></pre>\n\n<p>is a triangular number, the same as</p>\n\n<pre><code>n * (n + 1) / 2\n</code></pre>\n\n<p>This is the triangular function we all know and love. Rather, more formally, </p>\n\n<pre><code>triangle(n) = n * (n + 1) / 2\n</code></pre>\n\n<p>With that in mind, we next note that the sum of the series</p>\n\n<pre><code>3, 6, 9, 12, 15, 18, 21, 24, ...\n</code></pre>\n\n<p>is 3 * the above triangle function. And the sums of</p>\n\n<pre><code>5, 10, 15, 20, 25, 30, 35, ...\n</code></pre>\n\n<p>are 5 * the triangle function. We however have one problem with these current sums, since a number like 15 or 30 would be counted in each triangle number. Not to worry, the inclusion-exclusion principle comes to the rescue! The sum of</p>\n\n<pre><code>15, 30, 45 ,60, 75, 90, 105, ...\n</code></pre>\n\n<p>is 15 * the triangle function. Well, if this so far makes little sense don't worry. Finding the sum of the series from 1 up to n, incrementing by k, is but</p>\n\n<pre><code>triangle_with_increments(n, k = 1) = k * (n/k) * (n/k + 1) / 2\n</code></pre>\n\n<p>with this, and the inclusion-exclusion principle, the final answer is but</p>\n\n<pre><code>triangle_with_increments(100, 5) + triangle_with_increments(100, 3) - triangle_with_increments(100, 15)\n</code></pre>\n\n<p>Wow. Who'da thunk? an n complexity problem suddenly became a constant time one. That's what I call optimization IMHO :P. But in all seriousness, Project Euler asks you to answer problems in really the lowest computational complexity possible. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-12T01:39:34.380", "Id": "5978", "ParentId": "2", "Score": "15" } }, { "body": "<p>The list comprehension one is an awesome solution, but making use of set is a lot faster:</p>\n\n<pre><code>from __future__ import print_function\n\ndef euler_001(limit):\n s1, s2 = set(range(0, limit, 3)), set(range(0, limit, 5))\n\n return sum(s1.union(s2))\n\nprint(euler_001(1000))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-27T16:42:50.027", "Id": "75000", "ParentId": "2", "Score": "6" } }, { "body": "<p>I used a slightly simpler method, but essentially did the same thing:</p>\n\n<pre><code>total = 0\n\nfor n in range(3,1000):\n if n % 3 == 0:\n total += n\n elif n % 5 == 0:\n total += n\n\n\nprint total\n</code></pre>\n\n<p>The <code>elif</code> makes sure that you only count any factor/divisor once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-04T00:38:58.953", "Id": "262984", "Score": "1", "body": "(`did the same thing`: The order in which answers are shown is bound to change, and you might be referring to the question: please disambiguate with a quote or a hyperlink (e.g., from the `share`-link at the end of each post).)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-03T19:15:05.807", "Id": "140425", "ParentId": "2", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-19T21:04:27.573", "Id": "2", "Score": "56", "Tags": [ "python", "optimization", "algorithm", "programming-challenge" ], "Title": "Project Euler problem 1 in Python - Multiples of 3 and 5" }
2
<p>Basically, I had written this class a little while ago to ease autoloading of our local libraries. </p> <p>The premise is that everything is split by packages into multiple layers of sub-packages. Classes are named using CamelCasing. So, a class' name is related to its package as follows: <code>PackageSubpackageSubpackageName</code>. Now, each package can have package specific interfaces defined by <code>isPackageName</code> for interfaces, exceptions by <code>PackageNameException</code>, etc. I tried to make it flexible enough for reuse.</p> <pre><code>/** * A class for lazy-loading other classes * * This class enables lazy-loading of php classes. The benefit of this is * three-fold. First, there is a memory benefit, since not all classes are * loaded until they are needed. Second, there is a time benefit, since not all * classes are loaded. Third, it produces cleaner code, since there is no need * to litter files with require_once() calls. * * @category Libraries * @package Libraries * @author Me */ abstract class Loader { /** * @var array An array of class to path mappings */ protected static $classes = array(); /** * @var boolean Has the loader been initialized already */ protected static $initialized = false; /** * @var array An array of auto-search paths */ protected static $namedPaths = array( 'exception', 'interface', 'iterator', ); /** * @var array An array of include paths to search */ protected static $paths = array( PATH_LIBS, ); /** * Tell the auto-loader where to find an un-loaded class * * This can be used to "register" new classes that are unknown to the * system. It can also be used to "overload" a class (redefine it * elsewhere) * * @param string $class The class name to overload * @param string $path The path to the new class * * @throws InvalidArgumentException Upon an Invalid path submission * @return void */ public static function _($class, $path) { $class = strtolower($class); if (!file_exists($path)) { throw new InvalidArgumentException('Invalid Path Specified'); } self::$classes[$class] = $path; } /** * Add a path to the include path list * * This adds a path to the list of paths to search for an included file. * This should not be used to overload classes, since the default include * directory will always be searched first. This can be used to extend * the search path to include new parts of the system * * @param string $path The path to add to the search list * * @throws InvalidArgumentException when an invalid path is specified * @return void */ public static function addPath($path) { if (!is_dir($path)) { throw new InvalidArgumentException('Invalid Include Path Added'); } $path = rtrim($path, DS); if (!in_array($path, self::$paths)) { self::$paths[] = $path; } } /** * Add a path to the auto-search paths (for trailing extensions) * * The path should end with an 's'. Default files should not. * * @param string $path The name of the new auto-search path * * @return void */ public static function addNamedPath($path) { $path = strtolower($path); if (substr($path, -1) == 's') { $path = substr($path, 0, -1); } if (!in_array($path, self::$namedPaths)) { self::$namedPaths[] = $path; } } /** * Initialize and register the autoloader. * * This method will setup the autoloader. This should only be called once. * * @return void */ public static function initialize() { if (!self::$initialized) { self::$initialized = true; spl_autoload_register(array('Loader', 'load')); } } /** * The actual auto-loading function. * * This is automatically called by PHP whenever a class name is used that * doesn't exist yet. There should be no need to manually call this method. * * @param string $class The class name to load * * @return void */ public static function load($class) { $className = strtolower($class); if (isset(self::$classes[$className])) { $file = self::$classes[$className]; } else { $file = self::findFile($class); } if (file_exists($file)) { include_once $file; } } /** * Find the file to include based upon its name * * This splits the class name by uppercase letter, and then rejoins them * to attain the file system path. So FooBarBaz will be turned into * foo/bar/baz. It then searches the include paths for that chain. If baz * is a directory, it searches that directory for a file called baz.php. * Otherwise, it looks for baz.php under the bar directory. * * @param string $class The name of the class to find * * @return string The path to the file defining that class */ protected static function findFile($class) { $regex = '#([A-Z]{1}[a-z0-9_]+)#'; $options = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE; $parts = preg_split($regex, $class, null, $options); $subpath = ''; $file = strtolower(end($parts)); $test = strtolower(reset($parts)); if ($test == 'is') { array_shift($parts); return self::findNamedFile($class, $parts, 'interface'); } foreach ($parts as $part) { $subpath .= DS . strtolower($part); } foreach (self::$paths as $path) { $newpath = $path . $subpath; if (is_file($newpath . '.php')) { return $newpath . '.php'; } elseif (is_file($newpath . DS . $file . '.php')) { return $newpath . DS . $file . '.php'; } } if (in_array($file, self::$namedPaths)) { //Get rid of the trailing part array_pop($parts); return self::findNamedFile($class, $parts, $file); } return ''; } /** * Find a file for named directories (interfaces, exceptions, iterators, etc) * * @param string $class The class name of the exception to find * @param array $parts The parts of the class name pre-split * @param string $name The name of the named directory to search in * * @return string The found path, or '' if not found */ protected static function findNamedFile($class, array $parts, $name) { if (empty($parts)) { return ''; } $name = strtolower($name); //Add a trailing s, since individual files are not plural $filename = $name; $name .= 's'; //Try the global path first $subpath = DS . $name . DS . strtolower(implode('', $parts)) . '.php'; foreach (self::$paths as $path) { $newpath = $path . $subpath; if (is_file($newpath)) { return $newpath; } } //Try to build a full sub path for package specific named files $package = array_shift($parts); $subpath = DS . strtolower($package) . DS . $name . DS; if (!empty($parts)) { $subpath .= strtolower(implode('', $parts)) . '.php'; } else { $subpath .= $filename . '.php'; } foreach (self::$paths as $path) { $newpath = $path . $subpath; if (is_file($newpath)) { return $newpath; } } return ''; } } </code></pre> <p>It's also fully unit tested.</p> <p>What are your thoughts? Is it over-complex?</p>
[]
[ { "body": "<p>The first problem I see is that there are a lot of cases where someone will want to create a class with more than one word in the name (DataMapper), and the autoloader you have provided won't allow for that. I would recommend using another character to delimit between package names. The Zend Framework uses Package_SubPackage_SubPackage_Class and that works very well.</p>\n\n<p>As an aside, I'm not sure what your specific reasons are for writing your own autoloader (whether it is for production, education, etc.), but if you are planning to use it for production, I would recommend the Zend_Loader class from the Zend Framework, as it is supported, fully tested, and continually being developed. You can read it's quickstart guide <a href=\"http://framework.zend.com/manual/en/zend.loader.load.html\">Here</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:37:23.417", "Id": "36", "Score": "4", "body": "Well, it's personal preference, but I can't stand using `_` in class names. I find it's harder to type, and breaks it apart too much. As far as multiple words in a name, yes that's a valid point. And why don't I use Zend? Well, it's personal preference. I've tried it in the past, and didn't care for it. I can use it, but it just rubs me the wrong way... Thanks for the insight though..." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:50:22.010", "Id": "41", "Score": "2", "body": "To clarify, when I was talking about Zend, I wasn't recommending the entire framework, but just the autoloader class, which can be used completely decoupled from everything else in zf." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T23:36:09.610", "Id": "63", "Score": "2", "body": "`HiMyNameIsRobertAndIWorkLongHoursSadFace` vs `Hi_My_Name_Is_Robert_And_I_Work_Long_Hours_Sad_Face`, i belive this is the reason for the `_`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T14:40:26.333", "Id": "140", "Score": "0", "body": "@RobertPitt: I'd argue that if your class name is really that long, you need to refactor or rethink your packaging system..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:21:04.123", "Id": "10", "ParentId": "4", "Score": "14" } }, { "body": "<p>When it comes to Autoloaders, I would tend make it compatible with any of my projects, therefore I would always stay to the best coding standards such as Zend.</p>\n<p>There is a proposal that states the layout of classes, directory structure, namespaces where autoloaders work very good.</p>\n<p>The following describes the mandatory requirements that must be adhered to for autoloader interoperability.</p>\n<ul>\n<li><p>Mandatory:</p>\n</li>\n<li><p>A fully-qualified namespace and class must have the following structure:</p>\n<pre><code> \\&lt;Vendor Name&gt;\\(&lt;Namespace&gt;\\)*&lt;Class Name&gt;\n</code></pre>\n</li>\n<li><p>Each namespace must have a top-level namespace (&quot;Vendor Name&quot;).</p>\n</li>\n<li><p>Each namespace can have as many sub-namespaces as it wishes.</p>\n</li>\n<li><p>Each namespace separator is converted to a <code>DIRECTORY_SEPARATOR</code> when loading from the file system.</p>\n</li>\n<li><p>Each <code>_</code> character in the CLASS NAME is converted to a <code>DIRECTORY_SEPARATOR</code>. The <code>_</code> character has no special meaning in the namespace.</p>\n</li>\n<li><p>The fully-qualified namespace and class is suffixed with &quot;.php&quot; when loading from the file system.</p>\n</li>\n<li><p>Alphabetic characters in vendor names, namespaces, and class names may be of any combination of lower case and upper case.</p>\n</li>\n<li><p>Examples:</p>\n</li>\n<li><p><code>\\Doctrine\\Common\\IsolatedClassLoader</code> =&gt; <code>/path/to/project/lib/vendor/Doctrine/Common/IsolatedClassLoader.php</code></p>\n</li>\n<li><p><code>\\Symfony\\Core\\Request</code> =&gt; <code>/path/to/project/lib/vendor/Symfony/Core/Request.php</code></p>\n</li>\n<li><p><code>\\Zend\\Acl</code> =&gt; <code>/path/to/project/lib/vendor/Zend/Acl.php</code></p>\n</li>\n<li><p><code>\\Zend\\Mail\\Message</code> =&gt; <code>/path/to/project/lib/vendor/Zend/Mail/Message.php</code></p>\n</li>\n</ul>\n<p>Using the above to construct your autoloader will surely be migratable around your projects regarding weather you have namespaces or not.</p>\n<p><a href=\"http://groups.google.com/group/php-standards/web/psr-0-final-proposal?pli=1\" rel=\"nofollow noreferrer\">@Reference</a></p>\n<p>There is a very nice class that I use in around 6 projects, and I find that this is perfect and you should study and see what you can do with it.</p>\n<p><a href=\"https://gist.github.com/221634\" rel=\"nofollow noreferrer\">Class Link</a></p>\n<p>An example usage would be like so:</p>\n<pre><code>$classLoader = new SplClassLoader('Doctrine\\Common', '/libs/doctrine');\n$classLoader-&gt;register();\n\n$classLoader = new SplClassLoader('Ircmexell\\MyApplication', 'libs/internal');\n$classLoader-&gt;register();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-01-19T23:12:28.693", "Id": "40", "ParentId": "4", "Score": "6" } }, { "body": "<p>Some points i found:</p>\n\n<p>Thats the class is marked as <code>abstract</code> struck me as odd as i found out it only has static method calls and since it uses \"self::\" for static call i guess there is no meaningful way to extend the class anyways. (With the LSB issue).</p>\n\n<p>I don't see any big issue with the class beeing \"all static\" and i assume it fits into your project. (You don't have a clear bootstrap and you don't want/need multiple instances of that class)</p>\n\n<hr>\n\n<p>The <code>include_once $file;</code> strucks me as a little odd as the \"_once\" part shouldn't be need. But if you wrote the loader at a later stage in the project i see where it might be needed to not run into issues with classes getting loaded two times.</p>\n\n<p>Usually i'd say you don't have to make php remember if it already touched a file (and do a disk expensive realpath() on it) since the load function will only be called one time for each previously unknown class.</p>\n\n<hr>\n\n<p>All in all i think the code/usefulness ratio is fine and it isn't overly complex.</p>\n\n<h2>Alternatives</h2>\n\n<p>The upcoming \"standards\" and libs are alreay mentioned so i'll just point out another way to do autoloading that \"performs better\" and is less intrusive (requires less code in your application)</p>\n\n<p>The <a href=\"https://github.com/theseer/Autoload\"><code>PHP Autoload Builder</code></a> will scan your codebase and provide one file with a big array mapping for all your classes (interface etc.) that you only need to include in your bootstrap. It can be run again to pick up new classes or the resulting file can be edited by hand. (Some people build tools around it so it automatically recreates itself in development if a class isn't found).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T11:04:43.753", "Id": "86", "ParentId": "4", "Score": "8" } }, { "body": "<p>For about a year I used a very simple autoloader with common PHP files root for my project and all included libraries (Zend, Rediska and so on).</p>\n\n<p>The root of my project contains /app and /external directories.</p>\n\n<p>All libraries in /external are fully checked out from svn/git, and then I make a symlink for their PHP code in /app.</p>\n\n<p>For example, for <code>PHPExcel</code>:</p>\n\n<pre><code>pwd \n/var/www/project/app\nls -lah PHPE*\nPHPExcel -&gt; ../external/PHPExcel/PHPExcel\nPHPExcel.php -&gt; ../external/PHPExcel/PHPExcel.php\n</code></pre>\n\n<p>Then I put something like this in my index.php file:</p>\n\n<pre><code>set_include_path (PATH . 'app');\nrequire 'somepath/Autoloader.php';\nAutoloader::registerAutoload ();\n</code></pre>\n\n<p>It allows me to use one commonly (it's fully compatible with Zend, Rediska, PHPExcel and many other libraries) and is a very simple autoloader for all libraries.</p>\n\n<pre><code>class Autoloader\n{\n\n public static function registerAutoload ()\n {\n spl_autoload_register (array (__CLASS__, 'autoload'));\n }\n\n /**\n * @static\n * @param string $class\n * @return void\n */\n public static function autoload ($class)\n {\n require str_replace (array ('_', '\\\\'), '/', $class) . '.php';\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T16:25:43.170", "Id": "1812", "ParentId": "4", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-19T21:07:43.573", "Id": "4", "Score": "27", "Tags": [ "php", "library" ], "Title": "PHP Autoloader Library" }
4
<p>I started programming with Java and C++, so I'm used to having a 'main' function that calls other functions that do the actual work. At university I was always told that doing actual computation in the main function is bad practice. I'm currently playing around with Python, and I have trouble figuring out how to write a nice 'main' function, especially since I'm doing small stuff that doesn't need separate classes.</p> <p>What do you think about the following code? Is the main function necessary, or would you just write everything without functions? Is there a general consent on this in the Python world?</p> <pre><code># Finds sum of all multiples of 3 and 5 from 0 to 999 def find_multiples(): global numbers for i in range(0,1000): if i%3==0 or i%5==0: numbers.append(i); numbers = [] if __name__ == '__main__': find_multiples() print sum(numbers) </code></pre>
[]
[ { "body": "<p>In most of the Python code I've ever seen, there is normally a main function defined that you call from the condition you put to establish the script was executed and not imported. I believe that's the standard way of doing things in Python, but I don't believe its actually a written rule anywhere, though that is how they do it in <a href=\"http://docs.python.org/library/__main__.html\">their docs as well</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T20:20:28.427", "Id": "12902", "Score": "8", "body": "Lets state it clearly, what idiom this is, because all comments above are incorrectly formatted and this idiom is not visible: `if __name__ == \"__main__\":` (as stated on the page Mark Loeser linked to)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:19:20.217", "Id": "8", "ParentId": "7", "Score": "34" } }, { "body": "<p>Here's some superficial review. More for testing the site and some comment formatting than anything, but: do create main functions (helps us benchmarkers a lot) and do think that your module can be imported, so docstrings and local variables help. </p>\n\n<pre><code># Finds...\n###-^ Put this in a docstring\n\ndef find_multiples():\n \"\"\"Finds sum of all multiples of 3 and 5 from 0 to 999 \"\"\"\n###-^ This allows you to \"from x import find_multiples, help(find_multiples)\"\n numbers = []\n###-^ Avoid globals\n for i in xrange(1000):\n###-^ Use xrange if Python 2.x, no need to start at 0 (it's the default)\n if not (i % 3) or not (i % 5):\n###-^ Add spaces around operators, simplify\n###-^ the boolean/numeric checks\n numbers.append(i)\n###-^ Remove trailing ;\n return numbers\n\n###-^ Removed global\n\ndef main():\n###-^ Allows calling main many times, e.g. for benchmarking\n numbers = find_multiples()\n print sum(numbers)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T21:57:35.937", "Id": "166", "Score": "1", "body": "`xrange(1000)` would suffice. Which version is more readable is arguable. Otherwise, excellent code review! Chapeau bas!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T17:51:51.517", "Id": "19954", "Score": "0", "body": "I would be tempted (although perhaps not for such a small program) to move the print statement out of main, and to keep the main() function strictly for catching exceptions, printing error messages to stderr, and returning error/success codes to the shell." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-28T14:53:40.477", "Id": "117208", "Score": "0", "body": "Another reason for using a 'main function' is that otherwise all variables you declare are global." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T22:43:12.493", "Id": "32", "ParentId": "7", "Score": "53" } }, { "body": "<p>Usually everything in python is handled the <em>come-on-we-are-all-upgrowns</em> principle. This allows you to choose the way you want things to do. However it's best practice to put the <em>main-function</em> code into a function instead directly into the module.</p>\n\n<p>This makes it possible to import the function from some other module and makes simple scripts instantly programmable.</p>\n\n<p>However avoid the use of globals (what you did with <code>numbers</code>) for return values since this makes it difficult to execute the function a second time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T18:41:30.897", "Id": "216", "Score": "0", "body": "\"...since this makes it difficult to execute the function a second time.\" Do you mean by this that before calling `find_multiples` a second time in a main function I would need to empty `numbers`?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-08T09:37:41.567", "Id": "1214", "Score": "0", "body": "@Basil exactly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T10:26:13.127", "Id": "83", "ParentId": "7", "Score": "13" } }, { "body": "<p>Here's how I would do it:</p>\n\n<pre><code>def find_multiples(min=0, max=1000):\n \"\"\"Finds multiples of 3 or 5 between min and max.\"\"\"\n\n for i in xrange(min, max):\n if i%3 and i%5:\n continue\n\n yield i\n\nif __name__ == '__main__':\n print sum(find_multiples())\n</code></pre>\n\n<p>This makes find_multiples a generator for the multiples it finds. The multiples no longer need to be stored explicitly, and especially not in a global. </p>\n\n<p>It's also now takes parameters (with default values) so that the caller can specify the range of numbers to search. </p>\n\n<p>And of course, the global \"if\" block now only has to sum on the numbers generated by the function instead of hoping the global variable exists and has remained untouched by anything else that might come up.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T22:29:00.797", "Id": "231", "ParentId": "7", "Score": "15" } }, { "body": "<p>The UNIX Man's recommendation of using a generator rather than a list is good one. However I would recommend using a generator expressions over <code>yield</code>:</p>\n\n<pre><code>def find_multiples(min=0, max=1000):\n \"\"\"Finds multiples of 3 or 5 between min and max.\"\"\"\n return (i for i in xrange(min, max) if i%3==0 or i%5==0)\n</code></pre>\n\n<p>This has the same benefits as using <code>yield</code> and the added benefit of being more concise. In contrast to UNIX Man's solution it also uses \"positive\" control flow, i.e. it selects the elements to select, not the ones to skip, and the lack of the <code>continue</code> statement simplifies the control flow¹.</p>\n\n<p>On a more general note, I'd recommend renaming the function <code>find_multiples_of_3_and_5</code> because otherwise the name suggests that you might use it to find multiples of any number. Or even better: you could generalize your function, so that it can find the multiples of any numbers. For this the code could look like this:</p>\n\n<pre><code>def find_multiples(factors=[3,5], min=0, max=1000):\n \"\"\"Finds all numbers between min and max which are multiples of any number\n in factors\"\"\"\n return (i for i in xrange(min, max) if any(i%x==0 for x in factors))\n</code></pre>\n\n<p>However now the generator expression is getting a bit crowded, so we should factor the logic for finding whether a given number is a multiple of any of the factors into its own function:</p>\n\n<pre><code>def find_multiples(factors=[3,5], min=0, max=1000):\n \"\"\"Finds all numbers between min and max which are multiples of any number\n in factors\"\"\"\n def is_multiple(i):\n return any(i%x==0 for x in factors)\n\n return (i for i in xrange(min, max) if is_multiple(i))\n</code></pre>\n\n<hr>\n\n<p>¹ Of course the solution using <code>yield</code> could also be written positively and without <code>continue</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-28T14:55:39.270", "Id": "117210", "Score": "0", "body": "I like your second version. Perhaps you could make it even more general and succinct by removing the `min`, `max` argument, and just letting it take an iterator argument. That way the remaindin program would be `sum(find_multiples(xrange(1000)))`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T22:55:19.263", "Id": "238", "ParentId": "7", "Score": "25" } }, { "body": "<p>Regarding the use of a <code>main()</code> function.</p>\n\n<p>One important reason for using a construct like this:</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Is to keep the module importable and in turn much more reusable. I can't really reuse modules that runs all sorts of code when I import them. By having a main() function, as above, I can import the module and reuse relevant parts of it. Perhaps even by running the <code>main()</code> function at my convenience.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T10:22:13.827", "Id": "267", "ParentId": "7", "Score": "6" } }, { "body": "<p>Just in case you're not familiar with the generator technique being used above, here's the same function done in 3 ways, starting with something close to your original, then using a <a href=\"http://docs.python.org/tutorial/datastructures.html#list-comprehensions\" rel=\"noreferrer\">list comprehension</a>, and then using a <a href=\"http://docs.python.org/tutorial/classes.html#generator-expressions\" rel=\"noreferrer\">generator expression</a>:</p>\n\n<pre><code># Finds sum of all multiples of 3 and 5 from 0 to 999 in various ways\n\ndef find_multiples():\n numbers = []\n for i in range(0,1000):\n if i%3 == 0 or i%5 == 0: numbers.append(i)\n return numbers\n\ndef find_multiples_with_list_comprehension():\n return [i for i in range(0,1000) if i%3 == 0 or i%5 == 0]\n\ndef find_multiples_with_generator():\n return (i for i in range(0,1000) if i%3 == 0 or i%5 == 0)\n\nif __name__ == '__main__':\n numbers1 = find_multiples()\n numbers2 = find_multiples_with_list_comprehension()\n numbers3 = list(find_multiples_with_generator())\n print numbers1 == numbers2 == numbers3\n print sum(numbers1)\n</code></pre>\n\n<p><code>find_multiples()</code> is pretty close to what you were doing, but slightly more Pythonic. It avoids the <code>global</code> (icky!) and returns a list.</p>\n\n<p>Generator expressions (contained in parentheses, like a tuple) are more efficient than list comprehensions (contained in square brackets, like a list), but don't actually return a list of values -- they return an object that can be iterated through. </p>\n\n<p>So that's why I called <code>list()</code> on <code>find_multiples_with_generator()</code>, which is actually sort of pointless, since you could also simply do <code>sum(find_multiples_with_generator()</code>, which is your ultimate goal here. I'm just trying to show you that generator expressions and list comprehensions look similar but behave differently. (Something that tripped me up early on.)</p>\n\n<p>The other answers here really solve the problem, I just thought it might be worth seeing these three approaches compared.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T17:38:27.180", "Id": "299", "ParentId": "7", "Score": "6" } }, { "body": "<p>Here is one solution using ifilter. Basically it will do the same as using a generator but since you try to filter out numbers that don't satisfy a function which returns true if the number is divisible by all the factors, maybe it captures better your logic. It may be a bit difficult to understand for someone not accustomed to functional logic.</p>\n\n<pre><code>from itertools import ifilter\n\ndef is_multiple_builder(*factors):\n \"\"\"returns function that check if the number passed in argument is divisible by all factors\"\"\"\n def is_multiple(x):\n return all(x % factor == 0 for factor in factors)\n return is_multiple\n\ndef find_multiples(factors, iterable):\n return ifilter(is_multiple_builder(*factors), iterable)\n</code></pre>\n\n<p>The <code>all(iterable)</code> function returns <code>true</code>, if all elements in the <code>iterable</code> passed as an argument are <code>true</code>.</p>\n\n<pre><code>(x % factor == 0 for factor in factors)\n</code></pre>\n\n<p>will return a generator with true/false for all factor in factors depending if the number is divisible by this factor. I could omit the parentheses around this expression because it is the only argument of <code>all</code>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-25T05:59:23.090", "Id": "10314", "ParentId": "7", "Score": "1" } }, { "body": "<p>I would keep it simple. In this particular case I would do:</p>\n\n<pre><code>def my_sum(start, end, *divisors):\n return sum(i for i in xrange(start, end + 1) if any(i % d == 0 for d in divisors))\n\nif __name__ == '__main__':\n print(my_sum(0, 999, 3, 5))\n</code></pre>\n\n<p>Because it is readable enough. Should you need to implement more, then add more functions.</p>\n\n<p>There is also an O(1) version(if the number of divisors is assumed constant), of course.</p>\n\n<p><strong>Note:</strong> In Python 3 there is no <code>xrnage</code> as <code>range</code> is lazy.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-28T15:00:00.030", "Id": "117212", "Score": "1", "body": "Nice and clear. Perhaps don't make an `end` argument which is included in the range. It's easier if we just always make ranges exclusive like in `range`. If we do that, we never have to think about what values to pass again :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-25T19:21:07.970", "Id": "10325", "ParentId": "7", "Score": "3" } }, { "body": "<p>Adding more to @pat answer, a function like the one below has no meaning because you can NOT re-use for similar tasks. (Copied stripping comments and docstring.)</p>\n\n<pre><code>def find_multiples():\n numbers = []\n for i in xrange(1000):\n if not (i % 3) or not (i % 5):\n numbers.append(i)\n return numbers\n</code></pre>\n\n<p>Instead put parametres at the start of your function in order to be able to reuse it. </p>\n\n<pre><code>def find_multiples(a,b,MAX):\n numbers = []\n for i in xrange(MAX):\n if not (i % a) or not (i % b):\n numbers.append(i)\n return numbers\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-25T13:12:33.337", "Id": "70802", "ParentId": "7", "Score": "2" } } ]
{ "AcceptedAnswerId": "8", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-19T21:16:08.443", "Id": "7", "Score": "60", "Tags": [ "python", "programming-challenge" ], "Title": "Using separate functions for Project Euler 1" }
7
<p>I have a method that has a lot of loops:</p> <pre><code>private void update(double depth) { Console.WriteLine("update with level " + depth); this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate() { List&lt;Grid&gt; grids = new List&lt;Grid&gt;(); Dependencies.Children.Clear(); Grid g = new Grid(); //Canvas.SetZIndex(g, 100); g.Width = 50; g.Height = 50; g.Tag = focus; Ellipse e = new Ellipse(); e.Width = 50; e.Height = 50; e.Fill = Brushes.Red; if (depth == 1) { Canvas.SetTop(g, 163); } else if (depth == 2) { Canvas.SetTop(g, 108); } else if (depth == 3) { Canvas.SetTop(g, 81); } else if (depth == 4) { Canvas.SetTop(g, 65); } else if (depth == 5) { Canvas.SetTop(g, 54); } else if (depth == 6) { Canvas.SetTop(g, 46); } Canvas.SetLeft(g, 500); g.Children.Add(e); Viewbox box = new Viewbox(); box.Width = e.Width; box.Height = e.Height; TextBox txt = new TextBox(); txt.Text = focus.getName(); box.Child = txt; txt.Background = Brushes.Transparent; txt.BorderBrush = Brushes.Transparent; g.Children.Add(box); grids.Add(g); List&lt;SourceFile&gt; list = new List&lt;SourceFile&gt;(); list = focus.getInvocations(); int counter = 1; foreach (SourceFile sf in list) { Grid g1 = new Grid(); //Canvas.SetZIndex(g, 101); g1.Width = 50; g1.Height = 50; g1.Tag = sf; Ellipse e1 = new Ellipse(); //Dependencies.Children.Add(e1); sf.setGrid(g1); e1.Width = 50; e1.Height = 50; e1.Fill = Brushes.Red; g1.Children.Add(e1); if (depth == 1) { Canvas.SetTop(g1, 488); } else if (depth == 2) { Canvas.SetTop(g1, 324); } else if (depth == 3) { Canvas.SetTop(g1, 244); } else if (depth == 4) { Canvas.SetTop(g1, 195); } else if (depth == 5) { Canvas.SetTop(g1, 163); } else if (depth == 6) { Canvas.SetTop(g1, 139); } Canvas.SetLeft(g1, counter * (1000 / (list.Count + 1) )); Viewbox box1 = new Viewbox(); box1.Width = g1.Width; box1.Height = g1.Height; TextBox txt1 = new TextBox(); txt1.Text = sf.getName(); txt1.Background = Brushes.Transparent; txt1.BorderBrush = Brushes.Transparent; box1.Child = txt1; g1.Children.Add(box1); Line l = new Line(); //Canvas.SetZIndex(l, 1); l.Stroke = Brushes.Green; l.StrokeThickness = 10; Binding x1 = new Binding(); x1.Path = new PropertyPath(Canvas.LeftProperty); x1.Converter = new MyConverter(); x1.ConverterParameter = g; Binding y1 = new Binding(); y1.Path = new PropertyPath(Canvas.TopProperty); y1.Converter = new MyConverter(); y1.ConverterParameter = g; Binding x2 = new Binding(); x2.Path = new PropertyPath(Canvas.LeftProperty); x2.Converter = new MyConverter(); x2.ConverterParameter = g1; Binding y2 = new Binding(); y2.Path = new PropertyPath(Canvas.TopProperty); y2.Converter = new MyConverter(); y2.ConverterParameter = g1; x1.Source = y1.Source = g; x2.Source = y2.Source = g1; l.SetBinding(Line.X1Property, x1); l.SetBinding(Line.Y1Property, y1); l.SetBinding(Line.X2Property, x2); l.SetBinding(Line.Y2Property, y2); Dependencies.Children.Add(l); l.Tag = new Call(focus, sf); Contacts.AddPreviewContactDownHandler(l, OnLineDown); counter++; grids.Add(g1); SizeChangedEventHandler act = (Object s, SizeChangedEventArgs args) =&gt; { BindingOperations.GetBindingExpressionBase(l, Line.X1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.X2Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y2Property).UpdateTarget(); }; g.SizeChanged += act; g1.SizeChanged += act; } int counter2 = 1; if (depth &gt;= 2) { int invocCount = 0; foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { invocCount = invocCount + s.getInvocations().Count; } } Console.WriteLine(invocCount); foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { Console.WriteLine("`Found invocation of " + s.getName() + ": " + source.getName()); Grid g1 = new Grid(); g1.Width = 50; g1.Height = 50; Ellipse e1 = new Ellipse(); // Canvas.SetZIndex(g1, 102); grids.Add(g1); e1.Width = 50; e1.Height = 50; e1.Fill = Brushes.Red; source.setGrid(g1); g1.Tag = source; g1.Children.Add(e1); if (depth == 2) { Canvas.SetTop(g1, 540); } else if (depth == 3) { Canvas.SetTop(g1, 406); } else if (depth == 4) { Canvas.SetTop(g1, 325); } else if (depth == 5) { Canvas.SetTop(g1, 271); } else if (depth == 6) { Canvas.SetTop(g1, 232); } Canvas.SetLeft(g1, counter2 * (1000 / (invocCount + 1))); Viewbox box1 = new Viewbox(); box1.Width = g1.Width; box1.Height = g1.Height; TextBox txt1 = new TextBox(); txt1.Text = source.getName(); txt1.Background = Brushes.Transparent; txt1.BorderBrush = Brushes.Transparent; box1.Child = txt1; g1.Children.Add(box1); Line l = new Line(); //Canvas.SetZIndex(l, 2); l.Stroke = Brushes.Green; l.StrokeThickness = 10; Binding x1 = new Binding(); x1.Path = new PropertyPath(Canvas.LeftProperty); x1.Converter = new MyConverter(); x1.ConverterParameter = s.getGrid(); Binding y1 = new Binding(); y1.Path = new PropertyPath(Canvas.TopProperty); y1.Converter = new MyConverter(); y1.ConverterParameter = s.getGrid(); Binding x2 = new Binding(); x2.Path = new PropertyPath(Canvas.LeftProperty); x2.Converter = new MyConverter(); x2.ConverterParameter = g1; Binding y2 = new Binding(); y2.Path = new PropertyPath(Canvas.TopProperty); y2.Converter = new MyConverter(); y2.ConverterParameter = g1; x1.Source = y1.Source = findGrid(grids, s, source); x2.Source = y2.Source = g1; l.SetBinding(Line.X1Property, x1); l.SetBinding(Line.Y1Property, y1); l.SetBinding(Line.X2Property, x2); l.SetBinding(Line.Y2Property, y2); Dependencies.Children.Add(l); l.Tag = new Call(s, source); Contacts.AddPreviewContactDownHandler(l, OnLineDown); counter2++; SizeChangedEventHandler act = (Object o, SizeChangedEventArgs args) =&gt; { BindingOperations.GetBindingExpressionBase(l, Line.X1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.X2Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y2Property).UpdateTarget(); }; source.getGrid().SizeChanged += act; g1.SizeChanged += act; } } } int counter3 = 1; if (depth &gt;= 3) { int invocCount = 0; foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { foreach (SourceFile s1 in source.getInvocations()) { invocCount = invocCount + source.getInvocations().Count; } } } foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { foreach (SourceFile s1 in source.getInvocations()) { Grid g1 = new Grid(); grids.Add(g1); g1.Width = 50; g1.Height = 50; g1.Tag = s1; Ellipse e1 = new Ellipse(); e1.Width = 50; e1.Height = 50; e1.Fill = Brushes.Red; s1.setGrid(g1); g1.Children.Add(e1); if (depth == 3) { Canvas.SetTop(g1, 569); } else if (depth == 4) { Canvas.SetTop(g1, 455); } else if (depth == 5) { Canvas.SetTop(g1, 379); } else if (depth == 6) { Canvas.SetTop(g1, 325); } Canvas.SetLeft(g1, counter3 * (1000 / (invocCount + 1))); Viewbox box1 = new Viewbox(); box1.Width = g1.Width; box1.Height = g1.Height; TextBox txt1 = new TextBox(); txt1.Background = Brushes.Transparent; txt1.BorderBrush = Brushes.Transparent; txt1.Text = s1.getName(); box1.Child = txt1; g1.Children.Add(box1); Line l = new Line(); //Canvas.SetZIndex(l, 2); l.Stroke = Brushes.Green; l.StrokeThickness = 10; Binding x1 = new Binding(); x1.Path = new PropertyPath(Canvas.LeftProperty); x1.Converter = new MyConverter(); x1.ConverterParameter = source.getGrid(); Binding y1 = new Binding(); y1.Path = new PropertyPath(Canvas.TopProperty); y1.Converter = new MyConverter(); y1.ConverterParameter = source.getGrid(); Binding x2 = new Binding(); x2.Path = new PropertyPath(Canvas.LeftProperty); x2.Converter = new MyConverter(); x2.ConverterParameter = g1; Binding y2 = new Binding(); y2.Path = new PropertyPath(Canvas.TopProperty); y2.Converter = new MyConverter(); y2.ConverterParameter = g1; x1.Source = y1.Source = findGrid(grids, source, s1); x2.Source = y2.Source = g1; l.SetBinding(Line.X1Property, x1); l.SetBinding(Line.Y1Property, y1); l.SetBinding(Line.X2Property, x2); l.SetBinding(Line.Y2Property, y2); Dependencies.Children.Add(l); l.Tag = new Call(source, s1); Contacts.AddPreviewContactDownHandler(l, OnLineDown); counter3++; SizeChangedEventHandler act = (Object o, SizeChangedEventArgs args) =&gt; { BindingOperations.GetBindingExpressionBase(l, Line.X1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.X2Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y2Property).UpdateTarget(); }; s1.getGrid().SizeChanged += act; g1.SizeChanged += act; } } } } int counter4 = 1; if (depth &gt;= 4) { int invoCount = 0; foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { foreach (SourceFile s1 in source.getInvocations()) { foreach (SourceFile s2 in s1.getInvocations()) { invoCount = invoCount + s1.getInvocations().Count; } } } } foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { foreach (SourceFile s1 in source.getInvocations()) { foreach (SourceFile s2 in s1.getInvocations()) { Grid g1 = new Grid(); grids.Add(g1); g1.Width = 50; g1.Height = 50; g1.Tag = s2; Ellipse e1 = new Ellipse(); e1.Width = 50; e1.Height = 50; e1.Fill = Brushes.Red; s2.setGrid(g1); g1.Children.Add(e1); if (depth == 4) { Canvas.SetTop(g1, 585); } else if (depth == 5) { Canvas.SetTop(g1, 488); } else if (depth == 6) { Canvas.SetTop(g1, 418); } Canvas.SetLeft(g1, counter4 * (1000 / (invoCount + 1))); Viewbox box1 = new Viewbox(); box1.Width = g1.Width; box1.Height = g1.Height; TextBox txt1 = new TextBox(); txt1.Background = Brushes.Transparent; txt1.BorderBrush = Brushes.Transparent; txt1.Text = s2.getName(); box1.Child = txt1; g1.Children.Add(box1); Line l = new Line(); //Canvas.SetZIndex(l, 2); l.Stroke = Brushes.Green; l.StrokeThickness = 10; Binding x1 = new Binding(); x1.Path = new PropertyPath(Canvas.LeftProperty); x1.Converter = new MyConverter(); x1.ConverterParameter = s1.getGrid(); Binding y1 = new Binding(); y1.Path = new PropertyPath(Canvas.TopProperty); y1.Converter = new MyConverter(); y1.ConverterParameter = s1.getGrid(); Binding x2 = new Binding(); x2.Path = new PropertyPath(Canvas.LeftProperty); x2.Converter = new MyConverter(); x2.ConverterParameter = g1; Binding y2 = new Binding(); y2.Path = new PropertyPath(Canvas.TopProperty); y2.Converter = new MyConverter(); y2.ConverterParameter = g1; x1.Source = y1.Source = findGrid(grids, s1, s2); x2.Source = y2.Source = g1; l.SetBinding(Line.X1Property, x1); l.SetBinding(Line.Y1Property, y1); l.SetBinding(Line.X2Property, x2); l.SetBinding(Line.Y2Property, y2); Dependencies.Children.Add(l); l.Tag = new Call(s1, s2); Contacts.AddPreviewContactDownHandler(l, OnLineDown); counter4++; SizeChangedEventHandler act = (Object o, SizeChangedEventArgs args) =&gt; { BindingOperations.GetBindingExpressionBase(l, Line.X1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.X2Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y2Property).UpdateTarget(); }; s2.getGrid().SizeChanged += act; g1.SizeChanged += act; } } } } } int counter5 = 1; if (depth &gt;= 5) { int invoCount = 0; foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { foreach (SourceFile s1 in source.getInvocations()) { foreach (SourceFile s2 in s1.getInvocations()) { foreach (SourceFile s3 in s2.getInvocations()) { invoCount = invoCount + s2.getInvocations().Count; } } } } } foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { foreach (SourceFile s1 in source.getInvocations()) { foreach (SourceFile s2 in s1.getInvocations()) { foreach (SourceFile s3 in s2.getInvocations()) { Grid g1 = new Grid(); g1.Width = 50; g1.Height = 50; grids.Add(g1); g1.Tag = s3; Ellipse e1 = new Ellipse(); //Dependencies.Children.Add(e1); e1.Width = 50; e1.Height = 50; e1.Fill = Brushes.Red; s3.setGrid(g1); g1.Children.Add(e1); if (depth == 5) { Canvas.SetTop(g1, 596); } else if (depth == 6) { Canvas.SetTop(g1, 511); } Canvas.SetLeft(g1, counter5 * (1000 / (invoCount + 1))); Viewbox box1 = new Viewbox(); box1.Width = g1.Width; box1.Height = g1.Height; TextBox txt1 = new TextBox(); txt1.Background = Brushes.Transparent; txt1.BorderBrush = Brushes.Transparent; txt1.Text = s3.getName(); box1.Child = txt1; g1.Children.Add(box1); Line l = new Line(); //Canvas.SetZIndex(l, 2); l.Stroke = Brushes.Green; l.StrokeThickness = 10; Binding x1 = new Binding(); x1.Path = new PropertyPath(Canvas.LeftProperty); x1.Converter = new MyConverter(); x1.ConverterParameter = s2.getGrid(); Binding y1 = new Binding(); y1.Path = new PropertyPath(Canvas.TopProperty); y1.Converter = new MyConverter(); y1.ConverterParameter = s2.getGrid(); Binding x2 = new Binding(); x2.Path = new PropertyPath(Canvas.LeftProperty); x2.Converter = new MyConverter(); x2.ConverterParameter = g1; Binding y2 = new Binding(); y2.Path = new PropertyPath(Canvas.TopProperty); y2.Converter = new MyConverter(); y2.ConverterParameter = g1; x1.Source = y1.Source = findGrid(grids, s2, s3); x2.Source = y2.Source = g1; l.SetBinding(Line.X1Property, x1); l.SetBinding(Line.Y1Property, y1); l.SetBinding(Line.X2Property, x2); l.SetBinding(Line.Y2Property, y2); l.Tag = new Call(s2, s3); Contacts.AddPreviewContactDownHandler(l, OnLineDown); Dependencies.Children.Add(l); counter5++; SizeChangedEventHandler act = (Object o, SizeChangedEventArgs args) =&gt; { BindingOperations.GetBindingExpressionBase(l, Line.X1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.X2Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y2Property).UpdateTarget(); }; s3.getGrid().SizeChanged += act; g1.SizeChanged += act; } } } } } } foreach (Grid grid in grids) { Dependencies.Children.Add(grid); Contacts.AddPreviewContactDownHandler(grid, DownOnSourceFile); } } )); } </code></pre> <p>Is there any easy way to improve that? And to make it working not only for 6 steps but also for n steps?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:26:50.047", "Id": "29", "Score": "17", "body": "tl;dr. You'll likely have a better response if you remove a lot of the boilerplate or focus on the part you're really interested in. I think pseudo-code would help a lot here." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T00:20:41.843", "Id": "66", "Score": "12", "body": "Whenever you think of using copy and paste, don't. Make a method and call it twice." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T01:04:20.503", "Id": "175", "Score": "3", "body": "Break your method into a lot of smaller ones." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-03T00:15:14.470", "Id": "984", "Score": "0", "body": "Even with your code abstracted, changing this from a static depth to n-depth is very non-trivial and off topic for this site. You will require formulas instead of constants and recursion or otherwise completely different looping structure to walk the tree (depending on how deep you want to go recursion becomes problematic due to limited stack space, though optimizations on x64 machines may be able to help with that). Regardless, the review is unanimous: refactor/abstract and improve naming; the solution to your unsolved problem, however, is for a different site." } ]
[ { "body": "<p>Break this down into several methods - it's very long, meaning it's not easy to read.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T00:28:01.803", "Id": "67", "Score": "1", "body": "Actually it is even longer ;) I wasn't able to post the whole method because of the character limit;)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T01:10:53.220", "Id": "176", "Score": "2", "body": "@Roflcoptr You must be trying to beat my former supervisor 1200 lines-long methods. Definitely break it down, it is a nightmare in the making." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T10:24:32.597", "Id": "180", "Score": "1", "body": "+1 definitely break it down to smaller methods - and use some Linq as well!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-05T01:31:34.790", "Id": "161872", "Score": "0", "body": "@Roflcoptr In the future if you need to post a lot of code maybe try [GitHub Gists](https://gist.github.com/). *(Although, it's likely a good indicator that your example it too long if it won't fit.)*" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-19T21:24:59.400", "Id": "13", "ParentId": "9", "Score": "63" } }, { "body": "<p>Give some thought to abstracting the decisions around setting the top of the canvas (cf. all those <code>if</code> statements) out into a set of classes - or perhaps a single class with different suitable parameters in the constructor. A lot of this code differs only in the numbers being applied.</p>\n\n<p>A simple rule is \"Abstract the concept that varies\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:27:45.830", "Id": "15", "ParentId": "9", "Score": "18" } }, { "body": "<p>For the n steps bit, consider using recursion - but tread carefully.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:29:04.710", "Id": "17", "ParentId": "9", "Score": "6" } }, { "body": "<p>I might recommend the use of switch statements and white space along with LRE's suggestion of breaking this into multiple methods. It also looks like you have quite a bit of repeated code maybe try to break that out for sure it its own methods.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T22:41:45.367", "Id": "52", "Score": "0", "body": "In this case switch may not be the best option. It would make the code use case instead of if/else but the code will almost be equally lengthy" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:29:43.017", "Id": "18", "ParentId": "9", "Score": "9" } }, { "body": "<p>This code...</p>\n\n<pre><code>if (depth == 1)\n{\n Canvas.SetTop(g1, 163);\n}\nelse if (depth == 2)\n{\n Canvas.SetTop(g1, 108);\n}\nelse if (depth == 3)\n{\n Canvas.SetTop(g1, 81);\n}\nelse if (depth == 4)\n{\n Canvas.SetTop(g1, 65);\n}\nelse if (depth == 5)\n{\n Canvas.SetTop(g1, 54);\n}\nelse if (depth == 6)\n{\n Canvas.SetTop(g1, 46);\n}\n</code></pre>\n\n<p>Could be better implemented using an array...</p>\n\n<pre><code>int[] values = new [] { 0, 163, 108, 81, 65, 54, 46 }\n</code></pre>\n\n<p>Or Dictionary...</p>\n\n<pre><code>var values = new Dictionary&lt;int,int&gt;() { { 1, 163 }, { 2, 108 }, { 3, 81 }, { 4, 65 }, { 5, 54 }, { 6, 46} };\n</code></pre>\n\n<p>This way you could simple say</p>\n\n<pre><code>Canvas.SetTop(g1, values[depth])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T00:42:45.400", "Id": "69", "Score": "3", "body": "alternatively, a switch statement would help and introduce absolutely no overhead (in fact, it's faster than repeated `if/else` operations)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T02:18:44.180", "Id": "78", "Score": "16", "body": "@Felix: But a switch statement wouldn't really make the code shorter." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T22:03:07.877", "Id": "167", "Score": "4", "body": "There seem to be some prejudices towards using a control statement exactly for what it was made. I embrace brevity, but if this is in its own method it will be readable again, and if performance makes a difference, I would strongly prefer the switch statement" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T23:59:50.233", "Id": "171", "Score": "2", "body": "Don't forget The question says it should be done not just for 6 but for n iterations. There's no such thing as a dynamic-n-cases-switch. But I do agree that portion of code should be in it own method" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T09:19:19.733", "Id": "179", "Score": "0", "body": "I'm not sure if replacing the else ifs with this is any more readable and if the code would would perform better.." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T14:36:58.320", "Id": "187", "Score": "0", "body": "Mmmm let's see. How would you implement this mathematical function: f(x) = 3x . This way: F(int x) { return 3 * x } Or this way: F(int x) { if ( x == 1 ) return 3; if (x == 2) return 6; if (x == 3) return 9; ..... } or maybe this way: F(int x) { switch (x) { case 1: return 3; case 2: return 6; case 3 return 9; ..... } }" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T15:36:19.860", "Id": "197", "Score": "1", "body": "@Carlos right -- what we need is a formula to spit out a number for any *n*. I can't think of the right one just now, but it probably has do something with log2" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T22:34:52.687", "Id": "29", "ParentId": "9", "Score": "59" } }, { "body": "<p>Break your code into its own methods definitely, there are other ways, but that will probably be the easiest and less time consuming way to make it easier read and debug down the track for a start.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T00:18:27.980", "Id": "46", "ParentId": "9", "Score": "3" } }, { "body": "<p>There are a couple of immediately obvious things that havent been mentioned yet:</p>\n\n<p>You have a lot of magic numbers in your code. Try to define them as <code>const</code>s with meaningful names.</p>\n\n<p>For example </p>\n\n<p><code>g.Width = 50;</code></p>\n\n<p>becomes</p>\n\n<pre><code>private const int DefaultGridWidth = 50;\n...\ng.Width = DefaultGridWidth;\n</code></pre>\n\n<p>It seems like a trivial change but it makes a big difference to someone who is reading your code. It gives an indication of <strong>why</strong> the value is 50, not just that it <strong>is</strong> 50.\n<hr>\nYou should use more meaningful names for your identifiers. Names like <code>g</code> and <code>g1</code> do not tell me a lot about what the object is, but <code>mainGrid</code> and <code>innerGrid</code> contain more information for the reader.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T22:05:40.760", "Id": "168", "Score": "0", "body": "That is indeed true, too many literals in code make it harder to maintain and adapt, especially so if there are cross-dependencies among the values!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-23T07:47:00.157", "Id": "2434", "Score": "1", "body": "He should use static readonly instead of const - then he won't have to recompile assemblies that depend on his code with every change! Also, he's not limited to only values but can use references as constants as well." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T10:33:10.783", "Id": "84", "ParentId": "9", "Score": "29" } }, { "body": "<p>This should simplify the looping assuming that you can generalize the positioning code like mention in several of the other answers</p>\n\n<pre><code> //Get the initial set of sourcefiles\n var sourceFiles = from file in list\n from invocation in file.getInvocations()\n group invocation by (SourceFile)null into groupedByInvoker\n select groupedByInvoker;\n\n for (var currentDepth = 0; currentDepth &lt;= depth; currentDepth++)\n {\n foreach (var currentGroup in sourceFiles)\n {\n int sourceFileCount = currentGroup.Count();\n int counter = 0;\n\n foreach (var invocation in currentGroup)\n {\n /*\n * Generalized grid code goes here\n */\n counter++;\n }\n }\n\n //Select the current sub source files\n sourceFiles = from invokerGroup in sourceFiles\n from file in invokerGroup\n from invocation in file.getInvocations()\n group invocation by file into groupedByInvoker\n select groupedByInvoker;\n\n }\n</code></pre>\n\n<p>This is not an exact mapping to the above code in that this goes over the getInvocations tree breadth first instead of depth first.</p>\n\n<p>Updated with imput from <a href=\"https://codereview.stackexchange.com/questions/182/is-this-linq-code-clear-enough-and-how-could-i-improve-it/329#329\">Update grid from source hierarchy</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T21:43:51.547", "Id": "117", "ParentId": "9", "Score": "7" } }, { "body": "<p>Since you're using C#, you can make your initializers a bit nicer:</p>\n\n<pre><code>Grid g = new Grid()\n{\n Width = 50,\n Height = 50,\n Tag = focus,\n}\n//Canvas.SetZIndex(g, 100);\n</code></pre>\n\n<p>The last part of your code (or rather, the second half) does very similar things multiple times: code duplication is a sign your code can be made clearer. For instance (note that your code almost surely contains a bug! The statement inside all the loops invokes s2 and not s3):</p>\n\n<pre><code>foreach (SourceFile s in list)\n{\n foreach (SourceFile source in s.getInvocations())\n {\n foreach (SourceFile s1 in source.getInvocations())\n {\n foreach (SourceFile s2 in s1.getInvocations())\n {\n foreach (SourceFile s3 in s2.getInvocations())\n {\n invoCount = invoCount + s2.getInvocations().Count;\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>can be changed into</p>\n\n<pre><code>list.CountRecursive(t =&gt; t.getInvocations(), t =&gt; t.getInvocations().Count, 5);\n\n(...)\n\npublic static int CountRecursive&lt;T&gt;(this IEnumerable&lt;T&gt; x, Func&lt;T, IEnumerable&lt;T&gt;&gt; f, Func&lt;T, int&gt; c, int depth)\n{\n int counter = 0;\n foreach (T t in x)\n {\n if (depth &gt; 1)\n {\n counter += f(t).CountRecursive(f, c, depth - 1);\n }\n else\n {\n counter += c(t);\n }\n }\n return counter;\n}\n</code></pre>\n\n<p>which also makes it a lot easier to do it for different recursion levels.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-21T00:30:18.750", "Id": "122", "ParentId": "9", "Score": "18" } }, { "body": "<p>I refactored it for you. I did all of this without testing, so there's likely a bunch of bugs and off-by-one errors. I also made some assumptions about the code that you didn't include. Now that the code's a lot smaller, it should be easier for you to find those bugs.</p>\n\n<p>A couple of important points:</p>\n\n<ol>\n<li><p>Recursion is a fundamental concept in programming. If you are a professional programmer, you absolutely must be comfortable with it, or you will never be able to deal with nested structures effectively.</p></li>\n<li><p>If you copy and paste, you're doing it wrong. Every time you hit Ctrl+C, a kitten dies. No no no.</p></li>\n<li><p>If you have variables named <code>something1</code>, <code>something2</code>, <code>something3</code>, etc. <em>you're doing it wrong</em>. At the very least, those should be an array.</p></li>\n<li><p>You had <code>depth</code> as a <code>double</code> but were comparing it to literal values other than zero. That's bad.</p></li>\n</ol>\n\n<p>Here you go:</p>\n\n<pre><code>private void update(int depth)\n{\n Console.WriteLine(\"update with level \" + depth);\n\n Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()\n {\n List&lt;Grid&gt; grids = new List&lt;Grid&gt;();\n\n Dependencies.Children.Clear();\n\n Grid grid = MakeOuterGrid(grids, focus, e.Width, e.Height, depth);\n\n List&lt;SourceFile&gt; list = focus.getInvocations();\n\n for (int i = 1; i &lt;= depth; i++)\n {\n int invocCount = CountInvocations(focus, i + 1);\n int counter = 0;\n MakeRecursiveGrids(grids, null, focus, i, invocCount, i, ref counter);\n }\n\n foreach (Grid grid in grids)\n {\n Dependencies.Children.Add(grid);\n Contacts.AddPreviewContactDownHandler(grid, DownOnSourceFile);\n }\n }));\n}\n\nvoid AdjustTop(int depth, int table) {\n int[][] depthTable = new int[][] {\n new int[] { 163, 108, 81, 65, 54, 46 },\n new int[] { 488, 324, 244, 195, 163, 139 },\n new int[] { -1, 540, 406, 325, 271, 232 },\n new int[] { -1, -1, 569, 455, 379, 325 },\n new int[] { -1, -1, -1, 585, 488, 418 },\n new int[] { -1, -1, -1, -1, 596, 511 },\n }\n\n int[] depths = depthTable[table];\n if ((depth &lt; depths.Length) &amp;&amp; (depths[depth - 1] != -1)) {\n Canvas.SetTop(depths[depth - 1]);\n }\n}\n\nSizeChangedEventHandler UpdateBindings(Line line) {\n SizeChangedEventHandler act = (Object o, SizeChangedEventArgs args) =&gt;\n {\n BindingOperations.GetBindingExpressionBase(line, Line.X1Property).UpdateTarget();\n BindingOperations.GetBindingExpressionBase(line, Line.Y1Property).UpdateTarget();\n BindingOperations.GetBindingExpressionBase(line, Line.X2Property).UpdateTarget();\n BindingOperations.GetBindingExpressionBase(line, Line.Y2Property).UpdateTarget();\n };\n\n return act;\n}\n\nint CountInvocations(SourceFile source, int depth)\n{\n int count = 0;\n\n if (depth &gt; 0)\n {\n foreach (SourceFile inner in source.getInvocations())\n {\n count = count + CountInvocations(inner, depth - 1);\n }\n }\n else\n {\n count = source.Count;\n }\n\n return count;\n}\n\nGrid MakeGrid(List&lt;Grid&gt; grids, SourceFile source)\n{\n Grid grid = new Grid();\n grid.Width = 50;\n grid.Height = 50;\n grid.Tag = source;\n source.setGrid(grid);\n grids.Add(grid);\n\n Ellipse ellipse = new Ellipse();\n ellipse.Width = 50;\n ellipse.Height = 50;\n ellipse.Fill = Brushes.Red;\n\n grid.Children.Add(ellipse);\n\n return grids;\n}\n\nvoid MakeRecursiveGrids(List&lt;Grid&gt; grids, SourceFile outer, SourceFile source,\n int maxDepth, int invocCount, int recurseDepth, ref int counter)\n{\n if (recurseDepth &gt; 0)\n {\n foreach (SourceFile inner in source)\n {\n MakeRecursiveGrids(grids, source, inner, maxDepth, invocCount,\n recurseDepth - 1, ref counter);\n }\n }\n else\n {\n MakeGrid(grids, outer, inner, depth, maxDepth, invocCount, counter);\n counter++;\n }\n}\n\nGrid MakeGrid(List&lt;Grid&gt; grids, SourceFile outer, SourceFile inner,\n int depth, int[] depths, int invocCount, int counter)\n{\n Grid grid = MakeGrid(grids, inner);\n\n MakeViewbox(grid, grid.Width, grid.Height, inner.getName());\n\n AdjustTop(depth, depths);\n Canvas.SetLeft(grid, counter * (1000 / (invocCount + 1)));\n\n MakeLine(grids, grid, outer, inner);\n\n return grid;\n}\n\nGrid MakeOuterGrid(List&lt;Grid&gt; grids, SourceFile inner, int width, int height,\n int depth)\n{\n Grid grid = MakeGrid(grids, inner);\n\n MakeViewbox(grid, width, height, inner.getName());\n\n AdjustTop(depth, 0);\n Canvas.SetLeft(grid, 500);\n\n return grid;\n}\n\nBinding MakeBinding(Object parameter, Grid grid)\n{\n Binding binding = new Binding();\n binding.Path = new PropertyPath(parameter);\n binding.Converter = new MyConverter();\n binding.ConverterParameter = grid;\n}\n\nvoid MakeLine(List&lt;Grid&gt; grids, Grid grid, SourceFile outer, SourceFile inner)\n{\n Grid g2 = outer.getGrid();\n\n Line line = new Line();\n line.Stroke = Brushes.Green;\n line.StrokeThickness = 10;\n\n Binding x1 = MakeBinding(Canvas.LeftProperty, g2);\n Binding y1 = MakeBinding(Canvas.TopProperty, g2);\n Binding x2 = MakeBinding(Canvas.LeftProperty, grid);\n Binding y2 = MakeBinding(Canvas.TopProperty, grid);\n\n Grid g = findGrid(grids, outer, inner);\n x1.Source = g;\n y1.Source = g;\n x2.Source = grid;\n y2.Source = grid;\n\n line.SetBinding(Line.X1Property, x1);\n line.SetBinding(Line.Y1Property, y1);\n line.SetBinding(Line.X2Property, x2);\n line.SetBinding(Line.Y2Property, y2);\n\n Dependencies.Children.Add(line);\n\n Contacts.AddPreviewContactDownHandler(line, OnLineDown);\n\n line.Tag = new Call(outer, inner);\n\n SizeChangedEventHandler act = UpdateBindings(line);\n inner.getGrid().SizeChanged += act;\n g1.SizeChanged += act;\n}\n\nvoid MakeViewBox(Grid grid, int width, int height, string text)\n{\n Viewbox box = new Viewbox();\n box.Width = width;\n box.Height = height;\n\n TextBox textBox = new TextBox();\n textBox.Text = text;\n\n box.Child = textBox;\n\n grid.Children.Add(box);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T19:12:58.543", "Id": "315", "ParentId": "9", "Score": "8" } }, { "body": "<p>Instead of <code>Grid g</code> and <code>Ellipse e</code>, use <code>Grid grid</code> and <code>Ellipse ellipse</code>. A loc with <code>e.size=</code> says less than <code>ellipse.Size=</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:47:30.027", "Id": "523", "Score": "0", "body": "You're absoluletly right, but I don't think that this is the real problem here ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-27T19:44:05.510", "Id": "320", "ParentId": "9", "Score": "4" } } ]
{ "AcceptedAnswerId": "13", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-19T21:19:59.470", "Id": "9", "Score": "34", "Tags": [ "c#", "performance", "algorithm" ], "Title": "Too many loops in Drawing App" }
9
<p>I use <a href="https://codeigniter.com/" rel="nofollow noreferrer">CodeIgniter</a> at work, and one of our model files had a lot of subqueries in it. I originally had to manually write each subquery, and wondered if I could use active records instead.</p> <p>So, to make my life easier, I made a subquery library for CodeIgniter.</p> <p>I put it on the <a href="https://github.com/bcit-ci/CodeIgniter/wiki/Subqueries" rel="nofollow noreferrer">CodeIgniter Wiki</a>, but I never really had any one look over it. So, can you tell me if there is anything I should improve in this, or anything I really shouldn't be doing?</p> <p>P.S. Feel free to use this if you wish.</p> <p>P.P.S. <code>join_range</code> is a helper method for use with the answer to <a href="https://stackoverflow.com/questions/4155873/mysql-find-in-set-vs-in">this question</a>.</p> <p>P.P.P.S. The latest version can be found <a href="https://github.com/NTICompass/CodeIgniter-Subqueries" rel="nofollow noreferrer">here</a>.</p> <pre><code>class Subquery{ var $CI; var $db; var $statement; var $join_type; var $join_on; function __construct(){ $this-&gt;CI =&amp; get_instance(); $this-&gt;db = array(); $this-&gt;statement = array(); $this-&gt;join_type = array(); $this-&gt;join_on = array(); } /** * start_subquery - Creates a new database object to be used for the subquery * * @param $statement - SQL statement to put subquery into (select, from, join, etc.) * @param $join_type - JOIN type (only for join statements) * @param $join_on - JOIN ON clause (only for join statements) * * @return A new database object to use for subqueries */ function start_subquery($statement, $join_type='', $join_on=1){ $db = $this-&gt;CI-&gt;load-&gt;database('', true); $this-&gt;db[] = $db; $this-&gt;statement[] = $statement; if(strtolower($statement) == 'join'){ $this-&gt;join_type[] = $join_type; $this-&gt;join_on[] = $join_on; } return $db; } /** * end_subquery - Closes the database object and writes the subquery * * @param $alias - Alias to use in query * * @return none */ function end_subquery($alias=''){ $db = array_pop($this-&gt;db); $sql = &quot;({$db-&gt;_compile_select()})&quot;; $alias = $alias!='' ? &quot;AS $alias&quot; : $alias; $statement = array_pop($this-&gt;statement); $database = (count($this-&gt;db) == 0) ? $this-&gt;CI-&gt;db: $this-&gt;db[count($this-&gt;db)-1]; if(strtolower($statement) == 'join'){ $join_type = array_pop($this-&gt;join_type); $join_on = array_pop($this-&gt;join_on); $database-&gt;$statement(&quot;$sql $alias&quot;, $join_on, $join_type); } else{ $database-&gt;$statement(&quot;$sql $alias&quot;); } } /** * join_range - Helper function to CROSS JOIN a list of numbers * * @param $start - Range start * @param $end - Range end * @param $alias - Alias for number list * @param $table_name - JOINed tables need an alias(Optional) */ function join_range($start, $end, $alias, $table_name='q'){ $range = array(); foreach(range($start, $end) AS $r){ $range[] = &quot;SELECT $r AS $alias&quot;; } $range[0] = substr($range[0], 7); $range = implode(' UNION ALL ', $range); $sub = $this-&gt;start_subquery('join', 'inner'); $sub-&gt;select($range, false); $this-&gt;end_subquery($table_name); } } </code></pre> <p><strong>Example Usage</strong></p> <p>This query:</p> <pre><code>SELECT `word`, (SELECT `number` FROM (`numbers`) WHERE `numberID` = 2) AS number FROM (`words`) WHERE `wordID` = 3 </code></pre> <p>would become:</p> <pre><code>$this-&gt;db-&gt;select('word')-&gt;from('words')-&gt;where('wordID', 3); $sub = $this-&gt;subquery-&gt;start_subquery('select'); $sub-&gt;select('number')-&gt;from('numbers')-&gt;where('numberID', 2); $this-&gt;subquery-&gt;end_subquery('number'); </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:50:27.920", "Id": "42", "Score": "1", "body": "Why is $db an array?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:55:41.490", "Id": "46", "Score": "0", "body": "@Time Machine: `$db` is an array because every time you call `start_subquery` it makes a new database object. This allows subqueries inside subqueries." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T11:45:43.230", "Id": "113", "Score": "0", "body": "Can you give us an example usage ?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T14:29:40.943", "Id": "137", "Score": "0", "body": "@RobertPitt: I've added an example to the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T16:57:25.660", "Id": "7907", "Score": "0", "body": "If anyone's curious, the latest version of this is here: https://github.com/NTICompass/CodeIgniter-Subqueries" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-24T02:35:19.013", "Id": "22573", "Score": "0", "body": "nice... anyway, can we do a subquery under the subquery? on the other word, can I have unlimited recursively subqueries?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-24T13:20:26.657", "Id": "22603", "Score": "0", "body": "@zfm: Yes you can! `start_subquery` keeps track of how many times it was called, so when `end_subquery` is called, it knows where to put the subquery. http://pastebin.com/KxfrHb1J" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-25T03:26:10.343", "Id": "22623", "Score": "0", "body": "@Rocket: from what you wrote on pastebin, it was two subqueries on the same level. Is it possible to have something like `$sub2 = $sub->subquery...` so the result will be something like `SELECT * FROM A WHERE xxx IN (SELECT xxx FROM B WHERE yyy IN (SELECT ... ))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-25T06:12:47.473", "Id": "22624", "Score": "0", "body": "@zfm: The pastebin example will actually generate: `SELECT word, (SELECT number FROM (numbers) WHERE numberID = 2 AND ab IN (SELECT test FROM (testing) WHERE a = 12)) AS number FROM (words) WHERE wordID = 3` :-D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-25T06:15:47.503", "Id": "22625", "Score": "0", "body": "@zfm: When you call `end_subquery` it nests it under the last opened `start_subquery`. So the example on pastebin *will* do what you want. :-D" } ]
[ { "body": "<p>I may be missing something here,\nBut to me it seems that you have a class that you pass a pre-built query into?</p>\n\n<p>I am thinking would it not be beneficial to have a subquery built the same way as the top level queries?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T00:28:14.020", "Id": "68", "Score": "0", "body": "You're not passing in a pre-built query per se. `start_subquery` returns you (a reference to) CodeIgniter's database object. You can then call active query methods on that object. `end_subquery` gets the query from the db object, wraps it in `()` then adds it to the main query." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T09:13:29.730", "Id": "94", "Score": "1", "body": "I see, I like this approach, Much better than Writing them yourself. reading through it properly now I have time, Im not sure there is much different you could do. A+ code, Have you considered putting the code up as an enhancement in the CI issue tracker?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T14:28:42.647", "Id": "136", "Score": "0", "body": "I posted it on the CodeIgniter wiki." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T22:33:06.807", "Id": "28", "ParentId": "12", "Score": "5" } }, { "body": "<p>Personally I think your going the wrong way about things, you can easily pass in a query string into the <code>select</code> method and set the 2nd param to true to bypass backticks.</p>\n<p>So the output would place the sub query string within the main query select.</p>\n<p>I would do something along the lines of:</p>\n<pre><code>class MyModel extends Model\n{\n public function getRows()\n {\n //Create a subquery and render it to a stirng\n $sub = $this-&gt;db-&gt;select('number')-&gt;from('numbers')-&gt;where('numberID', 2)-&gt;_compile_select();\n\n //Clear the data from the CI Arrays\n $this-&gt;db-&gt;_reset_select();\n\n //Build the main query passing in the sub-query and disabling backticks\n $this-&gt;db-&gt;select(&quot;word,(&quot; . $sub . &quot;)&quot;, false)-&gt;where('wordID', 3);\n\n //Get the results\n $result = $this-&gt;get(&quot;words&quot;);\n }\n}\n</code></pre>\n<p>Sources:</p>\n<ul>\n<li>@ <a href=\"https://bitbucket.org/ellislab/codeigniter/src/b84189dcdfe3/system/database/DB_active_rec.php#cl-1693\" rel=\"noreferrer\">_compile_select()</a></li>\n<li>@ <a href=\"https://bitbucket.org/ellislab/codeigniter/src/b84189dcdfe3/system/database/DB_active_rec.php#cl-2022\" rel=\"noreferrer\">_reset_select()</a></li>\n</ul>\n<p>Firstly let me just state that the code above may not be fully working as i have not test machine a.t.m, but I do know that this is possible and you do not need all the extra logic specified.</p>\n<p>It seems pretty simple to me without creating new <code>$db</code>'s.</p>\n<p>I also would recommend you encapsulate the logic above into a class so you can pass the object's around and make life simpler as the above is a <strong>POC</strong></p>\n<hr />\n<h1>Concept:</h1>\n<pre><code>class InnerQuery extends CI_DB_active_record\n{\n public function __construct()\n { \n }\n\n public function __call($method,$params = array())\n {\n //Remove methods that modify the database\n switch(strtolower($method))\n {\n case 'get':\n case 'count_all_results':\n case 'get_where':\n trigger_error(&quot;Cannot use {$method} in InnerQuery&quot;);\n break;\n }\n return $this;\n }\n \n public function compile()\n {\n return &quot;(&quot; . $this-&gt;_compile_select() . &quot;)&quot;;\n }\n\n public function __tostring()\n {\n return $this-&gt;compile();\n }\n}\n</code></pre>\n<p>Ok so the above class extends the same object as <code>$this-&gt;db</code> in your controller, so you can use all the methods to build a query such as</p>\n<pre><code>$this-&gt;InnerQuery-&gt;select(&quot;item as item_key&quot;)-&gt;from(&quot;inner_table&quot;)-&gt;where(&quot;foo&quot;,&quot;zed&quot;);\n</code></pre>\n<p>You should disable the parent methods that change the database or run any queries as this is only used to build a select string.</p>\n<p>so you should in thoery be able to do:</p>\n<pre><code>$this-&gt;db-&gt;select(&quot;word&quot;)-&gt;where('wordID', 3);\n$this-&gt;db-&gt;select($this-&gt;InnerQuery,false);\n</code></pre>\n<p>which would use the DB class to build your query and can just be passed into the outer select and the <code>__tostring</code> will return the <code>(SELECT ...)</code> with braces and pass it into the main query.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T15:05:01.903", "Id": "440", "Score": "0", "body": "I'd rather not have to call `_compile_select()` and `_reset_select()` on the main DB object. That would mean I'd have to declare all subqueries before the rest of the query, and I don't want to have to do that. Also, the point of this library is to abstract this." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T15:08:36.913", "Id": "442", "Score": "0", "body": "But I also stated that *I aso would recommend you encapsulate the logic above into a class so you can pass the object's around and make life simpler.* this would resolve that issue" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T05:09:20.367", "Id": "549", "Score": "0", "body": "I originally tried to extend the active record class, but that failed. I think I was doing it wrong. I really like your method, I'll probably do that when I get the time to update my library." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T12:03:59.200", "Id": "666", "Score": "1", "body": "No problem, sorry for all the confusion above, hope you get a more stable class together :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T14:57:07.827", "Id": "277", "ParentId": "12", "Score": "16" } } ]
{ "AcceptedAnswerId": "277", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-01-19T21:24:11.093", "Id": "12", "Score": "29", "Tags": [ "php", "mysql", "codeigniter" ], "Title": "CodeIgniter Active Record Subqueries" }
12
<p>So I've had a problem where I need to compare data in 2 different tables on two different servers. Now, I know MySQL supports <code>CHECKSUM TABLES</code>, but from my testing and understanding, it's not reliable across server instances and versions. </p> <p>So I created this query:</p> <pre><code>$part = '@CRC := MD5(CONCAT_WS(\'#\', COALESCE(`'. implode('`, "#NULL#"), COALESCE(`', $this-&gt;_columns). '`, "#NULL#")))'; $sql1 = "SELECT COUNT(*) AS cnt, SUM(CONV(SUBSTRING({$part}, 1, 4), 16, 10)) as a1, SUM(CONV(SUBSTRING(@CRC, 5, 4), 16, 10)) as a2, SUM(CONV(SUBSTRING(@CRC, 9, 4), 16, 10)) as a3, SUM(CONV(SUBSTRING(@CRC, 13, 4), 16, 10)) as a4, SUM(CONV(SUBSTRING(@CRC, 17, 4), 16, 10)) as a5, SUM(CONV(SUBSTRING(@CRC, 21, 4), 16, 10)) as a6, SUM(CONV(SUBSTRING(@CRC, 25, 4), 16, 10)) as a7, SUM(CONV(SUBSTRING(@CRC, 29, 4), 16, 10)) as a8 FROM `dbname`.`tablename` WHERE `id` &gt;= $min AND `id` &lt;= $max "; </code></pre> <p>So basically, it's concatenating each row together (all the columns of each row more specifically) and then MD5ing them. Then it walks 4 hexbits at a time through that MD5 and sums them across all rows (4 hexbits to allow me to do huge tables without needing to worry about overflowing). Then, I just compare the result of this query on both tables to see if everything is the same.</p> <p>By using this binary search, I am able to rather quickly narrow down where the changes are so that I can port them.</p> <p>It's actually reasonably efficient, so I'm not too concerned about that. What I am concerned about is if this is even necessary. It's screaming to me "You're doing it wrong", but I can't figure out any cleaner method around it...</p> <p>What are your thoughts?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:37:10.357", "Id": "35", "Score": "1", "body": "It may be overkill for your problem but have you looked at MYSQL clusters to handle mirroring and distributing of data. It would offer other features that may be useful." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T21:38:21.553", "Id": "37", "Score": "0", "body": "They need to be syncronized lazily. Basically pushing QC into Production. And the data volume prohibits (or at least makes it expensive) to dump and restore the entire dataset each cycle..." } ]
[ { "body": "<p>We use <a href=\"http://www.maatkit.org/doc/mk-table-checksum.html\"><code>mk-table-checksum</code></a>. </p>\n\n<p>It works really great in Master-Slave context where it also allows to sync differences in both directions depending on your choice.</p>\n\n<p>Saidly from what i've seen most people it for replication and i can't provide any copy/pasteable output but if you don't know it it's definitly worth looking into. If you know it i'd like to hear why it doesn't work for you.</p>\n\n<p>To get an overview over many tables you can use something like <code>mk-table-checksum host1 host2 | mk-checksum-filter</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T13:16:41.477", "Id": "126", "Score": "0", "body": "The only issue that I have with that, is that it'll be hard to write a binary search using it. It does have chunk size, but it doesn't seem that I can specify the range of PK as well. So all it would tell me is if they differed. But looking there, the tool [mk-table-sync](http://www.maatkit.org/doc/mk-table-sync.html) would do it. But I need some custom work wrapped around it, so calling an external program is a last resort at best. Thanks though!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T02:17:07.157", "Id": "59", "ParentId": "16", "Score": "5" } }, { "body": "<p>Simply run in MySQL <code>CHECKSUM TABLE 'yourtable'</code></p>\n\n<p>Or for PHP solution read\n<a href=\"http://www.softwareprojects.com/resources/programming/t-how-to-check-mysql-replication-databases-are-in-syn-1832.html\" rel=\"nofollow\">How to check MySQL Replication databases are in Sync</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-24T18:36:20.337", "Id": "23086", "ParentId": "16", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-19T21:28:43.283", "Id": "16", "Score": "9", "Tags": [ "php", "mysql", "sql" ], "Title": "Comparing data in 2 tables on different servers with CHECKSUM" }
16
<p>A while back, I reverse-engineered a checksum algorithm from an <a href="http://en.wikipedia.org/wiki/Massively_multiplayer_online_game" rel="noreferrer">MMO</a> used to check the validity of an item that's linked to chat (similar to <a href="http://en.wikipedia.org/wiki/World_of_Warcraft" rel="noreferrer"><em>WoW</em></a>). The idea is that if the checksum is invalid then the game client would ignore the link when clicked. Otherwise clicking on the item link in in-game chat would display the stat and attrib for that item.</p> <pre><code>ushort16 CreateChecksum(const string &amp;itemlink) { stringstream parseitemlink(itemlink); uint32 hexform[ITEMLINKGROUPCOUNT] = {0}; uint32 hexsum = 0; //Parse itemLink string into hexform array for (int i = 0; i &lt; ITEMLINKGROUPCOUNT; ++i) parseitemlink &gt;&gt; hex &gt;&gt; hexform[i]; //sum all the itemlink group together for (int i = 0; i &lt; ITEMLINKGROUPCOUNT; ++i) hexsum += hexform[i]; for (int i = 0; i &lt; ITEMLINKGROUPCOUNT; ++i) { uint32 ebx = hexform[i], edi = ebx * i; //if loop iteration is odd store MSB 2-bytes. //Otherwise, store working hexgroup as is untouched if (i &amp; 0x01) ebx = hexform[i] &gt;&gt; 16; // aka same as dividing hexform[i] by 65,536 // (hexform[i] / 65,536) + (hexform[i] * i) + hexsum -- for odd groups // hexform[i] + (hexform[i] * i) + hexsum -- for even groups ebx += edi + hexsum; hexsum = ebx ^ hexform[i]; } for (int i = 0; i &lt; ITEMLINKGROUPCOUNT; ++i) { // the more familiar high-level form would be // hexform[i]^2 + hexform[i] * hexsum uint32 ecx = (hexform[i] + 1) * hexsum, eax = ecx * hexform[i]; eax &gt;&gt;= 16; eax += ecx; hexsum = eax ^ hexform[i]; } //return the lower 2-bytes of hexsum //as the final checksum return hexsum &amp; 0xFFFF; }//CreateChecksum </code></pre> <p>The format of the <code>itemlink</code> is comprised of a group of hexadecimal separated with a space in string format. It's passed into <code>main()</code> as an argument when the program is run.</p> <p>Here's what an <code>itemlink</code>'s hex string might look like:</p> <blockquote> <pre><code>const string EXAMPLELINK = "36c6a 0 3f000a54 d0f1 0 0 0 0 0 0 20d0"; </code></pre> </blockquote> <p>Are there any code smells or readability issues in this code segment? Can any part(s) of it be improved?</p>
[]
[ { "body": "<p>The only things I can see having problems are your acronym variable names i.e. (eax, ecx, ebx, and edi) don't explain what the variables are storing clearly for someone not experienced with doing checksums.</p>\n\n<p>The other thing I can see for readability issues is your all lowercase variable names which are descriptive (ie parseitemlink) should be camelCased so I can tell the different words (ie parseItemLink). That's the only thing I can think of readability wise.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T22:28:41.897", "Id": "26", "ParentId": "22", "Score": "5" } }, { "body": "<p>If you are using the standard library classes of the same name, I would give the following names the correct namespace qualifier: <code>std::string</code>, <code>std::stringstream</code>, <code>std::hex</code>.</p>\n\n<p>In C++, this works just as well, IMHO it's mildy more idiomatic.</p>\n\n<pre><code>uint32 hexform[ITEMLINKGROUPCOUNT] = {};\n</code></pre>\n\n<p><code>ebx</code>, <code>edi</code>, <code>ecx</code>, <code>eax</code> are not good variable names, if you can give them more meaningful names, then do.</p>\n\n<pre><code> uint32 ecx = (hexform[i] + 1) * hexsum,\n eax = ecx * hexform[i];\n</code></pre>\n\n<p>Personally, I think this is clearer:</p>\n\n<pre><code> uint32 ecx = (hexform[i] + 1) * hexsum;\n uint32 eax = ecx * hexform[i];\n</code></pre>\n\n<p>The comment is really bad because it talks about <code>hexform[i]^2 + hexform[i] * hexsum</code> whereas <code>ecx</code> gets the value <code>hexform[i] * hexsum + hexsum</code> and <code>eax</code> gets the value <code>hexform[i]^2 * hexsum + hexform[i] * hexsum</code>. I think the comment needs a pair of parentheses if the code is doing what you meant.</p>\n\n<p>To be robust, you should check whether the parse worked.</p>\n\n<pre><code>parseitemlink &gt;&gt; hex &gt;&gt; hexform[i];\n</code></pre>\n\n<p>You can trivially combine the first two for loops as well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T21:13:40.510", "Id": "978", "Score": "0", "body": "I guess the variable names come from a C++ 'translation' of an assembler routine. So, if you consider the assembler code as being the 'specification' then the names `eax,ecx` etc would be a good choice." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T21:17:35.187", "Id": "979", "Score": "1", "body": "re: namespace qualifiers: If this code is going in a header file, I'd agree. But in a .cpp file, I'd personally prefer to see a `using` statement." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-03T11:23:28.103", "Id": "1010", "Score": "2", "body": "@Roddy: Do you mean a using-declaration or a using-directive? I would be OK with sufficient using-declarations - although for the `std` namespace it seems barely worth it. I think that using-directives are only extremely rarely a good idea." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T22:35:29.030", "Id": "30", "ParentId": "22", "Score": "10" } }, { "body": "<ul>\n<li><p>Function and variable names in C++ are commonly camelCase or snake_case, while uppercase names are for user-defined types.</p>\n\n<p>If <code>ITEMLINKGROUPCOUNT</code> is a variable or a constant, then it should also follow camelCase or snake_case. All-caps naming is commonly used for macros, and the different words should be separated with underscores.</p></li>\n<li><p><code>uint32</code> is not standard C++ nor is it even C (which is <code>uint32_t</code>). Use <code>std::uint32_t</code> from <a href=\"http://en.cppreference.com/w/cpp/types/integer\" rel=\"nofollow noreferrer\"><code>&lt;cstdint&gt;</code></a>. More info about that <a href=\"https://stackoverflow.com/questions/11786113/difference-between-different-integer-types\">here</a> and <a href=\"https://stackoverflow.com/questions/14883896/why-is-stduint32-t-different-from-uint32-t\">here</a>.</p></li>\n<li><p>Instead of this sum loop:</p>\n\n<pre><code>for (int i = 0; i &lt; ITEMLINKGROUPCOUNT; ++i)\n hexsum += hexform[i];\n</code></pre>\n\n<p>use <a href=\"http://en.cppreference.com/w/cpp/algorithm/accumulate\" rel=\"nofollow noreferrer\"><code>std::accumulate</code></a> as a more clean and C++-like alternative:</p>\n\n<pre><code>uint32 hexsum = std::accumulate(hexform, hexform+ITEMLINKGROUPCOUNT, 0);\n</code></pre>\n\n<p>On another note, <code>hexsum</code> should be <em>initialized</em> here as this is where it's first used. Always keep variables as close in scope as possible.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-05T02:04:47.290", "Id": "46344", "ParentId": "22", "Score": "9" } }, { "body": "<p>It seems to me your code currently displays the fact that it was reverse engineered from assembly language a little more than I'd like.</p>\n\n<p>I'd try to rewrite it in a form closer to how you'd normally write C++ instead of basically just translating assembly language into C++ syntax, but retaining most of the assembly language flavor (up to, and still including, using the register names for your variables).</p>\n\n<p>For example, reading the input string and converting from strings to a vector of uint32 could be more like this:</p>\n\n<pre><code>class hex_word {\n uint32 val;\npublic:\n friend std::istream&amp; operator&gt;&gt;(std::istream &amp;is, hex_word &amp;h) { \n return is &gt;&gt; hex &gt;&gt; h;\n }\n operator uint32() { return val; }\n};\n\nstd::vector&lt;uint32&gt; hexform{std::istream_iterator&lt;hex_word&gt;(parseitemlink),\n std::istream_iterator&lt;hex_word&gt;()};\n</code></pre>\n\n<p>The to add those up, you could use <code>std::accumulate</code>:</p>\n\n<pre><code>uint32 hexsum = std::accumulate(hexform, hexform+ITEMLINKGROUPCOUNT, 0);\n</code></pre>\n\n<p>Skipping ahead a little, your last loop could use <code>std::accumulate</code>:</p>\n\n<pre><code>struct f {\n uint32 operator()(uint32 accumulator, uint32 val) {\n uint32 c = (val+1)*accumulator; \n uint32 a = c * val;\n return ((a&gt;&gt;16)+c) ^ accumulator;\n }\n};\n\nreturn std::accumulate(hexform.begin(), hexform.end(), hexsum, f) * 0xffff;\n</code></pre>\n\n<p>I'm not sure this leads to any startling new insights or dramatic simplification of the code, but it still strikes me as rather easier to understand than with all the code mashed together.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-05T03:53:31.883", "Id": "46351", "ParentId": "22", "Score": "7" } } ]
{ "AcceptedAnswerId": "30", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-19T22:02:29.033", "Id": "22", "Score": "20", "Tags": [ "c++", "checksum" ], "Title": "Custom checksum algorithm" }
22
<p>I'm generating CSV strings for various 3rd party utilities and this section of code gets repeated in many classes. Is there a better way to generate this string?</p> <pre><code>public override string CsvString() { return ( string.Format("\u0022{0}\u0022,\u0022{1}\u0022,\u0022{2}\u0022,\u0022{3}\u0022,\u0022{4}\u0022,\u0022{5}\u0022,\u0022{6}\u0022,\u0022{7}\u0022,\u0022{8}\u0022,\u0022{9}\u0022,\u0022{10}\u0022,\u0022{11}\u0022,\u0022{12}\u0022,\u0022{13}\u0022", this.BlockType, // 1, A_NAME this.Tag, // 2, A_TAG this.Description, // 3, A_DESC this.InitialScan, // 4, A_ISCAN this.AutoManual, // 5, A_SCAN this.ScanTime, // 6, A_SCANT this.IoDevice, // 7, A_IODV this.IoAddress, // 8, A_IOAD this.InitialAmStatus, // 9, A_IAM this.AlarmPriority, // 10, A_PRI this.AlarmEnable, // 11, A_ENAB this.EnableOutput, // 12, A_EOUT this.HistDescription, // 13, A_HIST_DESC this.SecurityArea1 // 14, A_SECURITYAREA1 )); } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T23:02:53.407", "Id": "56", "Score": "0", "body": "I would use a StringBuilder if this was for Java. There might be a C# equivalent?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T23:37:37.547", "Id": "64", "Score": "0", "body": "@Jeremy Heiler, There is :) the exact same structure as well I believe" } ]
[ { "body": "<p>Use a <code>StringBuilder</code>:</p>\n\n<pre><code>sbuilder.AppendFormat(\"\\u0022{0}\\u0022,\\u0022{1}\\u0022,\\u0022{2}\\u0022,\\u0022{3}\\u0022,\\u0022{4}\\u0022,\\u0022{5}\\u0022,\\u0022{6}\\u0022,\\u0022{7}\\u0022,\\u0022{8}\\u0022,\\u0022{9}\\u0022,\\u0022{10}\\u0022,\\u0022{11}\\u0022,\\u0022{12}\\u0022,\\u0022{13}\\u0022\",\n this.BlockType, // 1, A_NAME\n this.Tag, // 2, A_TAG\n this.Description, // 3, A_DESC\n this.InitialScan, // 4, A_ISCAN\n this.AutoManual, // 5, A_SCAN\n this.ScanTime, // 6, A_SCANT\n this.IoDevice, // 7, A_IODV\n this.IoAddress, // 8, A_IOAD\n this.InitialAmStatus, // 9, A_IAM\n this.AlarmPriority, // 10, A_PRI\n this.AlarmEnable, // 11, A_ENAB\n this.EnableOutput, // 12, A_EOUT\n this.HistDescription, // 13, A_HIST_DESC\n this.SecurityArea1 // 14, A_SECURITYAREA1\n ).AppendLine();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T23:40:07.167", "Id": "65", "Score": "1", "body": "I wonder if this is what `String.Format` uses under the hood?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T01:36:26.817", "Id": "76", "Score": "1", "body": "Actually string.Format uses StringBuilder inside it (or so Reflector says), so there wouldn't memory/performance benefit in this specific case (one shot formatting of the string)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-19T23:10:42.423", "Id": "39", "ParentId": "36", "Score": "10" } }, { "body": "<p>Maybe something like this:</p>\n\n<pre><code>public static string MakeCsvLine(params string[] items)\n{\n return String.Format(\"\\u0022{0}\\u0022\",String.Join(\"\\u0022,\\u0022\",items));\n}\n</code></pre>\n\n<p>Edit:</p>\n\n<p>On thinking about it might be better to use it to build up a string builder so:</p>\n\n<pre><code>public static void AddCsvLine(StringBuilder sb, params string[] items)\n{\n sb.AppendFormat(\"\\u0022{0}\\u0022\",String.Join(\"\\u0022,\\u0022\",items))\n .AppendLine();\n}\n</code></pre>\n\n<p>This would remove having to have long strings repeated all over the code.\nEdit: Made the funtion return the orginal result.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T04:40:23.470", "Id": "83", "Score": "1", "body": "You'd have to join on `\"\\u0022,\\u0022\"` and then also add \"\\u0022\" at the beginning and end to get the same result as the original." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T11:59:52.940", "Id": "117", "Score": "0", "body": "@sepp2k Your right, I change the code to reflect that" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T03:00:06.093", "Id": "65", "ParentId": "36", "Score": "6" } }, { "body": "<p>I doubt you'll find a way of not listing all those properties without using reflection, but the following helps to eliminate that huge format string which is likely to become the source of bugs.</p>\n\n<pre><code>var properties = new Object[]\n{\n this.BlockType, // 1, A_NAME\n this.Tag, // 2, A_TAG\n this.Description, // 3, A_DESC\n this.InitialScan, // 4, A_ISCAN\n this.AutoManual, // 5, A_SCAN\n this.ScanTime, // 6, A_SCANT\n this.IoDevice, // 7, A_IODV\n this.IoAddress, // 8, A_IOAD\n this.InitialAmStatus, // 9, A_IAM\n this.AlarmPriority, // 10, A_PRI\n this.AlarmEnable, // 11, A_ENAB\n this.EnableOutput, // 12, A_EOUT\n this.HistDescription, // 13, A_HIST_DESC\n this.SecurityArea1 // 14, A_SECURITYAREA1\n}.Select(x =&gt; String.Format(\"\\u0022{0}\\u0022\", x));\n\nreturn String.Join(\",\", properties);\n</code></pre>\n\n<p>A couple of things to note:</p>\n\n<p>This is hardly an efficient way of doing it, but offers fairly maintainable code. If you have an extra property, just add it to the array.</p>\n\n<p>This will only work in .NET 4.0. In earlier versions, you'll have to call <code>ToArray()</code> after that call to <code>Select</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T15:15:50.553", "Id": "141", "Score": "0", "body": "This is a much cleaner method and addresses the error prone format string. This made my life easier." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:30:33.510", "Id": "520", "Score": "2", "body": "If you do `return \"\\u0022\" + String.Join(\"\\u0022,\\u0022\", properties) + \"\\u0022\"`, you can avoid the need for the Select projection altogether." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T07:56:17.143", "Id": "74", "ParentId": "36", "Score": "19" } }, { "body": "<p>As a variant of <a href=\"https://codereview.stackexchange.com/questions/36/is-there-a-better-way-to-build-my-csv-output-than-string-format/74#74\">Alex Humphrey's solution</a>, You could try this for improved performance:</p>\n\n<pre><code>var properties = new Object[]\n{\n this.BlockType, // 1, A_NAME\n this.Tag, // 2, A_TAG\n this.Description, // 3, A_DESC\n this.InitialScan, // 4, A_ISCAN\n this.AutoManual, // 5, A_SCAN\n this.ScanTime, // 6, A_SCANT\n this.IoDevice, // 7, A_IODV\n this.IoAddress, // 8, A_IOAD\n this.InitialAmStatus, // 9, A_IAM\n this.AlarmPriority, // 10, A_PRI\n this.AlarmEnable, // 11, A_ENAB\n this.EnableOutput, // 12, A_EOUT\n this.HistDescription, // 13, A_HIST_DESC\n this.SecurityArea1 // 14, A_SECURITYAREA1\n};\n\nvar builder = new StringBuilder(properties.Length * 6);\nforeach (var property in properties)\n{\n builder.Append('\"').Append(property).Append('\"').Append(',');\n}\nbuilder.Remove(builder.Length - 1, 1); // remove the last comma\n\nreturn builder.ToString();\n</code></pre>\n\n<p>But beware that this code is susceptible for failure if any of the properties contains a double quote. You should make sure they are escaped.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T07:32:57.760", "Id": "5274", "ParentId": "36", "Score": "2" } }, { "body": "<p>in the new versions of C# you can use string interpolation to make it a little easier to code and know where the variables are going to be inserted into the string. all you do is put a $ before the opening quotation mark.</p>\n\n<p>Then the Return becomes this instead</p>\n\n<pre><code>return $\"\\u0022{this.BlockType}\\u0022,\\u0022{this.Tag}\\u0022,\\u0022{this.Description}\\u0022,\\u0022{This.InitialScan}\\u0022,\\u0022{this.AutoManual}\\u0022,\\u0022{this.ScanTime}\\u0022,\\u0022{this.IoDevice}\\u0022,\\u0022{this.IoAddress}\\u0022,\\u0022{this.InitialAmStatus}\\u0022,\\u0022{this.AlarmPriority}\\u0022,\\u0022{this.AlarmEnable}\\u0022,\\u0022{this.EnableOutput}\\u0022,\\u0022{this.HistDescription}\\u0022,\\u0022{this.SecurityArea}\\u0022\";\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-20T19:37:10.850", "Id": "150419", "ParentId": "36", "Score": "1" } } ]
{ "AcceptedAnswerId": "74", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-19T22:56:59.883", "Id": "36", "Score": "23", "Tags": [ "c#", "csv", "strings" ], "Title": "Generating CSV strings for various 3rd party utilities" }
36
<p>A few functions to let me manage TAGS files more easily. Typically, my projects contain at least one sub-folder. I got sick of manually updating, so I wrote this to help me update a single TAGS file per project (always in the projects' root directory).</p> <p>Please share your thoughts (aside from "Why are you using Emacs?", you're not likely to change my mind).</p> <p>One thing I've noticed that could trip me up is that it only tags files of one language (and if I had a project that had both Haskell and JS code, for example, I could tag one or the other). I would particularly appreciate advice on better ways to write find-parent-tags than just building each path from available sub-strings.</p> <pre><code>(defun create-tag-table () "This will recursively tag all files of a given type starting with the current buffers' directory. It overwrites the old TAGS file, if one exists. Haskell files assume you've installed `hasktags`." (interactive) (let ((file-type (get-taggable-extension)) (cur-dir default-directory) (tags-file (find-parent-tags default-directory))) (if (equalp file-type "hs") (shell-command "hasktags --ignore-close-implementation --etags `find . -type f -name \"*.*hs\"`") (shell-command (concat "find -name \"*." file-type "\" -print | etags -"))))) (defun find-parent-tags (dir) "Traverses the directory tree up to /home/[user]/ or / whichever comes first. Returns either nil or the directory containing the first TAGS file it finds." (interactive (list default-directory)) (find-parent-tags-rec (build-tag-paths dir))) (defun find-parent-tags-rec (list-of-filepath) (cond ((null list-of-filepath) nil) ((file-exists-p (car list-of-filepath)) (car list-of-filepath)) (t (find-parent-tags-rec (cdr list-of-filepath))))) (defun build-tag-paths (dir-string) (build-tag-paths-rec (remove-if #'empty-string? (split-string dir-string "/")) (list "/"))) (defun build-tag-paths-rec (steps acc) (if (null steps) (mapcar (lambda (p) (concat p "TAGS")) acc) (build-tag-paths-rec (cdr steps) (cons (concat (car acc) (car steps) "/") acc)))) (defun get-taggable-extension () "Either returns the current file's extension (if it's appropriate) or asks the user to pick one with completion" (let ((b-name (buffer-file-name (current-buffer))) (valid-exts (list "lisp" "py" "c" "hs" "rb" "ss" "scm" "js" "erl" "el"))) (string-match "\\.\\(.*?\\)$" b-name) (let ((current-filetype (match-string 1 b-name))) (if (member current-filetype valid-exts) current-filetype (completing-read "File type: " valid-exts nil 'confirm))))) (defun empty-string? (s) (equalp s "")) (provide 'tagariffic) </code></pre>
[]
[ { "body": "<h3>General notes</h3>\n\n<ul>\n<li>Always prefix your functions with the name of your package or project, e.g. <code>tagariffic-create-tag-table</code> and so on. Emacs has no package scoping.</li>\n<li>Whenever possible (i.e. in the absence of mutual recursion), define your functions before using them. It's a lot clearer for the reader. It's also necessary if you ever define macros.</li>\n<li>You're using some functions from the <code>cl</code> package, so you should start with <code>(require 'cl)</code>.</li>\n<li>The usual style for predicates in Lisp is <code>name-p</code>, not <code>name?</code> (that's Scheme).</li>\n<li>Emacs has functions to manipulate <a href=\"http://www.gnu.org/software/emacs/manual/html_node/elisp/File-Names.html#File-Names\">file and directory names</a>. Use them rather than going around concatenating slashes; this way your code will work on exotic platforms such as Windows.</li>\n</ul>\n\n<h3>Finding the tags file</h3>\n\n<p>Emacs 23 has a function <code>locate-dominating-file</code> (in <code>files.el</code>).</p>\n\n<blockquote>\n <p>Look up the directory hierarchy from <code>FILE</code> for a file named <code>NAME</code>.<br>\n Stop at the first parent directory containing a file <code>NAME</code>,\n and return the directory. Return <code>nil</code> if not found.</p>\n</blockquote>\n\n<p>Your <code>(find-parent-tags default-directory)</code> is almost equivalent to <code>(locate-dominating-file (buffer-file-name) \"TAGS\")</code>. If you want to use the current directory rather than the directory of the current buffer's file (they're almost always the same), use <code>(locate-dominating-file (concat (default-directory) \".\") \"TAGS\")</code>. <code>locate-dominating-file</code> stops at your home directory, too.</p>\n\n<p>The code you posted does nothing with the <code>tags-file</code> variable. Did you mean to run the tag generation command in that directory, or failing that in the current directory? If so, this should do it:</p>\n\n<pre><code>(let ((default-directory (if tags-file (file-name-directory tags-file) default-directory)))\n (shell-command …))\n</code></pre>\n\n<h3>From file type to shell commands</h3>\n\n<p>Rather than build in an exception for Haskell, the usual style would be to define an <a href=\"http://www.gnu.org/software/emacs/manual/html_node/elisp/Association-List-Type.html#Association-List-Type\">alist</a> from extensions to commands.</p>\n\n<pre><code>(defvar tagariffic-command-alist\n '((\"hs\" . \"… hasktags …\")\n (t . \"… etags …\")))\n</code></pre>\n\n<p>However, there's a better approach than separate commands for each type; see below.</p>\n\n<h3>The shell commands</h3>\n\n<p>Your <code>hasktags</code> command will choke on file or directory names that contain shell special characters: <code>\\[?*</code> and whitespace. This isn't very common in source trees, but it could happen. Generally speaking, never use command substitution to generate a list of file names. Instead, let <code>find</code> call the command.</p>\n\n<pre><code>find . -type f -name '*.hs' -exec hasktags --ignore-close-implementation --etags {} +\n</code></pre>\n\n<p>A second problem is that if there are too many files, the command you wrote will die of a command line too long error; the one I just showed will run <code>hasktags</code> several times with command lines of a permitted size, causing the tag file to be overwritten. As a workaround, start by creating an empty tags file and tell <code>hasktags</code> to append to the tags file.</p>\n\n<pre><code>: &gt;TAGS\nfind . -type f -name '*.hs' -exec hasktags --ignore-close-implementation -e -a {} +\n</code></pre>\n\n<p>An improvement to the <code>find</code> commands would be to ignore certain directories belonging to version control systems. Especially with svn, this could speed things up.</p>\n\n<pre><code>find . -type d \\( -name .bzr -o -name .git -o -name .hg -o -name .svn -o -name CVS -o -name _darcs \\) -prune -o \\\n -type f …\n</code></pre>\n\n<p>Above I mentioned a different approach to choosing the tag generation command. Your approach assumes that a given project will be in a single language. It's easy enough to cater for mixed-language projects: build a single tags file containing the output generated by <code>etags</code> and <code>hasktags</code>.</p>\n\n<pre><code>: &gt;TAGS\nfind . -type d \\( -name .bzr -o … \\) -prune -o \\\n -type f -name '*.hs' -exec hasktags -e -a {} + -o \\\n -type f \\( -name '*.[CScls]' -o -name '*.el' -o … \\) -exec etags {} +\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-16T22:29:51.700", "Id": "115253", "Score": "0", "body": "FWIW - a detail: I disagree with *define your functions before you use them*. Sometimes that is good practice, sometimes not. Sometimes things are more readable top-down, with the detailed utility functions defined after the high-level ones. IOW, master-detail order. And this is more the case in a declarative (e.g. functional, logic) language. [It is of course the case that sometimes definition order is imposed, as for macros, as you pointed out.]" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T23:26:27.180", "Id": "3633", "ParentId": "45", "Score": "6" } } ]
{ "AcceptedAnswerId": "3633", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T00:10:13.883", "Id": "45", "Score": "16", "Tags": [ "elisp" ], "Title": "Emacs Etags Shortcut Functions" }
45
<p>This shows a test case for an old caching library that I use for a project. It features simple save/load/delete functions (sadly static calls) but what I want to focus on is the test code written for this class.</p> <p>In my opinion the unit tests for a class should show how all functions in the class work and what to <em>expect</em> from that class.</p> <p>Recently we got this great change to show off code, so I'd like to ask you if you can read that test code, understand what the class might do and how you would improve upon it.</p> <pre><code>&lt;?php class DatenCacheTest extends PHPUnit_Framework_TestCase { function testNothingFound() { $this-&gt;assertSame(false, DatenCache::load("testNotHereCache")); } function testSaveLoadSimple() { $sDatenSimple = "testStringSaveLoadSimple"; $sDatenSimpleParam = "testStringParam"; $sDatenSimpleParam2 = "testStringParam2"; $sDatenSimpleParam3 = ""; $sDatenSimpleParam4 = 0; $this-&gt;assertSame(true, DatenCache::save("testCacheSimple", false, $sDatenSimple)); $this-&gt;assertSame($sDatenSimple, DatenCache::load("testCacheSimple", false)); $this-&gt;assertSame(true, DatenCache::save("testCacheLinearParam", "string", $sDatenSimpleParam)); $this-&gt;assertSame($sDatenSimpleParam, DatenCache::load("testCacheLinearParam", "string")); $this-&gt;assertSame(true, DatenCache::save("testCacheLinearParam", 5, $sDatenSimpleParam2)); $this-&gt;assertSame($sDatenSimpleParam2, DatenCache::load("testCacheLinearParam", 5)); $this-&gt;assertSame(true, DatenCache::save("testCacheBoundStringParam", false, $sDatenSimpleParam3)); $this-&gt;assertSame($sDatenSimpleParam3, DatenCache::load("testCacheBoundStringParam", false)); $this-&gt;assertSame(true, DatenCache::save("testCacheBoundIntParam", false, $sDatenSimpleParam4)); $this-&gt;assertSame($sDatenSimpleParam4, DatenCache::load("testCacheBoundIntParam", false)); $oObj = new stdClass(); $oObj-&gt;bob = 2; $this-&gt;assertSame(true, DatenCache::save("testCacheBoundObjParam", $oObj, "zwei")); $this-&gt;assertSame("zwei", DatenCache::load("testCacheBoundObjParam", $oObj)); } function testSaveLoadArray() { $aDaten = array("da" =&gt; "ten", array("ten" =&gt; "da"), "Striche" =&gt; "' \";s:5:", "h''uh" =&gt; "mep", "\\mep\\" =&gt; "^^", "Zeilenumbruch" =&gt; "\n", "Zeug" =&gt; "::}}{:", "'" =&gt; '"', '"' =&gt; "'"); $this-&gt;assertSame(true, DatenCache::save("testCacheArray", false, $aDaten)); $this-&gt;assertSame($aDaten, DatenCache::load("testCacheArray", false)); } function testSaveLoadExpired() { $this-&gt;assertSame(true, DatenCache::save("testCacheExpired", false, "testStringLoadExpired", "-1 seconds")); $this-&gt;assertSame(false, DatenCache::load("testCacheExpired", false)); } function testSaveLoadObject() { $oObj = new stdClass(); $oObj-&gt;bob = 2; $this-&gt;assertSame(true, DatenCache::save("testCacheBoundIntParam", false, $oObj)); $oNewObj = DatenCache::load("testCacheBoundIntParam", false); $this-&gt;assertEquals($oObj, $oNewObj); $this-&gt;assertSame($oObj-&gt;bob, $oNewObj-&gt;bob); } function testSaveLoadComplexParam() { $aKonfigEins = array(DatenCache::ANLAGEN_ID() =&gt; 1, DatenCache::SESSION_ID() =&gt; "id1"); $aKonfigZwei = array(DatenCache::ANLAGEN_ID() =&gt; 1, DatenCache::SESSION_ID() =&gt; "id2"); $aKonfigDrei = array(DatenCache::ANLAGEN_ID() =&gt; 1, DatenCache::SESSION_ID() =&gt; "id3"); $aKonfigVier = array(DatenCache::ANLAGEN_ID() =&gt; 1); $aKonfigFuenf = array(DatenCache::SESSION_ID() =&gt; "id3"); $aKonfigSechs = array(DatenCache::ANLAGEN_ID() =&gt; 1, DatenCache::SESSION_ID() =&gt; "id3", DatenCache::PERSON_ID() =&gt; 1); $this-&gt;assertSame(true, DatenCache::save("testCacheComplexParam", $aKonfigEins, "v1")); $this-&gt;assertSame("v1", DatenCache::load("testCacheComplexParam", $aKonfigEins)); $this-&gt;assertSame(true, DatenCache::save("testCacheComplexParam", $aKonfigZwei, "v2")); $this-&gt;assertSame("v2", DatenCache::load("testCacheComplexParam", $aKonfigZwei)); $this-&gt;assertSame(false, DatenCache::load("testCacheComplexParam", $aKonfigDrei)); $this-&gt;assertSame(false, DatenCache::load("testCacheComplexParam", $aKonfigVier)); $this-&gt;assertSame(false, DatenCache::load("testCacheComplexParam", $aKonfigFuenf)); $this-&gt;assertSame(false, DatenCache::load("testCacheComplexParam", $aKonfigSechs)); } function testInvalidate() { $this-&gt;assertSame(true, DatenCache::save("testCacheSimple", false, "testStringInvalidate")); DatenCache::invalidate("testCacheSimple"); $this-&gt;assertSame(false, DatenCache::load("testCacheSimple", false)); } function testInvalidateWithParams() { $sTestStringEins = "testStringInvalidateWithParams"; $sTestStringZwei = "testStringInvalidateWithParamsZwei"; $aKonfigEins = array(DatenCache::ANLAGEN_ID() =&gt; 1, "Pony" =&gt; false); $aKonfigZwei = array(DatenCache::ANLAGEN_ID() =&gt; 1, "Pony" =&gt; true); $this-&gt;assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigEins, $sTestStringEins)); $this-&gt;assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigZwei, $sTestStringEins)); DatenCache::invalidate("testCacheInvalidateWithParams", $aKonfigEins); $this-&gt;assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigEins)); $this-&gt;assertSame($sTestStringEins, DatenCache::load("testCacheInvalidateWithParams", $aKonfigZwei)); $aKonfigDrei = array(DatenCache::ANLAGEN_ID() =&gt; 1, DatenCache::BENUTZER_ID() =&gt; 123, "bob" =&gt; "please"); $aKonfigVier = array(DatenCache::ANLAGEN_ID() =&gt; 2, "Pony" =&gt; true, "bob" =&gt; "please"); $aPartEins = array(DatenCache::ANLAGEN_ID() =&gt; 1); $aPartZwei = array(DatenCache::BENUTZER_ID() =&gt; 123); $aPartDrei = array("bob" =&gt; "please"); $this-&gt;assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigDrei, $sTestStringZwei."1")); DatenCache::invalidate("testCacheInvalidateWithParams", $aPartEins); $this-&gt;assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigDrei)); $this-&gt;assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigDrei, $sTestStringZwei."2")); DatenCache::invalidate("testCacheInvalidateWithParams", $aPartZwei); $this-&gt;assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigDrei)); $this-&gt;assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigDrei, $sTestStringZwei."3")); DatenCache::invalidate("testCacheInvalidateWithParams", $aPartDrei); $this-&gt;assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigDrei)); $this-&gt;assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigEins, $sTestStringEins)); $this-&gt;assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigZwei, $sTestStringEins)); $this-&gt;assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigDrei, $sTestStringEins)); DatenCache::invalidate("testCacheInvalidateWithParams", array(DatenCache::ANLAGEN_ID() =&gt; 1)); $this-&gt;assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigEins)); $this-&gt;assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigZwei)); $this-&gt;assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigDrei)); $this-&gt;assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigEins, $sTestStringEins)); $this-&gt;assertSame(true, DatenCache::save("testCacheInvalidateWithParams", $aKonfigVier, $sTestStringEins)); DatenCache::invalidate("testCacheInvalidateWithParams", array(DatenCache::ANLAGEN_ID() =&gt; 1)); $this-&gt;assertSame(false, DatenCache::load("testCacheInvalidateWithParams", $aKonfigEins)); $this-&gt;assertSame($sTestStringEins, DatenCache::load("testCacheInvalidateWithParams", $aKonfigVier)); } function testCleanup() { $this-&gt;assertSame(true, DatenCache::save("testCacheSimple", false, "testString", "-5 seconds")); $this-&gt;assertSame(true, DatenCache::save("testCacheSimpleBleibt", false, "testString", "+30 seconds")); DatenCache::cleanup(); $this-&gt;assertSame("testString", DatenCache::load("testCacheSimpleBleibt", false)); $this-&gt;assertSame(false, DatenCache::load("testCacheSimple", false)); // Direkt auf der DB Prüfen ob der Datensatz wiklich gelöscht wurde und nicht nur ausgelaufen ist $this-&gt;assertSame( array(), McDb::getConnection(DB_MC_CACHES)-&gt;getRow( "SELECT * FROM mc_caches.T_DATEN_CACHE WHERE PARAMETER = ? AND VALUE = ?", "NAME", "testCacheSimple" ) ); } function testCleanupWithParam() { $aKonfig = array(DatenCache::ANLAGEN_ID() =&gt; 1); $this-&gt;assertSame(true, DatenCache::save("testCacheSimple", $aKonfig, "testString", "+120 seconds")); DatenCache::cleanup(); $this-&gt;assertSame("testString", DatenCache::load("testCacheSimple", $aKonfig)); } function testInvalidateByParam() { $mValue1 = 1; $mValue2 = 2; $aKonfigEins = array(DatenCache::ANLAGEN_ID() =&gt; $mValue1); $aKonfigZwei = array(DatenCache::ANLAGEN_ID() =&gt; $mValue2); $this-&gt;assertSame(true, DatenCache::save("testCacheInvalidateByParam", $aKonfigEins, "testString")); $this-&gt;assertSame(true, DatenCache::save("testCacheInvalidateByParam2", $aKonfigZwei, "testString2")); DatenCache::invalidateByParam(DatenCache::ANLAGEN_ID()); $this-&gt;assertSame(false, DatenCache::load("testCacheInvalidateByParam", $aKonfigEins)); $this-&gt;assertSame(false, DatenCache::load("testCacheInvalidateByParam2", $aKonfigZwei)); $this-&gt;assertSame(true, DatenCache::save("testCacheSimple", $aKonfigEins, "testString")); $this-&gt;assertSame(true, DatenCache::save("testCacheSimple2", $aKonfigZwei, "testString2")); DatenCache::invalidateByParam(DatenCache::ANLAGEN_ID(), $mValue1); $this-&gt;assertSame(false, DatenCache::load("testCacheSimple", $aKonfigEins)); $this-&gt;assertSame("testString2", DatenCache::load("testCacheSimple2", $aKonfigZwei)); } function testInvalidateByParamLike() { $mValue1 = "I wan't a Pony"; $mValue2 = "No Pony for you !"; $mValue3 = "xxx"; $this-&gt;assertSame(true, DatenCache::save("PonyCache", array("PonyParam" =&gt; $mValue1), "test1")); $this-&gt;assertSame(true, DatenCache::save("PonyCache", array("PonyParam" =&gt; $mValue2), "test2")); $this-&gt;assertSame(true, DatenCache::save("PonyCache", array("PonyParam" =&gt; $mValue3), "test3")); DatenCache::invalidateByParam("PonyParam", "%Pony%", true); $this-&gt;assertSame(false, DatenCache::load("PonyCache", array("PonyParam" =&gt; $mValue1))); $this-&gt;assertSame(false, DatenCache::load("PonyCache", array("PonyParam" =&gt; $mValue2))); $this-&gt;assertSame("test3", DatenCache::load("PonyCache", array("PonyParam" =&gt; $mValue3))); } /** * @expectedException PHPUnit_Framework_Error */ function testInvalidSaveTime() { $this-&gt;assertSame(false, DatenCache::save("testFail", null, "test1", "invalidStrtotime")); } function testInvalidSaveTimeReturn() { $this-&gt;assertSame(false, @DatenCache::save("testFail", null, "test1", "invalidStrtotime")); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T19:19:00.860", "Id": "162", "Score": "0", "body": "This looks like the long-code-questions version of Stack Overflow" } ]
[ { "body": "<p>I lack the syntax knowledge to say I understand the class. I can say reading it is a bit hard due to long lines and the fact that the dominant patterns are repetitive method/variable names. Test names are descriptive enough </p>\n\n<p>Maybe if you could extract methods like <code>DatenCache::load</code> to <code>Dload</code> and <code>$this-&gt;assertSame</code> to <code>aSame</code> it would get less busy. Or make an utility function, since you're asserting equality on booleans (so <code>assertTrue</code> and <code>assertFalse</code> could make it clearer). Where possible, constructing more arrays outside the calls could also help. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T01:29:45.003", "Id": "54", "ParentId": "47", "Score": "3" } }, { "body": "<p>Other than long lines, I'm not seeing something too unreadable. I don't advise shortening function names as doing so makes it less clear what the function is doing. Instead, try splitting the function calls being passed as parameters onto different lines by either splitting the line across multiple lines or storing the returned value as a variable and passing that variable in.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T02:40:02.943", "Id": "62", "ParentId": "47", "Score": "7" } }, { "body": "<p>You should provide the optional string message as last argument for assertion calls; turn this:</p>\n\n<pre><code>$this-&gt;assertSame(true, DatenCache::save(\"testCacheSimple\", false, $sDatenSimple));\n</code></pre>\n\n<p>Into this:</p>\n\n<pre><code>$this-&gt;assertSame(\n true,\n DatenCache::save(\"testCacheSimple\", false, $sDatenSimple),\n \"a successful [describe operation] \".\n \"is expected for [describe arguments]\");\n</code></pre>\n\n<p>This form reminds me of Perl instructions do something or die \"message\", and I use the indentation, keeping the message alone, right-aligned, on a separate line when needed, to put it in perspective:</p>\n\n<pre><code>assert( something, \"something expected\");\nassert( something else, \"something else expected\");\nassert( something long\n that spans multiple lines,\n \"something long \".\n \"that spans multiple lines expected\");\n</code></pre>\n\n<p>In this way, all the messages get aligned on the right, and can be read separately.</p>\n\n<p>Also, you should use the most specific assertion available instead of using assertSame() all the time. When comparing with true, using assertTrue() instead would clarify the intent.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T10:32:13.810", "Id": "155", "ParentId": "47", "Score": "7" } }, { "body": "<p>IMHO, much like when writing a class a single method should do one thing and do that one thing well.</p>\n\n<p>You should be doing less assertions per function in your test class, <strong>preferably 1 assertion per function</strong>.</p>\n\n<p>As a general rule the least lines of code in a test function the better the test.</p>\n\n<p>This way you can document a test of a usage example for each function and assertion pair and in effect you will be creating usage documentation for the class under test.</p>\n\n<p>Edit: I just noticed after another look at your test that you are testing two functions in alot of the tests (load and save). These should be tested individually as one may affect the other and may produce unpredictable results.</p>\n\n<p><strong>Simple = Robust</strong></p>\n\n<p>I obviously don't know the class under test but i suspect you should be writing tests similar to below. Isolating the methods being tested and breaking the tests into smaller units. Hopefully this will help you.</p>\n\n<pre><code>&lt;?php\n// Instead of $this-&gt;assertSame() use $this-&gt;assertTrue() when testing for true.\n// much easier to see what outcome is needed from test.\n\nclass DatenCacheTest extends PHPUnit_Framework_TestCase {\n\nfunction setup(){\n // runs before every test like __construct() in a class.\n $this-&gt;str = 'testString';\n}\n\nfunction tearDown(){\n // runs after every test like __destruct() in a class.\n}\n\nfunction testSaveSimple(){\n $this-&gt;assertTrue( DatenCache::save(\"testCacheSimple\", false, $this-&gt;str) );\n}\n\nfunction testSaveLinearParam(){\n $this-&gt;assertTrue( DatenCache::save(\"testCacheLinearParam\", \"string\", $this-&gt;str) );\n}\n\nfunction testSaveBoundObjParam(){\n $oObj = new stdClass();\n $oObj-&gt;bob = 2;\n $this-&gt;assertTrue( DatenCache::save(\"testCacheBoundObjParam\", $oObj, \"zwei\") );\n}\n// complete tests for all aspects of DatenCache::save()\n\n// Test DatenCache::load() because DatenCache::save() has been tested.\nfunction testLoadSimple(){\n DatenCache::save(\"testCacheSimple\", false, $this-&gt;str);\n $this-&gt;assertSame( $this-&gt;str, DatenCache::load($this-&gt;str, false) );\n}\n\nfunction testLoadNoCache(){\n $this-&gt;assertFalse( DatenCache::load(\"testNoCache\") );\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T03:26:02.510", "Id": "13502", "Score": "0", "body": "I agree with this. Also you can use @covers in the docblocks to ensure that your test coverage is not over-estimated and that each test covers only the method it is trying to test." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-04T19:35:14.483", "Id": "4586", "ParentId": "47", "Score": "6" } } ]
{ "AcceptedAnswerId": "62", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-20T00:42:35.173", "Id": "47", "Score": "12", "Tags": [ "php", "unit-testing", "cache" ], "Title": "Test case for a caching library" }
47
<p>I am currently developing a custom CMS being built on top of Codeigniter and was wondering if you can spot any flaws in my page fetching model code. The page fetching model is not entirely complete but the main functionality for retrieving a page is done, as well as retrieving modules assigned to a page (a module is really just a widget).</p> <p>Can this model be better in some parts, perhaps in relation to the joins I am doing? although not really joins, but multiple queries to pull out bits of related info the pages like modules and media.</p> <pre><code>&lt;?php class Mpages extends CI_Model { public function __construct() { parent::__construct(); } public function fetch_page($page_slug = 'home') { $db = $this-&gt;db; $query = $db -&gt;where('page_status', 1) -&gt;where('page_slug', strtolower($page_slug)) -&gt;get('pages') -&gt;result_array(); $page_id = $query[0]['id']; $query['modules'] = $db -&gt;select('modules.module_name, modules.module_slug, modules.id moduleid') -&gt;where('page_id', $page_id) -&gt;join('pages_modules lpm', 'moduleid = lpm.module_id') -&gt;order_by('module_order', 'asc') -&gt;get('modules') -&gt;result_array(); /*$query['media'] = $db -&gt;select('lucifer_media.media_file_name, lucifer_media.media_file_extension, lucifer_media.media_directory') -&gt;join('lucifer_pages_media', 'lucifer_pages_media.page_id = '.$page_id.'') -&gt;get('lucifer_media') -&gt;result_array();*/ if ($query) { return $query; } else { return false; } } public function fetch_navigation() { $result = $this-&gt;db-&gt;order_by("nav_order", "asc")-&gt;where('published', 1)-&gt;get('navigation')-&gt;result_array(); return $result; } public function fetch_layout($id) { $result = $this-&gt;db-&gt;where('id', $id)-&gt;get('layouts')-&gt;result_array(); return $result[0]; } } ?&gt; </code></pre>
[]
[ { "body": "<p>I don't know Codeigniter so i can't comment on \"is this a propper model\". For my answer i'm just going to assume it is.</p>\n\n<p>It's not much code so i'm going to focus on some details: </p>\n\n<hr>\n\n<pre><code> public function __construct()\n {\n parent::__construct();\n }\n</code></pre>\n\n<p>Those 5 lines do absolutely nothing. I'd remove them. If you need a constructor later, add it later.</p>\n\n<hr>\n\n<pre><code> public function fetch_navigation()\n {\n $result = $this-&gt;db-&gt;order_by(\"nav_order\", \"asc\")-&gt;where('published', 1)-&gt;get('navigation')-&gt;result_array();\n return $result;\n }\n</code></pre>\n\n<p>This is a pretty hard to read (113 Chars in that line). I'd go for something like this (to say with your formatting from above)</p>\n\n<pre><code> public function fetch_navigation()\n {\n return $this-&gt;db\n -&gt;order_by(\"nav_order\", \"asc\")\n -&gt;where('published', 1)\n -&gt;get('navigation')\n -&gt;result_array();\n }\n</code></pre>\n\n<hr>\n\n<pre><code>$db = $this-&gt;db;\n</code></pre>\n\n<p>Seems unnecessary to create a local variable, those 6 extra chars shoudn't hurt. I needed to look twice to see where that variable is from and if its local because changes are made to it.</p>\n\n<hr>\n\n<p>So far those are really minor notes.</p>\n\n<h2>Unreachable code ?</h2>\n\n<pre><code>if ($query) {\n return $query;\n} else {\n return false;\n}\n</code></pre>\n\n<p>you are setting <code>$query['modules'] = ...</code> so even if that is null $query will at least contain</p>\n\n<pre><code>array(\"modules\" =&gt; null); \n</code></pre>\n\n<p>and that will always be true.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T03:56:21.497", "Id": "81", "Score": "0", "body": "I appreciate you taking the time and effort to post a solution. As for the constructor, you need that to interface with the parent controller of the Codeigniter framework, otherwise I do believe you can't use pre-loaded libraries, models and other things loaded automatically in the core. Valid point about $this->db though. I've always done that, but have also wondered if assigning it to a $db variable was worth the extra effort and convoluted things. Thanks for the modules null tip as well." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T09:16:26.177", "Id": "95", "Score": "0", "body": "Erm, `$db =& $this->db;` would be more beneficial would it not?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T10:03:55.910", "Id": "97", "Score": "0", "body": "@RobertPitt Doing thats might be even harmful. Objects are passed \"as reference\" anyways and are hurtful php in general. There are only some very special cases where there is -any- benefit in using them" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T10:05:20.153", "Id": "98", "Score": "0", "body": "@Dwayne If you just leave the lines out the constructor of the parent class will be called by php. The only thing that you shoudn't to is leave it completely empty (thats also why i don't like \"always having an constructor\" someone might leave it blank and break stuff" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T10:20:23.257", "Id": "100", "Score": "0", "body": "@edorian, I believe that objects are only passed by reference as of PHP 5.2.0, as Codeigniter are sticking with the support of PHP 4 within CI 2.0, I think I was just sticking with the application standards in suggesting that." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T10:24:06.767", "Id": "102", "Score": "2", "body": "@RobertPitt Juding from http://www.php.net/manual/en/language.oop5.references.php this happed with the PHP 5.0 release - I don't have access quick to an really old 5.1.6 to test it but i'm pretty sure :) If not please let me know" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T11:36:16.800", "Id": "108", "Score": "0", "body": "My apologies, i had got that information from a comment on the php site, so i had taken it was specifically that release, after readong some Zend papers i can see that it was part of the big release in 5.0. +1" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T11:46:36.930", "Id": "114", "Score": "0", "body": "Great info guys, really insightful stuff. I ditched assigning the $this->db to a $db variable, didn't seem worth it to be honest. I want to keep my code as clean and efficient as possible." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T12:19:49.443", "Id": "124", "Score": "0", "body": "@Dwayne, Keeping code clean starts here: http://framework.zend.com/manual/en/coding-standard.coding-style.html" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T23:19:30.210", "Id": "170", "Score": "0", "body": "Thanks for the link Robert. I know of the Zend standard of coding style and conventions because I have to use it at work unfortunately. Here is the link to the Codeigniter style documentation, not as long, but still concise: http://codeigniter.com/user_guide/general/styleguide.html" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T02:34:27.033", "Id": "61", "ParentId": "48", "Score": "4" } }, { "body": "<p>aaaah, a CodeIgniter fella :-)</p>\n\n<p>I'm just working on a CI project myself and already implemented some of the <strong>optimization</strong> you could use for your CMS as well... so let's have a look:</p>\n\n<ol>\n<li><p>for as little <strong>overhead</strong> as possible, try implementing <strong>lazy-loading</strong> of your files (libraries, models...)</p></li>\n<li><p>for <strong>caching</strong> purposes, you can use KHCache - a library that allows you to cache parts of the website instead of full page</p></li>\n<li><p>instead of always doing $this->db->..., you can create a <strong>helper function</strong>, for instance \"function _db()\" and then simply do _db()->where...</p></li>\n<li><p>also, you can optionally create a helper function to give you the <strong>results array</strong> automatically, so ->result_array() will not be neccessary anymore: function res() {} ... $query = res(_db()->where...);</p></li>\n</ol>\n\n<hr>\n\n<p>now, for the <strong>code</strong> :-)</p>\n\n<pre><code>$query = \n $db\n -&gt;where('page_status', 1)\n -&gt;where('page_slug', strtolower($page_slug))\n -&gt;get('pages')\n -&gt;result_array();\n\n$page_id = $query[0]['id'];\n</code></pre>\n\n<p>here, you seem to be selecting <strong>all values from DB</strong>, while in need of a single first ID - try limiting number of results or this will create overhead in your database</p>\n\n<pre><code>$db-&gt;where...-&gt;limit(1);\n</code></pre>\n\n<hr>\n\n<p>the second query could probably use a <strong>LEFT JOIN</strong> instead of a regular JOIN, although I leave it to you to decide (the JOIN approach might not list everything you need)</p>\n\n<pre><code>$db-select...-&gt;join('pages_modules lpm', 'moduleid = lpm.module_id', 'left')\n</code></pre>\n\n<hr>\n\n<p>I guess that's all... just remember to put correct <strong>indexes</strong> on your SQL fields and use the <strong>EXPLAIN</strong> statement to check for bottlenecks</p>\n\n<p><em><strong>good luck!</em></strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:43:12.693", "Id": "457", "Score": "0", "body": "and since I can't post links in answers due to low rating, here they are - lazy load: http://codeigniter.com/forums/viewthread/134605/" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:43:47.763", "Id": "458", "Score": "0", "body": "you can find KHCache here: http://codeigniter.com/forums/viewthread/69843/" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:45:12.097", "Id": "459", "Score": "0", "body": "and at last, EXPLAIN statement from MySQL manual: http://dev.mysql.com/doc/refman/5.0/en/explain.html ... I'd be delighted if you accepted this answer if you found it useful, so I can get rid of these link limitations :-D" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T12:15:24.210", "Id": "667", "Score": "0", "body": "instead of a helper function why not `$db =& $this->db` and then do `$db->select()...`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T13:34:10.913", "Id": "671", "Score": "0", "body": "Robert - to save time... _db()->select is quicker and requires only 1 line of code, while as with your solution, you need to write more of the same code every time (which could also change in the future, so you'd need to do extensive search/replaces in all files)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:41:24.583", "Id": "289", "ParentId": "48", "Score": "4" } } ]
{ "AcceptedAnswerId": "289", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T00:51:36.533", "Id": "48", "Score": "7", "Tags": [ "php", "codeigniter", "mvc" ], "Title": "Critique My Codeigniter Custom CMS Pages Model" }
48
<p>Here's my <code>bootstrap.php</code> for my PHP/MySQL/Doctrine app. It's my first PHP app so I'm interested in learning from the experience of others how this could be improved - security-wise, performance-wise, or otherwise.</p> <pre><code>//------------------------------------------------------------------------- // Define global constants define('ROOT_PATH', dirname(__FILE__) . '/'); define('URL_BASE', 'http://localhost/myapp/public/'); define('LIB_PATH', 'C:\\wamp\\www\\lib\\'); define('OPENID_PATH', 'C:\\wamp\www\\lib\\lightopenid.git\\openid.php'); //------------------------------------------------------------------------- // Bootstrap Doctrine.php, register autoloader, specify // configuration attributes and load models. require_once(LIB_PATH . 'doctrine12/lib/Doctrine.php'); spl_autoload_register(array('Doctrine', 'autoload')); $manager = Doctrine_Manager::getInstance(); //------------------------------------------------------------------------- // Define database connection $dsn = 'mysql:dbname=mydb;host=127.0.0.1'; $user = 'xxx'; $password = 'yyy'; $dbh = new PDO($dsn, $user, $password); $conn = Doctrine_Manager::connection($dbh); //------------------------------------------------------------------------- // Set defaults $manager-&gt;setAttribute(Doctrine::ATTR_DEFAULT_COLUMN_OPTIONS, array('type' =&gt; 'string', 'length' =&gt; 255, 'notnull' =&gt; true)); $conn-&gt;setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true); $manager-&gt;setAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE, true); // Don't load a model until it's needed (causes problems when this is on) //$manager-&gt;setAttribute(Doctrine_Core::ATTR_MODEL_LOADING, Doctrine_Core::MODEL_LOADING_CONSERVATIVE); //------------------------------------------------------------------------- // Import model objects Doctrine_Core::loadModels(ROOT_PATH . 'app/models/generated'); // have to load base classes first Doctrine_Core::loadModels(ROOT_PATH . 'app/models'); </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T01:30:57.793", "Id": "73", "Score": "0", "body": "How different is this from the default template? Can you link to it?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T03:30:06.800", "Id": "80", "Score": "0", "body": "@TryPyPy: http://www.doctrine-project.org/projects/orm/1.2/docs/manual/getting-started%3Aimplementing%3Abootstrap-file/en" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-13T23:26:23.510", "Id": "496526", "Score": "0", "body": "@ZoranJankov I have rejected your suggested edit because it does not improve the quality of the title. A title must uniquely describe what the script does -- not what it is & what it is comprised of." } ]
[ { "body": "<p>Here are a few lines that might be useful to add if you would like to use these options:</p>\n\n<pre><code>/**\n * Needed for SoftDelete to work\n */\n$manager-&gt;setAttribute(Doctrine::ATTR_USE_DQL_CALLBACKS, true);\n\n/**\n * Tell doctrine to look for custom ___Table classes in the models folder\n */\n$manager-&gt;setAttribute(Doctrine::ATTR_AUTOLOAD_TABLE_CLASSES, true);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-20T01:48:02.827", "Id": "55", "ParentId": "49", "Score": "7" } }, { "body": "<p>where you state <strong>Define global constants</strong> your not defining your directories with the correct slashes for the Operating system</p>\n\n<p>You can use <code>/</code> slashes fluently on your application as both unix and windows supports them but if you really want to be on the safe side then you should use <code>DIRECTORY_SEPARATOR</code></p>\n\n<p>As Doctrine 2.0 is only supporting PHP 5.3.0 you can replace <code>dirname(__FILE__)</code> with <code>__DIR__</code></p>\n\n<p>I would also create a constant called <code>DS</code> which would normally be created in a constants file, and should be one of the first included.</p>\n\n<p>I would convert the above to:</p>\n\n<pre><code> define('ROOT_PATH' , __DIR__);\n define('URL_BASE' , 'http://localhost/myapp/public/');\n define('LIB_PATH' , realpath(\"../../path/to/libs\")); //Unix / Windows\n define('OPENID_PATH', realpath(\"../../path/to/openid\"));//Unix / Windows\n</code></pre>\n\n<p>And then change the <code>loadModels</code> accordingly?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T15:10:13.040", "Id": "675", "Score": "0", "body": "Excellent information, thanks! Just one point of clarification - you never stated what the `DS` constant is or where you would use it." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T15:50:28.310", "Id": "676", "Score": "1", "body": "sorry, the `DS` Constants is a shortor version for `DIRECTORY_SEPARATOR` and you would then build your paths like so: `LIB_ROOT . DS . \"openid\" . DS . \"openid.class.php\"` to save line space." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T14:48:29.900", "Id": "414", "ParentId": "49", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T00:52:25.113", "Id": "49", "Score": "6", "Tags": [ "php", "mysql", "doctrine" ], "Title": "PHP/Doctrine bootstrap for review" }
49
<p>I'm making a "guess that tune" game in Visual Basic 6 that is supposed to play each song in a random order:</p> <pre><code>' from frmGuessGame.frm Private Sub Swap(ByRef Value1 As Variant, ByRef Value2 As Variant) Dim Temporary As Variant Temporary = Value1 Value1 = Value2 Value2 = Temporary End Sub Private Sub ShuffleList() Dim LoopCtr As Integer, SwapWith As Integer For LoopCtr = LBound(InnerPlaylist) To UBound(InnerPlaylist) SwapWith = (Rnd * (UBound(InnerPlaylist) - LBound(InnerPlaylist))) + LBound(InnerPlaylist) Swap InnerPlaylist(LoopCtr), InnerPlaylist(SwapWith) Next End Sub </code></pre> <p>My initialization function does include the <code>Randomize</code> statement, so it should be a good, even shuffle.</p> <pre><code>' from mdiMain.frm Private Sub MDIForm_Load() 'initialize pseudo-random number generator Randomize frmMusiguess.Show frmSplash.Show End Sub </code></pre> <p>I'm not sure, however, that this is the best way to do it. Am I on the right track?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T00:55:48.870", "Id": "70", "Score": "0", "body": "Aside: [My question from the proposal](http://area51.stackexchange.com/proposals/11464/code-review/25308#25308). I actually wrote this code years ago (2004) before I knew any better." } ]
[ { "body": "<p>I would probably do something like this:</p>\n\n<p>I don't know VB so this is pseudo code.</p>\n\n<pre><code>Private Function Shuffle(playlist) as Playlist\n{\n Dim PlayList as NewPlayList\n Dim RandomIndex as Integer\n\n while(playlist has elements)\n {\n RandomIndex = (Random number between lowerbound and upperbound)\n\n remove song at RemoveIndex from playlist\n add removed song to NewPlaylist\n }\n\n return NewPlayList\n}\n</code></pre>\n\n<p>The issue I have with the way you did it is that there is ample opportunity to undo the shuffle. For example, Suppose you are at index 1 and the random number is 2. You swap 1 and 2. Now suppose you are at index 2 and the random number is 1. Now you just undid the shuffle that you preformed in the previous iteration. Also, I don't like the use of the global variable InnerPlaylist. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T02:12:36.947", "Id": "57", "ParentId": "50", "Score": "5" } }, { "body": "<p>No. <strong>Your shuffle will <em>not</em> be random.</strong> You are stepping through each card and swapping it with another random card. This is a common bug found in many shuffling algorithms. </p>\n\n<p>To illustrate why your shuffle is not random, let's assume you are shuffling three songs (1, 2, 3). There are six combinations of three song (123, 132, 213, 231, 321, 312). If your shuffle was random, each of these combinations should appear with equal probability. So if you run your shuffle algorithm 600,000 times, each combination should appear roughly 100,000 times each.</p>\n\n<p>But it doesn't. When you run your shuffle algorithm 600,000 times (as written), you will see results similar to this: </p>\n\n<p><img src=\"https://i.stack.imgur.com/f1Ri6.png\" alt=\"Shuffle results\"></p>\n\n<p>To understand <em>why</em> your implementation produces biased results, read this article on Coding Horror: <a href=\"http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html\" rel=\"noreferrer\">The Danger of Naïveté</a>.</p>\n\n<p>What you want is a <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"noreferrer\"><strong>Fisher-Yates shuffle</strong></a> where you swap the current card with any of the <em>remaining</em> cards (or itself). </p>\n\n<p>Here it is in pseudo code for an in-place shuffle:</p>\n\n<pre><code>To shuffle an array a of n elements:\n for i from n − 1 downto 1 do\n j ← random integer with 0 ≤ j ≤ i\n exchange a[j] and a[i]\n</code></pre>\n\n<p>There are other types of Fisher-Yates shuffles listed here: Wikipedia: <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"noreferrer\">Fisher–Yates shuffle</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T15:08:37.003", "Id": "98", "ParentId": "50", "Score": "35" } }, { "body": "<p>For a game with no serious consequences you could just run it a bunch of times and see if it seems satisfying. For something where there are serious consequences to it not being a good enough shuffle I would think that you shouldn't wonder if a shuffle is good enough, you need to have theory that tells you it is good enough (possibly under assumptions you are happy with). Related to this Vol. 2 of The Art of Computer Programming in its first chapter gives lots of information about generating random numbers, AND how to test them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T18:02:08.187", "Id": "134", "ParentId": "50", "Score": "0" } } ]
{ "AcceptedAnswerId": "98", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-20T00:54:38.853", "Id": "50", "Score": "19", "Tags": [ "algorithm", "vb6", "random", "shuffle" ], "Title": "Shuffling algorithm for a \"guess that tune\" game" }
50
<p>I implemented the Shamos-Hoey algorithm to check if a closed shape is self-intersected. Is this algorithm ok in terms of performance?</p> <pre><code>public boolean isSelfIntersected() { Set&lt;Line2D&gt; plines = new HashSet&lt;Line2D&gt;(); for (Path2D ps : this.getPath()) { PathIterator p_it = ps.getPathIterator(null, /*flatness*/ 1); List&lt;Line2D&gt; estPath = new ArrayList&lt;Line2D&gt;(); while (!p_it.isDone()) { p_it.next(); double[] coords = new double[6]; int s = p_it.currentSegment(coords); if (s == PathIterator.SEG_LINETO) { if (estPath.size() != 0) { Point2D pp = estPath.get(estPath.size() - 1).getP2(); estPath.add(new Line2D.Double(pp, new Point2D.Double(coords[0],coords[1]))); } else { estPath.add(new Line2D.Double(new Point2D.Double(), new Point2D.Double(coords[0],coords[1]))); } } } for (Line2D lq : estPath) { plines.add(tweakLine(lq)); } } return ShamosHoeyAlgorithm(plines); } /** * Moves first point of the line by 0.0000001 of it's length. * @return */ static Line2D tweakLine(Line2D l) { Line2D ql = new Line2D.Double( l.getX1() + 0.0000001*(l.getX2() - l.getX1()), l.getY1() + 0.0000001*(l.getY2() - l.getY1()), l.getX2() - 0.0000001*(l.getX2() - l.getX1()), l.getY2() - 0.0000001*(l.getY2() - l.getY1())); return ql; } public class ShamosHoeyAlgorithm { public static boolean ShamosHoeyAlgorithm(Collection&lt;Line2D&gt; lines) { List&lt;AlgEvent&gt; events = new ArrayList&lt;AlgEvent&gt;(lines.size() * 2); for (Line2D li : lines) { if (li.getX1() &lt; li.getX2()) { Line2D l = new Line2D.Double(li.getP1(), li.getP2()); events.add(new AlgEvent(l, true)); events.add(new AlgEvent(l, false)); } else if (li.getX1() &gt; li.getX2()) { Line2D l = new Line2D.Double(li.getP2(), li.getP1()); events.add(new AlgEvent(l, true)); events.add(new AlgEvent(l, false)); } else { if (li.getY1() &lt; li.getY2()) { Line2D l = new Line2D.Double(li.getP1(), li.getP2()); events.add(new AlgEvent(l, true)); events.add(new AlgEvent(l, false)); } else if (li.getY1() &gt; li.getY2()) { Line2D l = new Line2D.Double(li.getP2(), li.getP1()); events.add(new AlgEvent(l, true)); events.add(new AlgEvent(l, false)); } else { return true; } } } Collections.sort(events, new AlgEvtComparator()); TreeSet&lt;Line2D&gt; sl = new TreeSet&lt;Line2D&gt;(new LineComparator()); for (AlgEvent e : events) { if (e.isStart) { Line2D nl = e.line; Line2D above = sl.higher(nl); if (above != null) { if (above.intersectsLine(nl)) { return true; } } Line2D below = sl.lower(nl); if (below != null) { if (below.intersectsLine(nl)) { return true; } } sl.add(nl); } else { Line2D nl = e.line; Line2D above = sl.higher(nl); Line2D below = sl.lower(nl); sl.remove(nl); if (above != null &amp;&amp; below != null) { if (above.intersectsLine(below)) { return true; } } } } return false; } static class AlgEvent { public Line2D line; public boolean isStart; AlgEvent(Line2D l, boolean isStart) { line = l; this.isStart = isStart; } Point2D getPoint() { return (isStart) ? line.getP1() : line.getP2(); } double getX() { return (isStart) ? line.getX1() : line.getX2(); } double getY() { return (isStart) ? line.getY1() : line.getY2(); } @Override public String toString() { return "start = " + isStart + ", point = " + this.getPoint() + ", line = " + line.getP1() + " : " + line.getP2(); } } static class AlgEvtComparator implements Comparator&lt;AlgEvent&gt; { public int compare(AlgEvent o1, AlgEvent o2) { if (o1.getX() &lt; o2.getX()) { return -1; } else if (o1.getX() &gt; o2.getX()) { return 1; } else { if (o1.getY() &lt; o2.getY()) { return -1; } else { return 1; } } } } /** * Class to compare lines, to ensure above-below order. */ static class LineComparator implements Comparator&lt;Line2D&gt; { public int compare(Line2D o1, Line2D o2) { if (o1.getY1() &lt; o2.getY1()) { return -1; } else if (o1.getY1() &gt; o2.getY2()) { return 1; } else { if (o1.getY2() &lt; o2.getY2()) { return -1; } else if (o1.getY2() &gt; o2.getY2()) { return 1; } else { return 0; } } } } } </code></pre>
[]
[ { "body": "<p>The question of whether your code is performant enough is something your profiler can better answer for you. But from looking through the code above I notice quite a bit of duplication along with some rather deeply nested if's which you should try to refactor. Take this for example:</p>\n\n<pre><code> if (li.getX1() &lt; li.getX2()) {\n Line2D l = new Line2D.Double(li.getP1(), li.getP2());\n events.add(new AlgEvent(l, true));\n events.add(new AlgEvent(l, false));\n } else if (li.getX1() &gt; li.getX2()) {\n Line2D l = new Line2D.Double(li.getP2(), li.getP1());\n events.add(new AlgEvent(l, true));\n events.add(new AlgEvent(l, false));\n } else {\n if (li.getY1() &lt; li.getY2()) {\n Line2D l = new Line2D.Double(li.getP1(), li.getP2());\n events.add(new AlgEvent(l, true));\n events.add(new AlgEvent(l, false));\n } else if (li.getY1() &gt; li.getY2()) {\n Line2D l = new Line2D.Double(li.getP2(), li.getP1());\n events.add(new AlgEvent(l, true));\n events.add(new AlgEvent(l, false));\n } else\n // ...\n</code></pre>\n\n<p>The two statements <code>events.add(new AlgEvent(l, true));</code> and <code>events.add(new AlgEvent(l, false));</code> are being repeated 4 times here!</p>\n\n<p>Your line compare method here:</p>\n\n<pre><code>static class LineComparator implements Comparator&lt;Line2D&gt; {\n public int compare(Line2D o1, Line2D o2) {\n if (o1.getY1() &lt; o2.getY1()) {\n return -1;\n } else if (o1.getY1() &gt; o2.getY2()) {\n // ...\n}\n</code></pre>\n\n<p>can be shorted by taking advantage of logical short-circuit and the ternary operator. So something like this might be easier to read:</p>\n\n<pre><code> public int compare(Line2D o1, Line2D o2)\n {\n /* I'm not too familiar with java but can\n the equals method be used here to check\n if the lines are equal?\n */\n // if( o1.equals(o2) ) return 0;\n\n return (o1.getY1() &lt; o2.getY1() || \n o1.getY2() &lt; o2.getY2()) ? -1 :\n (o1.getY1() &gt; o2.getY2() ||\n o1.getY2() &gt; o2.getY2()) ? 1 : 0;\n }\n</code></pre>\n\n<p>You can apply the same idea to AlgEvtComparator's compare method. One other thing I noticed in your line compare method, the checks' aren't exactly symmetrical. You have o1.Y1 comparing to o2.Y2 while all the others are checking Y1 to Y1 or Y2 to Y2. Was that really intended? I think this deserves a comment.</p>\n\n<p>I'm guessing Line2D is a class you have defined somewhere. You might want to see if you're abstracting its usage enough or if an 'in-between' class is needed. The following code looks like it's leaking stuffing behind Line2D's interface:</p>\n\n<pre><code>if (estPath.size() != 0) {\n Point2D pp = estPath.get(estPath.size() - 1).getP2();\n estPath.add(new Line2D.Double(pp, new Point2D.Double(coords[0],coords[1])));\n} else {\n estPath.add(new Line2D.Double(new Point2D.Double(), new Point2D.Double(coords[0],coords[1])));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T15:27:02.183", "Id": "194", "Score": "0", "body": "Thanks a lot! Line2D is not my class, it is core Java class. And that comparator was made like this by intent - one of the points of algorithm is that lines need to be ordered by their first points. And your code for comparator - yes, when I profiled, I saw that there are problems exactly with comparators. And again, big Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T13:42:45.263", "Id": "127", "ParentId": "69", "Score": "11" } }, { "body": "<p>Performance aside, I think your LineComparator is incorrect(!) as it compares the points where the sweepline initially ran into the segments. The sweepline has swept on in the meanwhile and therefore, while the ordering of the segments on the sweepline has not changed, the actual location of their intersections with the sweepline has moved and you need to account for this when trying to figure out where to insert a new segment in the sweepline.</p>\n<p><img src=\"https://i.stack.imgur.com/qHqGo.jpg\" alt=\"illustration of the problem\" /></p>\n<p>When the vertical sweepline encounters segment number 5, it shouldn't compare its intersection point with 5 with the grey intersectionpoints of 1, 2, 3, and 4. If it does that, it'll insert 5 at the top. It needs to compare its intersection point with 5 with its <em>current</em> red intersection points with segments 1, 2, 3, and 4 and insert number 5 right in the middle.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T11:34:02.890", "Id": "50495", "Score": "0", "body": "First question after quick look: Won't you get nullpointer exceptions for zero values of rx and ry?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T15:42:44.467", "Id": "50503", "Score": "0", "body": "Yes, I most definitely will get problems with vertical lines. I'm rewriting that method again, right now. It turns out that defining that above-below relation properly is no easy task ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T16:17:16.230", "Id": "50505", "Score": "0", "body": "For example, did you know that Line2D.equals() only takes into account reference equality? I did not, and it took me almost an hour to debug the issue :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T16:22:14.457", "Id": "50506", "Score": "0", "body": "I updated the code. The `compareLines()` method is now an abomination, weighting in at 50 lines - but on the bright side, I think I handled all possible corner cases in it. Maybe you know how to simplify it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T16:30:44.023", "Id": "50508", "Score": "0", "body": "Heavens! It can do with a bit more comment, at the very least." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T14:50:06.713", "Id": "31426", "ParentId": "69", "Score": "2" } } ]
{ "AcceptedAnswerId": "127", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-20T05:20:50.317", "Id": "69", "Score": "17", "Tags": [ "java", "algorithm", "computational-geometry" ], "Title": "Shamos-Hoey algorithm for checking the self-intersection of a closed shape" }
69
<p>I've implemented a PID controller, but seeing as I'm not an expert in control theory, have I missed any edge cases?</p> <pre><code>public class PIDController { public enum PIDMode { Manual, Auto, } public enum PIDAction { Indirect, Direct, } public PIDMode Mode { get; set; } public PIDAction Action { get; set; } public double Proportional { get; set; } public double Integral { get; set; } public double Derivative { get; set; } public double Minimum { get; set; } public double Maximum { get; set; } public double DeltaMinimum { get; set; } public double DeltaMaximum { get; set; } private double _ProportionalTerm; private double _Integrator; private double _Derivator; public double Setpoint { get; set; } private double _Feedback; public double Feedback { get { return _Feedback; } } public void Calculate(double Input, long Time) { double output; // Compute the error value double Error = Setpoint - Input; if (Mode == PIDMode.Auto) { if (Action == PIDAction.Direct) Error = 0 - Error; // Compute the proportional component _ProportionalTerm = 1000.0f * (Error - _Derivator) / (double)Time; // Compute the integrator component, clamped to min/max delta movement _Integrator += (float)Error * (float)Time / 1000.0f; if (_Integrator &lt; DeltaMinimum) _Integrator = DeltaMinimum; if (_Integrator &gt; DeltaMaximum) _Integrator = DeltaMaximum; // Add the proportional component output = (Proportional * Error); // Add the integral component output += Integral * _Integrator; // Add the derivative component output += Derivative * _ProportionalTerm; // Clamp output to min/max if (output &lt; Minimum) output = Minimum; if (output &gt; Maximum) output = Maximum; } else { output = Input; } // Store values _Derivator = Error; // Returns the result _Feedback = output; } } </code></pre>
[]
[ { "body": "<p>It looks reasonable, but I don't see why you need to make the Proportional term a member of the class, it doesn't need to be saved, at best it might make sense to be able to query it with a get, but a set seems misleading.</p>\n\n<p>I'd be reluctant to allow public setting of the Integral and Derivatives too, querying them might be useful, but letting users of the class set it seems odd.</p>\n\n<p>Forcing the scaling by 1000.0 seems arbitrary and inflexible too, this would make sense to expose as a settable constant in my view.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T19:46:19.540", "Id": "113", "ParentId": "72", "Score": "9" } }, { "body": "<p>Having a time parameter for each iteration of a PID loop would imply that it may safely be run at a variable frequency; while there are occasions when that may be unavoidable, and there are ways of handling such variations safely, I would expect most conditions that would cause the sampling loop time to vary would also create considerable 'noise' in the D term, limiting its usefulness.</p>\n\n<p>One approach I've not seen discussed is replacing the PID loop with an IIR filter. A PID loop is a special case of an IIR filter, but with the second tap's time constant being infinitesimal, and the third tap's time constant being nearly infinite. The difference between the first two taps represents the delta, and the third tap represents the integral. Using more \"realistic\" time constants for the filter taps yields results which differ from a \"pure\" IIR filter, but in ways that are apt to be beneficial. Using a short-but-not-infinitesimal time constant on the second stage allows one to reduce the amount of high-frequency noise. Using a finite time constant on the third term allows one to effectively limit the \"wind-up\". Although going beyond three stages would make it harder to analyze system behavior, it may allow the PID system to better deal with various delay factors in the real-world system being controlled.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-20T05:29:17.930", "Id": "42974", "Score": "0", "body": "I'd be interested if you know of any more discussion on expressing a PID as an IIR." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-20T14:55:32.790", "Id": "43011", "Score": "0", "body": "@detly: I don't think I've seen such discussions since I wrote the above. If one figures out the frequency response of the integral and derivative terms, and those of the FIR filter described, the PID response matches the limiting case of the FIR as the second-stage time constant approaches zero and the third stage approaches infinity. Given that there's a limit to the frequencies of interest in the D term, and the amount of windup that's desired on the I term, I find it curious that the FIR model isn't used more." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T21:29:42.190", "Id": "386", "ParentId": "72", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-20T06:31:36.730", "Id": "72", "Score": "13", "Tags": [ "algorithm", "c#" ], "Title": "Implementation of a PID Controller" }
72
<p>This plugin is written in jQuery and is made to support <a href="http://codeigniter.com" rel="nofollow">the codeigniter framework</a>. It is an ajax powered table pagination plugin designed to provide only that. You should be able to use almost any other table scripts with this plugin.</p> <pre><code>(function($){ $.fn.extend({ tpaginate: function(options) { //Settings list and the default values var defaults = { page: 0, url : null, rows: 20, nodata: 'The table is empty!', actions: true }; var table; var foot; var body; var curpagespan; var totpagespan; var oldbody; var replaced = false; var options = $.extend(defaults, options); return this.each(function() { table = this; foot = $(table).find(' &gt; tfoot &gt; tr &gt; td'); body = $(table).find(' &gt; tbody'); create_footer(foot); curpagespan = foot.find(' &gt; #table_pagecount &gt; span#page'); totpagespan = foot.find(' &gt; #table_pagecount &gt; span#page_total'); curpagespan.html(0); totpagespan.html(0); $('#searchButton').click(function(){ var term = $('#search').val(); if(term.length &gt;= 3){ if(replaced) load_data(1, term, true, false); else load_data(1, term, true, true); } }); $('#search').keyup(function(){ if($(this).val() == ''){ create_tbody(false, false, true); } }); }); function create_footer() { var pagecount = $('&lt;div id="table_pagecount"&gt;Page &lt;span id="page"&gt;&lt;/span&gt; of &lt;span id="page_total"&gt;&lt;/span&gt;&lt;/div&gt;'); var pager = $('&lt;div id="table_pageination"&gt;&lt;a class="link" id="first" style="display:none;"&gt;First&lt;/a&gt;&lt;a class="link" id="prev" style="display:none;"&gt;Prev&lt;/a&gt;&lt;span id="pages"&gt;&lt;/span&gt;&lt;a class="link" id="next" style="display:none;"&gt;Next&lt;/a&gt;&lt;a class="link" id="last" style="display:none;"&gt;Last&lt;/a&gt;&lt;/div&gt;'); foot.append(pagecount); foot.append(pager); load_data(1, '', true); } function current_page(page){ curpagespan.html(page); } function total_page(page){ totpagespan.html(Math.ceil(page/options.rows)); } function load_data(page, search, action, save){ if(save == null) save = false; else save = true; $('#table_pageination a.link').unbind('click'); search = (search == null ? '' : search); var start = (page-1)*options.rows; if(page == 1) start = 0; var url = options.url+'/'+start+'/'+action+'/'+search; $.ajax({ url: url, success: function(data) { if(data.total != 0){ current_page(page); total_page(data.total); create_tbody(data.members, save); update_pages(page, Math.ceil(data.total/options.rows)); } else{ current_page(0); total_page(0); foot.find(' &gt; #table_pageination &gt; #pages').html('&lt;a class="link"&gt;0&lt;/a&gt;'); var newtr = $('&lt;tr&gt;&lt;/tr&gt;'); var newtd = $('&lt;td style="font-weight:bold;text-align: center;"&gt;&lt;/td&gt;').attr('colspan', foot.attr('colspan')).text(options.nodata); body.html(newtr.append(newtd)); } } }); } function create_tbody(rows, save, revert){ if(save == true){ oldbody = body.html(); replaced = true; } var newbody = $('&lt;tbody /&gt;'); if(revert == null){ for(var i in rows){ var row = $('&lt;tr /&gt;'); for(var j in rows[i]){ if(j != 'id' &amp;&amp; j != 'actions') row.append('&lt;td class="'+j+'td"&gt;'+(rows[i][j] == null ? '' : rows[i][j])+'&lt;/td&gt;'); if(j == 'actions' &amp;&amp; rows[i][j] != null &amp;&amp; options.actions) row.append(rows[i][j]); } newbody.append(row); } } else{ newbody.html(oldbody); replaced = false; } body.html(newbody.html()); $(table).trigger("update"); } function update_pages(page, total){ foot.find(' &gt; #table_pageination &gt; #pages').html(ranger(page, 5, total)); if(page == 1){ foot.find(' &gt; #table_pageination &gt; a#first').fadeOut('slow'); foot.find(' &gt; #table_pageination &gt; a#prev').fadeOut('slow'); } else{ foot.find(' &gt; #table_pageination &gt; a#first').attr('rel', 1).fadeIn('slow'); if(page != 2) foot.find(' &gt; #table_pageination &gt; a#prev').attr('rel', page-1).fadeIn('slow'); } if(total != page){ foot.find(' &gt; #table_pageination &gt; a#last').attr('rel', total).fadeIn('slow'); if(total != page+1) foot.find(' &gt; #table_pageination &gt; a#next').attr('rel', ++page).fadeIn('slow'); } else{ foot.find(' &gt; #table_pageination &gt; a#last').attr('rel', total).fadeOut('slow'); foot.find(' &gt; #table_pageination &gt; a#next').attr('rel', total).fadeOut('slow'); } $('#table_pageination a.link').click(function(){ replaced = false; load_data($(this).attr('rel'), '', true); }); } function ranger(num, range, max) { var left = num*1; var right = num*1; while (right - left &lt; range * 2) { if (right + 1 &lt;= max) right++; if (left - 1 &gt; 0) left--; if (right == max &amp;&amp; left == 1) break; } var str = ''; for (var i = left; i &lt;= right; i++) { if(i != num) str += '&lt;a class="link" rel="'+i+'"&gt;'+i+'&lt;/a&gt;'; if(i == num) str += '&lt;a rel="nolink"&gt;'+i+'&lt;/a&gt;'; } return str; } } }); })(jQuery); </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T12:10:59.513", "Id": "119", "Score": "2", "body": "I don't have time to take a bigger look at the code right now but I can point out some obvious issues. Not using the strict equals operator (`===`) may lead to subtle bugs. Not using `hasOwnProperty` in a `for in` is bad practice. Both of these combined will lead to bugs when native prototypes have been extended (e.g. in `create_tbody`). There *might* also be some leakage from the closures of the event handlers but I'm not sure how much of an issue that would be without digging further into the code. Overall structure looks good but many small changes could be made, gonna post something later" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T15:14:35.357", "Id": "190", "Score": "0", "body": "Users hate pagination. Are you sure you want to show only 20 items per page? Consider showing more items per page, like 200. Just a suggestion. :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T04:39:41.820", "Id": "233", "Score": "1", "body": "@Ivo Wetzel, Thankyou for your comment, I had not even thought about using the strict equality operator. Will update the codebase with that code.\n\n@Time Machine the 20 rows at a time can be overwritten when you call the plugin using `$(table).tpaginate({rows: 200});`\n\nand Yes, I agree users hate pagination, So Do I, but with 60k rows, sometimes it is necessary!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-24T21:56:38.667", "Id": "58812", "Score": "0", "body": "Consider using classes instead of IDs for the HTML elements you're inserting. IDs should be unique, and since they have generic names (like `#prev`), there is a high likelihood of unintended conflict with pre-existing markup." } ]
[ { "body": "<p>That's a large piece of code.</p>\n\n<p>I highly recommended to use lower camel case for variables.</p>\n\n<p>Here are some hints from me, just only micro-refactoring.</p>\n\n<blockquote>\n<pre><code>if(term.length &gt;= 3) {\n if(replaced)\n load_data(1, term, true, false);\n else\n load_data(1, term, true, true);\n}\n</code></pre>\n</blockquote>\n\n<p>into:</p>\n\n<pre><code>if(term.length &gt;= 3) {\n load_data(1, term, true, !replaced); \n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>function load_data(page, search, action, save) {\n if(save == null)\n save = false;\n else\n save = true;\n ...\n</code></pre>\n</blockquote>\n\n<p>into:</p>\n\n<pre><code>function load_data(page, search, action, save) {\n save = save == null ? false : true;\n...\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>for(var j in rows[i]) {\n if(j != 'id' &amp;&amp; j != 'actions')\n row.append('&lt;td class=\"'+j+'td\"&gt;'+(rows[i][j] == null ? '' : rows[i][j])+'&lt;/td&gt;');\n if(j == 'actions' &amp;&amp; rows[i][j] != null &amp;&amp; options.actions)\n row.append(rows[i][j]);\n }\n</code></pre>\n</blockquote>\n\n<p>into:</p>\n\n<pre><code>for(var j in rows[i]) {\n var rowsIJ = rows[i][j];\n\n if(j != 'id' &amp;&amp; j != 'actions')\n row.append('&lt;td class=\"'+j+'td\"&gt;'+(rowsIJ == null ? '' : rowsIJ)+'&lt;/td&gt;');\n if(j == 'actions' &amp;&amp; rowsIJ != null &amp;&amp; options.actions)\n row.append(rowsIJ);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T02:02:07.823", "Id": "535", "Score": "1", "body": "points one and two I agree with, however I fail to see the points of number 3? I will make the suggested changes for 1 and 2." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-27T21:01:20.130", "Id": "327", "ParentId": "77", "Score": "3" } }, { "body": "<p>As far as i remember, use of for … in statements <a href=\"https://stackoverflow.com/questions/500504/javascript-for-in-with-arrays\">is strongly discouraged</a>. Also, jQuery has a great <a href=\"http://api.jquery.com/jQuery.each/\" rel=\"nofollow noreferrer\">$.each() function</a>. </p>\n\n<p>So, this</p>\n\n<pre><code>for(var i in rows){\n var row = $('&lt;tr /&gt;');\n for(var j in rows[i]){\n if(j != 'id' &amp;&amp; j != 'actions')\n row.append('&lt;td class=\"'+j+'td\"&gt;'+(rows[i][j] == null ? '' : rows[i][j])+'&lt;/td&gt;');\n if(j == 'actions' &amp;&amp; rows[i][j] != null &amp;&amp; options.actions)\n row.append(rows[i][j]);\n }\n newbody.append(row);\n}\n</code></pre>\n\n<p>should rather be something along the lines of</p>\n\n<pre><code>$.each(rows, function(i,e){\n var row = $('&lt;tr /&gt;'); \n $.each(rows[i], function(j,ee){\n if(j != 'id' &amp;&amp; j != 'actions')\n row.append('&lt;td class=\"'+j+'td\"&gt;'+(rows[i][j] == null ? '' : rows[i][j])+'&lt;/td&gt;');\n if(j == 'actions' &amp;&amp; rows[i][j] != null &amp;&amp; options.actions)\n row.append(rows[i][j]);\n });\n newbody.append(row);\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-24T18:34:29.840", "Id": "58791", "Score": "1", "body": "you should read all the comments and all the answers and all the links on that question before giving it as an answer on another question. you need to fully understand what is going on in both circumstances to make sure they are both talking about the same thing." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T15:12:52.970", "Id": "4955", "ParentId": "77", "Score": "-1" } } ]
{ "AcceptedAnswerId": "327", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-20T09:21:34.217", "Id": "77", "Score": "7", "Tags": [ "javascript", "performance", "jquery", "ajax", "pagination" ], "Title": "Pagination plugin" }
77
<p>Is this the best way to implement this pattern in C#?</p> <pre><code>public sealed class Singleton { private static readonly Singleton instance = new Singleton(); public static Singleton Instance { get { return instance; } } static Singleton() {} private Singleton() {} } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-07T02:53:33.217", "Id": "18504", "Score": "8", "body": "[Singleton is an antipattern](http://thetechcandy.wordpress.com/2009/12/02/singletons-is-anti-pattern/)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-10T15:00:28.890", "Id": "25102", "Score": "0", "body": "Please watch: [\"Global State and Singletons\"](http://www.youtube.com/watch?v=-FRm3VPhseI)" } ]
[ { "body": "<p>I always use this solution if I have to implement a Singleton in C#</p>\n\n<pre><code>public sealed class Logging\n {\n static Logging instance = null;\n static readonly object lockObj = new object();\n\n private Logging()\n {\n }\n\n public static Logging Logger\n {\n get\n {\n lock (lockObj)\n {\n if (instance == null)\n {\n instance = new Logging();\n }\n return instance;\n }\n }\n }\n\n}\n</code></pre>\n\n<p>Compared to your solution this is threadsafe and uses a lazy-creation method. (The object is only instantiated if actually needed)</p>\n\n<p>The eager vs. lazy creation isn't really worth a discussion in this example, but I would whenever possible use the thread-safe implementation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T00:38:26.337", "Id": "172", "Score": "4", "body": "This is a very bad solution to the problem, it uses a lock on every single access. Which has a very high overhead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T12:03:53.763", "Id": "8549", "Score": "0", "body": "@Martin: The overhead is not that onerous unless you say `Logging.Logger.DoThis()` and `Logging.Logger.DoThat()` every time. Which i'd prefer to avoid that anyway, as (1) it pretty much entrenches the Logging class, making it even more of a pain to swap out for something else later, and (2) `Logging.Logger` will, by the definition of a singleton, always return the same thing, so re-getting it each time is silly. Oh, and (3) it's repetitive, and i hate repetition." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T13:41:46.150", "Id": "8556", "Score": "0", "body": "You're using a singleton now, but later you may wish to change your singleton so, for example, it swaps out to a new logger when the file gets full - so I tend to try to avoid caching the singleton. There's no point keeping hundreds of references to something around when you can centralise access in one place easily and efficiently with e.g. double checked locking" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T10:07:05.410", "Id": "80", "ParentId": "79", "Score": "6" } }, { "body": "<p>I use <a href=\"http://csharpindepth.com/Articles/General/Singleton.aspx\">Jon Skeet's version</a> of a <em>thread safe</em> Singleton with fully lazy instantiation in C#: </p>\n\n<pre><code>public sealed class Singleton\n{\n // Thread safe Singleton with fully lazy instantiation á la Jon Skeet:\n // http://csharpindepth.com/Articles/General/Singleton.aspx\n Singleton()\n {\n }\n\n public static Singleton Instance\n {\n get\n {\n return Nested.instance;\n }\n }\n\n class Nested\n {\n // Explicit static constructor to tell C# compiler\n // not to mark type as beforefieldinit\n static Nested()\n {\n }\n\n internal static readonly Singleton instance = new Singleton();\n }\n}\n</code></pre>\n\n<p>It works wonders for me! It's really easy to use, just get the instance from the Instance property like so; <code>SingletonName instance = SingletonName.Instance;</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T11:55:35.417", "Id": "115", "Score": "0", "body": "Wouldn't GetInstance be more appropriate for what is essentially an accessor? Or is that convention different in C#?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T12:08:01.097", "Id": "118", "Score": "5", "body": "I think that Instance is sufficient enough, but I suppose YMMV." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T13:24:39.443", "Id": "128", "Score": "0", "body": "Is there some specific benefit from creating a nested class?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T13:40:42.037", "Id": "131", "Score": "0", "body": "@AnnaLear: I believe that Jon Skeet explains it better himself than I can at the moment, check out the link. :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T15:55:22.850", "Id": "143", "Score": "3", "body": "The nested class is what makes it lazy. The runtime will not instantiate the Singleton instance until Singleton.Instance is called. That way, if you have other static members or something on Singleton, you can access them without creating the Singleton instance." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T11:37:19.320", "Id": "182", "Score": "9", "body": "I'd like to encourage everyone to read Jon Skeet's article (following the link Zolomon has provided), as it coverts almost all answers in this topic, listing all their pros and cons." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T17:43:24.333", "Id": "468", "Score": "2", "body": "This is also thread safe." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-06T08:08:52.170", "Id": "1154", "Score": "0", "body": "That's pretty darn clever. But I had to read Jon's article to actually understand what's going on. But the next guy that maintains your code probably won't get all the trickery just by looking at it. I'd add a comment that links to Jon's article." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-06T09:21:19.930", "Id": "1158", "Score": "0", "body": "@AngryHacker: That's what I do in my implementations. ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-02T03:54:40.963", "Id": "6780", "Score": "1", "body": "How would you use this in tests - what if you needed to mock it or parts of it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T11:54:43.450", "Id": "8546", "Score": "7", "body": "@Chris: You wouldn't. That's part of why singletons suck -- they're essentially hidden global state, making it nearly impossible to reliably test code that contains or uses them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T15:44:56.653", "Id": "8567", "Score": "0", "body": "@cHao +1 good job on pointing out the suckiness of singletons!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T16:33:22.267", "Id": "8572", "Score": "0", "body": "It's actually not all that bad. Have the singleton class implement an interface and mock that interface. It's not like any version of the class is static, just the one instance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T17:56:05.910", "Id": "8575", "Score": "1", "body": "@Jesse: Only problem is, code that uses singletons almost always ends up going to get them itself. There end up being calls to `Singleton.Instance` scattered all over the place. You can't easily mock your way around that. If code expected to be passed a Singleton that it'd use, then sure, you could easily mock it. At which point you have dependency injection, though, and no longer need a singleton." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T07:48:49.587", "Id": "8627", "Score": "0", "body": "@cHao Not quite true; some pay-for test products can mock static classes, and Pex can mock static methods: http://research.microsoft.com/en-us/projects/pex/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-26T20:21:45.047", "Id": "19363", "Score": "0", "body": "@ChrisMoschini : Yes, you can Mole it out, Pex it out or even use the old TypeMock isolator but when you need to replace it then.. CTRL-SHIFT-H... :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-09T22:23:48.860", "Id": "44316", "Score": "1", "body": "Try googling \"ambient context\" for some good ideas of how to have your single return an abstract type which has a default concrete value at runtime but which would be easily replaceable for testing." } ], "meta_data": { "CommentCount": "17", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-20T10:15:28.753", "Id": "81", "ParentId": "79", "Score": "74" } }, { "body": "<p>I always use this, it allows lazy initialisation of generics, instead of creating a new singleton class for each type of singleton I want. It's also threadsafe but does not use locks on every access.</p>\n\n<pre><code>public static class Singleton&lt;T&gt; where T : class, new()\n{\n private T instance = null;\n\n public T Instance\n {\n get\n {\n if (instance == null)\n Interlocked.CompareExchange(ref instance, new T(), null);\n\n return instance;\n }\n }\n}\n</code></pre>\n\n<p>If you're unfamiliar with the interlocked class, it performs atomic operations in a manner which is often quicker than a lock. Three possible cases:</p>\n\n<p>1) <strong>First access by a single thread</strong>. Probably roughly the same performance as the obvious method using a lock</p>\n\n<p>2) <strong>First access by many threads at the same time</strong>. Many threads might enter the interlocked exchange, in which case several items may get constructed but only 1 will \"win\". So long as your constructor has no global side effects (which is really shouldn't) behaviour will be correct. Performance will be slightly less than a lock, because of multiple allocations, but the overhead is small and this is a very rare case.</p>\n\n<p>3) <strong>Later accesses</strong>. No locking or interlocked operations, this is pretty much optimal and is obviously the majority case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T03:59:44.783", "Id": "178", "Score": "0", "body": "+1 for good solution, but the problem #2 requiring your Constructors to have no side effects has always scared me off this approach." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T13:41:12.393", "Id": "184", "Score": "1", "body": "How often do your constructors have side effects? I've always considered that to be a pretty bad code smell. Especially in multithreaded code!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T15:04:01.323", "Id": "189", "Score": "0", "body": "Additionally, your constructor can have side effects so long as they're threadsafe and do not assume that this is the only instance to be created. Remember, several instances may be created but only one will \"win\", so if you do have side effects they'd better be implemented properly!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T11:58:22.257", "Id": "8548", "Score": "0", "body": "@Martin: Isn't the whole point of singletons that only one instance can be created? It'd seem to me that relying on that assumption is a quite reasonable thing to do..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T13:45:44.977", "Id": "8557", "Score": "0", "body": "@cHao true, but as I said before I consider any side effects in a constructor which leak beyond the instance being constructed one of the worst code smells, doubly so in multithreaded code. Assuming we agree on this, there's no way constructing 2 instances can have any external affect on your program." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-19T07:53:23.560", "Id": "29944", "Score": "1", "body": "-1, Not thread safe (constructor could be called several times), thus defeating the purpose of a singleton." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-20T12:55:00.193", "Id": "91", "ParentId": "79", "Score": "18" } }, { "body": "<p>I use a pattern similar to one already posted, but with the following difference:</p>\n\n<pre><code>public sealed class Logging\n{\n static Logging instance = null;\n static readonly object lockObj = new object();\n\n private Logging()\n {\n }\n\n public static Logging Logger\n {\n get\n {\n **if (instance == null)**\n {\n lock (lockObj)\n {\n if (instance == null)\n {\n instance = new Logging();\n }\n\n }\n }\n return instance;\n }\n }\n</code></pre>\n\n<p>}</p>\n\n<p>The reason being that it avoids calling lock every time, which can help you with performance. So you check for null, then, if it is null, lock it. Then you have to check for null again (because someone may have come in right that second) but then you should be ok. That way, you'll only hit the lock the first time (or two), and blow past it without locking the rest of the time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T10:33:02.550", "Id": "181", "Score": "0", "body": "Great example.I only have to add the name: it is called \"Double-checked Locking\"" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T13:30:32.933", "Id": "183", "Score": "1", "body": "The return statement needs to be outside of the first if(instance==null) statement. Otherwise it will not return an instance if the instance already exists." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T13:56:15.487", "Id": "185", "Score": "0", "body": "@Dan quite correct, my mistake." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T03:57:08.000", "Id": "123", "ParentId": "79", "Score": "9" } }, { "body": "<p>Dependency Injection containers like Unity support a singleton concept. Unity is from Microsoft (and is open source), but there are <a href=\"http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx\" rel=\"nofollow\">lots of open source DI containers</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:58:53.863", "Id": "248", "ParentId": "79", "Score": "4" } }, { "body": "<p>If you are using .NET 4.0, you can take advantage of the <a href=\"http://msdn.microsoft.com/en-us/library/dd642331.aspx\">System.Lazy</a> class. It ensures the instance is created only once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T01:05:56.707", "Id": "20817", "Score": "5", "body": "You should add a code sample since I believe this is by far the best way to implement a singleton with .NET 4.0." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T09:30:48.093", "Id": "60799", "Score": "0", "body": "A code sample is available at http://csharpindepth.com/Articles/General/Singleton.aspx (\"sixth version\")" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:07:20.607", "Id": "282", "ParentId": "79", "Score": "12" } }, { "body": "<p>Here's an example from Wikipedia's Double-checked locking page:</p>\n\n<pre><code>public class MySingleton\n{\n private static object myLock = new object();\n private static MySingleton mySingleton = null;\n\n private MySingleton()\n { }\n\n public static MySingleton GetInstance()\n {\n if (mySingleton == null) // check\n {\n lock (myLock)\n {\n if (mySingleton == null) // double check\n {\n MySingleton newSingleton = new MySingleton();\n System.Threading.Thread.MemoryBarrier();\n mySingleton = newSingleton;\n }\n }\n }\n\n return mySingleton;\n }\n}\n</code></pre>\n\n<p>Notice the use of <code>System.Threading.Thread.MemoryBarrier();</code>, unlike GWLlosa's answer. See <a href=\"http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html\" rel=\"nofollow\">The \"Double-checked locking is broken\" declaration</a> for an explanation. (It is written for Java, but the same principles apply.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T19:22:58.003", "Id": "318", "ParentId": "79", "Score": "4" } }, { "body": "<p>Here's an implementation that uses <a href=\"http://msdn.microsoft.com/en-us/library/dd642331.aspx\" rel=\"nofollow\"><code>Lazy&lt;T&gt;</code></a>:</p>\n\n<pre><code>public class Foo : IFoo\n{\n private static readonly Lazy&lt;IFoo&gt; __instance\n = new Lazy&lt;IFoo&gt;(valueFactory: () =&gt; new Foo(), isThreadSafe: true);\n\n private Foo() { }\n\n public static IFoo Instance { get { return __instance.Value; } }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-10T12:10:32.517", "Id": "15476", "ParentId": "79", "Score": "4" } }, { "body": "<p>Simple way to I would like to suggest a simple way using volatile keyword , static variable are not thread safe but atomic execution are considered as thread safe. by using volatile we can enforce atomic operation.</p>\n\n<pre><code>public sealed class Singleton\n{\n private static **volatile** readonly Singleton instance = new Singleton();\n public static Singleton Instance { get { return instance; } }\n private Singleton() { }\n}\n</code></pre>\n\n<p>Locking is not the sure way to go , as it is expensive.</p>\n\n<p>I like john skeet way of creating the singleton way of creating the objects.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-21T16:21:55.707", "Id": "19847", "ParentId": "79", "Score": "0" } } ]
{ "AcceptedAnswerId": "81", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-20T10:02:03.633", "Id": "79", "Score": "67", "Tags": [ "c#", "singleton" ], "Title": "Implementing a Singleton pattern in C#" }
79
<p>I'm listing elements with a <code>foreach</code>, and I would like to enclose items in something tag <code>n</code> by <code>n</code>:</p> <pre><code>$i = 0; $open = $done = TRUE; $n = 3; $opening = "&lt;div&gt;"; $closing = "&lt;/div&gt;"; $names = array("Doc", "Marty", "George", "Lorraine", "Einstein", "Biff"); foreach($names as $name) { /** $condition was not a bool. My fault. */ if($open &amp;&amp; !($i % n)) { print $opening; $open = FALSE; $done = !$open; } elseif(!($i % n)) $done = FALSE; /** print element. */ print $name; if(!$open &amp;&amp; !($i % n) &amp;&amp; !$done) { print $closing; $open = TRUE; $done = !$open; } $i++; } </code></pre> <p>Do you think this snippet can be improved? It would be better to have fewer check variables such as <code>$open</code> or <code>$done</code>.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T11:03:10.900", "Id": "104", "Score": "1", "body": "@albert can you also add what n and the condition is suppose to represent? Does it get it's value from another part of the code?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T11:11:26.663", "Id": "105", "Score": "3", "body": "Can you provide as working example ? (Without parser errors). From its current state i pretty much have no clue that code is supposed to be doing (or at least it's nothing i think i can improve apon in a meaningfull way) . i, open and done are php variables ? ($ sign ?)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T11:34:03.900", "Id": "107", "Score": "1", "body": "I am very sorry. I updated the question." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T11:39:29.277", "Id": "109", "Score": "2", "body": "`} elseif(!(i % n)) done = FALSE;` is not PHP!, `}elseif(!($i % $n)) $done = FALSE;` is, this is a job for StackOverflow before you it can be improved" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T11:40:29.727", "Id": "111", "Score": "1", "body": "open and close still me the $ signs, saidly i can't edit it myself (and i don't want to put in a question just for that.) Thanks for the edit ! Much clearer now." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T11:59:21.387", "Id": "116", "Score": "0", "body": "Could you provide more explanation about what this method is meant to do? It might help people trying to improve it.. Are $i and $n magic numbers?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T14:10:00.693", "Id": "431", "Score": "0", "body": "@Alberteddu, Please only submit working code for review. Your code is not going to run because you miss some $'s at the start of some variables." } ]
[ { "body": "<p>One problem with your solution is that it won't print the last closing <code>&lt;/div&gt;</code> tag if there are less than <code>$n</code> elements inside the last <code>&lt;div&gt;</code>.</p>\n\n<p>An approach which fixes that problem and also simplifies the conditional logic for deciding when to print the tags is to chunk the array first using <code>array_chunk</code> and then iterate over the chunks. Now we only need one boolean variable to remember which chunks to surround in tags.</p>\n\n<pre><code>function alternate($names, $n, $opening, $closing) {\n $tag = TRUE;\n foreach(array_chunk($names, $n) as $chunk) {\n if($tag) {\n print $opening;\n }\n foreach($chunk as $name) {\n print $name;\n }\n if($tag) {\n print $closing;\n }\n $tag = !$tag;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T12:09:07.367", "Id": "90", "ParentId": "82", "Score": "9" } }, { "body": "<p>Alternate solution without the overhead of the array_chunk call. (Don't get me wrong, I love array_chunk and use it for a lot of things, but this isn't one where it's needed.)</p>\n\n<pre><code>$array = getData(...);\n$n = 5; //or whatever you want to chunk into\necho \"&lt;div&gt;\"; //always open one\n$lcv = 1; // loop count variable\nforeach ($array as $key =&gt; $val) {\n //format $key/$val as needed here...\n if ($lcv++ % $n == 0) { //every Nth item\n echo \"&lt;/div&gt;&lt;div&gt;\"; //close old one and open new one\n }\n}\necho \"&lt;/div&gt;\"; //always close the last one.\n</code></pre>\n\n<p>Worst case here is you might have an empty <code>&lt;div&gt;&lt;/div&gt;</code> block at the end if you had an exact multiple of n.... but that's not really that big a deal 99.999% of the time. :) If it is... then you can catch it like so:</p>\n\n<pre><code>$array = getData(...);\n$num = count($array);\n$n = 5; //or whatever you want to chunk into\necho \"&lt;div&gt;\"; //always open one\n$lcv = 1; // loop count variable\nforeach ($array as $key =&gt; $val) {\n //format $key/$val as needed here...\n if ($lcv++ % $n == 0 &amp;&amp; $lcv &lt; $num) { // every Nth item, unless we're done\n echo \"&lt;/div&gt;&lt;div&gt;\"; //close old one and open new one\n }\n}\necho \"&lt;/div&gt;\"; //always close the last one.\n</code></pre>\n\n<p>(Of course you can use <code>print</code>, <code>echo</code>, or <code>?&gt;...&lt;?</code> tags... whatever you want to actually do all the output, doesn't matter.)</p>\n\n<p>And to be honest, I'd probably add one more case to it:</p>\n\n<pre><code>$array = getData(...);\n$num = count($array);\nif ($num == 0) {\n echo \"&lt;div&gt;No results?&lt;/div&gt;\";\n} else {\n $n = 5; //or whatever you want to chunk into\n echo \"&lt;div&gt;\"; //always open one\n $lcv = 1; // loop count variable\n foreach ($array as $key =&gt; $val) {\n //format $key/$val as needed here...\n if ($lcv++ % $n == 0 &amp;&amp; $lcv &lt; $num) { // every Nth item, unless we're done\n echo \"&lt;/div&gt;&lt;div&gt;\"; //close old one and open new one\n }\n }\n echo \"&lt;/div&gt;\"; //always close the last one.\n}\n</code></pre>\n\n<p>Just to cover the case that whatever search it is didn't actually return anything.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-01T21:08:00.120", "Id": "528", "ParentId": "82", "Score": "3" } } ]
{ "AcceptedAnswerId": "90", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-20T10:25:28.040", "Id": "82", "Score": "7", "Tags": [ "php" ], "Title": "Loop with enclosing items every 'n' steps" }
82
<p>I was wondering for quite some time how to clean up the below code without blowing it up any further. The extension of the classes is the main concern here, it looks a bit too much like magic. That's mainly because it has to handle all the different cases, and I haven't figured out a way to reduce the code in a meaningful fashion here.</p> <p>Maybe I'm paranoid and the code is just fine, but I'd still love to get some feedback on it.</p> <p>The original code and test cases are <a href="https://github.com/BonsaiDen/neko.js" rel="nofollow">here</a>.</p> <pre><code>function is(type, obj) { return Object.prototype.toString.call(obj).slice(8, -1) === type; } function copy(val) { /* ...make shallow copy */ } function wrap(caller, obj) { obj = obj || Function.call; return function() { return obj.apply(caller, arguments); }; } function Class(ctor) { // ...default ctor stuff here.... function clas(args) { /* ...actual instance ctor stuff... */} var proto = {}; clas.init = wrap(ctor); // extend needs to be reduced in width, it easily goes over 80 columns // without some ugly if statements clas.extend = function(ext) { if (is('Function', ext)) { return ext.extend(proto); // holy closure! } for (var e in ext) { if (!ext.hasOwnProperty(e)) { continue; // a bit ugly imo, but it helps to prevent the indentation // from blowing up } // this needs some refactoring, it creates bound and unbound var val = ext[e], func = is('Function', val); if (/^\$/.test(e)) { // statics proto[e] = copy(val); clas[e] = clas.prototype[e] = func ? wrap(clas, val) : val; } else if (func) { clas[e] = wrap(proto[e] = clas.prototype[e] = val); } } return clas; }; // this could also need some clean up I suppose for (var i = ctor.hasOwnProperty('init') ? 0 : 1, l = arguments.length; i &lt; l; i++) { var arg = arguments[i]; is('Object', arg) ? clas.extend(arg) : arg.extend(clas); } return clas; } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:40:36.333", "Id": "391", "Score": "2", "body": "Don't emulate classes. This is ECMAScript." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-10T23:32:30.313", "Id": "1335", "Score": "0", "body": "A while back I took a crack at making my own class definition system and if I recall my goals were similar to the things you accomplish herein. Yours looks more concise in various ways and JS development in general has come a long way since then, but I'll see if I can dig it up and find any nuggets of cleverness that might apply as well here. All in all, I find the latest revision to be pretty succinct for what it is, though admittedly I haven't given it a full on review. Still, I like what I see :)" } ]
[ { "body": "<p>A few tips:</p>\n\n<ul>\n<li>Make sure your using good indentation</li>\n<li>Do not create a function that runs a native method\n<ul>\n<li>so: <code>if(is(\"Function\",ext))</code> becomes <code>if(typeof ext == \"Function\")</code></li>\n</ul></li>\n<li>remove unnecessary comments and comments should only be at the head of an entity.</li>\n<li>Do not shorten your variables as it causes issues with the latter developers</li>\n<li>use stricter typecasting:\n<ul>\n<li><code>if (!ext.hasOwnProperty(e))</code> becomes <code>if(ext.hasOwnProperty(e) == false)</code></li>\n</ul></li>\n<li>Keep your conditions in the for loops on one line</li>\n<li>There's is not point in reassigning a value from an array becuase you want to send it to a function\n<ul>\n<li><code>var arg = arguments[i];</code> gets removed and <code>arguments[i]</code> is sent to the function</li>\n</ul></li>\n</ul>\n\n<p>Taking into account the above your class would look like so:</p>\n\n<pre><code>function Class(ClassBase)\n{\n /*\n * Default Constructor, used to do XXX with YYY\n */\n var Arguments = args || [];\n\n function __Class(Arguments)\n {\n\n }\n\n var Prototype = {};\n __Class.Initialize= Wrap(ClassBase);\n\n\n /*\n * extend needs to be reduced in width, it easily goes over 80 columns\n * without some ugly if statements\n */\n\n __Class.Extend = function(ExtendableEntity)\n {\n if (typeof ExtendableEntity == \"function\")\n {\n return ExtendableEntity.extend(Prototype);\n }\n\n for (var Entity in ExtendableEntity)\n {\n if (ext.hasOwnProperty(Entity) == true)\n {\n var Value = ext[Entity]\n var _Function = (typeof Value == \"function\");\n\n if (/^\\$/.test(Entity)) \n {\n Prototype[Entity] = Copy(Value);\n __Class[Entity] = __Class.Prototype[Entity] = function ? Wrap(__Class, Value) : Value;\n }else \n {\n __Class[Entity] = Wrap(Prototype[Entity] = __Class.Prototype[Entity] = Value);\n }\n }\n }\n return __Class;\n }\n\n for (var i = ClassBase.hasOwnProperty('Initialize') ? 0 : 1, l = Arguments.length; i &lt; l; i++)\n {\n (typeof Arguments[i] == 'object') ? __Class.Extend(Arguments[i]) : Arguments[i].Extend(__Class);\n }\n return __Class;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T12:17:17.903", "Id": "121", "Score": "5", "body": "Uh, that's exactly what I didn't want :D Someone with a lot less knowledge about JS posting an answer. First of `is(\"Function\",ext)` is **not** `typeof`. `typeof` is completely broken, **never** use it for getting the type of an object. `arguments` is a special variable inside a functions scope. Starting method names with uppercase goes against all common practice in JS land. `hasOwnProperty` only returns `true` or `false` so `!` is completely ok in this case. Braces on next line can introduce subtle bugs. Check out: http://bit.ly/JSGarden for more infos." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T12:17:51.070", "Id": "122", "Score": "0", "body": "Aside from the above, you're right on using longer variable names and that there's no point of `var arg = arguments[i]`. PS: Your code fails all tests :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T12:25:32.187", "Id": "125", "Score": "0", "body": "Thats a fair comment, `is()` function is not available for review therefore I had to assume (you also stated in comment *Check for type*), Why is should you not use Upper-cased function within JavaScript, who said you should not and is there a reason? and the reason for `== true` is its always good to get used to strict type and value checking, Also my coded wasn't made to work, the reason for there format is to show an example of what my comments was for, pseudo only sir." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T14:00:05.407", "Id": "133", "Score": "5", "body": "`== true` is in **no** way strict typing. `==` **does do** type coercion. If you really wanted *strict* comparison of types, you would have used `===`. Also, it might be a good idea to check the source for left out methods before guessing around what they do, not that I'm ranting here, but I suppose that people who review code here actually put some effort into it when the links are provided. Concerning the use of uppercase, most of the big JS projects that I've seen (and also most of my code) uses uppercase only for user defined Types." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T10:46:23.970", "Id": "241", "Score": "2", "body": "@RobertPitt there is actually a reason not to use upper-case for regular function names: this is a convention that indicates that the function is a constructor, i.e. it is intended to be used with the keyword new. For example, new Date() vs getDate()." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T10:51:39.800", "Id": "242", "Score": "1", "body": "I would definitely *not* \"remove unnecessary comments\" and I strongly disagree that \"comments should only be at the head of an entity\". Comments should be as close as possible to the thing that is commented (principle of proximity, which helps to understand the association) if only because it's best to keep the comment within the same screen as commented code." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T12:06:55.883", "Id": "89", "ParentId": "85", "Score": "1" } }, { "body": "<p>I would suggest to add comments (Javadoc-style, but probably best if much lighter) to describe the intent of each method. Even the most simple ones. I found it especially useful in JavaScript to describe:</p>\n\n<ul>\n<li>the type and range of arguments expected</li>\n<li>which arguments are optional and what are the default values</li>\n<li>the type of the result value, if any</li>\n<li>what is the result when provided arguments do not match expectations</li>\n</ul>\n\n<p>Otherwise I agree with your inline comment \"this needs some refactoring, it creates bound and unbound\", corresponding code should be extracted into a separate function, which will also reduce nesting, which seems to be one of your worries.</p>\n\n<p>Regarding the code itself, I would rename wrap() to bind() to match <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind\">the bind() function added in ECMAScript 5</a> and I would rename l to length in the for loop as letter l is easily confused with number 1.</p>\n\n<p>I have doubts about this portion of the code:</p>\n\n<pre><code>if (is('Function', ext)) {\n return ext.extend(proto); // holy closure!\n}\n</code></pre>\n\n<p>In my understanding: you check first that ext is a funciton before calling the extend() method, but:</p>\n\n<ul>\n<li>extend() is not defined in JavaScript, it is one of your custom methods, so there is no guarantee that you will find this property on the function. You should probably add a check.</li>\n<li>I do not understand the intent: an inline comment would help :)</li>\n</ul>\n\n<p>All in all, I think it's fine that the code is a bit hairy because <a href=\"http://www.crockford.com/javascript/inheritance.html\">adding support for classes in JavaScript is no simple matter</a>, but a lot more inline comments (up to one comment per line of code for the most complex stuff) would improve the code readability immensely.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T15:20:47.520", "Id": "248", "Score": "1", "body": "Hm renaming `wrap` to `bind` seems indeed like a good idea. the `ext.extend` expects another `Class` instance, maybe an `ext instanceof clas` would be a better choice here. Adding comments might help too, my main problem is that it's hard to keep them short and simple, just as it is hard naming things. I'll try to clean it up and update the question then." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T13:17:03.077", "Id": "422", "Score": "0", "body": "Looks like you're on the right path :) I would suggest adding descriptions of parameters for each function, and inline comments for each bit of cleverness such as use of regular expression: \"if (/^\\$/.test(i))\"." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T11:21:24.270", "Id": "156", "ParentId": "85", "Score": "11" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-20T10:56:43.527", "Id": "85", "Score": "19", "Tags": [ "javascript", "classes" ], "Title": "Cleaning up class creation / extension" }
85
<p>I'm new to Postgres and PostGIS, but not to geospatial applications.</p> <p>I have a table loaded up with graph data in the form of links (edges). The link database has about <strong>60,000,000</strong> rows. I am trying to extract the nodes to allow for quicker searching. For some of my proof-of-concept work I was able to use the link table for the searches, but there will be lots of duplicates, and there's no guarantee that either the source column or the target column contains all nodes.</p> <p>This is Postgres &amp; PostGIS, so I am also using the table to cache a geometry->geography conversion. Yes I do need to use geography fields. I'm also copying the geometry information "just in case".</p> <p>Table creation SQL:</p> <pre><code>-- Recreate table and index DROP TABLE IF EXISTS nodes; CREATE TABLE nodes (node integer PRIMARY KEY, geog geography(POINT,4326) ); CREATE INDEX geogIndex ON nodes USING GIST(geog); SELECT AddGeometryColumn('nodes', 'geom', 4326, 'POINT', 2); -- Insert all unique nodes from the source column INSERT INTO nodes (node,geog,geom) SELECT DISTINCT ON (source) source,geography( ST_Transform(geom_source,4326)),geom_source FROM view_topo; -- Insert any nodes in the target column that we don't have already INSERT INTO nodes (node,geog,geom) SELECT DISTINCT ON (target) target,geography( ST_Transform(geom_target,4326)),geom_target FROM view_topo WHERE NOT EXISTS( SELECT 1 FROM nodes WHERE nodes.node = view_topo.target); VACUUM ANALYZE; </code></pre> <p>I left the first <code>INSERT</code> running overnight and it took about 2-3hrs to run. This resulted in about <strong>40,000,000</strong> unique nodes being added.</p> <p>I have just enabled the second <code>INSERT</code> and the <code>VACUUM ANALYZE</code>. I am expecting it to take until at least lunchtime.</p> <p>Luckily this is only a batch job that has to be executed once after I've loaded a new link table, but is there a better way? Is there a faster way?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T00:40:10.920", "Id": "173", "Score": "0", "body": "Yes Postgres doesn't like the VACUUM ANALYZE in a script like that. However the rest appears to have worked okay." } ]
[ { "body": "<p>Check out <a href=\"http://www.postgresql.org/docs/8.2/static/populate.html\" rel=\"noreferrer\">PostgreSQL's tips on adding a lot of data into a table</a>. In particular, are you sure that you need that index before <code>INSERT</code>ing all that data? It might speed things up if you create the index after all the data has been added to the table.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T14:48:29.170", "Id": "438", "Score": "1", "body": "Thanks. Yesterday I founded I needed an index on the geometry field - retroactively adding that took quite a while to execute. This initially made me doubtful, but then in conventional programming a create-store-access-destroy pattern on sorted data is usually a lot faster implemented with an unsorted container and as create-store-sort-access-destroy - ie. essentially what you are suggesting. Build it then sort it one big sort." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T04:46:33.527", "Id": "254", "ParentId": "92", "Score": "5" } }, { "body": "<p>WHERE NOT EXISTS is not fast SQL. How about a union of the two selects, inside a select distinct? I haven't got a postgresql instance to test this on, but maybe something like this:\nINSERT INTO nodes (node, geom, geom)\nSELECT DISTINCT ON (node), geom1, geom2\nFROM\n (SELECT source AS node,\n geography( ST_Transform(geom_source,4326)) AS geom1,\n geom_source AS geom2\n FROM view_topo\nUNION\n SELECT target AS node,\n geography( ST_Transform(geom_target,4326)) AS geom1,\n geom_target AS geom2\n FROM view_topo)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T15:17:34.970", "Id": "445", "Score": "0", "body": "Thanks, I'm trying a UNION. I guess the NOT EXISTS relies on a nested SQL statement which would be executed for each row." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T15:35:31.077", "Id": "449", "Score": "0", "body": "Out of memory! It sounds like your approach should be faster for smaller datasets but with 60M rows in my view_topo view, and about 8-9M unique rows to be inserted, my PC can't hack it. (4GB installed, but booted as 32 bit because PostGIS is currently only available for 32 bit)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T14:00:43.447", "Id": "273", "ParentId": "92", "Score": "4" } } ]
{ "AcceptedAnswerId": "254", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-20T13:55:23.193", "Id": "92", "Score": "8", "Tags": [ "sql", "postgresql" ], "Title": "Extracting nodes from a graph database" }
92
<p>I have written a method to tokenize HTTP request paths such as <code>/employee/23/edit</code>:</p> <pre><code>protected void compile(String path){ int mark=0; for(int i=0; i&lt;path.length(); ++i){ if(path.charAt(i)==DELIM){ if(mark!=i) tokens.add(path.substring(mark,i)); mark=i+1; } else if(path.length()==i+1){ tokens.add(path.substring(mark,i+1)); } } } </code></pre> <p>And a method to tokenize the consumer of these paths such as <code>/employee/[id]/edit</code>:</p> <pre><code>protected void compile(String path){ int mark=0; boolean wild=false; for(int i=0; i&lt;path.length(); ++i){ if(!wild){ if(path.charAt(i)==DELIM){ if(mark!=i) tokens.add(path.substring(mark,i)); mark=i+1; } else if(path.length()==i+1){ tokens.add(path.substring(mark,i+1)); } else if(path.charAt(i)=='['){ wild=true; } } else if(path.charAt(i)==']'){ tokens.add("?"); wild=false; mark=i+1; } } } </code></pre> <p>The idea here is that there will be an implicit variable called <code>id</code> with the value <code>23</code>. However, that isn't here nor there. How does my approach look? Can it be improved? Also: <code>DELIM = '/'</code>.</p> <p>This is more-or-less an exercise in writing a parser, which is why I didn't use <code>String#split()</code>.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T18:23:19.373", "Id": "155", "Score": "1", "body": "Wouldn't String.split() work better for tokenizing a String (http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String))?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T18:26:43.273", "Id": "156", "Score": "1", "body": "It looks like anything between the last `/` and an opening `[` will be ignored. Is that intentional?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T18:28:54.130", "Id": "157", "Score": "0", "body": "@shambleh: This was more or less an exercise in writing a simple parser. I anticipate it becoming more complicated over time where `String#split()` wont suffice." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T18:44:48.290", "Id": "160", "Score": "0", "body": "It also seems weird to me that you're just discarding the names of the variables like that. Though without knowing how you'll use the result of the compile method, it's hard to say whether it's bad or not." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T18:54:44.520", "Id": "161", "Score": "0", "body": "@sepp2k: For sake of posting less code, you don't see anything more than the parsing aspect. I took out the part you are referring to." } ]
[ { "body": "<p>Your first <code>compile</code> method can be replaced by a single call to <code>String.split</code>.</p>\n\n<p>Assuming the intended behavior for the second <code>compile</code> method is such that \"/foo/b[a]r/baz\" will compile to <code>{\"foo\", \"?\", \"baz\"}</code>, it can be replaced by a call to <code>split</code> and then iterating over the result and replacing any string the includes square brackets with \"?\".</p>\n\n<p>If the intended behavior is rather that it will compile to <code>{\"foo\", \"b\", \"?\", \"r\", \"baz\"}</code>, you can first replace <code>[anything]</code> by <code>/?/</code> using <code>String.replace</code> and then use <code>String.split</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T18:30:53.690", "Id": "110", "ParentId": "109", "Score": "11" } }, { "body": "<p>Just as an exercise in making the code easier to read, I'd recommend better variable names. I can figure out what \"wild\" and \"mark\" are, but it should be immediately apparent to me so I don't have to spend time trying to figure out what they are.</p>\n\n<p>Also, I'm assuming you are going to eventually handle URLs with \"?\" and such in them. You may want to consider checking for invalid characters in the URL so you know when you hit the end of the actual request path.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T19:59:53.783", "Id": "165", "Score": "0", "body": "I have to disagree about the variable names, unless you can suggest better ones? `mark` is a perfectly valid in my opinion because it is marking a point in the string. I could change `wild` to `isWild` I suppose. As for handling question marks, no, the purpose for the paths with wildcards is to be parsed on the server when the web application starts up. I intend to annotate a method like this: `@Get(\"/employees/[id]\")`. I am just dealing with paths, not the query string." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T17:20:46.847", "Id": "254", "Score": "0", "body": "Well, 'position' might make the intent clearer than 'mark' :) As for 'wild', a name including 'wildcard' might be easier to understand." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T19:49:02.543", "Id": "114", "ParentId": "109", "Score": "5" } } ]
{ "AcceptedAnswerId": "110", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-20T18:14:40.340", "Id": "109", "Score": "14", "Tags": [ "java", "parsing", "url" ], "Title": "HTTP request path parser" }
109
<p>I have written this (truncated) code to fetch some tweets:</p> <pre><code> dispatch_async(dispatch_get_global_queue(0, 0), ^{ [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; NSString *JSONStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://search.twitter.com/search.json?q=haak&amp;lang=nl&amp;rpp=100"] encoding:NSUTF8StringEncoding error:nil]; if (!JSONStr) { [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; return; } /*... PARSING ETC ...*/ dispatch_sync(dispatch_get_main_queue(), ^{ [delegate didReceiveTweets:foundTweets]; }); [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; }); </code></pre> <p>Note the lines from <code>dispatch_sync(dispatch_get_main_queue(), ^{</code> to <code>});</code>. This will update the UI.</p> <p>Is this the good way to do it, or are there better ways than using <code>dispatch_sync</code> within a <code>dispatch_async</code>? Or should I not do this at all? Should I also send <code>setNetworkActivityIndicatorVisible:</code> from within the main thread?</p> <p>The reason I'm not using <code>NSURLConnection</code> is because this code comes from a class method, so I need to create an object containing the delegate for the <code>NSURLConnection</code>, which seems overkill to me.</p>
[]
[ { "body": "<p>you don't necessarily have to call -setNetworkActivityIndicatorVisible: from the main thread. I didn't find anything in the documentation about UIApplication not being thread safe, and since your application's main thread doesn't have anything in common with the system, you are free to call it whenever you like.</p>\n\n<p>dispatch_sync: that's fine. you could also call dispatch_async, since i'm not really sure you would want do display the network indicator while the feeds are actually being set on the UI - instead you probably only want the downloading to be indicated. I would probably go for dispatch_async.</p>\n\n<p>But to answer your question, that piece of code is perfectly fine ( with the minor addition that maybe you should really use only one exit point from your method ... )</p>\n\n<p>Hope this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-20T10:33:54.050", "Id": "17554", "Score": "0", "body": "But if the method makes any UI calls, it still needs to be called on the main thread." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T09:26:03.907", "Id": "195", "ParentId": "112", "Score": "7" } }, { "body": "<p>Typically you want to perform UI interactions from the main thread, I would just move it to before the first dispatch_async call to turn it on. Then have it turn off in the later dispatch in the main_queue, so that it also happens on the main thread. This of course assumes that you were calling from the main thread to start with. If not you could just make another call to dispatch_async with the main_queue at the beginning.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T00:52:33.923", "Id": "249", "ParentId": "112", "Score": "4" } }, { "body": "<p>Avoid to dispatch sync code on main queue. This can cause freezing because this code supposed to run on main thread will wait until main thread will be able to run it. In the same time this code will block main thread. Try always use:</p>\n\n<pre><code>dispatch_async(dispatch_get_main_queue(), ^{});\n</code></pre>\n\n<p>Also this is bad style to use direct numerical values of system constants. Try to use predefined values:</p>\n\n<pre><code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ .. });\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-20T05:16:53.597", "Id": "13857", "ParentId": "112", "Score": "1" } } ]
{ "AcceptedAnswerId": "195", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-20T19:19:39.800", "Id": "112", "Score": "14", "Tags": [ "multithreading", "objective-c", "twitter" ], "Title": "Fetching tweets" }
112
<p>I have a Perl application that allows the user to choose between two different formats for data output (and there will likely be more in the near future). In the heart of the algorithm, the code makes a call to a print subroutine.</p> <pre><code>my $stats = analyze_model_vectors( $reference_vector, $prediction_vector ); print_result( $stats, $tolerance ); </code></pre> <p>The <code>print_result</code> subroutine simply calls more specific methods.</p> <pre><code>sub print_result { if($outformat eq "text") { print_result_text(@_); } elsif($outformat eq "xml") { print_result_xml(@_); } else { # Should not reach this far if input checking is done correctly printf(STDERR "Error: unsupported output format '%s'\n", $outformat); } } </code></pre> <p>Is this good practice? What other alternatives are there and what are their pros/cons? I could think of the following alternatives.</p> <ul> <li>Test for output format in the heart of the algorithm, and call the appropriate printing subroutine there.</li> <li>I've never used subroutine references before, but perhaps when I could store a reference to the correct subroutine in a scalar variable and call the print method with that scalar in the heart of the algorithm.</li> <li>Place code for all output formats in a single subroutine, separated by <code>if/elsif/else</code> statements.</li> </ul> <p>Keep in mind there may be more output formats required in the near future.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T18:26:59.350", "Id": "4224", "Score": "1", "body": "Big if/elsif/else chains are ugly. The canonical method of handling this case in Perl is to use a dispatch table: a hash containing subroutine references. See Charles Bailey's response. A tempire offers a more exotic approach, that uses Perl's internal symbol tables for the lookup." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-13T18:33:41.423", "Id": "121221", "Score": "0", "body": "How/where is `$outformat` specified?" } ]
[ { "body": "<p>I try to avoid Perl if I can, so this is more of a general answer: I've coded like this in an old VB6 app. Each output function had a wrapper function that then called the required implementation using a series of IFs. Sometimes a particular output method wouldn't need anything - eg. \"Start New Line\" is relevant for text file output, but not Excel worksheet output.</p>\n\n<p>I'm currently in the process of porting/re-writing that particular app in C#/.NET 4, where I've been able to take a much more object oriented approach. \nI have defined an \"output base class\" with a standard interface. This is then inherited by the various implementations. As I start the output, I can create the required implementation using a factory method/class, and pass data to it using the standard interface.</p>\n\n<p>This particular implementation is actually multi-threaded, so the bulk of the output base class is actually the thread &amp; queue management. Data is then passed in using a small \"data chunk\" class, and queued for output using a thread-safe queue.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T17:16:29.267", "Id": "253", "Score": "1", "body": "The OO approach is definitely making things easier to handle, conceptually and practically. Thanks!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-09T13:06:13.803", "Id": "1277", "Score": "2", "body": "Can't downvote this yet, but the OOP approach is completely overkill and unnecessary here. Languages like VB6 and Java (not too sure about C#) don't have first-class functions so that you are supposed to do some OOP magic. Perl has first-class functions and thus you can use them as any other variable. The answer provided by Charles Bailey is thus more correct and also more appropriate for the provided code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T23:57:39.137", "Id": "10829", "Score": "1", "body": "Seriously, I would down-vote this twice if I could. ( I don't have enough rep to down-vote yet )" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-20T20:55:54.960", "Id": "116", "ParentId": "115", "Score": "4" } }, { "body": "<p>If you can pass in the subroutine it makes the code a lot simpler, you also don't have to deal with an unknown string format as the subroutine itself has been passed in.</p>\n\n<pre><code>sub print_result\n{\n my $subroutine = shift;\n &amp;$subroutine( @_ );\n}\n\nprint_result( \\&amp;print_result_text, $arg1, $arg2 )\n</code></pre>\n\n<p>Otherwise I think I'd go with with a hash of subroutine references. It's easily readable and simple to update.</p>\n\n<pre><code>sub print_result\n{\n my %print_hash = ( text =&gt; \\&amp;print_result_text,\n xml =&gt; \\&amp;print_result_xml );\n\n if( exists( $print_hash{ $outformat } ) )\n {\n &amp;{$print_hash{ $outformat }}( @_ );\n }\n else\n {\n printf(STDERR \"Error: unsupported output format '%s'\\n\", $outformat);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T17:15:36.787", "Id": "252", "Score": "0", "body": "I think I'll try using the subroutine references." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T22:47:15.107", "Id": "118", "ParentId": "115", "Score": "15" } }, { "body": "<p>I'd use anonymous subroutines to make the code cleaner:</p>\n\n<pre><code>my %output_formats = (\n 'text' =&gt; sub {\n # print_result_text code goes here\n },\n 'xml' =&gt; sub {\n # print_result_xml code goes here\n },\n # And so on\n);\n\nsub print_result {\n my ($type, $argument1, $argument2) = @_;\n\n if(exists $output_formats{$type}) {\n return $output_formats{$type}-&gt;($argument1, $argument2);\n } else {\n die \"Type '$type' is not a valid output format.\";\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T04:34:43.130", "Id": "253", "ParentId": "115", "Score": "5" } }, { "body": "<p>I find that Perl's flexibility can help you eliminate many IF/ELSIF/* code constructs, making code much easier to read.</p>\n\n<pre><code>sub print_result {\n my ($stats, $tolerance, $outformat) = @_;\n\n my $name = \"print_result_$outformat\";\n\n print \"$outformat is not a valid format\" and return\n if !main-&gt;can($name);\n\n no strict 'refs';\n &amp;$name(@_);\n}\n\nsub print_result_xml { ... }\nsub print_result_text { ... }\nsub print_result_whatever { ... }\n</code></pre>\n\n<p><br>\n<strong>Walkthrough</strong></p>\n\n<pre><code>print \"$outformat is not a valid format\" and return if !main-&gt;can($name);\n</code></pre>\n\n<p>This checks the main namespace <em>(I presume you're not using classes, given your code sample)</em> for the $name subroutine. If it doesn't exist, print an error message and get out. The sooner you exit from a subroutine, the easier your code will be to maintain.</p>\n\n<pre><code> no strict 'refs';\n</code></pre>\n\n<p>no strict 'refs' turns off warnings &amp; errors that would be generated for creating a subroutine reference on the fly <em>(You're using 'use strict', aren't you? If not, for your own sanity, and for the children, start)</em>. In this case, since you've already checked for it's existence with main->can, you're safe.</p>\n\n<pre><code> &amp;$name(@_);\n</code></pre>\n\n<p>Now you don't need any central registry of valid formatting subroutines - just add a subroutine with the appropriate name, and your program will work as expected.</p>\n\n<p>If you want to be super hip <em>(some might say awesome)</em>, you can replace the last 5 lines of the subroutine with:</p>\n\n<pre><code>no strict 'refs';\nmain-&gt;can($name) and &amp;$name(@_) or print \"$outformat is not a valid format\";\n</code></pre>\n\n<p>Whether you find that more readable or not is a simple personal preference; just keep in mind the sort of folk that will be maintaining your code in the future, and make sure to code in accordance with what makes the most sense to them.</p>\n\n<p>Perl is the ultimate in flexibility, making it inherently the hippest language in existence. Make sure to follow <a href=\"http://blogs.perl.org\">http://blogs.perl.org</a> and ironman.enlightenedperl.org to keep up with the latest in Modern::Perl.</p>\n\n<p>On a separate note, it's Perl, not PERL. The distinction is important in determining reliable &amp; up-to-date sources of Perl ninja-foo.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T18:30:59.923", "Id": "4225", "Score": "0", "body": "Why not use eval? `eval { &$name(@_); 1 } or print \"$outformat is not a valid format\\n\";` `can()` may be fooled by autoloaded functions and other magics, but simply trying the call is as authoritative as it gets." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-03T03:39:24.197", "Id": "4327", "Score": "0", "body": "eval is brute force. Calling the function outright assumes it's idempotent and has no unintended side effects. Also, it seems to me errors should always be avoided. Using eval/try/catch is for the !@#$ moments that _should_ never happen." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T06:17:24.057", "Id": "256", "ParentId": "115", "Score": "6" } } ]
{ "AcceptedAnswerId": "118", "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-20T20:31:26.477", "Id": "115", "Score": "14", "Tags": [ "perl", "subroutine" ], "Title": "Subroutine to call other subroutines" }
115
<p>So I have a series of objects, which I will call Impl1, Impl2, and Impl3. They each implement an interface, called IImpl. I have a Factory class who's task is to retrieve the ImplX which is appropriate for a given circumstance, and pass it on to its callers. So the code in the factory looks like:</p> <pre><code>public IImpl GetInstance(params object[] args) { if (args[0]=="Some Value") return new IImpl1(); else if (args[0]=="Other Value") return new IImpl2(args[1]); else return new IImpl3(args[1]); } </code></pre> <p>So depending on the arguments passed in, different instances are selected. All well and good and works ok. The problem now is, that I have a class which needs to call this factory method. It has no references to IImplX, which is good, but it winds up having to know exactly how to construct the input array to GetInstance, in order to ensure it receives the correct kind of instance. Code winds up looking like:</p> <pre><code>switch (_selectedInputEnum) { case InputType.A: myIImplInst = Factory.GetInstance("Some Value"); case InputType.B: myIImplInst = Factory.GetInstance("Other Value",this.CollectionB); case InputType.C: myIImplInst = Factory.GetInstance("Third Value",this.CollectionC); } </code></pre> <p>This feels very redundant, and off somehow. What would be the best way to abstract the actual parameters of the factory? I feel like with the above switch statement, I am strongly coupled to the implemenations of IImplx, even if I don't have a direct reference.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T13:52:27.023", "Id": "245", "Score": "0", "body": "I think either we need more information, or you're expectations can't be met: if you are required to pass different kinds of parameters to this factory for it to work properly, then the client code always has to provide these parameters, and therefore always has to know which overload to call or which parameters to supply." } ]
[ { "body": "<p>How about some kind of intermediary blackboard that the client code constructs before calling the factory, and each concrete Impl can poll to construct itself?</p>\n\n<pre><code>// client code:\n\nBlackboard blackboard = new Blackboard();\nblackboard.pushCollectionB(collectionB);\nblackboard.pushCollectionC(collectionC);\nblackboard.pushFoo(foo); \n\nIImpl myInstance = Factory.GetInstance(b);\n\n///////////////////////////\n\n// in Factory.GetInstance():\n\nreturn new Impl3(blackboard);\n\n////////////////////////////\n\n// in Impl3:\n\nImpl3(Blackboard b) { process(b.getCollectionC()); }\n</code></pre>\n\n<p>I've hidden the switch statement in the client code, but you could move that into the blackboard as well.</p>\n\n<p>What data each concrete Impl needs is now hidden from both the Factory and the client code. However if you need more data in your Blackboard for Impl(x+1) you will need to update every place in your code that creates a Blackboard.</p>\n\n<p>Depending on application, over-constructing the Blackboard like this may be expensive for you. You could construct a cached version at startup, or you could make the Blackboard an interface and have your client code derive from it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T14:45:38.703", "Id": "188", "Score": "0", "body": "In this construct, the factory itself would have to know which ImplX to call, presumably by polling the blackboard itself?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T15:17:04.793", "Id": "191", "Score": "0", "body": "You could go either way, leaving the switch in the client code to translate from InputType, and passing the string into the Factory alongside the Blackboard, or push it into the Blackboard as you suggest. Either way works." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T14:42:09.250", "Id": "129", "ParentId": "128", "Score": "9" } }, { "body": "<p>It seems to me that the factory should be choosing the ImplX based on arg[1] then instead of arg[0]. </p>\n\n<p>So something like this would remove the need for the switch, arg[1] is now arg[0] in this example:</p>\n\n<pre><code>public IImpl GetInstance(params object[] args)\n{\n if (args.length == 0)\n return new IImpl1();\n else if (args[0] is IEnumerable&lt;string&gt;)\n return new IImpl2(args[0]);\n else\n return new IImpl3(args[0]);\n}\n</code></pre>\n\n<p>You could then call it like:</p>\n\n<pre><code>var impl1 = GetInstance();\nvar impl2 = GetInstance(new List&lt;string&gt;{\"1\",\"2\"});\nvar impl3 = GetInstance(\"\");\n</code></pre>\n\n<p>Edit:\nIf you don't want the caller to have to know the inner works of it then you should expose overloads for getInstance so:</p>\n\n<pre><code>public IImpl GetInstance()\n{ \n return new Impl1();\n}\npublic IImpl GetInstance(IEnumberable&lt;string&gt; strings)\n{\n return new Impl2(strings);\n}\npublic IImpl GetInstance(string string)\n{\n return new Impl3(string);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T19:52:37.873", "Id": "221", "Score": "1", "body": "That still requires that the caller of GetInstance (your second code block in this case) know about the internals of how GetInstance works (in this case, knowing to pass different parameters in different orders to GetInstance)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T20:02:08.073", "Id": "223", "Score": "0", "body": "Then I think you will need to create some overrides for GetInstance that support the different calling methods." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T20:31:13.130", "Id": "225", "Score": "1", "body": "Wouldn't they still have to know which override to call?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T20:37:36.823", "Id": "226", "Score": "0", "body": "Are they supposed to be able to decide what ImplX they are getting? If so then instead of GetInstance(IEnumerable<string> strings) it would be GetInstanceImpl2(IEnumerable<string> strings)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T19:44:38.703", "Id": "141", "ParentId": "128", "Score": "1" } }, { "body": "<p>Seems like your abusing the factory pattern, the whole purpose of a factory is that you pass it some general object and the factory decides what is most appropriate to return. The passed object doesnt need to know about the factory but the factory should know about the object it's passed.</p>\n\n<p>If you need to pass it very explicit parameters then that is a code smell in your architecture and I'd think seriously about doing some refactoring rather than just \"fixing\" this problem</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T14:43:17.427", "Id": "272", "Score": "1", "body": "That's the exact intent of this question; refactoring this into a better solution." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T12:23:40.070", "Id": "169", "ParentId": "128", "Score": "1" } }, { "body": "<p>Where are CollectionB and CollectionC coming from? The approach I'd shoot for is to have a variety of factories that all accept the same type of input, and then store them in some type of collection. For example, if one has a list of objects to be created, one object per line, and the portion of each line before the first blank defines the type of each item, one could have a factories that take a string and yield an appropriately-configured object. For example, if the input looked like:</p>\n\n<pre>\nsquare 0,5,5,29\nline 5,2 19,23 6,8\ntext 0,29,Hello there!\n</pre>\n\n<p>one could have a SquareFactory, LineFactory, and TextFactory all of which inherit from GraphicObjectFactory, which accept a string and return GraphicObject. One could then have a Dictionary that maps String to GraphicsObjectFactory, and put in it an instance of each of the above mentioned factories. To allow the file reader to handle more types of graphics objects, just add more factories into the Dictionary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T02:03:01.817", "Id": "627", "Score": "0", "body": "Unless I'm misreading this, it seems like a similar concept to tenpn's answer, which is near to what I did, so I like it :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T23:40:25.250", "Id": "764", "Score": "0", "body": "It's somewhat like tenpn's answer, except that his \"blackboard\" is configured by code in various clients of the class, while I would expect to have the factory constructed from a configuration file or other single point of definition." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T21:08:47.497", "Id": "385", "ParentId": "128", "Score": "7" } }, { "body": "<p>It says this question was first posted 5 years ago, but no one ever answered it so here goes.</p>\n<p>First of all, let's get a bit more detail into the example.\nI suggest we use an IPersistable interface which supports one public method named Save(). It'll look like the following:</p>\n<pre><code>interface IPersistable {\n bool Save();\n}\n</code></pre>\n<p>Next, we want three classes which implement this method:</p>\n<pre><code>class FileSaver : IPersistable{\n public bool Save(){\n Console.WriteLine(&quot;I'm saving into a FILE.&quot;);\n return true;\n }\n}\n\nclass DatabaseSaver : IPersistable{\n public bool Save(){\n Console.WriteLine(&quot;I'm saving into a DATABASE.&quot;);\n return true;\n }\n}\n\nclass TcpSaver : IPersistable{\n public bool Save(){\n Console.WriteLine(&quot;I'm saving into a WEB LOCATION.&quot;);\n return true;\n }\n}\n</code></pre>\n<p>Finally, we need a factory class which will build our appropriate class on demand.</p>\n<pre><code>class SaverFactory{\n private string type;\n public SaverFactory(string type){\n this.type = type;\n }\n \n public IPersistable CreateSaver(){\n switch (type){\n case &quot;FileSaver&quot; :\n {\n return new FileSaver();\n }\n case &quot;DatabaseSaver&quot; :\n {\n return new DatabaseSaver();\n }\n case &quot;TcpSaver&quot; :\n {\n return new TcpSaver();\n }\n default : \n return null;\n }\n }\n}\n</code></pre>\n<p>You can now copy that C# code and paste it into a LINQPad (<a href=\"http://linqpad.net\" rel=\"nofollow noreferrer\">http://linqpad.net</a>) session and add the following main method and it will work beautifully.</p>\n<pre><code>void Main()\n{\n List&lt;IPersistable&gt; allItems = new List&lt;IPersistable&gt;();\n List&lt;String&gt; fakeData = new List&lt;String&gt;();\n fakeData.Add(&quot;FileSaver&quot;); fakeData.Add(&quot;DatabaseSaver&quot;);\n \n foreach (String s in fakeData){\n IPersistable ip = new SaverFactory(s).CreateSaver();\n if (ip != null)\n allItems.Add(ip);\n }\n \n foreach (IPersistable ip in allItems)\n {\n ip.Save();\n }\n}\n</code></pre>\n<p><strong>Code Run Result</strong></p>\n<p>If you run that code you will see the following:</p>\n<blockquote>\n<p>I'm saving into a FILE.</p>\n<p>I'm saving into a DATABASE.</p>\n</blockquote>\n<p>That is a proper working Factory method. It is dependent upon the type string that you pass in. That is expected, because you are telling it that you are building a specific type and that is expected.</p>\n<p><strong>What If Dependent Type Needs Parameters For Configuration?</strong></p>\n<p>However, what you are wondering now is what happens if the type you are requesting to be built by the factory needs some other parameters so that it can configure itself.</p>\n<p>For example in this case I would want to send in a database connection for the DatabaseSaver and a file path and name for the FileSaver and a URI for the TcpSaver. You believed that providing that configuration information for building the implementation object somehow sullied your design, but I don't believe it does.</p>\n<p>I mean the whole point of a factory is that something tells it to build a specific implementation class. In my case I create a list of strings which are then passed in to the factory. Imagine those strings were loaded with other information which configures my IPersistable implementation. That would be fine.</p>\n<p>Let's move the example ahead a bit by showing how I might pass the needed configuration item into the factory so the IPersistable implementation class can be constructed around that extra configuration information.</p>\n<p><strong>Create New Interface and Classes : IConfigurable</strong></p>\n<pre><code>interface IConfigurable{\n String type{get;set;}\n}\n\nclass FileConfig : IConfigurable{\n public String type{get;set;}\n public string FileName{get;set;}\n public FileConfig(String type, String fileName=null){\n this.type = type;\n FileName = fileName;\n }\n \n}\nclass DatabaseConfig : IConfigurable{\n public String type{get;set;}\n public string ConnectionString{get;set;}\n public DatabaseConfig(String type, String ConnectionString=null){\n this.type = type;\n this.ConnectionString = ConnectionString;\n }\n}\n\nclass TcpConfig : IConfigurable{\n public String type{get;set;}\n public string Uri {get;set;}\n}\n</code></pre>\n<p>I became a little lazy on that last one and didn't implement it all because I know no one will read all of this. I will leave you with the entire code listing which you can run and examine using LINQPad.</p>\n<pre><code>void Main()\n{\n List&lt;IPersistable&gt; allItems = new List&lt;IPersistable&gt;();\n List&lt;IConfigurable&gt; fakeData = new List&lt;IConfigurable&gt;();\n fakeData.Add(new FileConfig(&quot;FileSaver&quot;,@&quot;c:\\superpath&quot;)); \n fakeData.Add(new DatabaseConfig(&quot;DatabaseSaver&quot;,@&quot;connection=superdb;integrated security=true&quot;));\n \n foreach (IConfigurable ic in fakeData){\n IPersistable ip = new SaverFactory(ic).CreateSaver();\n if (ip != null)\n allItems.Add(ip);\n }\n \n foreach (IPersistable ip in allItems)\n {\n ip.Save();\n }\n}\n\ninterface IPersistable {\n bool Save();\n}\n\ninterface IConfigurable{\n String type{get;set;}\n}\n\nclass FileConfig : IConfigurable{\n public String type{get;set;}\n public string FileName{get;set;}\n public FileConfig(String type, String fileName=null){\n this.type = type;\n FileName = fileName;\n }\n \n}\nclass DatabaseConfig : IConfigurable{\n public String type{get;set;}\n public string ConnectionString{get;set;}\n public DatabaseConfig(String type, String ConnectionString=null){\n this.type = type;\n this.ConnectionString = ConnectionString;\n }\n}\n\nclass TcpConfig : IConfigurable{\n public String type{get;set;}\n public string Uri {get;set;}\n}\n\nclass FileSaver : IPersistable{\n IConfigurable config;\n public FileSaver(IConfigurable config){\n this.config = config;\n }\n public bool Save(){\n Console.WriteLine(&quot;I'm saving into a FILE.&quot;);\n var configItem = config as FileConfig;\n Console.WriteLine(configItem.FileName);\n return true;\n }\n}\n\nclass DatabaseSaver : IPersistable{\n IConfigurable config;\n public DatabaseSaver(IConfigurable config){\n this.config = config;\n }\n public bool Save(){\n Console.WriteLine(&quot;I'm saving into a DATABASE.&quot;);\n var configItem = config as DatabaseConfig;\n Console.WriteLine(configItem.ConnectionString);\n return true;\n }\n}\n\nclass TcpSaver : IPersistable{\n IConfigurable config;\n public TcpSaver(IConfigurable config){\n this.config = config;\n }\n public bool Save(){\n Console.WriteLine(&quot;I'm saving into a WEB LOCATION.&quot;);\n return true;\n }\n}\n\nclass SaverFactory{\n IConfigurable config;\n public SaverFactory(IConfigurable config){\n this.config = config;\n }\n \n public IPersistable CreateSaver(){\n switch (config.type){\n case &quot;FileSaver&quot; :\n {\n return new FileSaver(config);\n }\n case &quot;DatabaseSaver&quot; :\n {\n return new DatabaseSaver(config);\n }\n case &quot;TcpSaver&quot; :\n {\n return new TcpSaver(config);\n }\n default : \n return null;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-21T20:45:26.283", "Id": "235932", "Score": "2", "body": "Errr, did you post to the right question? The code you are reviewing has nothing to do with the code in the question. Also, there are 4 answers already so it was answered." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-21T20:49:09.713", "Id": "235935", "Score": "0", "body": "I know. I know it's 5 years old. I thought the OP wanted an explanation of the Factory pattern and how it is possible to configure. OP's original code made it very difficult for others to answer and needed some details behind it. My sample runs and shows that you can send in params to the Factory to create your implementation classes and that sending in params can be a valid part of using the Factory pattern." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-22T03:08:05.027", "Id": "235986", "Score": "0", "body": "This old question was off-topic at the time (and with good answers) and is no longer off-topic, thus it's been historical locked. If you would like to discuss it with the OP more (if he/she sees this), then it can be taken to chat." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-21T20:25:07.637", "Id": "126357", "ParentId": "128", "Score": "0" } } ]
{ "AcceptedAnswerId": "129", "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T14:07:09.330", "Id": "128", "Score": "23", "Tags": [ "c#", ".net", "design-patterns" ], "Title": "Best way to pass parameters to Factory class?" }
128
<p><em>Inspired by <a href="https://codereview.stackexchange.com/q/97">this question</a>, but hopefully not a duplicate.</em></p> <p>I understand that the Law of Demeter is very useful in case of services interacting with other services, for example it's much easier to mock the other services in unit tests. What about services interacting with data models, though?</p> <p>Let's say I have a hierarchy of immutable classes:</p> <pre><code>public final class Document { private final List&lt;Page&gt; pages; // Constructor, getter, ... } public final class Page { private final List&lt;Paragraph&gt; paragraphs; // Constructor, getter, ... } public final class Paragraph { private final List&lt;Line&gt; lines; // Constructor, getter, ... } </code></pre> <p>Let's say I want to do something with certain lines in a document <code>doc</code>:</p> <pre><code>public void doSomething(Document doc) { for (Page page : doc.getPages()) { for (Paragraph para : page.getParagraphs()) { for (Line line : para.getLines()) { if (someCondition(line)) { someAction(line); } } } } </code></pre> <p>Now, as far as I understand, the above code doesn't obey the Law of Demeter. However, I don't want to force the law at all cost and clutter the model (here, the <code>Document</code> class) with tens of methods like:</p> <pre><code>public List&lt;Line&gt; filterWrtSomeCondition(); public List&lt;Line&gt; filterWrtSomeOtherCondition(); </code></pre> <p>Or maybe there's a third way? I suspect that the Law of Demeter applies primarily to services interacting with other services. Is it a valid interpretation?</p>
[]
[ { "body": "<p>I'd say that it isn't cluttering the model personally. You are actually protecting yourself by not exposing internal implementation of your document class. The entire idea is to put all of your behavior into your class instead of having external code modify the class in such a way that it may not pass its own internal invariants.</p>\n\n<p>Perhaps it also would make sense to make subclasses of your Document class which are specialized and only have the methods related to that usage of your Document. You don't have to have a one stop shop where you can do absolutely everything, since that's probably not going to be your primary use case in all instances.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T17:41:24.653", "Id": "208", "Score": "0", "body": "Thanks for your answer! Although I didn't stress that, I've mentioned that the model is immutable, so there is no way to \"break\" it once it's created. Does that change anything?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T17:42:08.957", "Id": "209", "Score": "2", "body": "I'm skeptical of adding subclasses, though. For one, I can clearly name and document the `Document` class, but how do I name a `Document` subclass with methods for evaluating text readability, or with methods for finding occurrences of a given phrase? As in: \"If you can't name it, it shouldn't be a class.\"" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T17:59:42.617", "Id": "210", "Score": "0", "body": "Didn't catch on to the immutable part. It at least makes it so you can't break it, but exposing the internal implementation is still valid. Without knowing your use case, I'm just guessing and saying that subclasses may be a valid way to address your concern of adding many methods (they may be broken up)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T17:07:04.617", "Id": "133", "ParentId": "131", "Score": "2" } }, { "body": "<p>For some perspective on the LoD, read \"<a href=\"http://haacked.com/archive/2009/07/14/law-of-demeter-dot-counting.aspx\" rel=\"nofollow noreferrer\">The Law of Demeter Is Not A Dot Counting Exercise</a>\". In particular the part under the heading \"I Fought The Law and The Law Won\".</p>\n\n<p>I think in this instance that pages, paragraphs and lines are very logical subcomponents of documents. These each have different but related behaviour. The each also serve different purposes.</p>\n\n<p>Forcing the document to handle interactions with subcomponents will - as you say - lead to clutter (and more chance of introducing troublesome issues).</p>\n\n<p>The big thing about the LoD is that it aims to reduce coupling. However adding methods to Document doesn't <em>really</em> reduce coupling as you're still writing code that says \"do x to line y\" - you're just asking Document to do it for you.</p>\n\n<p>Don't get me wrong, the LoD is useful. But like all principles it has to be used correctly to stay useful.</p>\n\n<p>(Funnily enough a similar <a href=\"https://stackoverflow.com/questions/3706463/am-i-breaking-the-law-of-demeter\">question</a> with a similar answer as been asked at SO.)</p>\n\n<p><br /><strong>Conclusion</strong></p>\n\n<p>In short I don't see any benefit for you in talking to Document rather than it's contained Pages, Paras, &amp; Lines. Frankly I don't think there's any ROI for you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T08:52:43.757", "Id": "237", "Score": "3", "body": "Interesting reference, especially: \"If LoD is about encapsulation (aka information hiding) then why would you hide the structure of an object where the structure is exactly what people are interested in and unlikely to change?\". I tend to think that OO design principles intended for objects with responsibilities and behaviors should be left aside when working with data structures, which are really a different kind of objects." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T05:24:42.827", "Id": "153", "ParentId": "131", "Score": "16" } }, { "body": "<p>I'll argue the counterpoint ...</p>\n\n<p>The LoD would say that this client code is being tied to a particular model of the Document. In the end, the code is really interested in the lines of a document. How reasonable is it that we tie that code to the <code>getPage / getParagraph / getLine</code> model?</p>\n\n<p>Its perfectly reasonable to believe that pages wills always be made up of paragraphs and paragraphs made up of lines, but I don't think this is the only consideration. The other question to ask is what other models should Document support? Stated differently:</p>\n\n<p><em><strong>\"Is it reasonable to look at a Document as a series of Lines without regard to what page or paragraph they are in?\"</em></strong></p>\n\n<p>I think it is, so I would give <code>Document</code> a <code>getLines()</code> method and not force our code to go through the Page/Paragraph/Line model.</p>\n\n<p>This <code>getLines()</code> method is also a good thing, because: <em>if it its reasonable for our <code>Document</code>'s client to see things this way, it is reasonable that <code>Document</code> may see things this way too</em>. That is, isn't it possible that the <code>Document</code> <em>may</em> have an efficient structure for moving from line to line (if not now, then perhaps in the future) that may not involve pages and paragraphs? If so, forcing client code to go through the <code>getPage / getParagraph / getLine</code> is hurting the opportunity to use that efficient structure.</p>\n\n<p>I also think its unreasonable \"Forcing the document to handle interactions with subcomponents\" in every conceivable case, so there has to be a happy medium out there. As a counter example, consider:</p>\n\n<p><em><strong>\"is it reasonable to look at a Library as a series of Lines without regard to what document they are in?\"</em></strong></p>\n\n<p>I don't think I'll be providing a <code>getLines()</code> method to my <code>Library</code> class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:18:58.190", "Id": "242", "ParentId": "131", "Score": "12" } }, { "body": "<p>I also agree that this code violates LoD. The caller is tying the implementation down to a model of nested objects.</p>\n\n<p>Adding a bunch of filter methods also doesn't seem like the right idea, but this is an opportunity in disguise. You really want a general filtering method that can take a \"verb\" to apply to the matching elements. Or, alternatively, a filter method that takes a predicate and returns just the collection of matching elements.</p>\n\n<p>This is one of the useful things about LoD. It helps you uncover places where you are operating at a low level of abstraction, and raise the level. In this case, once you introduce general predicates or verbs, you'll be very likely to find other places to use the same idiom. What begins as a local cleanup can uncover a very general mode of expression.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:51:16.763", "Id": "292", "ParentId": "131", "Score": "3" } } ]
{ "AcceptedAnswerId": "153", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T16:26:15.320", "Id": "131", "Score": "27", "Tags": [ "java", "design-patterns" ], "Title": "Law of Demeter and data models?" }
131
<p>Code Review - Stack Exchange is for <strong>sharing code from projects you are working on</strong> for peer review. If you are looking for feedback on a specific working piece of code from your project in the following areas&hellip;</p> <ul> <li>Best practices and design pattern usage</li> <li>Security issues</li> <li>Performance</li> <li>Correctness in unanticipated cases</li> </ul> <p>then you are in the right place!</p> <p>However, if your question is not about a particular piece of code and instead is a generally applicable question about &hellip;</p> <ul> <li>Tools, best practices, improving, or conducting code reviews</li> <li>Trouble-shooting, debugging, or understanding code snippets</li> <li>Higher-level architecture and design of software systems</li> </ul> <p>then your question is off-topic for this site.</p> <h3>I'm confused! What questions are on-topic for this site?</h3> <p>Simply ask yourself the following questions. To be on-topic the answer must be yes to all questions:</p> <ol> <li>Does my question contain code? (Please include the code in the question, not a link to it)</li> <li>Did I write that code?</li> <li>Is it actual code from a project rather than pseudo-code or example code?</li> <li>Do I want the code to be good code, (i.e. not code-golfing, obfuscation, or similar)</li> <li>To the best of my knowledge, does the code work?</li> <li>Do I want feedback about any or all facets of the code?</li> </ol> <p>If you answered yes to all the above questions, your question is on-topic for Code Review.</p> <h3>Make sure you include your code in your question</h3> <p>This site is for code reviews, which are hard to do when the code is behind a link somewhere out there on the internet. If you want a code review, you <em>must</em> post the relevant snippets of code <em>in your question</em>. It is fine to post a "see more" link (though, do be careful &mdash; very few reviewers will be willing to click through and read thousands of lines of your code), but the most important parts of the code <em>must</em> be placed directly in the question.</p> <h3>Reviewers may comment on any part of the code.</h3> <p>Feel free to call attention to specific areas you are concerned about (performance, formatting, etc). However, <em>any</em> aspect of the code posted is fair game for feedback and criticism.</p> <h3>What? Questions <em>about</em> code reviews are off topic?</h3> <p>Conducting code reviews is an important skill, much like any other programming discipline. These "whiteboard"-style questions are best asked on <a href="http://programmers.stackexchange.com">Programmers Stack Exchange</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-21T18:08:20.040", "Id": "135", "Score": "0", "Tags": null, "Title": null }
135
<p>Would this function be sufficient enough to remove all malicious code and foreign characters from a string?</p> <pre><code>//Clean the string $out = ltrim($do); $out = rtrim($out); $out = preg_replace('/[^(\x20-\x7F)]*/','', strip_tags($out)); </code></pre> <p>This data is not going into a SQL database, so I dont have to worry about sql injection attempts. Is there any way to improve my code and make it more efficient?</p> <p>This function would clean any user inputted data (forms, and ?), and then save it do a database. This would be used in a global sanitizing function.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T18:09:36.597", "Id": "211", "Score": "2", "body": "How are you using this string that you are worried about it being an attack vector? Where is the string coming from? What do you expect it to contain? Please add that to the question." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T19:50:51.563", "Id": "220", "Score": "6", "body": "The context is still not clear of what you are trying to prevent injection of." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T15:33:03.393", "Id": "305", "Score": "0", "body": "`$out = preg_replace('/[^(\\x20-\\x7F)]*/','', strip_tags(rtrim(ltrim($do))));`" } ]
[ { "body": "<p>That one is quite simple (for me at least) since there is a very general answer :)</p>\n\n<h2>NO</h2>\n\n<p>There is no way you can ever really safely \"repair\" user input.</p>\n\n<blockquote>\n <p>\"Please provide a list of everything you shouldn't to with a hammer\" </p>\n</blockquote>\n\n<p>is <em>way</em> harder than </p>\n\n<blockquote>\n <p>\"list all appropriate uses of a hammer\". </p>\n</blockquote>\n\n<p>You might forget one or two but no harm done there if you go back and add them.</p>\n\n<p>It might sound harsh but something will always byte you and if it's only <code>EVAL(UNHEX(ASD23426363))</code> or something like that. (Sql example even so you did say it not sql but whatever).</p>\n\n<p>Of course you might want to do things like strip out tags out of input for html context anyways so that a hole in your other code is not as easily exploited and less damage will be done but i shouldn't be your only defense.</p>\n\n<hr>\n\n<p>Someone that said <a href=\"http://terrychay.com/article/php-advent-security-filter-input-escape-output.shtml\"><code>Filter Input, Escape Output</code></a> way better than i could. Terry Chay</p>\n\n<hr>\n\n<p>In short: Whatever you are doing there, find the appropriate escaping function and use it.</p>\n\n<p>Shell context ? <a href=\"http://php.net/escapeshellarg\"><code>escapeshellarg</code></a></p>\n\n<p>Html context ? <a href=\"http://php.net/htmlentities\"><code>htmlspecialchars</code></a></p>\n\n<p>Database context ? Use prepared statements and never worry about sql injection again</p>\n\n<hr>\n\n<p>Little edit:\nI know what i said and the blog post contradict a little but thats fine with me. 'In practice' will always differ from general advice and sometimes you want to do everything you can ;) </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T18:14:05.447", "Id": "137", "ParentId": "136", "Score": "17" } }, { "body": "<p>I'm doing a copy-pasta from <a href=\"https://stackoverflow.com/questions/4762824/php-security-sanitize-clean/4763314#4763314\">My Answer to a similar question on SO</a>:</p>\n\n<p>Always remember, <em>Filter In, Escape Out</em> for all user supplied (or untrusted) input.</p>\n\n<p>When reading user supplied data, filter it to known values. <strong>DO NOT BLACKLIST!</strong> Always always always <strong>always</strong> whitelist what you are expecting to get. If you're expecting a hex number, validate it with a regex like: <code>^[a-f0-9]+$</code>. Figure out what you expect, and filter towards that. Do none of your filenames have anything but alpha, numeric and <code>.</code>? Then filter to <code>^[a-z0-9.]+$</code>. But don't start thinking blacklisting against things. It won't work.</p>\n\n<p>When using user-data, escape it properly for the use at hand. If it's going in a database, either bind it as a parameterized query, or escape it with the database's escape function. If you're calling a shell command, escape it with <a href=\"http://us.php.net/manual/en/function.escapeshellarg.php\" rel=\"nofollow noreferrer\"><code>escapeshellarg()</code></a>. If you're using it in a regex pattern, escape it with <a href=\"http://us.php.net/manual/en/function.preg-quote.php\" rel=\"nofollow noreferrer\"><code>preg_quote()</code></a>. There are more than that, but you get the idea.</p>\n\n<p>When outputting user data, escape it properly for the format you're outputting it as. If you're outputting it to HTML or XML, use <a href=\"http://us.php.net/manual/en/function.htmlspecialchars.php\" rel=\"nofollow noreferrer\"><code>htmlspecialchars()</code></a>. If you're outputting to raw headers for some reason, escape any linebreaks (<code>str_replace(array(\"\\r\", \"\\n\"), array('\\r', '\\n'), $string)</code>). Etc, etc, etc.</p>\n\n<p>But always filter using a white-list, and always escape using the correct method for the context. Otherwise there's a significant chance you'll miss something...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T20:17:55.463", "Id": "143", "ParentId": "136", "Score": "8" } } ]
{ "AcceptedAnswerId": "137", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-21T18:08:22.390", "Id": "136", "Score": "11", "Tags": [ "php", "strings", "security", "regex" ], "Title": "Is this a sufficient way to prevent script injections and other bad stuff in strings" }
136
<p>I don't like the fact that I am selecting all the points, even though I only care about the count of them.</p> <p>Which of the <code>from</code> parts should appear first, if it even matters?</p> <pre><code>var count = (from type in ValidTypes() from point in GetData(type) where point.Radius &gt; referencePoint.Radius &amp;&amp; point.Theta &gt; referencePoint.Theta select point).Count() </code></pre> <p><code>ValidTypes()</code> returns a few types, about 5.</p> <p><code>GetData(type)</code> may return many points, possibly 100,000.</p> <p>This query is counting the number of points that have both a larger theta and a larger radius than a given point.</p> <p>Is there a way to write this faster or more readable?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T19:28:47.677", "Id": "218", "Score": "1", "body": "Is this a Linq to sql query or linq to objects?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T19:56:25.033", "Id": "222", "Score": "0", "body": "This is linq to objects." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T12:08:20.080", "Id": "243", "Score": "1", "body": "As has been said already, your code is fine. I'm not sure what you mean by \"selecting\" when you say \"I am selecting all the points\"? That you're iterating over all of them? You can't count them without iterating over them, so that's ok. Or do you think that your linq query creates a temporary array which you then call Count on? It doesn't." } ]
[ { "body": "<p>First, your query is written fine. Its structure is not a concern; the order of the froms is clearly correct, the select is appropriate. Where you could look for improvement that could change the query (code and possibly performance) would be in the <code>GetData</code> method. If, for example, <code>GetData</code> is <em>getting data</em> from an external, queryable source, then you may want to offload the filtering to <em>it</em> rather than getting all of the data points and filtering it inside your application, particularly since you have so many points of data (potentially). So maybe your query could instead be </p>\n\n<pre><code>(from type in ValidTypes() \n select GetData(type, referencePoint).Count())\n.Sum();\n\n// or same meaning, different phrasing\n\n(from type in ValidTypes()\nfrom point in GetData(type, referencePoint)\nselect point).Count();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T20:22:39.207", "Id": "144", "ParentId": "138", "Score": "9" } }, { "body": "<p>Why are you doing:</p>\n\n<pre><code>Point.Radius &gt; referencePoint.Radius &amp;&amp; point.Theta &gt; referencePoint.Theta\n</code></pre>\n\n<p>Seems this probably should be a function like <code>IsCorrectReferencePoint</code> or whatnot. That will both make your code more readable and more understandable since you can simply look at the function name to see what it does.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-08T02:21:31.187", "Id": "99284", "Score": "0", "body": "Make sure the function is a proper `Predicate<>` so it can be used in the overload of `.Count()` as in Martin's answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T12:26:04.200", "Id": "170", "ParentId": "138", "Score": "7" } }, { "body": "<p>I don't like writing a statement that combines both \"fluent\" and \"expression\" syntax for LINQ. (See SO: <a href=\"https://stackoverflow.com/questions/214500/which-linq-syntax-do-you-prefer-fluent-or-query-expression/214610#214610\">Which LINQ syntax do you prefer? Fluent or Query Expression</a>)</p>\n\n<p>I also would choose multiple <code>where</code> clauses over a single <code>where</code> with <code>&amp;&amp;</code>. So, either:</p>\n\n<pre><code>var points = from type in ValidTypes()\n from point in GetData(type)\n where point.Theta &gt; referencePoint.Theta\n where point.Radius &gt; referencePoint.Radius\n select point;\n\nvar count = points.Count();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var count = ValidTypes\n .Select(type =&gt; type.GetData())\n .Where(point.Theta &gt; referencePoint.Theta)\n .Where(point.Radius &gt; referencePoint.Radius)\n .Count();\n</code></pre>\n\n<p>I'd look at the code before &amp; after, and see if one of these lends itself to further refactoring.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-30T22:45:47.257", "Id": "16739", "Score": "1", "body": "ugh, Your fluent version is syntactically incorrect and should be using `SelectMany` or else you'll get the wrong result. Also, see <a href=\"http://stackoverflow.com/questions/664683/should-i-use-two-where-clauses-or-in-my-linq-query\">should-i-use-two-where-clauses-or-in-my-linq-query</a> regarding multiple `where` vs `&&`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T23:06:47.027", "Id": "394", "ParentId": "138", "Score": "2" } }, { "body": "<p>This is an old question, but maybe worth reminding for people that .Count() has a useful overload. Re-writing the query in fluent syntax could let you write:</p>\n\n<pre><code>int count = ValidTypes()\n .SelectMany(type =&gt; GetData(type))\n .Count(point =&gt; point.Radius &gt; referencePoint.Radius \n &amp;&amp; point.Theta &gt; referencePoint.Theta);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-30T22:50:04.020", "Id": "10516", "ParentId": "138", "Score": "3" } } ]
{ "AcceptedAnswerId": "144", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-21T19:10:07.230", "Id": "138", "Score": "13", "Tags": [ "c#", "linq" ], "Title": "Counting the number of points that have both a larger theta and a larger radius than a given point" }
138
<p>This is a function I wrote yesterday and have tested with lots of input. It's been committed and is in use, but no review was done, so it seems like a good candidate for Code Review: it could be more readable and maybe refactored into simpler functions.</p> <p>Its purpose is to give the longest common path and a string listing filenames for lists of dictionaries with full file paths. It's used to process <a href="https://api.bitbucket.org/1.0/repositories/jespern/django-piston/changesets/c9fe89f3ec79/">Bitbucket API results</a>.</p> <pre><code>import os.path import py # Used for other functions, listed for possible use in refactoring def getpaths(files, listfiles=False): """For a list of files, a common path prefix and optionally list filenames Returns a tuple (common_prefix, filenames): common_prefix: Longest common path to all files in the input. If input is a single file, contains full file path. Slash-terminated if present and directory, empty string otherwise. filenames: String containing the names of modified files, in the format " M(file1, file2)" if listfiles=True, empty string if either listfiles=False or no file was modified. """ # Handle empty input if not files: return '', '' files = [f['file'] for f in files] if not any(files): return '', '' dirname = os.path.dirname basename = os.path.basename common_prefix = [dirname(f) for f in files] # Single file, show its full path if len(files) == 1: common_prefix = files[0] listfiles = False else: common_prefix = [path.split(os.sep) for path in common_prefix] common_prefix = os.sep.join(os.path.commonprefix(common_prefix)) if common_prefix and not common_prefix.endswith('/'): common_prefix += '/' if listfiles: filenames = [basename(f) for f in files if f and basename(f)] filenames = ' M(%s)' % ', '.join(filenames) else: filenames = '' return common_prefix, filenames # Test suite # Don't worry too much about test style, this is informative enough with py.test. # Adequate coverage and readibility are the main concern. # However, if you think a doctest or classic unittest is better, I'm open to change. def test_getpaths(): d = dict barefile = [d(file='file')] distinct = [d(file='path1/file1'), d(file='path2/file2'), d(file='path3/file')] shared = [d(file='path/file1'), d(file='path/file2'), d(file='path/file')] deepfile = [d(file='a/long/path/to/deepfile.py')] slashesfile = [d(file='/slashesfile/')] slashleft = [d(file='/slashleft')] slashright = [d(file='slashright/')] nocommon = distinct + [d(file='path4/file')] nocommonplusroot = distinct + barefile common = [d(file='some/path/to/file'), d(file='some/path/to/deeper/file'), d(file='some/path/to/anotherfile'), d(file='some/path/to/afile')] commonplusroot = shared + barefile empty = d(file='') nocommonplusempty = distinct + [empty] commonplusempty = shared + [empty] nocommonplusslash = distinct + [d(file='path4/dir/')] commonplusslash = shared + [d(file='path/dir/')] pypydoubleslash = [d(file='pypy/jit/metainterp/opt/u.py'), d(file='pypy/jit/metainterp/test/test_c.py'), d(file='pypy/jit/metainterp/test/test_o.py')] nothing = ('', '') # (input, expected output) for listfiles=False files_expected = [([], nothing), ([empty], nothing), ([empty, empty], nothing), (barefile, ('file', '')), (deepfile, ('a/long/path/to/deepfile.py', '')), (slashesfile, ('/slashesfile/', '')), (slashleft, ('/slashleft', '')), (slashright, ('slashright/', '')), (nocommon, nothing), (nocommonplusroot, nothing), (nocommonplusempty, nothing), (common, ('some/path/to/', '')), (commonplusroot, nothing), (commonplusempty, nothing), (nocommonplusslash, nothing), (commonplusslash, ('path/', '')), (pypydoubleslash, ('pypy/jit/metainterp/', '')), ] for f, wanted in files_expected: assert getpaths(f) == wanted # (input, expected output) for listfiles=True files_expected = [([], nothing), ([empty], nothing), ([empty, empty], nothing), (barefile, ('file', '')), (deepfile, ('a/long/path/to/deepfile.py', '')), (slashesfile, ('/slashesfile/', '')), (slashleft, ('/slashleft', '')), (slashright, ('slashright/', '')), (nocommon, ('', ' M(file1, file2, file, file)')), (nocommonplusroot, ('', ' M(file1, file2, file, file)')), (nocommonplusempty, ('',' M(file1, file2, file)')), (common, ('some/path/to/', ' M(file, file, anotherfile, afile)')), (commonplusroot, ('', ' M(file1, file2, file, file)')), (commonplusempty, ('',' M(file1, file2, file)')), (nocommonplusslash, ('',' M(file1, file2, file)')), (commonplusslash, ('path/',' M(file1, file2, file)')), (pypydoubleslash, ('pypy/jit/metainterp/', ' M(u.py, test_c.py, test_o.py)')), ] for f, wanted in files_expected: assert getpaths(f, listfiles=True) == wanted </code></pre> <p>Improvements for both the function and its tests are welcome. For some context, this is how it's used:</p> <pre><code># Here's the kind of data we want to process. The return for listfiles=False # should be ('bit/', ''). For True, # ('bit/', ' M(hook.py, __init__.py, __init__.py, test_hook.py)') commit = { u'files': [{u'file': u'bit/hook.py', u'type': u'modified'}, {u'file': u'bit/__init__.py', u'type': u'added'}, {u'file': u'bit/test/__init__.py', u'type': u'added'}, {u'file': u'bit/test/test_hook.py', u'type': u'added'}] } files = commit.get('files', []) common_prefix, filenames = getpaths(files, True) common_prefix = '/' + common_prefix print '%s%s: ' % (common_prefix, filenames) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T05:12:09.947", "Id": "49000", "Score": "0", "body": "nice bit of code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-15T09:31:37.710", "Id": "347859", "Score": "0", "body": "Starting with Python 3.5 one should be compelled to use the function `commonpath` provided in Python's `os.path`: https://docs.python.org/3.5/library/os.path.html#os.path.commonpath" } ]
[ { "body": "<pre><code>dirname = os.path.dirname\nbasename = os.path.basename\n</code></pre>\n\n<p>This can be written as:</p>\n\n<pre><code>from os.path import dirname, basename\n</code></pre>\n\n<p>The from..import will check that os.path is imported (and import it if not), but is otherwise identical. I find it more clear than repeating the names – especially when you get to three or more.</p>\n\n<hr>\n\n<pre><code>filenames = [basename(f) for f in files if f and basename(f)]\n</code></pre>\n\n<p>This can be simplified, as basename on an empty string gives an empty string:</p>\n\n<pre><code>filenames = filter(None, (basename(f) for f in files))\n# or\nfilenames = [x for x in (basename(f) for f in files) if x]\n# or\nfilenames = [x for x in map(basename, files) if x]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T09:41:53.407", "Id": "266", "ParentId": "142", "Score": "9" } } ]
{ "AcceptedAnswerId": "266", "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T20:09:42.960", "Id": "142", "Score": "15", "Tags": [ "python", "unit-testing" ], "Title": "Function for finding longest common path and formatting it along with filenames" }
142
<p>I do most of my programming in C/C++ and Perl, but I currently learning Fortran. I began by coding up a simple program, something that took me &lt; 5 minutes in Perl (see <a href="http://biostar.stackexchange.com/questions/4993/extracting-set-of-numbers-from-a-file" rel="noreferrer">this thread</a> from BioStar). After working for several hours on a solution in Fortran 95 (teaching myself as I go), I came to this solution.</p> <p>implicit none</p> <pre><code>! Variable definitions integer :: argc integer :: num_digits integer :: i, j integer :: iocode integer :: line_length integer :: value character ( len=256 ) :: infile character ( len=16 ) :: int_format character ( len=16 ) :: int_string character ( len=2048 ) :: line ! Verify and parse command line arguments argc = iargc() if( argc &lt; 1 ) then write(*, '(A, I0, A)') "Error: please provide file name (argc=", argc, ")" stop endif call getarg(1, infile) ! Open input file, croak if there is an issue open( unit=1, file=infile, action='read', iostat=iocode ) if( iocode &gt; 0 ) then write(*, '(A, A, A)') "Error: unable to open input file '", trim(infile), "'" stop endif ! Process the file, print in CSV format do while(1 == 1) ! Read the line, skip if it is empty 100 read( unit=1, fmt='(A)', end=200 ) line line_length = len_trim(line) if( line_length == 0 ) then goto 100 endif ! The first value in the line is a string ! Find string boundaries and print it out i = 0 do while( line(i:i) == ' ' ) i = i+1 end do j = i do while( line(j:j) /= ' ' ) j = j+1 end do write(*, '(A)', advance="no") line(i:j-1) ! Now grab the rest of the integer values ! on the line, multiply them by 3, and print i = j j = 0 do while( i &lt; line_length) do while( line(i:i) == ' ' ) i = i+1 end do j = i do while( j &lt; line_length .and. line(j:j) /= ' ' ) j = j+1 end do int_string = line(i:j-1) read(int_string, '(I)') value value = value*3 write(*, '(A, I0)', advance="no") ",", value i = j j = 0 end do print * end do 200 close( 1 ) end program </code></pre> <p>There is a lot that I don't like about how I've written this program, but it's hard to separate my inexperience with the new syntax from bad practice. One thing in particular that I don't like is my use of labels and the infamous <code>goto</code> statement. I'm interested in any feedback whatsoever, but I'm particularly interested in better ways to handle the control structure of the program (without using the <code>goto</code> statement and <code>end</code> parameter in the <code>read</code> function if possible).</p> <p>The compilers I have access to only support features through f95.</p>
[]
[ { "body": "<p>I've seen some pretty nasty Fortran in my time: Research departments seem to be the worse source! Your code is far, far superior to their code!</p>\n\n<p>In those days we were using an extended form of Fortran 77 with some structured extensions and formatting niceties. There was no avoiding GOTOs and FORMATs and their labels. I tried to keep them to a minimum and to only use them for break/cycle types of jumps like you are doing. So although I lack modern Fortran experience, you look to be on the right track.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T04:31:40.910", "Id": "265", "Score": "1", "body": "Thanks for the reassurance! I had to chuckle a little when at your mention of \"modern Fortran experience\" though. :) Being on the cutting edge is definitely NOT why I'm learning Fortran!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T21:34:48.647", "Id": "162", "ParentId": "145", "Score": "2" } }, { "body": "<p>You could get rid of the <code>GOTO</code> statements by using labelled loops with <code>EXIT</code> and <code>CYCLE</code> statements. These allow you to do the sort of flow control that you've used the <code>GOTO</code>s for, but don't permit the less desirable features, such as computed <code>GOTO</code>s. Using these newer Fortran features also gives you a clearer idea of the flow control at the point at which the branching occurs. E.g., <code>CYCLE</code> or <code>EXIT</code> statements send you respectively further up or down the source code, and a well chosen label may indicate what the branching is trying to achieve.</p>\n\n<p>Another suggestion, although this is more of a personal preference, is to avoid the potentially endless <code>DO WHILE(1 == 1)</code> loop by using a normal <code>DO</code> loop with a large upper limit and adding warning message if that limit is reached before the end of file is encountered. Plenty of people might find that overly fussy though.</p>\n\n<p>Example code showing these two points:</p>\n\n<pre><code>PROGRAM so_goto\n\n IMPLICIT NONE\n\n INTEGER,PARAMETER :: line_max = 100000\n\n INTEGER :: i, ios, line_length\n CHARACTER( len=2048 ) :: line\n\n OPEN(UNIT=10,FILE=\"so_goto.txt\",ACTION=\"read\")\n\n fread: DO i=1,line_max\n READ(UNIT=10,FMT='(A)',IOSTAT=ios) line\n IF( ios &lt; 0 ) EXIT fread\n line_length = LEN_TRIM(line)\n IF( line_length == 0 ) CYCLE fread\n\n IF( i == line_max ) THEN\n print*,\"BTW, you've hit your read limit before the end of the file.\"\n ENDIF\n ENDDO fread\n CLOSE(10)\n\nEND PROGRAM so_goto\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T14:25:34.650", "Id": "435", "Score": "0", "body": "+1 I *much* prefer the `EXIT/CYCLE` syntax to the `GOTO` statements. It makes the intent of the statements much more explicit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-29T20:38:56.997", "Id": "26096", "Score": "1", "body": "Either use a normal do or if an endless loop, than just `do` is enough. The `while` part is superfluous and should be only used when a real condition is needed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T13:16:41.520", "Id": "269", "ParentId": "145", "Score": "7" } }, { "body": "<p>You can squeeze the program considerably by using some of the string intrinsics.</p>\n<ul>\n<li><p>style: use <code>program</code> - <code>end program</code> statements</p>\n</li>\n<li><p>style: use <code>INPUT_UNIT</code> and <code>OUTPUT_UNIT</code> from <code>iso_fortran_env</code></p>\n</li>\n<li><p>style: the expression <code>croak if there is an issue</code> is adorable &lt;3</p>\n</li>\n<li><p>style: variables for optional parameters can have the same name as the parameter itself, as in <code>read(uid,'(a)',iostat=iostat)</code>. This circumstance helps quite a bit standardizing boiler-plate code.</p>\n</li>\n<li><p>best practices: use <code>implicit none</code></p>\n</li>\n<li><p>best practices: use <code>newunit</code> rather than explicit numbers of your choosing</p>\n</li>\n<li><p>best practices: <em>never ever</em> use any label or <code>goto</code>: they are dangerous, unsightly relics of the past. Use <code>cycle</code> and <code>exit</code> instead.</p>\n</li>\n</ul>\n<p>To get acquainted with the simple syntax of modern Fortran, I suggest the following <a href=\"https://fortran-lang.org/learn/quickstart\" rel=\"nofollow noreferrer\">quick modern Fortran tutorial</a>.</p>\n<p>Here's my alternative solution:</p>\n<pre class=\"lang-fortran prettyprint-override\"><code>Program PrintFileInCVSFormat\n\n use, intrinsic :: iso_fortran_env, only : ERROR_UNIT, OUTPUT_UNIT\n implicit none\n character(len=2048) :: inFile,line, sBuf, iomsg\n integer :: i, j, uid, iostat\n\n !.. Fetch input-file name\n call get_command_argument(1,inFile,status=iostat)\n if( iostat &gt; 0 ) write(ERROR_UNIT, '(A)') &quot;Error: file name missing from CMDLN.&quot;\n if( iostat &lt; 0 ) write(ERROR_UNIT, '(A)') &quot;Error: file name too long.&quot;\n if( iostat/= 0 ) error stop\n\n !.. Open input file, croak if there is an issue\n open( newunit=uid, file=trim(adjustl(inFile)), action='read', iostat=iostat, iomsg=iomsg )\n if( iostat /= 0 ) then\n write(ERROR_UNIT,'(i0,A)') iostat,&quot; &quot;//trim(iomsg)\n error stop\n endif\n \n do !.. Process the file, print in CSV format\n\n !.. Read next non-empty line, if available\n read(uid,'(A)',iostat=iostat) line\n if(iostat/=0)exit\n if(len_trim(line)==0)cycle\n line=adjustl(line)\n \n !.. Print the first token in the line as a string\n i = index(line,&quot; &quot;)\n write(OUTPUT_UNIT,&quot;(a)&quot;,advance=&quot;no&quot;) line(1:i-1)\n line=line(i+1:)\n\n do !.. Print the integers in the line, multiplied by 3\n read(line,*,iostat=iostat)j\n if(iostat/=0)exit\n write(OUTPUT_UNIT,&quot;(x,i0)&quot;,advance=&quot;no&quot;) 3*j\n i=index(line,&quot; &quot;)\n line=line(i+1:)\n enddo\n write(OUTPUT_UNIT,*)\n\n end do\n \n close(uid)\n\nend Program PrintFileInCVSFormat\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-18T15:09:32.353", "Id": "254903", "ParentId": "145", "Score": "1" } } ]
{ "AcceptedAnswerId": "269", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-21T20:28:47.330", "Id": "145", "Score": "14", "Tags": [ "file", "fortran" ], "Title": "Extracting a set of numbers from a file" }
145
<p>It's a little bit more code but I wanted to show the full class. I highlight the points I'd like input after the source.</p> <p>I've cut comments since they where not in English and translated the important ones.</p> <p>The class is inspired by PearDb (too old) and Zend_DB (to cluttered / unfinished at the time) and is used in a inhouse application. I know it's not ideal to write your own database handler (I'd go so far to say it's pretty pointless).</p> <pre><code>&lt;?php class DbStatement { private $oStatement; private $aFieldnames = array(); private $aResultRow = array(); private $aResultSet = array(); private $bMetadata = true; private $bPreparedFetch = false; private $iNumRows = false; private $sQuery; private $aArgs; private $fQuerytime; /** * @throws DbException * @param mysqli $oDb Datenbankverbindung * @param string $sQuery */ public function __construct(mysqli $oDb, $sQuery) { $this-&gt;oStatement = $oDb-&gt;prepare($sQuery); $this-&gt;sQuery = $sQuery; if($this-&gt;oStatement === false) { switch($oDb-&gt;errno) { case 1054: throw new DbNoSuchFieldException($oDb-&gt;error, $oDb-&gt;errno); case 1146: throw new DbNoSuchTableException($oDb-&gt;error, $oDb-&gt;errno); default: throw new DbException( "Prepared Statement could not be created: ". $oDb-&gt;error." (".$oDb-&gt;errno."). Query was: '$sQuery'", $oDb-&gt;errno ); } } } /**#@+ * * @param mixed $mParams,... */ public function execute() { $this-&gt;_execute(func_get_args()); $this-&gt;_done(); } /** * @return null|bool|int|string|float */ public function getOne() { $this-&gt;_execute(func_get_args()); $this-&gt;_fetchRow(); if(isset($this-&gt;aResultSet[0][$this-&gt;aFieldnames[0]])) { return $this-&gt;aResultSet[0][$this-&gt;aFieldnames[0]]; } return null; } /** * @return array */ public function getCol() { $this-&gt;_execute(func_get_args()); $this-&gt;_fetchAll(); $sIndex = $this-&gt;aFieldnames[0]; $aReturn = array(); foreach($this-&gt;aResultSet as $aResultRow) { $aReturn[] = $aResultRow[$sIndex]; } return $aReturn; } /** * @return array */ public function getRow() { $this-&gt;_execute(func_get_args()); $this-&gt;_fetchRow(); if(isset($this-&gt;aResultSet[0])) { return $this-&gt;aResultSet[0]; } return array(); } /** * @return array */ public function getAssoc() { $this-&gt;_execute(func_get_args()); $this-&gt;_fetchAll(); if(isset($this-&gt;aFieldnames[0]) &amp;&amp; isset($this-&gt;aFieldnames[1])) { $sIndexKey = $this-&gt;aFieldnames[0]; $sIndexValue = $this-&gt;aFieldnames[1]; $aReturn = array(); foreach($this-&gt;aResultSet as $aResultRow) { $aReturn[$aResultRow[$sIndexKey]] = $aResultRow[$sIndexValue]; } return $aReturn; } return array(); } /** * @return array */ public function getAll() { $this-&gt;_execute(func_get_args()); $this-&gt;_fetchAll(); return $this-&gt;aResultSet; } /**#@-*/ /** * @return false|int */ public function numRows() { return $this-&gt;iNumRows; } /** * @return int */ public function affectedRows() { return $this-&gt;oStatement-&gt;affected_rows; } /** * @return int */ public function lastInsertId() { return $this-&gt;oStatement-&gt;insert_id; } public function getLastExecutedQuery() { $sReturn = $this-&gt;sQuery; if($this-&gt;aArgs) { $sReturn .= "; -- Argumente: ~".implode("~,~", $this-&gt;aArgs)."~"; } return $sReturn; } /** * @throws DbException * * @param array $aArgs */ private function _execute($aArgs) { $aArgs = $this-&gt;_parseFuncArgs($aArgs); $this-&gt;aArgs = $aArgs; $iArgs = count($aArgs); if($iArgs) { if($this-&gt;oStatement-&gt;param_count !== $iArgs ) { throw new DbException( "Inserting parameters failed: ".$this-&gt;oStatement-&gt;param_count. " Parameters expected but ".$iArgs." passed." ); } $aRefArgs = array(); foreach(array_keys($aArgs) as $mIndex) { $aRefArgs[$mIndex] = &amp;$aArgs[$mIndex]; } array_unshift($aRefArgs, str_repeat("s", $iArgs)); // Needs References call_user_func_array(array($this-&gt;oStatement, "bind_param"), $aRefArgs); } $bWorked = $this-&gt;oStatement-&gt;execute(); if($bWorked === false) { $sError = sprintf( "Query failed: %s (%s) Query was: '%s'", $this-&gt;oStatement-&gt;error, $this-&gt;oStatement-&gt;errno, $this-&gt;sQuery ); switch($this-&gt;oStatement-&gt;errno) { case 1062: throw new DbKeyViolationException($sError, $this-&gt;oStatement-&gt;errno); default: throw new DbException($sError, $this-&gt;oStatement-&gt;errno); } } $this-&gt;_prepareFetch(); } private function _prepareFetch() { if($this-&gt;bMetadata &amp;&amp; !$this-&gt;bPreparedFetch) { $oMeta = $this-&gt;oStatement-&gt;result_metadata(); if($oMeta === false) { $this-&gt;bMetadata = false; } else { $this-&gt;_prepareMetadata($oMeta); $this-&gt;aResultRow = array_fill(0, count($this-&gt;aFieldnames), null); // Ugly but 'bind_result' forces you to pass references $aRefs = array(); foreach ($this-&gt;aResultRow as $iIndex =&gt; &amp;$rmValue) { $aRefs[$iIndex] = &amp;$rmValue; } call_user_func_array(array($this-&gt;oStatement, "bind_result"), $this-&gt;aResultRow); $this-&gt;bPreparedFetch = true; } } } /** * @param mysqli_result $oMeta */ private function _prepareMetadata(mysqli_result $oMeta) { $aFields = $oMeta-&gt;fetch_fields(); foreach($aFields as $oField) { $this-&gt;aFieldnames[] = $oField-&gt;name; } } private function _fetchRow() { $this-&gt;_fetch(true); } private function _fetchAll() { $this-&gt;_fetch(false); } /* * @param bool $bOne One line ? */ private function _fetch($bOne) { $this-&gt;aResultSet = array(); if($bOne !== true) { $this-&gt;oStatement-&gt;store_result(); } while($this-&gt;oStatement-&gt;fetch()) { // Deref $aTmp = array(); foreach($this-&gt;aResultRow as $mValue) { $aTmp[] = $mValue; } $this-&gt;aResultSet[] = array_combine($this-&gt;aFieldnames, $aTmp); if($bOne === true) { break; } } $this-&gt;iNumRows = $this-&gt;oStatement-&gt;num_rows; $this-&gt;_done(); } private function _done() { $this-&gt;oStatement-&gt;free_result(); } /** * @param array $aArgs * @return array */ private function _parseFuncArgs($aArgs) { if(isset($aArgs[0]) &amp;&amp; is_array($aArgs[0])) { return $aArgs[0]; } return $aArgs; } } </code></pre> <p>The ugly bits (I think, that is why we are here I guess), are in <code>_execute</code> and <code>_prepareFetch</code> as the MySQLi API forced us to use references.</p> <p>The class takes for granted that the passed in MySQLi object is already connected to a database.</p> <p>If I missed something please let me know.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T21:14:24.183", "Id": "227", "Score": "3", "body": "This is one of the most readable bits of PHP I've ever seen, should be even better with the original comments. Maybe you could extract the common massaging before `call_user_func_array` in `_execute` and `_prepareFetch` into a helper? Hmm, not worth it, good enough as-is." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T04:46:19.710", "Id": "234", "Score": "0", "body": "This is an awesome piece of code. I cant really see much where you can optimize it.\n\nOne possible addition you could add is the ability to use the class to build your query as well.\n\nSomething like the CodeIgniter methods of `$db->select('id, name')->from(...`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-24T23:08:31.730", "Id": "287", "Score": "0", "body": "One tip to make any code better is to write comments directly in English. This will save a lot of problems in the future." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T08:28:58.603", "Id": "293", "Score": "0", "body": "@Time Machine that doesn't work out that well if not everyone on your team is able to understand English (strange, i know, but we are working on it) Thanks :)" } ]
[ { "body": "<p>Maybe you could extract the common massaging before call_user_func_array in <code>_execute</code> and <code>_prepareFetch</code> into a helper?</p>\n\n<pre><code>private function _execute($aArgs) {\n/// [...]\n $aRefArgs = array();\n foreach(array_keys($aArgs) as $mIndex) {\n $aRefArgs[$mIndex] = &amp;$aArgs[$mIndex];\n }\n array_unshift($aRefArgs, str_repeat(\"s\", $iArgs));\n // Needs References\n call_user_func_array(array($this-&gt;oStatement, \"bind_param\"), $aRefArgs);\n///-^ This part...\n/// [...]\n\nprivate function _prepareFetch() {\n/// [...]\n $this-&gt;aResultRow = array_fill(0, count($this-&gt;aFieldnames), null);\n // Ugly but 'bind_result' forces you to pass references\n $aRefs = array();\n foreach ($this-&gt;aResultRow as $iIndex =&gt; &amp;$rmValue) {\n $aRefs[$iIndex] = &amp;$rmValue;\n }\n\n call_user_func_array(array($this-&gt;oStatement, \"bind_result\"), $this-&gt;aResultRow);\n///-^ ... matches this one loosely. \n/// [...]\n</code></pre>\n\n<p>Probably not worth it, good enough as-is.</p>\n\n<p>This is one of the most readable bits of PHP I've ever seen, should be even better with the original comments.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T21:11:12.583", "Id": "211", "ParentId": "146", "Score": "15" } }, { "body": "<p>While I have not reviewed the private methods closely, I wanted to provide some feedback on several of the public methods.</p>\n\n<pre><code>$dbStatement = new dbStatement($mysqliDb, 'SELECT * FROM users');\necho $dbStatement-&gt;numRows(); // false\n$users = $dbStatement-&gt;getAll(); // Users array\necho $dbStatement-&gt;numRows(); // Some int\n</code></pre>\n\n<ol>\n<li><p>There seems to be some inconsistency how some methods work. Some methods will trigger the execution of the statement while others will not. As a result, I believe this will result in some unexpected behavior. See above for code example.</p></li>\n<li><p>You may have good reason for this however I am also curious why numRows() is defaulted to false, while affectedRows() and lastInsertId() are not.</p></li>\n<li><p>I also noticed that getLastExecutedQuery() returns the query that was passed in to the class regardless of whether or not it was executed. It is prepared in the constructor, but is not executed until the private _execute() method.</p></li>\n</ol>\n\n<blockquote>\n <p>The class takes for granted that the passed in mysqli object is already connected to a database.</p>\n</blockquote>\n\n<p>Lastly, I would recommend ensuring that the class throws an exception or gracefully handles this another way if the mysqli object is not connected to a database.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T21:19:01.727", "Id": "2945", "Score": "0", "body": "It's been some month since I asked the question but nevertheless: Thanks a lot for the feedback! Point 1) and 2) touch upon a point that i never ever considered or tested. Also it seems that i was never used the wrong way. Really great that you caught that, it should at least report this in a way I guess :) - 3) was named wrong and was removed some time ago. ---- The \"not connected\" problem is handled somewhat gracefully by the execute method as it throws a \"not connected\" exception when trying to execute the query. Thanks a buch for the feeback!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T20:17:25.690", "Id": "1687", "ParentId": "146", "Score": "8" } } ]
{ "AcceptedAnswerId": "211", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-01-21T20:58:41.327", "Id": "146", "Score": "19", "Tags": [ "php", "mysql", "mysqli" ], "Title": "A take on DB Abstraction" }
146
<p>I want to have fast cache in which I want to keep all my nomenclature data. I don't want to go with Memcached because I have to do serialize/de-serialize on each object which is slow.</p> <p>So I choose to be less effective in memory and keep the cache in each server instance. I am sure I am doing it in the wrong way because the NoCache module - which skips my cache and hits the Rails cache is faster than mine.</p> <p>Here is how it is initialized</p> <pre><code>$cache = Cache.new </code></pre> <p>Here is the example usage</p> <pre><code>property_types = $cache['PropertyType'] </code></pre> <p>and here is the source</p> <pre><code>module DirectCache def init_cache end def reload_model(model_class) key = get_key(model_class) klass = key.constantize object = klass.scoped puts "Loading cache for #{key}..." if klass.respond_to?(:translates) and klass.translates? puts " Adding translation in the model for #{klass}" object = object.includes(:translations) self.storage[key] = object.send("all") end end def [] class_name_or_object puts "Hiting cache for #{class_name_or_object}" key = get_key(class_name_or_object) reload_model(class_name_or_object) if self.storage[key].blank? or self.storage[key].empty? raise "#{key} is missing in the cache #{@cache.keys.join ', '}" unless key? key self.storage[key] end def init_cache end end module NoCache def reload_model(model_class) key = get_key(model_class) self.storage[key] = key.constantize end def [] class_name_or_object key = get_key(class_name_or_object) raise "#{key} is missing in the cache #{@cache.keys.join ', '}" unless key? key klass = self.storage[key] object = klass.scoped if klass.respond_to?(:translates) and klass.translates? puts "Adding translation in the model for #{klass}" object = object.includes(:translations) end object.send("all") end def init_cache end end class Cache include DirectCache # include NoCache # include OpenStructCache @@models = [ PropertyFunction, PropertyCategoryLocation, ConstructionType, ....20 more .... ExposureType, ] cattr_reader :models def initialize @cache = {} begin init_cache rescue puts "missing tables" end end def storage @cache end # returns the the key - aways string def get_key class_name_or_record case class_name_or_record when Class key = class_name_or_record.to_s when String key = class_name_or_record else key = class_name_or_record.class.to_s end key end def key? class_name_or_object key = get_key(class_name_or_object) self.storage.keys.include? key end end </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T14:31:28.477", "Id": "246", "Score": "0", "body": "what is you really question ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-04T06:30:03.687", "Id": "51447", "Score": "0", "body": "I like your idea. Could you post this is StackOverflow instead? Would be interesting to solve this." } ]
[ { "body": "<p>The ActiveSupport::Cache is not mandatory in Memcached, there are a cache in memory if you use the :memory_store ( <a href=\"http://api.rubyonrails.org/classes/ActiveSupport/Cache/MemoryStore.html\" rel=\"nofollow\">http://api.rubyonrails.org/classes/ActiveSupport/Cache/MemoryStore.html</a> )</p>\n\n<p>config.cache_store = :memory_store</p>\n\n<p>Maybe can be a good start to implement your own Cache in memory</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T14:33:18.130", "Id": "157", "ParentId": "147", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-21T21:27:07.623", "Id": "147", "Score": "7", "Tags": [ "ruby", "ruby-on-rails", "cache" ], "Title": "Object cache storage for Rails" }
147
<p>I'm working on a personal project to keep different snippets/examples/small projects of mine organized. I want to make the most of my page width, so I decided to write a navigation menu that slides out. It works as expected, but the code is kinda big.</p> <p>I provided the HTML/CSS just in case that helps, but I'm really only looking for help with the JavaScript. I don't need anyone to rewrite the whole thing.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() { $('#tab').click(function() { if($('#main').attr('class') != 'out') { $('#main').animate({ 'margin-left': '+=340px', }, 500, function() { $('#main').addClass('out'); }); } else { $('#main').animate({ 'margin-left': '-=340px', }, 500, function() { $('#main').removeClass('out'); }); } }); //does the same as above, but when I press ctrl + 1. from /http://www.scottklarr.com/topic/126/how-to-create-ctrl-key-shortcuts-in-javascript/ $(document).keyup(function (e) { if(e.which == 17) isCtrl=false; }).keydown(function (e) { if(e.which == 17) isCtrl=true; if(e.which == 97 &amp;&amp; isCtrl == true) { if($('#main').attr('class') != 'out') { $('#main').animate({ 'margin-left': '+=340px', }, 500, function() { $('#main').addClass('out'); }); } else { $('#main').animate({ 'margin-left': '-=340px', }, 500, function() { $('#main').removeClass('out'); }); } return false; } }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#sidebar { top: 0; left: 0; position: relative; float: left; } #main { width: 320px; padding: 10px; float: left; margin-left: -340px; } #tab { width: 30px; height: 120px; padding: 10px; float: left; } .clear { clear: both; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="sidebar"&gt; &lt;div id="main"&gt;&lt;/div&gt; &lt;div id="tab"&gt;&lt;/div&gt; &lt;br class="clear"&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T00:26:29.440", "Id": "401", "Score": "4", "body": "I'd recommend that you always start with jslint.com which would have caught your non-declared variable and the braceless control statement referenced in the Answer." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-21T13:06:42.423", "Id": "2389", "Score": "0", "body": "Try Google's own Closure Compiler from Google http://code.google.com/closure/compiler/, which is a tool for making JavaScript download and run faster. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.\n\nThere's a web version too: http://closure-compiler.appspot.com\nand a Linter." } ]
[ { "body": "<p>First, it seems that <code>isCtrl</code> is not declared anywhere in your code. Put <code>var isCtrl = false;</code> as your first line inside the ready function. Otherwise, you will get a JavaScript error when the first key the user presses is <em>not</em> the <kbd>Ctrl</kbd> key. Also, <code>== true</code> is unnecessary within an <code>if</code> statement; it can be omitted.</p>\n\n<p>Second, this line could be improved, as it fails if the element is a member of another class:</p>\n\n<pre><code>if($('#main').attr('class') != 'out') {\n</code></pre>\n\n<p>It can be rewritten using <a href=\"http://api.jquery.com/hasClass/\"><code>.hasClass()</code></a> as:</p>\n\n<pre><code>if(!$('#main').hasClass('out')) {\n</code></pre>\n\n<p>In fact, you should refactor this entire block out to a separate function to avoid duplicating code:</p>\n\n<pre><code>function toggleMenu() {\n if(!$('#main').hasClass('out')) {\n // ...\n } else {\n // ...\n }\n}\n</code></pre>\n\n<p>And put <code>toggleMenu();</code> where the duplicate code was in each function. Also, if performance is a concern, you should <a href=\"http://www.artzstudio.com/2009/04/jquery-performance-rules/#cache-jquery-objects\">cache the jQuery object</a> <code>$('#main')</code> by declaring another variable at the beginning of the ready function. Not doing so is slow because jQuery would have to find the matched elements within the document again.</p>\n\n<p>A more minor criticism is that of braceless control statements, such as:</p>\n\n<pre><code>if(e.which == 17) isCtrl=false;\n</code></pre>\n\n<p>Some say that it is best to always put the code within indented braces to avoid errors caused by incorrectly placed semicolons.</p>\n\n<p>Finally, the indentation doesn't look right throughout the entire code. Fix that, and your code will become somewhat more readable.</p>\n\n<p><strong>To add:</strong> It also looks like you have an extra comma at the end of:</p>\n\n<pre><code>'margin-left': '+=210px',\n</code></pre>\n\n<p>This is syntactically valid, but <a href=\"http://netbeans.org/bugzilla/show_bug.cgi?id=164626#c6\">it causes problems with Internet Explorer 7 and below</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T02:57:08.507", "Id": "229", "Score": "0", "body": "Thanks for the suggestions! Updated my question with the new [and improved] code. Also, thanks for the link to that performance page. I used the chaining tip for adding/removing the classes in addition to the \"jQuery object as a variable\" thing. Is it ok to take out the `function {...}` that was right after the `500` in `.animate()`? It works, but I don't know if that means I should leave it out. Anyways - thanks again! :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T03:03:30.530", "Id": "230", "Score": "0", "body": "@Andrew: The key difference is that the `function {...}` part runs only *after* the animation has completed. `.addClass()` isn't something added to the 'fx' queue, so the behavior will be different." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T03:15:36.510", "Id": "231", "Score": "0", "body": "@Andrew: Your new version of the code looks a lot better, although there are still some unnecessary trailing commas I had not noticed. I don't know what the best way to handle the different versions is. Perhaps you could give some insight in [this Meta question](http://meta.codereview.stackexchange.com/questions/41/iterative-code-reviews-how-can-they-happen-successfully)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T03:30:59.293", "Id": "232", "Score": "0", "body": "Fixed the commas (which cleared up 4 more lines.) Updated the code in the question. Also, that Meta question brings up a good point. Something like that would've helped here." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T02:06:10.973", "Id": "149", "ParentId": "148", "Score": "12" } }, { "body": "<p>idealmachine's advice is pretty sound.\nOne more minor criticism, using if's to set boolean values is a bit redundant.</p>\n\n<pre><code>if(e.which == 17) { isCtrl = false; }\n</code></pre>\n\n<p>You can rewrite that a bit more elegantly as</p>\n\n<pre><code>isCtrl = e.which != 17;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:08:25.733", "Id": "284", "ParentId": "148", "Score": "6" } }, { "body": "<p>You don't need to wrap toggleMenu in a function, you can just use</p>\n\n<pre><code>$('#tab').click(toggleMenu);\n</code></pre>\n\n<p>If you don't include the parenthesis, it's taken to mean a reference to the function rather than a function invocation.</p>\n\n<p>It's a bad idea to try and manually keep track of keyboard modifiers. For instance, if your website looses focus while the key is held down, it will think it's still down when you return focus, even if it isn't.</p>\n\n<p>The keyboard event has a <code>ctrlKey</code> property which will be <code>true</code> if the control key is being held down.</p>\n\n<p>It's also probably a good idea to put the key code into a variable which describes which key it is, as having to remember what <code>97</code> maps to can be tricky.</p>\n\n<pre><code>$(document).keydown(function (e) {\n if (e.ctrlKey &amp;&amp; e.which === aKey) {\n toggleMenu();\n return false;\n }\n});\n</code></pre>\n\n<p>Lastly, it might be a good idea to extract the offset into variable.</p>\n\n<pre><code>var menuSize = '210px';\nvar $main = $(\"#main\"); \n\nfunction toggleMenu() {\n if(!$main.hasClass('out')) {\n $main.animate({'margin-left': '+=' + menuSize}, 500).addClass('out'); \n } else {\n $main.animate({'margin-left': '-=' + menuSize}, 500).removeClass('out');\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T23:09:58.323", "Id": "339", "ParentId": "148", "Score": "4" } } ]
{ "AcceptedAnswerId": "149", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-22T00:59:16.190", "Id": "148", "Score": "16", "Tags": [ "javascript", "jquery", "html", "css" ], "Title": "Using a navigation menu to help keep material organized" }
148
<p>I have a class with quite a few attributes, most of which are known when I create an instance of the object. So I pass all the values in the constructor:</p> <pre><code>$op = new OpenIdProvider($imgPath . $name . $ext, 'openid_highlight', 0, 0, 108, 68, 6, $info[0], $info[1], $name); </code></pre> <p>I'm finding that having this many parameters makes it confusing both when writing and reading the code, as it's not easy to determine which attribute each value corresponds to. Also, this has a bit of a code smell to it - seems like there should be a better way. Any suggestions?</p>
[]
[ { "body": "<p>Martin Fowler's <strike>bible</strike> book <a href=\"http://rads.stackoverflow.com/amzn/click/0201485672\"><em>Refactoring</em></a> does identify a smell called \"<a href=\"http://c2.com/cgi/wiki?LongParameterList\">Long Parameter List</a>\" (p78) and proposes the following refactorings:</p>\n\n<ul>\n<li><a href=\"http://refactoring.com/catalog/replaceParameterWithMethod.html\">Replace Parameter with Method</a> (p292)</li>\n<li><a href=\"http://refactoring.com/catalog/introduceParameterObject.html\">Introduce Parameter Object</a> (295)</li>\n<li><a href=\"http://refactoring.com/catalog/preserveWholeObject.html\">Preserve Whole Object</a> (298)</li>\n</ul>\n\n<p>Of these I think that \"Introduce Parameter Object\" would best suit:</p>\n\n<p>You'd wrap the attributes up in their own object and pass that to the constructor. You may face the same issue with the new object if you choose to bundle all the values directly into its' constructor, though you could use setters instead of parameters in that object.</p>\n\n<p>To illustrate (sorry, my PHP-fu is weak):</p>\n\n<pre><code>$params = new OpenIDParams();\n$params-&gt;setSomething( $imgPath . $name . $ext );\n$params-&gt;setSomethingElse( 'openid_highlight' );\n</code></pre>\n\n<p></p>\n\n<pre><code>$params-&gt;setName( $name );\n\n$op = new OpenIdProvider( $params );\n</code></pre>\n\n<p>This is a little more verbose but it addresses your concern about not being clear about the attributes' purpose / meaning. Also it'll be a little less painful to add extra attributes into the equation later.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T05:01:36.577", "Id": "235", "Score": "1", "body": "Thanks, very helpful. So is the parameter object recommended over instantiating my object with the default constructor and calling setters directly on the object?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T05:05:05.357", "Id": "236", "Score": "0", "body": "@BenV you could go either way there. I mulled over both approaches and picked using parameter object because it separates the concern of managing the settings away from the Provider - which has a different responsibility." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T08:58:58.133", "Id": "238", "Score": "0", "body": "I would go with \"Replace Parameter with Method\" directly, removing all/most params from the constructor, and adding getters/setters. At least if there is no clear-cut semantic in the set of parameters provided, e.g. OpenIDParams does not seem to add much here, it just moves the issue: \"Do I need a constructor with all those parameters for OpenIDParams?\"... One more level of abstraction does not always solve the issue :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T16:44:30.597", "Id": "249", "Score": "2", "body": "This works particularly nice in a language with object literals (javascript): new OIDP ({ \"arg1\" : val1, \"arg2\": val2 ...}). Similar readability increase works in a language with keyword arguments like python. In both these cases you get something very compact and readable (the keyword strategy doesn't really correspond to a parameter object, but reads close enough that I figured I'd include it)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-24T16:09:05.810", "Id": "73531", "Score": "1", "body": "Before refactoring the constructor specifically, also ask yourself this: could any of these parameters be grouped into something useful? Maybe all these numbers are related and you could create an object from that? That would reduce the number of parameters to the constructor, and generally give you better readability, while being reusable in other places than just that one constructor." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-22T04:51:00.673", "Id": "152", "ParentId": "150", "Score": "52" } }, { "body": "<p>In addition to LRE's answer I would suggest you consider the idea that your class needs that many constructor arguments because it's trying to do too many things.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T10:24:58.690", "Id": "154", "ParentId": "150", "Score": "20" } }, { "body": "<p>As @LRE answer (+1) mentioned his PHP-fu is weak and since his points are correct and valid i just want to provide some more php code to illustrate :</p>\n\n<pre><code>class OpenIdProviderOptions {\n\n private $path;\n private $name = \"default_name\";\n private $param1;\n private $optionalParam2 = \"foo\";\n\n public function __construct($path, $param1) {\n /* you might take a $options array there for bc */\n /* Also if you have 2-3 REQUIRED parameters and the rest is optional\n i like putting all the required stuff in the constructor so you don't\n have to do any \"is that value set\" checking here.\n\n If you have 20 REQUIRED values you might split those into some objects\n or something ;) \n */\n }\n\n public function getPath() {\n return $this-&gt;path;\n }\n\n /* etc */\n\n\n}\n\nclass OpenIdProvider {\n\n private $settings;\n\n public function __construct(OpenIdProviderOptions $options) {\n $this-&gt;settings = $options;\n }\n\n public function foo {\n $path = $this-&gt;settings-&gt;getPath();\n }\n}\n\n$settings = new OpenIdProviderOptions(\"myopenid.example.com\", \"i need this\");\n$settings-&gt;setFoo(\"bar\");\n$settings-&gt;setBar(\"fubar\");\n\n$myProvider = new OpenIdProvider($settings);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T15:46:38.083", "Id": "158", "ParentId": "150", "Score": "8" } }, { "body": "<p>I think it would be better to put all of your parameters into one array. You then construct the array in a single command when you want to call the constructor.</p>\n\n<p>This approach also has the benefit that it is possible to add more options for the class, see the code below for an example:</p>\n\n<pre>\n<code>\nclass OpenIdProvider\n{\n public $_width = 0;\n public $_highliting = '';\n public $_Xposition = 0;\n public $_Yposition = 0;\n ...\n ...\n\n /**\n * Main constractor to set array of parameters.\n * param array $parameters\n * description _Xposition , _width , _Yposition ...\n */\n function __constrauct($parameters)\n {\n if(is_array($parameters))\n foreach($parameters as $needle=>$parameter)\n $this->{'_'.$needle} = $parameter;\n }\n}\n$options = array('path'=>$imgPath . $name . $ext,\n 'highliting'=> 'openid_highlight', \n 'width'=>108, \n 'height'=>68, \n '...'=>6, \n '...'=>$info[0], \n '...'=>$info[1],\n '...'=>$name);\n$openIdObj = new OpenIdProvider($options);\n</code>\n</pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-24T12:24:12.400", "Id": "283", "Score": "4", "body": "I really dislike this for a number of reasons: No type hinting for classes, no enfored required parameters so you need more error checking for foremost: It's incredible hard to use, the implantation is easy but the api suffers greatly. You'd need to _at least_ repeat all the parameters in the doc block you one even has a **chance** to create the class without looking at the sourcecode. Still, reading the docs and building an obscure alone is painfull enough for me to dislike that :) Still: Thanks for sharing, just my thoughs" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-09T16:33:39.610", "Id": "40197", "Score": "0", "body": "@edorian can you elaborate? This is how lots of legacy code at my current job works and I'm trying to understand why it's wrong and what's better. Are you basically saying a params array that's just floating around like this is hard to maintain? That objects offer more structure & are more standardized? Can you explain the doc block point?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-29T20:20:58.280", "Id": "301776", "Score": "0", "body": "Be aware that this class allows setting arbitrary variables inside the OpenIdProvider. `$this->{'_'.$needle} = $parameter;` this will create any underscore-prefixed variable you like. Even though this is only potentially unsafe, it can also lead to \"typo\" bugs. As seen in \"highliting\" in the actual code above! That would silently create `$this->_highliting` instead of setting `$this->_highlighting`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-24T09:42:18.467", "Id": "175", "ParentId": "150", "Score": "7" } }, { "body": "<p>PHP arrays are powerful. Similar to highelf I would use an array.</p>\n\n<p>However, I would do a number of things differently to highelf.</p>\n\n<ol>\n<li>Don't create public properties from the array you receive (especially using unknown array keys).</li>\n<li>Check the values that you receive.</li>\n</ol>\n\n<p>As edorian said, there is no type hinting, but you can enforce the required parameters manually. The advantages of this approach are:</p>\n\n<ol>\n<li>Its easy to remember the number of parameters (1).</li>\n<li>The order of the parameters is no longer important. (No need to worry about keeping a consistent order of parameters, although alphabetically works well.)</li>\n<li>The calling code is more readable as the parameters are named.</li>\n<li>It is very hard to accidentally set the width to the height even though the type is the same. (This is easily overlooked by type hinting).</li>\n</ol>\n\n<p>So here is what I would do:</p>\n\n<pre><code>class OpenIdProvider\n{\n protected $path;\n protected $setup;\n\n public function __construct(Array $setup)\n {\n // Ensure the setup array has keys ready for checking the parameters.\n // I decided to default some parameters (height, highlighting, something).\n $this-&gt;setup = array_merge(\n array('height' =&gt; 68,\n 'highlighting' =&gt; 'openid_highlight',\n 'info' =&gt; NULL,\n 'name' =&gt; NULL,\n 'path' =&gt; NULL, \n 'something' =&gt; 6, \n 'width' =&gt; NULL),\n $setup);\n\n // The following checks may look lengthy, but it avoids the creation of\n // the OpenIdProviderOptions class that seems to do very little. Also,\n // these would appear in that class to check the constructor values it\n // received properly.\n if (!is_array($this-&gt;setup['info']))\n {\n throw new InvalidArgumentException(\n __METHOD__ . ' requires info as array');\n }\n\n if (!is_string($this-&gt;setup['name']))\n {\n throw new InvalidArgumentException(\n __METHOD__ . ' requires name as string');\n }\n\n if (!is_string($this-&gt;setup['path']))\n {\n throw new InvalidArgumentException(\n __METHOD__ . ' requires path as string');\n }\n\n if (!is_int($this-&gt;setup['width']))\n {\n throw new InvalidArgumentException(\n __METHOD__ . ' requires width as int');\n }\n\n // If you use a setup parameter a lot you might want to refer to it from\n // this, rather than having to go via setup.\n $this-&gt;path =&amp; $this-&gt;setup['path'];\n }\n\n public function internalFunction()\n {\n // Use the parameters like so.\n echo $this-&gt;setup['width'];\n echo $this-&gt;path;\n }\n}\n\n// The call is very easy.\n$op = new OpenIdProvider(\n array('info' =&gt; $info,\n 'name' =&gt; $name,\n 'path' =&gt; $imgPath . $name . $ext,\n 'width' =&gt; 108));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-16T03:11:52.680", "Id": "7853", "ParentId": "150", "Score": "4" } }, { "body": "<p>Had same problem. Here's my solution:</p>\n\n<ol>\n<li>Try as hard as possible to break up your class into various pieces.</li>\n<li>Have these pieces passed as parameters.</li>\n</ol>\n\n<p>For example it seems your object draws it's own image. Delegate that to another class (IOpenIDImage). If your provider is supposed to open up a frame or tab to do its work then have another class handle that IOpenIDFrame.</p>\n\n<p>Now your code becomes:</p>\n\n<pre><code>$Image = new OPenIDImage('google', 100, 150);\n$Frame = new OPenIDFrame(......);\n$Data = new OPenIDSettings('host', 'name', 'auth-key');\n$Provider = new OpenIDProvider(Image $Image, Frame $Frame, Settings $Data);\n</code></pre>\n\n<p>This makes your code:</p>\n\n<ol>\n<li>Smaller / Compact. More easy to understand.</li>\n<li>Easier to debug. Since Everything is in a separate area.</li>\n<li>Easier to test. You can test different aspects like image.</li>\n<li>Easier to modify. You dont have to modify the entire class.</li>\n</ol>\n\n<p>I follow the following rules:</p>\n\n<ul>\n<li>2 Functions are better than 1</li>\n<li>2 Classes are better than 1</li>\n<li>2 Variables are better than 1</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-24T15:51:54.620", "Id": "42669", "ParentId": "150", "Score": "4" } }, { "body": "<p>You may use builder pattern here. I strongly recommend introduce fluent interface within it.</p>\n\n<p>Here's <a href=\"https://stackoverflow.com/questions/328496/when-would-you-use-the-builder-pattern\">stackoverflow link</a></p>\n\n<blockquote>\n <p>The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.</p>\n</blockquote>\n\n<p>At the end you will have something like</p>\n\n<pre><code>$op = new OpenIdProviderBuilder()\n .setImagePath($imgPath . $name . $ext)\n .setOpenId('openid_highlight')\n .setX(0)\n .setY(0)\n .setR(100)\n .setG(80)\n .setB(120)\n .setInfo(\"some info\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-14T19:13:45.770", "Id": "185104", "ParentId": "150", "Score": "1" } } ]
{ "AcceptedAnswerId": "152", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T02:37:01.583", "Id": "150", "Score": "45", "Tags": [ "php", "constructor" ], "Title": "Instantiating objects with many attributes" }
150
<p>I installed settingslogic and in the configuration file I put the regex for the email as follows:</p> <pre><code>#config/settings.yml defaults: &amp;defaults email_regex: /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i development: &lt;&lt;: *defaults # neat_setting: 800 test: &lt;&lt;: *defaults production: &lt;&lt;: *defaults </code></pre> <p>That I load in devise configuration in this way:</p> <pre><code>#config/initializers/devise.rb # Regex to use to validate the email address # config.email_regexp = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i config.email_regexp = eval Settings.email_regex </code></pre> <p>It works, but what do you think about that <code>eval</code>? Is it the correct way to convert a string to a regex?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T19:09:03.610", "Id": "973", "Score": "0", "body": "the solution is for getting the regex from a yaml, while if you have it in a regular string this could help you http://stackoverflow.com/questions/4840626/handle-a-regex-getting-its-value-from-a-database" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:43:58.777", "Id": "64502", "Score": "0", "body": "Did you choose email only as an example or are you actually making the regexp pattern that matches emails a configurable option? If the latter, allow me to ask: why? Are you really planning to deploy multiple versions of this app that need to match emails in different ways?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T21:58:02.233", "Id": "64503", "Score": "0", "body": "sorry for late answer, I store several email around the prj and I taught to have a single place where to store the regex all the emails have to respect, a constant would be enough" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-08T23:01:01.353", "Id": "64504", "Score": "0", "body": "Sorry for my even later reply. To clarify, I was asking why this needs to be set in a config file at all instead of being somewhere in the code where it makes sense - only once of course. E.g. something like this: Email.valid?(string)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-10T09:11:44.347", "Id": "64505", "Score": "0", "body": "The string is read in devise configuration, it's not my own auth and I use Settingslogic to store all my config in one place." } ]
[ { "body": "<p>I would definately not put the regex in the comment. That means that it needs to be changed in two places, one of which doesn't matter and will be misleading. Place a comment on the declaration of <code>email_regex</code> that explains what it is filtering. That way if it ever changes, all the places to change are contained and easy to find.</p>\n\n<pre><code>#config/initializers/devise.rb\n # Regex to use to validate the email address\n config.email_regexp = eval Settings.email_regex \n</code></pre>\n\n<p>and</p>\n\n<pre><code># Email validation regex - &lt;short explanation to taste&gt;\nemail_regex: /^([\\w\\.%\\+\\-]+)@([\\w\\-]+\\.)+([\\w]{2,})$/i \n</code></pre>\n\n<p>I see no readability problems with the code, if that is the correct method of retrieving a setting. (I'm not a Ruby expert.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T19:34:50.490", "Id": "256", "Score": "0", "body": "the comment was the old code before I put the setting, I left in there in case I had to go back to the old solution, you right, I'll remove it or comment it better." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T18:53:30.807", "Id": "160", "ParentId": "159", "Score": "7" } }, { "body": "<p>I'm not crazy about using eval for such a simple task, it's easy and it works but it just doesn't sit well with me; it's like giving your gran' an Indy car to go get a loaf of bread. Instead you could do something like this.</p>\n\n<pre><code>split = Settings.email_regex.split(\"/\")\noptions = (split[2].include?(\"x\") ? Regexp::EXTENDED : 0) |\n (split[2].include?(\"i\") ? Regexp::IGNORECASE : 0) |\n (split[2].include?(\"m\") ? Regexp::MULTILINE : 0) unless split[2].nil?\nRegexp.new(split[1], options)\n</code></pre>\n\n<p>This will work if there are options or not and doesn't require a potentially dangerous eval.</p>\n\n<p>P.S. Sinetris made the much better suggestion of just adding <code>!ruby/regexp</code> before your regex and wrapping it in single quotes in your settings.yml file. That still doesn't fix the issue with the RegExp class not properly dealing with string representations of regex statements though so I'll leave the above code for anyone that wants to do that outside of a YML file.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T23:16:14.043", "Id": "259", "Score": "0", "body": "I agree on everything and by the way thanks for editing, where then would you put this function for reuse?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T23:17:01.190", "Id": "260", "Score": "0", "body": "It's a little verbose anyway..." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T02:13:37.870", "Id": "261", "Score": "1", "body": "It's almost criminal that this kind of basic functionality isn't in the Regexp class so I'd monkey patch it into there. I would use a new function name though like Regexp#new_from_string or whatever you think sounds best. (I just added the \"ruby\" tag since it's more of a Ruby question than a Rails one)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T17:11:31.417", "Id": "460", "Score": "0", "body": "It's probably not part of the class because you can just prepend (?xim) to the regex itself. Monkeypatching a new constructor into a core class because the default doesn't do what you want /at first glance/ is a little nuts." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T20:45:34.577", "Id": "506", "Score": "0", "body": "I think you may not have bothered to read the actual question. Your comment makes no sense otherwise. The issue has nothing to do with regex options but converting a string representation of a regex to an actual regex. I'll bet you feel pretty nuts yourself now huh? Next time you might find it benificial to actually read the whole issue before commenting." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T22:34:53.437", "Id": "525", "Score": "0", "body": "Err, no, I understand the issue, though I don't understand why you're being hostile. Your code mainly deals with splitting out and handling regex modifiers, which you can include inside the pattern; put \"(?i)foo\" in the config file instead of \"/foo/i\", and pass it directly to Regexp.new(). Or am I missing something weird about Ruby's regex implementation?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T03:33:32.077", "Id": "546", "Score": "0", "body": "Funny, I don't read my response as hostile at all, but I do read yours that way with the whole \"nuts\" comment. Your comment made no sense because you weren't clear. Now that you've actually explained it instead of attacking someone giving an answer and the name calling I would agree, he could do that as well. I was more interested in fixing a design flaw in the Regexp class itself and I stand by my answer. The Regex class should support conversion of a standard string representation of a regex without the use of non-standard notation, it does not." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-22T19:58:08.453", "Id": "161", "ParentId": "159", "Score": "9" } }, { "body": "<p>If you want avoiding the eval you can. It's a little more trick but you can be sure, you have a regexps after this code in your devise :</p>\n\n<pre><code>#config/initializers/devise.rb\n# Regex to use to validate the email addres\n# config.email_regexp = /^([\\w\\.%\\+\\-]+)@([\\w\\-]+\\.)+([\\w]{2,})$/i\nSetting.email_regexp[/\\/(.*)\\/(.?)/] \nconfig.email_regexp = x ; Regexp.new(/#{$1}/)\n</code></pre>\n\n<p>The problem with this trick is you failed the second argument in your case the insensitive-case. You just need add a new setting like :</p>\n\n<pre><code>email_regexp_sensitive_case: true\n</code></pre>\n\n<p>And now you just need call like this :</p>\n\n<pre><code>#config/initializers/devise.rb\n# Regex to use to validate the email addres\n# config.email_regexp = /^([\\w\\.%\\+\\-]+)@([\\w\\-]+\\.)+([\\w]{2,})$/i\nSetting.email_regexp[/\\/(.*)\\/(.?)/] \nconfig.email_regexp = Regexp.new(/#{$1}/, Setting.email_regexp_sensitive_case)\n</code></pre>\n\n<p>In my case you are sure to have a Regexp define in your email_regexp without any eval.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T14:46:31.210", "Id": "273", "Score": "0", "body": "but what do you think about the code the way it was? is there anything we should be aware of (using eval this way)? because right now the initial implementation is the one that offers more readability" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T00:23:08.537", "Id": "163", "ParentId": "159", "Score": "4" } }, { "body": "<p>If you want to use a regexp in a yaml file you need to use <code>!ruby/regexp</code></p>\n\n<pre><code>#config/settings.yml\ndefaults: &amp;defaults\n\n email_regex: !ruby/regexp '/^([\\w\\.%\\+\\-]+)@([\\w\\-]+\\.)+([\\w]{2,})$/i'\n</code></pre>\n\n<p><strong>Edit</strong>:\n The solution proposed by Mike Bethany is very similar to the yaml implementation.</p>\n\n<p>You can take a look to what is used in Ruby 1.9.2 here (search for \"!ruby/regexp\"):\n<a href=\"https://github.com/tenderlove/psych/blob/master/lib/psych/visitors/to_ruby.rb\">https://github.com/tenderlove/psych/blob/master/lib/psych/visitors/to_ruby.rb</a></p>\n\n<p>PS (and OT): I think, like Mike Bethany, that this basic functionality belong to the Regexp class not yaml, and need to be moved to a Regexp method. What do you think?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T02:35:21.220", "Id": "251", "ParentId": "159", "Score": "28" } }, { "body": "<p>As Sinetris mentioned, YAML has support for loading an instance of Regexp from a string.</p>\n\n<pre><code>require 'yaml'\nYAML.load('!ruby/regexp /abc/ix')\n# =&gt; /abc/ix\nYAML.load('!ruby/regexp /abc/ix').class\n# =&gt; Regexp \n</code></pre>\n\n<p><a href=\"http://apidock.com/ruby/Regexp/yaml_new/class\" rel=\"nofollow\">http://apidock.com/ruby/Regexp/yaml_new/class</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T13:26:03.990", "Id": "270", "ParentId": "159", "Score": "4" } } ]
{ "AcceptedAnswerId": "251", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-22T18:09:18.930", "Id": "159", "Score": "25", "Tags": [ "ruby", "ruby-on-rails", "regex", "converting" ], "Title": "Use of a regex stored inside a YAML file" }
159
<p>Is this code good enough, or is it stinky? </p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace DotNetLegends { public class LogParser { /// &lt;summary&gt; /// Returns a populated Game objects that has a list of players and other information. /// &lt;/summary&gt; /// &lt;param name="pathToLog"&gt;Path to the .log file.&lt;/param&gt; /// &lt;returns&gt;A Game object.&lt;/returns&gt; public Game Parse(string pathToLog) { Game game = new Game(); //On actual deployment of this code, I will use the pathToLog parameter. StreamReader reader = new StreamReader(@"D:\Games\Riot Games\League of Legends\air\logs\LolClient.20110121.213758.log"); var content = reader.ReadToEnd(); game.Id = GetGameID(content); game.Length = GetGameLength(content); game.Map = GetGameMap(content); game.MaximumPlayers = GetGameMaximumPlayers(content); game.Date = GetGameDate(content); return game; } internal string GetGameID(string content) { var location = content.IndexOf("gameId"); var gameID = content.Substring(location + 8, 10); gameID = gameID.Trim(); return gameID; } internal string GetGameLength(string content) { var location = content.IndexOf("gameLength"); var gamelength = content.Substring(location + 13, 6); gamelength = gamelength.Trim(); var time = Convert.ToInt32(gamelength) / 60; return time.ToString(); } internal string GetGameMap(string content) { var location = content.IndexOf("mapId"); var gameMap = content.Substring(location + 8, 1); switch (gameMap) { case "2": return "Summoner's Rift"; default: return "nul"; } } internal string GetGameMaximumPlayers(string content) { var location = content.IndexOf("maxNumPlayers"); var maxPlayers = content.Substring(location + 16, 2); maxPlayers = maxPlayers.Trim(); return maxPlayers; } internal string GetGameDate(string content) { var location = content.IndexOf("creationTime"); var creationDate = content.Substring(location + 14, 34); creationDate = creationDate.Trim(); return creationDate; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T03:12:41.193", "Id": "264", "Score": "1", "body": "Is there a reason that you are converting the length back to a string?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T02:39:07.880", "Id": "64483", "Score": "0", "body": "You should close the file stream, and probably declare it with a using statement so it gets disposed." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T02:41:07.700", "Id": "64484", "Score": "0", "body": "Totally, but I'm asking about the way I'm parsing itself, and how I'm passing the parameters. (Upvote either way!)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T03:00:03.117", "Id": "64485", "Score": "0", "body": "Ahh, hadn't noticed the rest on my phone, it didn't have scrollbars." } ]
[ { "body": "<ol>\n<li>Remove the code responsible for retrieving the log file contents. If this is a type that is just responsible for parsing log files than that is all it should do. Think about either passing in the file contents to this method or using Dependency Injection so that you can mock out the <code>StreamReader</code> call in your tests. You do have tests right?</li>\n<li>Return the appropriate types from these methods. <code>GetGameLength</code> should return an int and <code>Game.Length</code> should likewise be an int. Same thing for Maximum Players and Game Date.</li>\n<li>The 'Get' methods should be private or protected unless there is some specific reason to make them internal. </li>\n<li>If there are a finite number of maps (and they are all known) you may want to consider using an enum rather than a string. If an enum is not appropriate you may want to create a <code>GameMap</code> (or some such type to encapsulate the information you care about with regards to a map) and return that instead.</li>\n<li>Each 'Get' method needs to check that the location variable is set to something >= 0 when you search for the specified text.</li>\n<li>Throw helpful exceptions if the log file does not contain the expected data (or the data isn't the expected type). A NullReferenceException is not a helpful exception.</li>\n<li>There are too many magic numbers and strings here. Move these into constants with helpful names.</li>\n<li>Add comments with examples of the log file text that you will be searching for in each 'Get' method. This makes maintenance significantly easier as you know the type of text you were expecting to be parsing.</li>\n<li>Wrap the <code>StreamReader</code> in a using block.</li>\n<li>Check that the file exists before attempting to load it.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T05:40:01.360", "Id": "266", "Score": "0", "body": "My reasoning for using string instead of ints for Length is that I won't be calculating anything with it. Why would I cast it to string when outputting it to the browser? Just leaving it as string from the get go seems the best course of action. Thanks for the other tips." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T11:59:45.730", "Id": "268", "Score": "0", "body": "for point 3 don't you mean external since the idea is to make it only accessible within this class? agreed with all the other points." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-24T03:47:54.230", "Id": "282", "Score": "0", "body": "@victor The method accessibility is set to internal, that's what I was referring to." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T05:03:24.143", "Id": "166", "ParentId": "164", "Score": "6" } }, { "body": "<p>You have a lot of undescriptive magic numbers and code repetition whilst retrieving the contents of a field. You could eliminate the repetition and make those numbers a little more meaningful by introducing a single method:</p>\n<pre><code>protected string GetFieldContent(string content, string field,\n int padding, int length)\n{\n var location = content.indexOf(field);\n padding += field.Length;\n\n var fieldVal = content.Substring(location + padding, length);\n fieldVal = fieldVal.Trim();\n return fieldVal;\n}\n</code></pre>\n<p>Use it like so:</p>\n<pre><code>internal string GetGameMaximumPlayers(string content)\n{\n var maxPlayers = GetFieldContent(content, &quot;maxNumPlayers&quot;, 3, 2);\n return maxPlayers;\n}\n</code></pre>\n<p>Something to note here is the padding value has changed. You no longer need to include the length of the field name itself and can just describe the number of junk characters afterwards.</p>\n<h3>Padding length</h3>\n<p>Upon examining your code I noticed one peculiarity - the fields have inconsistent, magical padding lengths:</p>\n<ul>\n<li><strong>gameID padding: 2</strong></li>\n<li>gameLength padding: 3</li>\n<li>mapId padding: 3</li>\n<li>maxNumPlayers padding: 3</li>\n<li><strong>creationTime padding: 2</strong></li>\n</ul>\n<p>As a symptom of these being magic numbers I have no idea why this is the case. This is one of the many reasons to avoid magic numbers like the plague: it's difficult to understand their meaning. I'll trust you to evaluate whether varying padding lengths is necessary, or whether you can just assume a constant padding for all fields.</p>\n<p><strong>If we can assume a constant padding amount for all fields</strong> then we can change the code further a little bit to make your life easier. There are two steps to this change.</p>\n<p>First, give your <code>LogParser</code> class a private field:</p>\n<p><code>private const var defaultPadding = 2</code></p>\n<p>Second, <code>GetFieldContent</code> can be refactored to produce this:</p>\n<pre><code>protected string GetFieldContent(string content, string field, int length)\n{\n var location = content.indexOf(field);\n var padding = defaultPadding + field.Length;\n\n var fieldVal = content.Substring(location + padding, length);\n fieldVal = fieldVal.Trim();\n return fieldVal;\n}\n</code></pre>\n<p>Then getting the contents of a field becomes simpler:</p>\n<p><code>var maxPlayers = GetFieldContent(content, &quot;maxNumPlayers&quot;, 2);</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T09:09:29.140", "Id": "167", "ParentId": "164", "Score": "24" } }, { "body": "<p>Seems like you're doing a lot of unecessary and standard managing of a simple logfile. If you were saving the log in binary perhaps it could be excused but seeing as you're working with text files, why not go with xml? or rather, why not go with XML Fragments? Linq to XML has excellent support for managing those kinds of files, both creating, parsing and querying.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T12:48:09.010", "Id": "269", "Score": "2", "body": "I'm parsing a log file that is completely out of my hands. Trust me, if I had a choice, I'd be parsing json. :P" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T01:48:41.200", "Id": "292", "Score": "0", "body": "Based on the filepath Sergio Tapia appears to be parsing League of Legends' logfiles, presumably those generated just after completion of a match which describe the events of that match." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T12:18:55.570", "Id": "168", "ParentId": "164", "Score": "1" } }, { "body": "<p>I would rename the methods GetGameID(), GetGameLength(), GetGameMap()... because they look like getters, that could be called in any order, while they are actually performing parsing and must be called in a given order. This is confusing at first glance.</p>\n\n<p>I suggest replacing 'Get' with 'Read' or 'Parse':</p>\n\n<ul>\n<li>ReadGameID()</li>\n<li>ReadGameLength()</li>\n<li>ReadGameMap()</li>\n<li>...</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T16:07:03.653", "Id": "277", "Score": "0", "body": "They can be called in any order any number of times. This wouldn't be the case if the methods were operating on the `reader` file stream, but the entire file is read into `content` right after it's opened. Since the methods operate on a string there's no need to read them in any particular order." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T14:09:21.540", "Id": "171", "ParentId": "164", "Score": "0" } }, { "body": "<p>You have basically created a <strong>procedural implementation</strong> of your own mechanism to <strong>serialize</strong> a game object to and from a file wich is ok if you want to be in full controll of the file format. </p>\n\n<p>Have you looked at the concept of <a href=\"http://msdn.microsoft.com/en-us/library/7ay27kt9%28v=VS.80%29.aspx\" rel=\"nofollow\">dotnet-serialisation</a>? There you can see how <strong>declarative</strong> style could minimize the code to write by attaching Attributes to the Game-Class and/or its properties.</p>\n\n<p>There are implementatins for binary, xml and json</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T09:16:32.897", "Id": "788", "Score": "0", "body": "I don't think it's such a great idea. The game is going to be evolving a lot, and if the class evolves, the serializer will probably be unable to compute it. The custom deserializer is more robust." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-09T07:51:44.323", "Id": "19998", "Score": "0", "body": "DonkeyMaster:\nAre you saying that you and a custom serializer because you want to be able to deserialise logs written by and old version of of the program?\nI think that might be an antipattern.\nIf nothing else you might consider a custom Xml Serialser, over your own flat file format.\nIn any case the Poster has said inanother comment that he isn't incontrol of the fileformat, so this disucssion is irellervent" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:57:45.853", "Id": "293", "ParentId": "164", "Score": "3" } }, { "body": "<p>You could also replace:</p>\n\n<pre><code>StreamReader reader = new StreamReader(@\"D:\\Games\\Riot Games\\League of Legends\\air\\logs\\LolClient.20110121.213758.log\");\nvar content = reader.ReadToEnd();\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>var content = File.ReadAllText(@\"D:\\Games...log\");\n</code></pre>\n\n<p><code>ReadAllText</code> method, as MSDN says: Opens a text file, reads all lines of the file into a string, and then closes the file.</p>\n\n<p>Which is even shorter than <code>using</code> block.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:10:10.730", "Id": "308", "ParentId": "164", "Score": "2" } }, { "body": "<ol>\n<li>You should put a comment with the reference to the log format if it exists .</li>\n<li>There is no error checking at all.</li>\n<li>There is nothing in your code which reflects the structure of the file. If I were in your place I would use regex.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T01:27:20.200", "Id": "3731", "ParentId": "164", "Score": "0" } } ]
{ "AcceptedAnswerId": "167", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-23T02:24:12.317", "Id": "164", "Score": "17", "Tags": [ "c#", "game", "parsing" ], "Title": "Parsing a file for a game" }
164
<p><strong>Note:</strong> This file is out of my hands. I cannot change the format or type of file I have to parse.</p> <p>Here is some sample data that I'm trying to parse. This is information for just <strong>one</strong> player:</p> <pre><code>[0] (com.riotgames.platform.gameclient.domain::PlayerParticipantStatsSummary)#8 _profileIconId = 4 elo = 0 eloChange = 0 gameId = 82736631 gameItems = (null) inChat = false leaver = false leaves = 1 level = 5 losses = 2 profileIconId = 4 skinName = "Vladimir" statistics = (mx.collections::ArrayCollection)#9 filterFunction = (null) length = 26 list = (mx.collections::ArrayList)#10 length = 26 source = (Array)#11 [0] (com.riotgames.platform.gameclient.domain::RawStatDTO)#12 displayName = (null) statTypeName = "PHYSICAL_DAMAGE_TAKEN" value = 11156 [1] (com.riotgames.platform.gameclient.domain::RawStatDTO)#13 displayName = (null) statTypeName = "TOTAL_DAMAGE_TAKEN" value = 20653 [2] (com.riotgames.platform.gameclient.domain::RawStatDTO)#14 displayName = (null) statTypeName = "ITEM2" value = 3158 [3] (com.riotgames.platform.gameclient.domain::RawStatDTO)#15 displayName = (null) statTypeName = "ITEM4" value = 3089 [4] (com.riotgames.platform.gameclient.domain::RawStatDTO)#16 displayName = (null) statTypeName = "WIN" value = 1 [5] (com.riotgames.platform.gameclient.domain::RawStatDTO)#17 displayName = (null) statTypeName = "PHYSICAL_DAMAGE_DEALT_PLAYER" value = 18413 [6] (com.riotgames.platform.gameclient.domain::RawStatDTO)#18 displayName = (null) statTypeName = "TOTAL_HEAL" value = 16877 [7] (com.riotgames.platform.gameclient.domain::RawStatDTO)#19 displayName = (null) statTypeName = "ITEM0" value = 3083 [8] (com.riotgames.platform.gameclient.domain::RawStatDTO)#20 displayName = (null) statTypeName = "LARGEST_CRITICAL_STRIKE" value = 173 [9] (com.riotgames.platform.gameclient.domain::RawStatDTO)#21 displayName = (null) statTypeName = "ITEM3" value = 3116 [10] (com.riotgames.platform.gameclient.domain::RawStatDTO)#22 displayName = (null) statTypeName = "ITEM1" value = 0 [11] (com.riotgames.platform.gameclient.domain::RawStatDTO)#23 displayName = (null) statTypeName = "GOLD_EARNED" value = 11123 [12] (com.riotgames.platform.gameclient.domain::RawStatDTO)#24 displayName = (null) statTypeName = "ASSISTS" value = 8 [13] (com.riotgames.platform.gameclient.domain::RawStatDTO)#25 displayName = (null) statTypeName = "LARGEST_MULTI_KILL" value = 2 [14] (com.riotgames.platform.gameclient.domain::RawStatDTO)#26 displayName = (null) statTypeName = "MAGIC_DAMAGE_DEALT_PLAYER" value = 103124 [15] (com.riotgames.platform.gameclient.domain::RawStatDTO)#27 displayName = (null) statTypeName = "BARRACKS_KILLED" value = 0 [16] (com.riotgames.platform.gameclient.domain::RawStatDTO)#28 displayName = (null) statTypeName = "LARGEST_KILLING_SPREE" value = 5 [17] (com.riotgames.platform.gameclient.domain::RawStatDTO)#29 displayName = (null) statTypeName = "ITEM5" value = 0 [18] (com.riotgames.platform.gameclient.domain::RawStatDTO)#30 displayName = (null) statTypeName = "MINIONS_KILLED" value = 176 [19] (com.riotgames.platform.gameclient.domain::RawStatDTO)#31 displayName = (null) statTypeName = "CHAMPIONS_KILLED" value = 11 [20] (com.riotgames.platform.gameclient.domain::RawStatDTO)#32 displayName = (null) statTypeName = "MAGIC_DAMAGE_TAKEN" value = 8581 [21] (com.riotgames.platform.gameclient.domain::RawStatDTO)#33 displayName = (null) statTypeName = "NEUTRAL_MINIONS_KILLED" value = 12 [22] (com.riotgames.platform.gameclient.domain::RawStatDTO)#34 displayName = (null) statTypeName = "TOTAL_TIME_SPENT_DEAD" value = 189 [23] (com.riotgames.platform.gameclient.domain::RawStatDTO)#35 displayName = (null) statTypeName = "TURRETS_KILLED" value = 0 [24] (com.riotgames.platform.gameclient.domain::RawStatDTO)#36 displayName = (null) statTypeName = "NUM_DEATHS" value = 5 [25] (com.riotgames.platform.gameclient.domain::RawStatDTO)#37 displayName = (null) statTypeName = "TOTAL_DAMAGE_DEALT" value = 121538 uid = "B6F2F234-2E37-D979-E896-AA7614FCE9CB" sort = (null) source = (Array)#11 summonerName = "WeFearTheSun" teamId = 100 userId = 21672484 wins = 6 </code></pre> <p>Now there are ten players in a game, meaning ten of that snippet above, each one with an increasing counter, [1],[2],[3], and so on.</p> <p>As you can see <strong>inside</strong> of this data there are further numbers, ie. another <code>[0]</code>.</p> <p>If the numbers were unique I could just parse the <code>[0]</code>, then the <code>[1]</code>, then the <code>[2]</code>, etc.</p> <p>Right now I'm parsing the files like so:</p> <pre><code>private IEnumerable&lt;Player&gt; GetGamePlayers(string content) { List&lt;Player&gt; Players = new List&lt;Player&gt;(); var location = content.IndexOf("com.riotgames.platform.gameclient.domain::EndOfGameStats"); var cutContent = content.Substring(location, 65000); var playerOneLocation = cutContent.IndexOf("[0]"); //var playerOneContent = cutContent.Substring(playerOneLocation, 6231); var playerOneContent = cutContent.Substring(playerOneLocation, 6255); Players.Add(ParsePlayer(playerOneContent)); cutContent = cutContent.Substring(playerOneLocation + 6229, cutContent.Length - playerOneLocation - 6229); var playerTwoLocation = cutContent.IndexOf("[1]"); var playerTwoContent = cutContent.Substring(playerTwoLocation, 6255); Players.Add(ParsePlayer(playerTwoContent)); cutContent = cutContent.Substring(playerTwoLocation + 6229, cutContent.Length - playerTwoLocation - 6229); var playerThreeLocation = cutContent.IndexOf("[2]"); var playerThreeContent = cutContent.Substring(playerThreeLocation, 6255); Players.Add(ParsePlayer(playerThreeContent)); cutContent = cutContent.Substring(playerThreeLocation + 6229, cutContent.Length - playerThreeLocation - 6229); var playerFourLocation = cutContent.IndexOf("[3]"); var playerFourContent = cutContent.Substring(playerFourLocation, 6255); Players.Add(ParsePlayer(playerFourContent)); cutContent = cutContent.Substring(playerFourLocation + 6229, cutContent.Length - playerFourLocation - 6229); var playerFiveLocation = cutContent.IndexOf("[4]"); var playerFiveContent = cutContent.Substring(playerFiveLocation, 6255); Players.Add(ParsePlayer(playerFiveContent)); location = cutContent.IndexOf("teamPlayerParticipantStats"); cutContent = cutContent.Substring(location, 32000); var playerSixLocation = cutContent.IndexOf("[0]"); var playerSixContent = cutContent.Substring(playerSixLocation, 6255); Players.Add(ParsePlayer(playerSixContent)); cutContent = cutContent.Substring(playerSixLocation + 6229, cutContent.Length - playerSixLocation - 6229); var playerSevenLocation = cutContent.IndexOf("[1]"); var playerSevenContent = cutContent.Substring(playerSevenLocation, 6255); Players.Add(ParsePlayer(playerSevenContent)); cutContent = cutContent.Substring(playerSevenLocation + 6229, cutContent.Length - playerSevenLocation - 6229); var playerEightLocation = cutContent.IndexOf("[2]"); var playerEightContent = cutContent.Substring(playerEightLocation, 6255); Players.Add(ParsePlayer(playerEightContent)); cutContent = cutContent.Substring(playerEightLocation + 6229, cutContent.Length - playerEightLocation - 6229); var playerNineLocation = cutContent.IndexOf("[3]"); var playerNineContent = cutContent.Substring(playerNineLocation, 6255); Players.Add(ParsePlayer(playerNineContent)); cutContent = cutContent.Substring(playerNineLocation + 6229, cutContent.Length - playerNineLocation - 6229); var playerTenLocation = cutContent.IndexOf("[4]"); var playerTenContent = cutContent.Substring(playerTenLocation, 6255); Players.Add(ParsePlayer(playerTenContent)); return Players; } </code></pre> <p>I can tell the code is horrible, and there is a lot of room for improvement. How would I divide the huge content into single blocks for each individual player?</p> <p>I need to get the string content:</p> <pre><code>[0] (com.riotgames.platform.gameclient.domain::PlayerParticipantStatsSummary)#8 to [1] (com.riotgames.platform.gameclient.domain::PlayerParticipantStatsSummary)#8 then: [1] (com.riotgames.platform.gameclient.domain::PlayerParticipantStatsSummary)#8 to [2] (com.riotgames.platform.gameclient.domain::PlayerParticipantStatsSummary)#8 </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T19:52:28.650", "Id": "281", "Score": "0", "body": "Just a minor point, you should always return the most specific type while requiring the least specific as parameter. So I'd return a List rather than an IEnumerable in this case so you can access count etc. Using IEnumerable for an input parameter rather than List had been good design though" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-09T13:52:53.837", "Id": "1281", "Score": "0", "body": "@mko - You should not return a `List<T>` object, [FxCop](http://msdn.microsoft.com/en-us/library/ms182142%28v=VS.100%29.aspx) will be very upset if you do. Also, you should check out this article by [Dave Donaldson](http://arcware.net/use-collectiont-instead-of-listt-for-public-api/) and from [StackOverflow](http://stackoverflow.com/questions/387937/why-is-it-considered-bad-to-expose-listt) that discuss why it is a bad practice to return a `List<T>`. I don't disagree that returning the most specific type you can is a good practice in general, but List would not be a good candidate to return." } ]
[ { "body": "<p>Some rules of thumb that should improve your code:</p>\n<ul>\n<li>If you have variables with names resembling <code>varOne</code>, <code>varTwo</code>, <code>varThree</code>, etc - no matter what the number you should probably be using an array.</li>\n<li>If you are doing several identical actions over a sequence of values you should be using a loop.</li>\n<li>Code should never need to be repeated.</li>\n</ul>\n<p>Now with these in mind let's get to work.</p>\n<pre><code>private IEnumerable&lt;Player&gt; GetGamePlayers(string content)\n{\n List&lt;Player&gt; Players = new List&lt;Player&gt;();\n\n // Get the endgame stats text\n string endgameStatsMarker = &quot;com.riotgames.platform.gameclient.domain::EndOfGameStats&quot;\n int endgameStatsLocation = content.IndexOf(endgameStatsMarker);\n string endgameStats = content.Substring(endgameStatsLocation);\n \n // Split the endgame stats text into an array of player information sections\n string[] charBeginMarker = new string[] {&quot;(com.riotgames.platform.gameclient.domain::PlayerParticipantStatsSummary)&quot;}\n string[] playerInfoSet = endgameStats.Split(charBeginMarker, SplitStringOptions.None);\n\n // don't assume there's 10; get this from the logfile\n int numPlayers = GetMaxPlayers();\n\n // playerDataSet[0] is before any playerInfo begins, so we skip it.\n for (int i = 1; i &lt;= numPlayers; i++);\n {\n Players.Add(ParsePlayer(playerData));\n // The string passed to ParsePlayer will be a little different now.\n // It will contain a [#] on the end except in the case of the last player.\n // This is since we split the text at the beginning of the player field\n // and AFTER the [#].\n // You will have to ensure your ParsePlayer method will work with this\n // new input.\n }\n \n return Players;\n}\n</code></pre>\n<p>... Well's most of your code removed following some simple rules. <a href=\"http://www.folklore.org/StoryView.py?project=Macintosh&amp;story=Negative_2000_Lines_Of_Code.txt\" rel=\"noreferrer\">The story of Bill Atkinson</a> is probably quite relevant here. ;)</p>\n<h2>On better parsing</h2>\n<p>There is one large problem in your approach to file parsing I must talk to you about.</p>\n<p>You are <em>guessing</em> how long the player data section is going to be based on the <em>current</em> logfile format's appearance and hardcoding this into the program. Let's examine this method's faults. Tell me what happens when any of these things happen:</p>\n<ol>\n<li>Player data sections become one character longer.</li>\n<li>Player data sections get one one more line of information.</li>\n<li>Player data sections have another array introduced to them.</li>\n</ol>\n<p>The answers (no peeking): 1. Your parsing of player data might go funny. 2. Your parsing will probably explode. 3. Your parsing will definitely explode in a horrible mess.</p>\n<p>If you were parsing the file correctly, your program would be at least an order of magnitude less likely to stuff up in each case, until a <em>major</em> change is made to the logfile format.</p>\n<p>The key to parsing this file is recognising that <strong>this file is full of human-readable <em>and</em> computer-readable markup you are not exploiting at all.</strong></p>\n<p>Here is what you are doing: Open file. Identify where sections split. Count the number of characters. Hardcode this into the program and extract those characters.</p>\n<p>Here is what you <em>should</em> be doing: Open file. Identify where sections split. Determine <em>how</em> you identified where the sections split. Write code that is able to recognise this split, and splits the file content accordingly.</p>\n<p><strong>Thus, the key is:</strong> understanding how <em>you</em> understand what you see, then teaching your program to understand it as well!</p>\n<p>For instance, consider these rules:</p>\n<ul>\n<li>A character information section begins at a particular string and ends at the next occurrence of the same string, so you can just split the character information sections on that string.</li>\n<li>Once you reach a <code>#</code> you've found a special field. It may be a simple comment or it may be an ID for each unique object, allowing reusing objects from cache in case two objects are identical. It is probably safe to ignore from a <code>#</code> to the end of a line unless you find a use for it.</li>\n<li>A variable can be found at the beginning of a line after any whitespace. The amount of whitespace is significant (see last point).</li>\n<li>If the first character found on a line is <code>[</code> it's an element of an array, not a variable name.</li>\n<li>A variable name ends at the first space.</li>\n<li>A variable's value is on the other side of the <code>=</code>, removing any unnecessary spaces on the other side.</li>\n<li>If a value starts with an integer it is an integer. If it starts with quotation marks it is a string.</li>\n<li>Variables will always contain an element ID then a type declaration. The variables that follow are probably the properties of an object of that type.</li>\n<li>An array item's contents are always indented. An increase in indent depth means you're now reading the contents of the array from the line above. A decrease in indent depth means you've finished reading the contents of that array.</li>\n</ul>\n<p>Nine rules just from understanding and describing how I understand what I see. They should be fairly simple to implement in the parser in the form of methods - then all of a sudden your parser can already deal with 90% of the logfile's syntax! Only a few things are missing at this point, such as parsing an array element's type declaration or inferring the type of a variable's value (string? integer?).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T17:11:41.490", "Id": "278", "Score": "0", "body": "Thanks a bunch for your help. Since posting this question this morning I have changed the code significantly and most of the things you mentioned glared at me during lunch. :D You're suggestions regarding using .Split is very good! It significantly reduced my LOC count and made it very understandable. However there is an error firing when trying to compile saying that the .Split() method doesn't use a string, but a char." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T17:17:52.333", "Id": "279", "Score": "0", "body": "@Sergio: Whoops! I was misusing `Split`. The overload I was after takes a `String[]` and a `StringSplitOptions`. No wonder it was complaining. I've rewritten those two lines." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T17:26:56.830", "Id": "280", "Score": "0", "body": "Thanks a lot Jonathan. Your time is very much appreciated and I'm learning tons on this site! Check my edit for the final version after following your .Split advice. It's SIGNIFICANTLY cleaner. :D Can't thank you enough." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-23T16:53:49.287", "Id": "173", "ParentId": "172", "Score": "14" } } ]
{ "AcceptedAnswerId": "173", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-23T14:33:21.713", "Id": "172", "Score": "9", "Tags": [ "c#", "parsing" ], "Title": "Parsing a game file" }
172
<p>The code below is a plugin I wrote for <code>Ext.grid.GridPanel</code>, which basically allows you to have a bit more control over how rows are striped in the grid. By default you can only have every other row in alternate colour. With this plugin you an have for example 5 in basic color, 5 in alternate and so on.</p> <p>What bothers me about it, is that it basically is 100+ lines copied from <code>Ext.grid.GridView</code> with no more than 10 lines of my modifications. I would love to know if there's a way to do it in a more elegant way.</p> <p>My second concern is with that it's a plugin for <code>Ext.grid.GridPanel</code>, but it actually modifies the underlying <code>Ext.grid.GridView</code>. As far as I know, there is no way to attach a plugin to a <code>GridView</code> with current framework architecture, but perhaps you DO know the way.</p> <p>Legal stuff: The code is largely based on ExtJS source code, and as such it's released under <a href="http://www.gnu.org/copyleft/gpl.html">GNU GPL license v3 license</a></p> <pre><code>MyNamespace.grid.plugins.RowStriper = Ext.extend(Object, { constructor : function(config) { config = config || {}; Ext.apply(this, config); }, init : function(parent) { if (parent instanceof Ext.grid.GridPanel) { this.parent = parent; this.parent.stripeInterval = this.stripeInterval; parent.on('destroy', this.onDestroy, this); Ext.apply(parent.getView(), this.parentViewOverrides); } }, onDestroy : Ext.emptyFn, parentViewOverrides : { doRender : function(columns, records, store, startRow, colCount, stripe) { var templates = this.templates, cellTemplate = templates.cell, rowTemplate = templates.row, last = colCount - 1; var tstyle = 'width:' + this.getTotalWidth() + ';'; // buffers var rowBuffer = [], colBuffer = [], rowParams = {tstyle: tstyle}, meta = {}, column, record; //build up each row's HTML for (var j = 0, len = records.length; j &lt; len; j++) { record = records[j]; colBuffer = []; var rowIndex = j + startRow; //build up each column's HTML for (var i = 0; i &lt; colCount; i++) { column = columns[i]; meta.id = column.id; meta.css = i === 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : ''); meta.attr = meta.cellAttr = ''; meta.style = column.style; meta.value = column.renderer.call(column.scope, record.data[column.name], meta, record, rowIndex, i, store); if (Ext.isEmpty(meta.value)) { meta.value = '&amp;#160;'; } if (this.markDirty &amp;&amp; record.dirty &amp;&amp; Ext.isDefined(record.modified[column.name])) { meta.css += ' x-grid3-dirty-cell'; } colBuffer[colBuffer.length] = cellTemplate.apply(meta); } //set up row striping and row dirtiness CSS classes var alt = []; if (stripe &amp;&amp; (rowIndex % (this.grid.stripeInterval * 2)) &gt; (this.grid.stripeInterval - 1)) { alt[0] = 'x-grid3-row-alt'; } if (record.dirty) { alt[1] = ' x-grid3-dirty-row'; } rowParams.cols = colCount; if (this.getRowClass) { alt[2] = this.getRowClass(record, rowIndex, rowParams, store); } rowParams.alt = alt.join(' '); rowParams.cells = colBuffer.join(''); rowBuffer[rowBuffer.length] = rowTemplate.apply(rowParams); } return rowBuffer.join(''); }, processRows : function(startRow, skipStripe) { if (!this.ds || this.ds.getCount() &lt; 1) { return; } var rows = this.getRows(), len = rows.length, i, r; skipStripe = skipStripe || !this.grid.stripeRows; var stripeInterval = this.grid.stripeInterval || 1; startRow = startRow || 0; for (i = 0; i&lt;len; i++) { r = rows[i]; if (r) { r.rowIndex = i; if (!skipStripe) { r.className = r.className.replace(this.rowClsRe, ' '); if ((i % (stripeInterval * 2)) &gt; (stripeInterval - 1)){ r.className += ' x-grid3-row-alt'; } } } } // add first/last-row classes if (startRow === 0) { Ext.fly(rows[0]).addClass(this.firstRowCls); } Ext.fly(rows[rows.length - 1]).addClass(this.lastRowCls); } } }); </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-24T18:17:37.610", "Id": "284", "Score": "0", "body": "Relevant links: docs http://dev.sencha.com/deploy/dev/docs/?class=Ext.grid.GridPanel and source: http://dev.sencha.com/deploy/dev/docs/source/GridPanel.html#cls-Ext.grid.GridPanel (is that correct?)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-24T20:07:37.190", "Id": "286", "Score": "1", "body": "Yup. Although most of the code is from http://dev.sencha.com/deploy/dev/docs/?class=Ext.grid.GridView component (source http://dev.sencha.com/deploy/dev/docs/source/GridView.html#cls-Ext.grid.GridView )" } ]
[ { "body": "<p>I don't see how to improve the duplication much: you're extending code that unfortunately wasn't meant to be extended. </p>\n\n<p>What you could do to help anyone finding your code in the wild is to highlight changes and maybe explain why you're doing the calculations you're doing. How would you generalize your code to alternate between three or more row styles?</p>\n\n<pre><code> //set up row striping and row dirtiness CSS classes\n var alt = [];\n\n/// -&gt; Comment about how you're making the stripe interval magic happen here\n if (stripe &amp;&amp; (rowIndex % (this.grid.stripeInterval * 2)) &gt; (this.grid.stripeInterval - 1)) {\n/// -^ Consider breaking this up into assignment into a var and subsequent if, or \n/// even nesting ifs: it might be more readable by separating logical steps.\n/// A helper to be used below would be an option, and if you're going to generalize\n/// it could make extending easier.\n\n alt[0] = 'x-grid3-row-alt';\n }\n\n/// [...]\n\n if (!skipStripe) {\n r.className = r.className.replace(this.rowClsRe, ' ');\n if ((i % (stripeInterval * 2)) &gt; (stripeInterval - 1)){\n r.className += ' x-grid3-row-alt';\n/// -^ Same comments apply here, specially about highlighting your changes.\n</code></pre>\n\n<p>You could improve modularity in your version then propose a patch to make upstream easier to work with, so we don't have to suffer the same fate you did ;)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T22:06:33.387", "Id": "343", "Score": "1", "body": "Thanks for the input! I didn't really consider having more than two alternating styles. This is a plugin I created for an intranet app in my company, so it was never meant to be released into the wild actually, that's why it lacks comments, and also indentation seems to be off (only noticed it now). As far as submitting a patch to ExtJS developers goes, I'll wait until there's 4.0 beta release to see how (if) the situation changes there. It's supposed to have more hooks for plugins." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T21:56:15.180", "Id": "212", "ParentId": "174", "Score": "4" } } ]
{ "AcceptedAnswerId": "212", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-23T19:46:34.387", "Id": "174", "Score": "12", "Tags": [ "javascript", "plugin", "ext.js" ], "Title": "ExtJS Grid Plugin" }
174
<p>Here's a class I'm designing:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; namespace Artworking.classes { // A group permission level public class PermissionGroup { public int ID; // Unique ID for this group public bool hasFullControl; // Does this group have complete control public user creator; // Who created this group public string groupName; // Reference name for group // Constructor for when a permission group ID is passed public PermissionGroup(SqlConnection cn, int ID) { using (SqlCommand cmd = new SqlCommand("SELECT creatorUserID, group_name, fullControl FROM tblATPermissionGroups WHERE ID = " + ID, cn)) { SqlDataReader rdr = cmd.ExecuteReader(); if (rdr.Read()) { this.creator.ID = int.Parse(rdr["creatorUserID"].ToString()); this.groupName = rdr["group_name"].ToString(); this.hasFullControl = bool.Parse(rdr["fullControl"].ToString()); } rdr.Close(); } } } } </code></pre> <p>Am I on the right track? Please note I'm not using the built in authentication as it needs to be backwards compatible for an old system. What I'm just checking is that I'm handling these classes properly and loading the data in correctly etc. As I understand it I'm meant to put my SQL commands in the classes and away from the actual pages right?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T21:07:49.150", "Id": "703", "Score": "0", "body": "Comments are not bad, but why not go ahead and use the XML comments (http://msdn.microsoft.com/en-us/magazine/cc302121.aspx) and let them flow back through IntelliSense®?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T22:43:58.500", "Id": "711", "Score": "0", "body": "Thanks LArry, didn't know about XML comments, but for my project it would be overkill :)" } ]
[ { "body": "<p>I know nothing about C#, so this is just a comment based on the design. Is there any reason those members aren't private? Why don't you provide accessors, or (as I've said in many comments on this site already) actually move behavior into this class rather than exposing each individual data member? For example, this is a permission group, have a function called \"isAuthorized\" to which you can pass a command to find out if this group is allowed to do that thing. This way when you move forward, you can make the permissions possibly more fine grained and no one else has to even know that consumes this class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-24T17:24:56.667", "Id": "178", "ParentId": "177", "Score": "0" } }, { "body": "<p>I would agree with Mark: I'd make the members private, and then add property accessors to them. You can then control access if you need to now or in the future.</p>\n\n<p>For example, you might want to make one of the members read-only. Easy to do: implement the get() property but not the set() property.</p>\n\n<p>Similarly, data range checking can easily be added to the set().</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-24T17:53:41.910", "Id": "179", "ParentId": "177", "Score": "0" } }, { "body": "<p>It is generally not a good idea to do this type of processing in the .ctor. Move it to a Load (or some such name) method. This however means your object is not really loaded after instantiated which is another issue. As such, I would recommend separating the entity information (<code>HasFullControl</code>, <code>Creator</code>, <code>GroupName</code>, etc) type from the type that loads the information from the database. You could change <code>PermissionGroup</code> type to just have the data properties and then move the loading logic to a data layer that is responsible for creating the instance a loading the data.</p>\n\n<p>Concatenating text to the end of a sql string leaves you open to <strong>Sql Injection attacks</strong> (though not in this specific case). Use a parameter instead: </p>\n\n<pre><code>using (SqlCommand cmd = new SqlCommand(\"SELECT creatorUserID, group_name, \n fullControl FROM tblATPermissionGroups WHERE ID = @id\", cn))\n{\n cmd.Parameters.AddWithValue(\"@id\", id);\n ...\n}\n</code></pre>\n\n<p>You need to wrap the <code>SqlDataReader</code> in a using block.</p>\n\n<p>Use public readonly properties rather than public fields.</p>\n\n<p>Consider using a <code>IDbConnection</code> rather than <code>SqlConnection</code>. Doing so will allow you to more easily mock the data call when testing this method and makes it easier to support other RDBMS's should the need arise.</p>\n\n<p>Throw helpful exceptions if something goes wrong when populating the data fields.</p>\n\n<p>Follow the <a href=\"http://msdn.microsoft.com/en-us/library/ms229002.aspx\">.Net Framework naming guidelines</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-24T18:19:54.843", "Id": "180", "ParentId": "177", "Score": "11" } }, { "body": "<p>Consider C# accepted practices. As other answers mention, you have member fields marked public. In C#, you typically expose values as properties and keep members private. Starting with C# 3, you do not even need to explicitly create member fields to back your properties unless getters and setters are non-trivial. So consider replacing your fields with </p>\n\n<pre><code>public int ID { get; private set; }\npublic bool HasFullControl { get; private set; }\n</code></pre>\n\n<p>Note that I added <code>private</code> to the setter. This is on the assumption that you do not want code external to your class setting these values, overriding your permissions, as it were. Feel free to remove that modifier if that is not the case. </p>\n\n<p>Note also that C# practices dictate that publicly visible names are Pascal cased instead of your camel casing. Capitalize the first character of your namespace (including nested namespaces), classes, properties, methods, etc.</p>\n\n<p>@akmad has addressed an additional set of concerns, such as the constructor doing expensive work and the vulnerability to SQL injection in a general sense (though not specifically here, as akmad also points out). If you need to do a database call to construct your object, consider a factory approach.</p>\n\n<pre><code>public class PermissionGroup\n{\n private PermissionGroup() { } // class cannot be constructed from outside\n\n public static PermissionGroup GetPermissionGroup(/* your parameters */)\n {\n // build the object starting here!\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-24T18:28:08.747", "Id": "181", "ParentId": "177", "Score": "6" } }, { "body": "<p>I would split up the Read operation to an repository and an domain object that holds the data. I would also send in an unit of work handler into the repository which handles the dbconnection and transaction</p>\n\n<pre><code>public class PermissionGroupRepository\n{\n public PermissionGroupRepository(IUnitOfWork unitOfWork)\n { }\n public PermissionGroup GetPermissionGroup(/* your parameters */)\n { }\n}\n\n\npublic class PermissionGroup\n{\n /* Properties */\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-06T11:27:54.753", "Id": "4614", "ParentId": "177", "Score": "0" } } ]
{ "AcceptedAnswerId": "180", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-24T17:05:50.147", "Id": "177", "Score": "11", "Tags": [ "c#", "sql", "asp.net", "classes" ], "Title": "Simple ASP.NET C# class design" }
177
<p>In <a href="https://codereview.stackexchange.com/questions/9/how-to-improve-very-loopy-method">this question</a> I answered with this Linq. While it does what I was looking for, I am not sure how easy the linq queries are for others to follow. So I am looking for feedback on formating, what comments would be helpful and other alternative approaches to moving through the children records.</p> <pre><code> private void UpdateGridFromSourceHierarchy(int depth, IEnumerable&lt;SourceFile&gt; list) { //Get the initial set of sourcefiles var sourceFiles = list .SelectMany(current =&gt; current.getInvocations() .Select(invocation =&gt; new {current = (SourceFile) null, invocation})) .ToList() //This ensures that getInvocations is only called once for each sourcefile .GroupBy(x =&gt; x.current, x =&gt; x.invocation); for (var currentDepth = 0; currentDepth &lt;= depth; currentDepth++) { foreach (var currentGroup in sourceFiles) { int sourceFileCount = currentGroup.Count(); int counter = 0; foreach (var invocation in currentGroup) { /* * Generalized grid code goes here * In my code it was a call to: * UpdateGridPosition(currentGroup,invocation,counter); */ counter++; } } //Select the current sub source files sourceFiles = sourceFiles.SelectMany(current =&gt; current.Select(invocation =&gt; invocation)) //Get all of the invocations paired with the new current level of source files .SelectMany(newCurrent =&gt; newCurrent.getInvocations() .Select(invocation =&gt; new { newCurrent, invocation })) //Group them so that we can loop through each set of invocations seperately .ToList().GroupBy(x =&gt; x.newCurrent, x =&gt; x.invocation); } } </code></pre>
[]
[ { "body": "<p><strong>No</strong></p>\n\n<p>Your code looks pretty messy and that last linq statement is just a killer. To top it off the triple-nested foreach statement looks like serious code smell. I'd suggest breaking your code up into smaller methods that each do one thing which might reduce the perceived complexity of it</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T11:08:50.977", "Id": "296", "Score": "0", "body": "You could use a refactoring tool like Resharper to make this code more readable." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T11:12:11.333", "Id": "297", "Score": "3", "body": "could you give me alternatives for the first and last linq statements, preferably in code? Just saying it is messy doesn't help much, it was the whole reason I asked the question. They are both basically the same statement, it is just that in the question above a reference to the previous current level of the tree needed to be maintained." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T13:02:03.813", "Id": "301", "Score": "1", "body": "+1 to cancel out an unjustified -1. @Sean: Why is answering the question you explicitly asked unhelpful? He has no obligations to rewrite your Linq queries for you. This is Code Review, not Code Write It For Me." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T13:05:30.013", "Id": "302", "Score": "0", "body": "@Aim Kai resharper doesn't really have much to say about the code." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T13:09:06.047", "Id": "303", "Score": "2", "body": "@Jonathan Your right, rereading my question I had not explicitly stated that I knew the last linq statement was a messy. However I think the somewhat copy and past answer of break it into smaller methods without even a links to examples what you are suggesting just adds clutter." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T07:00:17.120", "Id": "194", "ParentId": "182", "Score": "4" } }, { "body": "<p>I decided to work a bit on the second LINQ query and here is what I came up with:</p>\n\n<pre><code> //Select the current sub source files \n sourceFiles = GetNextSourceFileLevel(sourceFiles);\n }\n }\n\n private IEnumerable&lt;IGrouping&lt;SourceFile, SourceFile&gt;&gt; GetNextSourceFileLevel(IEnumerable&lt;IGrouping&lt;SourceFile, SourceFile&gt;&gt; sourceFiles)\n {\n var previousLevelOfSourceFiles = sourceFiles.SelectMany(current =&gt; current.Select(invocation =&gt; invocation));\n\n var previousLevelOfSourceFilesWithInvocations = previousLevelOfSourceFiles\n .SelectMany(newCurrent =&gt; newCurrent.getInvocations()\n .Select(invocation =&gt;new {newCurrent, invocation}));\n var listOfSourceFiles = previousLevelOfSourceFilesWithInvocations.ToList();\n\n return listOfSourceFiles.GroupBy(x =&gt; x.newCurrent, x =&gt; x.invocation);\n }\n</code></pre>\n\n<p>I thought about making each loop in the method into its own method, and broke it up into smaller steps, I could have gone farther but did not want to have to create the annonymous class I was using.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T13:24:03.787", "Id": "198", "ParentId": "182", "Score": "1" } }, { "body": "<p>I also decided to try spliting breaking the triple loop as mko into smaller methods, each is needed since i want to go down the hierachy x number of times, loop through the parents and update the grid based on the children so here is what I came up with. I am not sure it made it better though.</p>\n\n<pre><code> private void UpdateGridFromSourceHierarchy(int depth, IEnumerable&lt;SourceFile&gt; list)\n {\n //Get the initial set of sourcefiles \n var sourceFiles = list.SelectMany(current =&gt; current.getInvocations() \n .Select(invocation =&gt; new {current = (SourceFile) null, invocation})) \n .ToList() //This ensures that getInvocations is only called once for each sourcefile \n .GroupBy(x =&gt; x.current, x =&gt; x.invocation); \n for (var currentDepth = 0; currentDepth &lt;= depth; currentDepth++)\n {\n LookThroughParentSourceFilesToUpdateGrid(sourceFiles);\n //Select the current sub source files \n sourceFiles = GetNextSourceFileLevel(sourceFiles);\n }\n }\n\n private void LookThroughParentSourceFilesToUpdateGrid(IEnumerable&lt;IGrouping&lt;SourceFile, SourceFile&gt;&gt; sourceFiles)\n {\n foreach (var currentGroup in sourceFiles)\n {\n currentGroup.Count(); \n LoopThroughSourceFilesToUpdateGrid(currentGroup);\n }\n }\n\n private void LoopThroughSourceFilesToUpdateGrid(IGrouping&lt;SourceFile, SourceFile&gt; currentGroup)\n {\n int counter = 0;\n foreach (var invocation in currentGroup)\n {\n /* \n * * Generalized grid code goes here\n * */ \n counter++;\n UpdateGridPosition(currentGroup,invocation,counter);\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T13:37:23.807", "Id": "199", "ParentId": "182", "Score": "4" } }, { "body": "<p>This looks really weird:</p>\n\n<pre><code> var sourceFiles = list\n .SelectMany(current =&gt; current.getInvocations()\n .Select(invocation =&gt; new {current = (SourceFile) null, invocation}))\n .ToList() //This ensures that getInvocations is only called once for each sourcefile\n .GroupBy(x =&gt; x.current, x =&gt; x.invocation);\n</code></pre>\n\n<p>Why do you need to create a property <code>current</code> with null value and then group by it? Am I missing something?</p>\n\n<p>Also if you do not use <code>current</code> variable from <code>SelectMany</code> lambda in <code>Select</code> statement then I think it is better to reduce nesting and pull <code>Select</code> out from <code>SelectMany</code>:</p>\n\n<pre><code> var sourceFiles = list\n .SelectMany(current =&gt; current.getInvocations())\n .Select(invocation =&gt; new {current = (SourceFile) null, invocation})\n .ToList() //This ensures that getInvocations is only called once for each sourcefile\n .GroupBy(x =&gt; x.current, x =&gt; x.invocation);\n</code></pre>\n\n<p>Your code looks wrong to me (regarding grouping by null value). And if it wrong how can we improve it's readability?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T14:55:10.380", "Id": "439", "Score": "0", "body": "I did it so that the type would be the same as the type returned from LINQ statement at the bottom." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T15:13:01.307", "Id": "443", "Score": "0", "body": "@Sean - does `getInvocations()` return `IEnumerable<SourceFile>`?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T15:29:34.937", "Id": "448", "Score": "0", "body": "Yes. But I don't know what the real implementation of it is, since it is an implementation detail not given in http://codereview.stackexchange.com/questions/9/how-to-improve-very-loopy-method." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T14:15:31.787", "Id": "274", "ParentId": "182", "Score": "3" } }, { "body": "<p>Leaving aside the problem of deeply nested code for now, I think readability is greatly improved by the use of LINQ syntax:</p>\n\n<pre><code>var sourceFiles = from file in list\n from invocation in file.getInvocations()\n group invocation by (SourceFile)null into groupedByInvoker\n select groupedByInvoker;\n\nfor (var currentDepth = 0; currentDepth &lt; depth; currentDepth++)\n{\n foreach (var invokerGroup in sourceFiles)\n {\n int sourceFileCount = currentGroup.Count();\n int counter = 0;\n\n foreach (var invocation in invokerGroup) {\n // Do stuff\n counter++;\n }\n }\n\n sourceFiles = from invokerGroup in sourceFiles\n from file in invokerGroup\n from invocation in file.getInvocations()\n group invocation by file into groupedByInvoker\n select groupedByInvoker;\n}\n</code></pre>\n\n<p>For me, this makes the SelectMany a lot easier to follow. There are some other tweaks to the queries too:</p>\n\n<ul>\n<li>You can just group by null directly, rather than projecting to an anonymous type and selecting that back out as the key.</li>\n<li>You don't need to convert to a list if you follow it by a groupby. The groupby traverses and stores the result of the enumerable anyway. You can test this by removing the ToList and adding a break point/debug output inside getInvocations.</li>\n<li>By forcing it to evaluate to to a list instead of allowing deferred execution you are actually calling getInvocation too many times. When <code>currentDepth == depth - 1</code>, you don't need to evaluate sourceFiles again and so you don't need to call getInvocations. With deferred execution, because the final sourceFiles is never read getInvocations is never called and everything is fine and dandy.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:30:33.523", "Id": "521", "Score": "0", "body": "Your right that is much cleaner." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:14:56.843", "Id": "329", "ParentId": "182", "Score": "8" } } ]
{ "AcceptedAnswerId": "329", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-24T18:28:37.577", "Id": "182", "Score": "9", "Tags": [ "c#", "linq" ], "Title": "Update grid from source hierarchy" }
182
<p>This is performance critical. I measured and determined that using the <code>sqrt</code> is faster then using the <code>cos</code> method.</p> <p>I am aware that this code only works for some points, so that is not an issue.</p> <p><code>Point</code> is <code>System.Drawing.Point</code>. <code>_offset</code> is also of type <code>Point</code>.</p> <p>I assumed, and the profiler seemed to confirm, that the <code>try</code>/<code>catch</code> will not slow down the code unless an exception occurs. Please correct me if that is wrong.</p> <pre><code>/// &lt;summary&gt; /// Convert from polar coordinates to rectangular coordinates. /// Only works for points to the left of the origin. /// &lt;/summary&gt; /// &lt;param name="radius"&gt;The radius of the point in pixels.&lt;/param&gt; /// &lt;param name="theta"&gt;The angle of the point in radians.&lt;/param&gt; /// &lt;returns&gt;The point in rectangular coordinates.&lt;/returns&gt; internal Point PolarToRectangular( double radius, double theta) { try { double sin = Math.Sin(theta); // This is faster then: // double cos = Math.Cos(theta); double cos = -Math.Sqrt(1 - (sin * sin)); Int32 x = _offset.X + (Int32)Math.Round(radius * cos); Int32 y = _offset.Y + (Int32)Math.Round(radius * sin); return new Point(x, y); } catch (OverflowException ex) { ex.Data.Add("Screen polar Radius", radius); ex.Data.Add("Screen polar Theta", theta); throw; } } </code></pre>
[]
[ { "body": "<p>Yes I think that is going to be pretty quick. It might be tempting to move the cos calc so that it does a full Pythagoras with the radius. This will save an assignment, but I thi it requires an additional multiplication (1*1 being known already in your current version).</p>\n\n<p>As a matter of personal style (possible because I code in multiple languages) but I would use different names for your sin and cos variables. most languages would not accept this, and it would, personally, have the potential to confuse me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-24T19:46:04.313", "Id": "184", "ParentId": "183", "Score": "13" } }, { "body": "<p>I would consider using a lookup table to find your sines. How precise an angle are you calculating for? <a href=\"https://stackoverflow.com/questions/1382322/calculating-vs-lookup-tables-for-sine-value-performance/1382380#1382380\">This answer on stackoverflow</a> has some interesting information on how to construct one and the benchmarks for using it to two decimal points. If you are using the full precision of a double, then your current method will be faster, but if you have a fixed precision, a lookup table will be benificial.</p>\n\n<p>As long as the exception IS exceptional (and it looks to me like it is) it will add very little overhead to your run times. See: <a href=\"https://stackoverflow.com/q/52312/487663\">https://stackoverflow.com/q/52312/487663</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T03:12:37.303", "Id": "193", "ParentId": "183", "Score": "17" } }, { "body": "<p>As a completely untested micro-optimisation, I would suspect <code>(Int32)(radius * cosTheta + 0.5)</code> is going to be marginally quicker than <code>(Int32)Math.Round(radius * cosTheta)</code>. It does, however, round up on 0.5 instead of rounding down, which may not be what you want.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T19:53:05.457", "Id": "321", "ParentId": "183", "Score": "3" } } ]
{ "AcceptedAnswerId": "184", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-24T19:36:29.233", "Id": "183", "Score": "21", "Tags": [ "c#", "performance", "converting", "coordinate-system" ], "Title": "Converting from polar coordinates to rectangular coordinates" }
183
<p>I am unsure if my use of <code>Monitor.Wait</code> and <code>Monitor.Pulse</code> is correct. It seems to work alright, but there is a nagging doubt I am doing something wrong.</p> <p>Am I dealing with a timeout OK, or is there a better way to do it?</p> <p>All examples I have seen use <code>Monitor.Wait</code> with a <code>while</code> loop, and not with an <code>if</code> to re-check the blocking condition after <code>Pulse</code>, but I need to determine if a timeout occurred.</p> <p><code>_cmdDispatcher.EnqueueCommand(cmd)</code> sends a command to the device, and it responds with an event that executes the <code>CommResponseReceived</code> method on another thread.</p> <pre><code>private readonly object _connectLock = new object(); public bool Connect() { if (this._connected) throw new InvalidOperationException("Plc is already connected."); ICommand cmd = new Command(MessageIdentifier.Name); try { if (this._channel.Open() &amp;&amp; !this._connected) { // Wait for communications to be fully established or timeout before continuing. lock (this._connectLock) { this._cmdDispatcher.EnqueueCommand(cmd); if (!this._connectSignal) { if (Monitor.Wait(this._connectLock, this._timeout)) { this._connected = true; this._connectSignal = false; Debug.WriteLine("Connection succeeded."); } else { //TODO Log timeout. Debug.WriteLine("Connection timed out."); } } } if (this._connected) this.OnConnectionChangedEvent(ConnectionStatus.Connected); } } catch (Exception ex) { //TODO Log errors. Debug.WriteLine("Connection failed."); } return this._connected; } </code></pre> <p>Executed in another thread when the device responds:</p> <pre><code>private void CommResponseReceived(object sender, CommsResponseEventArgs e) { // // Signal that communications are successfully established. lock (this._connectLock) { this._connectSignal = true; Monitor.Pulse(this._connectLock); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:04:09.687", "Id": "382", "Score": "1", "body": "Just skimmed your question, but thought you might be interested in http://www.albahari.com/threading/part4.aspx#_WaitPulseVsWaitHandles. Joe Albahari is the creator of LINQPad and co-author of C# In A Nutshell. Basically, he's a genius." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:17:57.020", "Id": "385", "Score": "0", "body": "@Pat: I have indeed seen that site, and it is excellent. With regard to a Monitor.Wait with timeout, it only lightly touches on that subject and doesn't have an example. Otherwise it is a great resource." } ]
[ { "body": "<p>I believe you are using them correctly as-is, but if I was working on your team, I would deny you a commit on basic principal:</p>\n\n<p><code>Monitor.Wait</code> and <code>Monitor.Pulse</code> are amazingly low-level constructs with very difficult semantics to try to figure out after you've written them. Assuming this is used in a large application, I'm going to have to search for every possible reference to the object contained by <code>_connectLock</code> and see how its used, just to make sure that the only thing that <code>Pulse</code>s it is the connection code.</p>\n\n<p>It doesn't look like you're doing anything here that you couldn't just use <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent%28v=VS.80%29.aspx\" rel=\"nofollow\"><code>System.Threading.ManualResetEvent</code></a> for instead, which has a much simpler API for your application's future maintenance developers to figure out.</p>\n\n<hr>\n\n<p>P.S. Remember that your application's future maintenance developer might be you. Also remember that in the future you will be older, and thus crankier and more forgetful than you are now.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T09:16:51.337", "Id": "657", "Score": "0", "body": "@Alex: My team consists of just me, and I'm already at the older and crankier stage :) Seriously though, thanks for the answer. Good suggestion about the ManualResetEvent and I will consider that. However, wouldn't you still have to search for every reference that calls .Set, in the same way you would search for .Pulse?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T09:33:04.297", "Id": "658", "Score": "0", "body": "Still have to search, yes--but, in my experience, MRE's tend to exude a better sense of single-use-only-ness (in your example, the MRE would only be used to signal connectedness, nothing else). Objects seem to creep in and gather extra uses: maybe you'll add another flag called _disconnectSignal, and rather than adding a second object to Pulse/Wait on, you could just use the one thats already there..." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T23:39:20.880", "Id": "982", "Score": "0", "body": "@Alex: there are situations for both or only one would exist so I'm hoping that's not a blank-check commit-denial. It's just an assumption, but the \"_\" in \"_connectLock\" makes me think it's a private field so you would only have to search the one class. If people are just grabbing up existing sync objects just because they need one it sounds to me like you've got a different problem entirely. It's rare (in my experience) that an instance of System.Object finds other uses or reason to later be publicly exposed." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-03T08:16:45.553", "Id": "1002", "Score": "0", "body": "@TheXenocide: _connectLock is indeed a private class member." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-13T09:55:26.867", "Id": "1397", "Score": "0", "body": "@TheXenocide: I don't believe in a blank-check commit-denial, only gut reaction ones: if I see something I disagree with, I always reject. If the coder can back up his choice with a sound argument that their way has an advantage that I have overlooked, then I'm perfectly willing to green light. That said, I have found very few legitimate cases where Monitor.Pulse would provide a clear-cut advantage over MRE's." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-16T15:32:37.530", "Id": "1496", "Score": "0", "body": "@Alex: So long as there's room to refute sounds fine by me :) The situations where Pulse is *necessary* over MREs are rare but do exist, though I agree that they tend to be more simple." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-29T07:54:04.583", "Id": "410", "ParentId": "185", "Score": "6" } }, { "body": "<p>I agree with Alex that <code>ManualResetEvent</code> may be a little cleaner simply because you don't need to perform manual signal tracking to ensure you don't wait due to the <code>Monitor</code> already pulsing but, as I understand it, <code>WaitHandle</code> (used by <code>ManualResetEvent</code>) has more overhead. It's also quite possible to use memory barriers and <code>Application.DoEvents</code>/<code>Thread.Sleep</code> in a time-limited loop to achieve a lockless solution, but none of this matters unless you have very strict resource/performance concerns. </p>\n\n<p>Regardless, there's always more than one way to skin a cat and your usage is indeed safe and correct.</p>\n\n<p>If the <code>Connect</code> method is running on your UI thread be sure your timeout isn't really long or windows may think your application is not responding because blocking in <code>Monitor.Wait</code> does not resume the window's message pumping; if you need a long timeout or it is not running on the UI thread you will need to ensure the <code>Connect</code> method cannot be called again before the last has finished (if <code>this._channel.Open()</code> returns <code>false</code> if it is already open that should suffice). In the case of it being on the UI thread, besides preventing double execution, you would want to switch to a small timeout in a time-limited loop that calls <code>Application.DoEvents()</code>. You may already be aware of these concerns but I'm having to make a lot of assumptions to review the code. While I'm at it, it's probably trivial, but you can also move you <code>Command</code> instantiation to just before the lock to save yourself unnecessary instance creation in some cases.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-03T08:17:00.717", "Id": "1003", "Score": "0", "body": "Your asumptions are pretty much spot on. The code is not running on the UI thread, so those concerns are not applicable here. Good call with regard to the Command instantiation. Thank you for taking a look." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-02T23:32:08.783", "Id": "575", "ParentId": "185", "Score": "8" } }, { "body": "<p>I'd just add on more thing on top of the input provided by Alex and TheXenocide.</p>\n\n<p>You're relying quite a lot on the <code>this._connected</code> state. It's probably a shared state within that class so could change mid-way if several threads are trying to open the connection at once. Thus, I'd use something like <code>Thread.VolatileRead</code>, <code>Thread.VolatileWrite</code> outside the critical section.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-15T14:49:59.500", "Id": "7840", "ParentId": "185", "Score": "4" } } ]
{ "AcceptedAnswerId": "575", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-24T20:58:58.610", "Id": "185", "Score": "21", "Tags": [ "c#", ".net", "winforms", "synchronization", "timeout" ], "Title": "Determining if a connection has been made to a communications device" }
185
<p>Imagine that I need a color palette for my Winforms application to have a consistent look.</p> <p>What I did was create a static helper class and helper methods that I can call from anywhere in my code, and invoke what I need from the <code>App.settings</code> file.</p> <p>Here for example, I am getting the school name from the <code>App.config</code> file, so I can sell this application to other schools with minimal changes on my part.</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;appSettings&gt; &lt;add key="schoolName" value="Uboldi"/&gt; &lt;/appSettings&gt; &lt;/configuration&gt; </code></pre> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; namespace Uboldi.Helpers { public static class CustomizationHelper { public static string GetSchoolName() { return ConfigurationManager.AppSettings["schoolName"]; } } } </code></pre> <p>Usage:</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Uboldi.Helpers; namespace Uboldi { public partial class MainForm : Form { public MainForm() { InitializeComponent(); LoadFormTitle(); } private void LoadFormTitle() { var schoolName = CustomizationHelper.GetSchoolName(); this.Text = String.Format("Sistema {0} - Pagina Principal", schoolName); } } } </code></pre> <p>Are there any glaring mistakes I'm making by choosing this type of architecture?</p>
[]
[ { "body": "<p>The presented code seems okay, there aren't any obvious problems with it. <code>CustomizationHelper</code> could probably use a better name though to indicate what's being customized. If this is part of a larger project, putting a comment to indicate which classes are suppose to use <code>CustomizationHelper</code> would be a good idea.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-24T23:46:12.303", "Id": "189", "ParentId": "186", "Score": "2" } }, { "body": "<p>I think that'd be fine. Another option would be to create a second constructor for the form and pass the title in:</p>\n\n<pre><code>public class MainForm : Form\n{\n public MainForm()\n {\n InitializeComponent();\n }\n\n public MainForm(string schoolName) : this()\n {\n this.Text = String.Format(\"Sistema {0} - Pagina Principal\", schoolName);\n }\n}\n</code></pre>\n\n<p>This may be just personal preference, though.</p>\n\n<p>You could also further extract the hardcoded form title into a config or resource file and instantiate the form like this instead:</p>\n\n<pre><code>var titleFormat = ...; // retrieve format from some place\nvar schoolName = CustomizationHelper.GetSchoolName();\nvar form = new MainForm() { Text = string.Format(titleFormat, schoolName) };\n</code></pre>\n\n<p>The payoff from doing that would depend on how likely it is that it'll change in the future or whether or not you're planning to translate the application into other languages.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T00:26:28.480", "Id": "191", "ParentId": "186", "Score": "9" } }, { "body": "<p>Is the purpose of CustomizationHelper just to abstract away the ConfigurationManager/AppConfig stuff? Because otherwise I'd just stick with the straight ConfigurationManager call. </p>\n\n<p>The less hoops required to understand what's going on, the better in my book. Unless you see the need to someday get SchoolName from another source (like say a Database).</p>\n\n<p>In any event the class name could probably be improved, maybe something like \"SchoolConfiguration\" and have a \"Name\" property or \"GetName()\" method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T01:12:56.610", "Id": "192", "ParentId": "186", "Score": "8" } }, { "body": "<p>Personally I would have made them static properties rather than static methods. Just seems more natural with C#. But the concept of having a static helper class to retrieve configuration values is a sound one. It becomes even more useful when you are retrieving non-string types since you can abstract away the casting to the helper class.</p>\n\n<p>Just one comment - how about some error handling in the helper class to ensure that the configuration values are actually there?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T22:19:12.893", "Id": "229", "ParentId": "186", "Score": "3" } }, { "body": "<p>While somewhat of a tangent from your question but you may find it helpful nonetheless.</p>\n\n<p>I would recommend looking at a custom <a href=\"http://msdn.microsoft.com/en-us/library/2tw134k3.aspx\">ConfigurationSection</a> which allows you to define more complex configuration hierarchies that are strongly-typed. I find it much easier to use a custom configuration section than having to remember a bunch of magic strings in the appSettings element and also allows you to specific which values are required, what the defaults values are, etc. </p>\n\n<p>Using a custom configuration section you could create a configuration type like:</p>\n\n<pre><code>public class UboldiConfigurationSection : System.Configuration.ConfigurationSection {\n [ConfigurationProperty(\"schoolName\")]\n public string SchoolName {\n get { return (string)this[\"schoolName\"]; }\n set { this[\"schoolName\"] = value; }\n }\n}\n</code></pre>\n\n<p>Then to load that configuration type:</p>\n\n<pre><code>public static class UboldiApplication {\n public static UboldiConfigurationSection Config { get; internal set; }\n\n public static void Initialize() {\n Config = ConfigurationManager.GetSection(\"uboldi\") as UboldiConfigurationSection;\n }\n}\n</code></pre>\n\n<p>The app.config then would look something like this:</p>\n\n<pre><code>&lt;configuration&gt;\n &lt;configSections&gt;\n &lt;section name=\"uboldi\" type=\"Uboldi.UboldiConfigurationSection, Uboldi\" /&gt;\n &lt;/configSections&gt;\n &lt;uboldi schoolName=\"Fillmore Central\" /&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>Lastly, you use the configuration by:</p>\n\n<pre><code>public void Test() { \n //This only needs to be done once, presumably in your Program.Main method\n UboldiApplication.Initialize();\n\n var name = UboldiApplication.Config.SchoolName;\n}\n</code></pre>\n\n<p>A couple of notes:</p>\n\n<ol>\n<li>You'll need to reference the System.Configuration assembly as it's not usually referenced in VS by default.</li>\n<li>The <code>ConfigurationManager.GetSection(\"uboldi\")</code> is expecting the name of the section in the app.config file. You'll note that this matches in the example above.</li>\n<li>The section element in the app.config file uses the standard .Net type name convention to locate the specified configuration section. In this example I am assuming that the <code>UboldiConfigurationSection</code> type is the Uboldi namespace and in an Uboldi assembly (dll or exe).</li>\n<li>You can add hierarchy by creating <code>ConfigurationElement</code> sub classes and using them as properties in your configuration section and elements.</li>\n<li>The link above is for a Web.config, but the same thing is possible in an app.config file.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-26T22:46:13.177", "Id": "237", "ParentId": "186", "Score": "43" } }, { "body": "<p>I second the config section. It has the advantage to set a setting as required, throwing an exception at the GetSection call, instead of passing a null value with AppSettings[nonexistingKey] </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T22:59:46.213", "Id": "240", "ParentId": "186", "Score": "1" } }, { "body": "<p>A few thoughts:</p>\n\n<ul>\n<li>The name \"CustomizationHelper\" is not very specific. How about CustomerBrandingService? Even though it \"just\" fetches data from a config file, that may not always be the case, and it is still an application service. (Naming classes with \"Helper\" is similar to naming with \"Manager\" - see reference on that below.)</li>\n</ul>\n\n<p>Also, while your question is reasonable and simple, it is not clear to me what decisions you will make from this. For example, if this is the basis for a whole app, I suggest some other options to consider:</p>\n\n<ul>\n<li><p>Why are you building a WinForm app in 2011? Consider WPF or Silverlight (possibly Silverlight Out-of-Browser \"SLOOB\").</p></li>\n<li><p>If you choose WPF or Silverlight, the title would be assigned most naturally using Data Binding through the Model-View-ViewModel pattern.</p></li>\n</ul>\n\n<p>Pointers for more information:</p>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1866794/naming-classes-how-to-avoid-calling-everything-a-whatevermanager\" title=\"How to avoid calling every class a Manager class\">How to avoid calling every class a \"Manager\" class</a></p></li>\n<li><p><a href=\"http://msdn.microsoft.com/en-us/library/ms752347.aspx\" rel=\"nofollow noreferrer\" title=\"Data Binding in WPF\">Data Binding with WPF</a> (Silverlight is very similar)</p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/1405739/mvvm-tutorial-from-start-to-finish\" title=\"MVVM Tutorials\">The Model-View-ViewModel Design Pattern for WPF and Silverlight</a></p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:40:07.913", "Id": "245", "ParentId": "186", "Score": "2" } }, { "body": "<p>I think the appSettings section is a pretty neat solution for something as simple as your example, and I use this frequently over creating config sections, when no hierarchy is required. I do however find the following pattern useful to add consistency to the way appSettings are used, adding some typing, building in the idea of whether the setting is expected to be found in the .config file, and providing the ability to specify a default value.</p>\n\n<pre><code>public static class AppSettingsHelper\n{\n private static TReturnType LoadAppSetting&lt;TReturnType&gt;(string name, bool required, TReturnType defaultValue)\n {\n // Check for missing settings\n if (!ArrayExt.Contains&lt;string&gt;(ConfigurationManager.AppSettings.AllKeys, name))\n {\n if (required)\n throw new ConfigurationErrorsException(string.Format(\"Required setting missing: {0}\", name));\n else\n return defaultValue;\n }\n\n // Read the setting and return it\n AppSettingsReader reader = new AppSettingsReader();\n return (TReturnType)reader.GetValue(name, typeof(TReturnType));\n }\n\n //example boolean property\n public static bool IsSomethingSet\n {\n get\n {\n return ApplicationSettingsHelper.LoadAppSetting&lt;bool&gt;(\n \"settingName\",\n true,\n false);\n }\n }\n\n //int property\n public static int SomeCount\n {\n get\n {\n return ApplicationSettingsHelper.LoadAppSetting&lt;int&gt;(\n \"someCount\",\n true,\n 0);\n }\n }\n}\n</code></pre>\n\n<p>Use like this:</p>\n\n<pre><code>if (AppSettingsHelper.IsSomethingSet)\n{\n Console.WriteLine(AppSettingsHelper.SomeCount);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T17:15:12.503", "Id": "380", "ParentId": "186", "Score": "1" } } ]
{ "AcceptedAnswerId": "237", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-24T21:58:21.663", "Id": "186", "Score": "75", "Tags": [ "c#", "winforms", "configuration" ], "Title": "Getting/setting default values from my App.config" }
186
<p>I'm learning Django as I go. I know this model is missing user authentication, registration, comments/comment threading, and voting. But this is my starting code for my model. What are some of the things I can improve on, modify, rewrite, etc?</p> <pre><code>from django.contrib.auth.models import User from django.db import models from django.contrib import admin from django.template.defaultfilters import escape from django.utils.translation import ugettext as _ from django.utils.encoding import force_unicode from django.http import HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse class DateTime(models.Model): datetime = models.DateTimeField(auto_now_add=True) def __unicode__(self): return unicode(self.datetime.strftime("%b %d, %Y, %I:%M %p")) class Country(models.Model): country = models.CharField(max_length=50) def __unicode__(self): return unicode(self.country) class Artist(models.Model): artist = models.CharField(max_length=50) country = models.ForeignKey(Country, blank=True, null=True) user = models.ForeignKey(User, blank=True, null=True) created = models.ForeignKey(DateTime) notes = models.TextField() def __unicode__(self): return artist class Song(models.Model): name = models.CharField(max_length=200) artist = models.ForeignKey(Artist, blank=True, null=True) # language = models.ForeignKey(Country, blank=True, null=True) user = models.ForeignKey(User, blank=True, null=True) created = models.ForeignKey(DateTime) notes = models.TextField() def __unicode__(self): return song class FileType(models.Model): file_type = models.CharField(max_length=3) description = models.TextField() user = models.ForeignKey(User, blank=True, null=True) created = models.ForeignKey(DateTime) notes = models.TextField() def __unicode__(self): return file_type class Level(models.Model): level = models.CharField(max_length=3) description = models.TextField() user = models.ForeignKey(User, blank=True, null=True) created = models.ForeignKey(DateTime) notes = models.TextField() def __unicode__(self): return level class MusicSheet(models.Model): version = models.CharField(max_length=2) song = models.ForeignKey(Song, blank=True, null=True) artist = models.ForeignKey(Artist, blank=True, null=True) file_type = models.ForeignKey(FileType, blank=True, null=True) level = models.ForeignKey(Level, blank=True, null=True) user = models.ForeignKey(User, blank=True, null=True) created = models.ForeignKey(DateTime) text = models.TextField() notes = models.TextField() #include votes #include comments #include registration code ######################################################################################################################## ######################################## ADMIN STUFF ################################################################### ######################################################################################################################## class MusicSheetAdmin(admin.ModelAdmin): list_display = ["version", "song", "artist", "file_type", "level", "user" , "created", "text", "notes"] search_fields = ["version"] class MusicSheetInline(admin.TabularInline): model = MusicSheet class DateAdmin(admin.ModelAdmin): list_display = ["datetime"] inlines = [MusicSheetInline] def response_add(self, request, obj, post_url_continue='../%s/'): """ Determines the HttpResponse for the add_view stage. """ opts = obj._meta pk_value = obj._get_pk_val() msg = "Song(s) were added successfully." # Here, we distinguish between different save types by checking for # the presence of keys in request.POST. if request.POST.has_key("_continue"): self.message_user(request, msg + ' ' + _("You may edit it again below.")) if request.POST.has_key("_popup"): post_url_continue += "?_popup=1" return HttpResponseRedirect(post_url_continue % pk_value) if request.POST.has_key("_popup"): return HttpResponse( '&lt;script type="text/javascript"&gt;opener.dismissAddAnotherPopup(window, "%s", "%s");' '&lt;/script&gt;' % (escape(pk_value), escape(obj))) elif request.POST.has_key("_addanother"): self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name))) return HttpResponseRedirect(request.path) else: self.message_user(request, msg) for music_sheet in MusicSheet.objects.filter(created=obj): if not music_sheet.user: music_sheet.user = request.user music_sheet.save() return HttpResponseRedirect(reverse("admin:musicsheet_musicsheet_changelist")) class CountryAdmin(admin.ModelAdmin): list_display = ["country"] search_fields = ["country"] class CountryInline(admin.TabularInline): model = MusicSheet class SongAdmin(admin.ModelAdmin): list_display = ["name", "artist", "user", "created", "notes"] search_fields = ["name", "artist"] class SongInline(admin.TabularInline): model = MusicSheet class ArtistAdmin(admin.ModelAdmin): list_display = ["artist", "country", "user", "created", "notes"] search_fields = ["artist", "country"] class ArtistInline(admin.TabularInline): model = MusicSheet class FileTypeAdmin(admin.ModelAdmin): list_display = ["file_type", "description", "user", "created", "notes"] search_fields = ["file_type"] class FileTypeInline(admin.StackedInline): model = MusicSheet class LevelAdmin(admin.ModelAdmin): list_display = ["level", "description", "user", "created", "notes"] search_fields = ["level"] class LevelInline(admin.StackedInline): model = MusicSheet admin.site.register(MusicSheet, MusicSheetAdmin) admin.site.register(Country, CountryAdmin) admin.site.register(Song, SongAdmin) admin.site.register(Artist, ArtistAdmin) admin.site.register(FileType, FileTypeAdmin) admin.site.register(Level, LevelAdmin) admin.site.register(DateTime, DateAdmin) </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-24T23:16:06.700", "Id": "288", "Score": "1", "body": "I suggest you highlight places you want feedback on. Other than that, sorting imports and (maybe) field names will make your life easier on the long run." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T12:23:11.740", "Id": "298", "Score": "0", "body": "@TryPyPY - Mostly around the model itself, structure of the classes, how can I make it more efficient? increasingly better? How can I take this code from newb to pro" } ]
[ { "body": "<p>Disclaimer: I'm not a Django guru. Here are my thoughts, for what it's worth.</p>\n\n<ul>\n<li><p><strong>Common fields</strong>: <code>user</code>, <code>created</code>, and <code>nodes</code> occur in almost every class. I'd consider creating an <a href=\"http://docs.djangoproject.com/en/dev/topics/db/models/#abstract-base-classes\">abstract base class</a> with these three fields.</p></li>\n<li><p><strong>Field names</strong>: for the sake of readability, I'd change <code>Artist.artist</code> to <code>Artist.name</code>, and <code>*.user</code> to <code>*.creator</code>.</p></li>\n<li><p><strong>File extensions</strong>: occasionally have more than 3 chars (e.g.: <code>.jpeg</code>, <code>.java</code>).</p></li>\n<li><p><strong>Indexing</strong>: I'd add <code>db_index=True</code> to the <code>name</code> fields, for the very least.</p></li>\n<li><p><strong>Redundancy</strong>: since you have <code>MusicSheet.song</code> and <code>Song.artist</code>, you no longer need <code>MusicSheet.artist</code>. It's called <a href=\"http://en.wikipedia.org/wiki/Data_redundancy\">redundancy</a> and it's generally a bad thing.</p></li>\n<li><p><strong>Primary keys, unique constraints</strong>: you probably don't want two <code>FileType</code>s with the same <code>file_type</code>, so that field is a good candidate for <a href=\"http://en.wikipedia.org/wiki/Primary_key\">primary key</a> (<code>primary_key=True</code>). I'm not sure what <code>Level</code> is supposed to model, but my guess is that its <code>level</code> is a good candidate for primary key as well. Add <code>unique=True</code> for <code>Country.country</code>, or add a primary key with <a href=\"http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2\">country code</a>.</p></li>\n<li><p><strong>DateTime</strong>: I don't see a need for this class. Simply replace every occurrence of: <code>created = models.ForeignKey(DateTime)</code> with <code>models.DateTimeField(auto_now_add=True)</code>.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T10:00:20.167", "Id": "196", "ParentId": "187", "Score": "18" } }, { "body": "<p>A few things come to mind:</p>\n\n<ul>\n<li>Lose the DateTime model and instead add a DateTimeField directly to the models that need it. The ForeignKey buys you nothing except incuring an additional database join for even the simplest of operations.</li>\n<li>You probably did this only so you could paste this code in one piece, but if not: You should put your admin code in a file called admin.py inside your application. That way you can use the <a href=\"http://docs.djangoproject.com/en/dev/ref/contrib/admin/#hooking-adminsite-instances-into-your-urlconf\" rel=\"noreferrer\">admin autodiscover feature</a></li>\n<li>In DateAdmin you overwrite the response_add method to (as far as I can see) set the user/creator field. This can be acomplished much easier by overwriting the <a href=\"http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model\" rel=\"noreferrer\">save_model method</a>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T19:35:27.657", "Id": "319", "ParentId": "187", "Score": "6" } }, { "body": "<ul>\n<li><p>Instead of the (very long) list of Admin classes at the end, you can integrate them in the model, so:</p>\n\n<pre><code>class MusicSheet(models.Model):\n version = models.CharField(max_length=2)\n song = models.ForeignKey(Song, blank=True, null=True)\n artist = models.ForeignKey(Artist, blank=True, null=True)\n file_type = models.ForeignKey(FileType, blank=True, null=True)\n level = models.ForeignKey(Level, blank=True, null=True)\n user = models.ForeignKey(User, blank=True, null=True)\n created = models.ForeignKey(DateTime)\n text = models.TextField()\n notes = models.TextField()\n\nclass MusicSheetAdmin(admin.ModelAdmin):\n list_display = [\"version\", \"song\", \"artist\", \"file_type\", \"level\", \"user\" , \"created\", \"text\", \"notes\"]\n search_fields = [\"version\"]\n\nclass MusicSheetInline(admin.TabularInline):\n model = MusicSheet\n\nadmin.site.register(MusicSheet, MusicSheetAdmin)\n</code></pre>\n\n<p>can be simplified (and neatened) to:</p>\n\n<pre><code>class MusicSheet(models.Model):\n version = models.CharField(max_length=2)\n song = models.ForeignKey(Song, blank=True, null=True)\n artist = models.ForeignKey(Artist, blank=True, null=True)\n file_type = models.ForeignKey(FileType, blank=True, null=True)\n level = models.ForeignKey(Level, blank=True, null=True)\n user = models.ForeignKey(User, blank=True, null=True)\n created = models.ForeignKey(DateTime)\n text = models.TextField()\n notes = models.TextField()\n\n class Admin:\n list_display = [\"version\", \"song\", \"artist\", \"file_type\", \"level\", \"user\" , \"created\", \"text\", \"notes\"]\n search_fields = [\"version\"]\n</code></pre>\n\n<p>Make sure that <code>class Admin</code> is <em>inside</em> the main class.</p>\n\n<p>Alternatively, if you <em>did</em> want them separate, the admin classes and registrations belong inside a separate file, <code>admin.py</code>. (You will have to import the models <code>from myapp.models import *</code>)</p></li>\n<li><p>Some of your <code>ForeignKey</code>s have both <code>blank=True</code> and <code>null=True</code>. This is generally not a good idea. Do you want to allow them to be null (no value) or blank (an empty value)? Looking at your code, I'd say you want <code>null=True</code> but I can't be sure. Try one, then the other, and see which one does what you want. I highly doubt you need both. As a general rule, I only use <code>blank=True</code> for <code>CharField</code>s, so you can have a null string instead of an empty database field.</p></li>\n<li><p>I can't work out what <code>DateAdmin</code> is meant to do. You probably won't need it when you switch to DateTimeField as recommended above, but I would want to know what its intended purpose is before I make a call.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-25T06:24:33.480", "Id": "63831", "ParentId": "187", "Score": "1" } } ]
{ "AcceptedAnswerId": "196", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-24T22:35:07.103", "Id": "187", "Score": "25", "Tags": [ "python", "beginner", "django" ], "Title": "Music info model" }
187
<p>I've recently assembled some jQuery that allows a user to build out a bulleted list in MS Word with hyperlinks and turn that into a HTML unordered list. Ideas for uses are website menu systems where the user may not have a clue about HTML. You can also extend this with jQuery UI plugins for effects. Looking for edge cases.</p> <pre><code>/* The following will read in a bullet list from in a MS Word XML file and turn it into a unordered list with hyperlinks. Perhaps to use as a menu. */ $.ajax({ type: "GET", async: false, url: "Menu.xml", dataType: "xml", success:function(results){ var currentDepth = 0; $("#menu").append('&lt;ul class="menuLvl'+currentDepth+'"&gt;&lt;/ul&gt;'); $(results).find("[nodeName=w:p]").each(function(){ if($(this).find("[nodeName=w:pStyle]").attr('w:val') == 'ListParagraph'){ var liValue = $(this).find("[nodeName=w:t]").text(); var hyper = $(this).find("[nodeName=w:hyperlink]").attr('r:id'); var placeAtDepth = parseInt($(this).find("[nodeName=w:ilvl]").attr('w:val'), 10); if(placeAtDepth &gt; currentDepth){ $(".menuLvl"+ currentDepth).append('&lt;ul class="menuLvl'+ placeAtDepth +'"&gt;'); } currentDepth = placeAtDepth; //Determine if we have an hyperlink if(hyper != null){ var link = $(results).find('Relationship[Id='+hyper+']').attr('Target'); liValue = '&lt;a href="'+ link +'"&gt;'+ liValue +'&lt;/a&gt;'; } $(".menuLvl"+currentDepth).last().append('&lt;li&gt;'+ liValue +'&lt;/li&gt;'); } }); } }); </code></pre>
[]
[ { "body": "<p>Looks fine (maybe some stricter formatting could help readibility, but not an issue), so I'll suggest completely optional improvements that might help spotting important improvements.</p>\n\n<p>As a general principle, try to <a href=\"http://en.wikipedia.org/wiki/Robustness_principle\" rel=\"noreferrer\">be ready for bogus values in your input so you can avoid generating nonsense</a>. Being more robust will also make reusing your code for somewhat different tasks easier.</p>\n\n<pre><code>$.ajax({\n/// [...]\n success:function(results){\n/// [...]\n $(results).find(\"[nodeName=w:p]\").each(function(){\n if($(this).find(\"[nodeName=w:pStyle]\").attr('w:val') == 'ListParagraph'){\n var liValue = $(this).find(\"[nodeName=w:t]\").text();\n/// -^ What if the input has an empty value here? Skip? \n\n var hyper = $(this).find(\"[nodeName=w:hyperlink]\").attr('r:id');\n var placeAtDepth = parseInt($(this).find(\"[nodeName=w:ilvl]\").attr('w:val'), 10);\n/// -^ parseInt can return a NaN, maybe you want to bail out in that case?\n/// Should also handle some bogus results for .find.\n\n if(placeAtDepth &gt; currentDepth){\n $(\".menuLvl\"+ currentDepth).append('&lt;ul class=\"menuLvl'+ placeAtDepth +'\"&gt;');\n }\n\n currentDepth = placeAtDepth;\n\n //Determine if we have an hyperlink\n if(hyper != null){\n var link = $(results).find('Relationship[Id='+hyper+']').attr('Target');\n/// -^ This can result in an invalid link for broken input. But what if\n the input is malicious (JS hrefs)? \n\n liValue = '&lt;a href=\"'+ link +'\"&gt;'+ liValue +'&lt;/a&gt;';\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T22:37:59.573", "Id": "213", "ParentId": "190", "Score": "5" } } ]
{ "AcceptedAnswerId": "213", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-25T00:13:26.037", "Id": "190", "Score": "7", "Tags": [ "javascript", "jquery", "xml", "ms-word" ], "Title": "Build menu from MS Word XML" }
190
<p>I'm looking into Administration Elevation and I've come up with a solution that seems like it's perfectly sane, but I'm still in the dark about the professional methods to accomplish this.</p> <p>Is there a better way to do this or is this fine? </p> <pre><code>using System; using System.Diagnostics; using System.Security.Principal; using System.Windows.Forms; namespace MyVendor.Installation { static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (!IsRunAsAdmin()) { Elevate(); Application.Exit(); } else { try { Installer InstallerForm = new Installer(); Application.Run(InstallerForm); } catch (Exception e) { //Display Exception message! Logging.Log.Error("Unrecoverable exception:", e); Application.Exit(); } } } internal static bool IsRunAsAdmin() { var Principle = new WindowsPrincipal(WindowsIdentity.GetCurrent()); return Principle.IsInRole(WindowsBuiltInRole.Administrator); } private static bool Elevate() { var SelfProc = new ProcessStartInfo { UseShellExecute = true, WorkingDirectory = Environment.CurrentDirectory, FileName = Application.ExecutablePath, Verb = "runas" }; try { Process.Start(SelfProc); return true; } catch { Logging.Log.Error("Unable to elevate!"); return false; } } } } </code></pre>
[]
[ { "body": "<p>You can create a manifest file and set the app to require administrative privileges. This will trigger the UAC user prompt with the dimmed screen when your application is run without requiring any code on your part.</p>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/bb756929.aspx\">MSDN</a> for the gory details:</p>\n\n<blockquote>\n <p>This file can be created by using any text editor. The application manifest file should have the same name as the target executable file with a .manifest extension.</p>\n</blockquote>\n\n\n\n<blockquote>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?&gt;\n&lt;assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\"&gt; \n &lt;assemblyIdentity version=\"1.0.0.0\"\n processorArchitecture=\"X86\"\n name=\"&lt;your exec name minus extension&gt;\"\n type=\"win32\"/&gt; \n &lt;description&gt;Description of your application&lt;/description&gt; \n &lt;!-- Identify the application security requirements. --&gt;\n &lt;trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v2\"&gt;\n &lt;security&gt;\n &lt;requestedPrivileges&gt;\n &lt;requestedExecutionLevel\n level=\"requireAdministrator\"\n uiAccess=\"false\"/&gt;\n &lt;/requestedPrivileges&gt;\n &lt;/security&gt;\n &lt;/trustInfo&gt;\n&lt;/assembly&gt;\n</code></pre>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T19:25:52.243", "Id": "327", "Score": "0", "body": "Would it be possible to elevate the application during runtime ?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T19:33:56.487", "Id": "329", "Score": "0", "body": "@RobertPitt This way it will elevate on startup. It will not start unless admin rights are granted." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-25T19:03:30.140", "Id": "208", "ParentId": "197", "Score": "22" } }, { "body": "<p>Other options:</p>\n\n<p>First: there is a mechanism to elevate \"part\" of an application via COM Monikers: run a part of the application out of process via COM, using a correctly formatted name to elevate (this is how Explorer elevates parts of itself). See MSDN <a href=\"http://msdn.microsoft.com/en-us/library/ms679687(v=vs.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms679687(v=vs.85).aspx</a></p>\n\n<p>Second: as Anna says: <a href=\"https://codereview.stackexchange.com/questions/197/administration-elevation/208#208\">use a manifest</a>.</p>\n\n<p>Third: run via <code>runas</code> as in the Q.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T07:14:50.793", "Id": "257", "ParentId": "197", "Score": "4" } }, { "body": "<p>There are a couple of things that I would change in your code to make it clearer or mix well with standards.</p>\n\n<pre><code> internal static bool IsRunAsAdmin()\n {\n var Principle = new WindowsPrincipal(WindowsIdentity.GetCurrent());\n return Principle.IsInRole(WindowsBuiltInRole.Administrator);\n }\n</code></pre>\n\n<p>I would change the name of this Method to <code>RunningAsAdmin</code> and the variable <code>Principle</code> should be lowercase to match the standard naming scheme for variables of camelCasing.</p>\n\n<p>also I would change the structure of your if then statement in the Main Method.</p>\n\n<p>instead of negating the boolean method I would let it play out, you are checking it one way or the other anyway so the negation just looks wrong</p>\n\n<pre><code> if (RunningAsAdmin()) \n {\n try\n {\n Installer InstallerForm = new Installer();\n Application.Run(InstallerForm);\n }\n catch (Exception e)\n {\n //Display Exception message!\n\n Logging.Log.Error(\"Unrecoverable exception:\", e);\n Application.Exit();\n }\n }\n else\n {\n Elevate();\n Application.Exit();\n }\n</code></pre>\n\n<p>Do we need <code>Elevate</code> to Return a boolean? from what I can see it doesn't really do anything with the true/false value.</p>\n\n<p>Let's just make it a void method and let it do it's stuff and get outta there, no return statements.</p>\n\n<pre><code> private static void Elevate()\n {\n var SelfProc = new ProcessStartInfo\n {\n UseShellExecute = true,\n WorkingDirectory = Environment.CurrentDirectory,\n FileName = Application.ExecutablePath,\n Verb = \"runas\"\n };\n try\n {\n Process.Start(SelfProc);\n }\n catch\n {\n Logging.Log.Error(\"Unable to elevate!\");\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-24T21:48:40.513", "Id": "63804", "ParentId": "197", "Score": "11" } } ]
{ "AcceptedAnswerId": "208", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-25T12:11:42.320", "Id": "197", "Score": "33", "Tags": [ "c#", "authorization" ], "Title": "Administration Elevation" }
197
<p>I have a database class that in <code>__construct()</code> initialize a PDO connection and insert the instance into a $db private var. Now i'm working on a method that can be used to query in this way:</p> <pre><code>$db = new db; $db-&gt;query(array( 'select' =&gt; 1, 'from' =&gt; 'table', 'where' =&gt; array('id' =&gt; 1, 'name' =&gt; 'charlie'), 'limit' =&gt; array(1, 5) )); </code></pre> <p>I did something that works pretty nicely long time ago while PDO was something unknown, but i was wondering:</p> <ol> <li>How could i improve this code a bit</li> <li>How can i end it? I mean how to use the PDO then to submit the query?</li> </ol> <p>Here's the method <code>query()</code>:</p> <pre><code># Defining the type if (isset($array['select'])) { $type = 'SELECT'; $type_value = (is_int($array['select'])) ? '*' : $array['select']; } if (isset($array['update'])) { $type = 'UPDATE'; $type_value = $array['update']; } if (isset($array['delete'])) { $type = 'DELETE FROM'; $type_value = $array['delete']; } if (isset($array['insert'])) { $type = 'INSERT INTO'; $type_value = $array['insert']; } if (!isset($type)) { trigger_error("Database, 'type' not selected."); } // Error # From if (isset($array['from'])) { $from = 'FROM'; $from_value = mysql_real_escape_string($array['from']); // table cannot be pdoed } # Where if (isset($array['where'])) { if (!is_array($array['where'])) { trigger_error("Database, 'where' key must be array."); } $where = 'WHERE'; $where_value = $array['where']; # Fixing the AND problem if (count($array['where']) &gt; 1) { $list = $where_value; foreach ($list as $a =&gt; $b) { $w[] = "{$a} = {$b}"; } $and = implode(' AND ', $w); $where_value = $and; } } # Limit if (isset($array['limit'])) { if (!is_array($array['limit'])) { trigger_error("Database, 'limit' key must be array."); } if (count($array['limit']) != 2) { trigger_error("Database, 'limit' array must be two-keys-long"); } $limit_first = $array['limit'][0]; $limit_second = $array['limit'][1]; $limit = 'LIMIT'; $limit_value = "{$limit_first}, {$limit_second}"; } # Set if (isset($array['set'])) { if (!is_array($array['set'])) { trigger_error("Database, 'set' key must be array."); } $edits = $array['set']; foreach ($edits as $a =&gt; $b) { $e[] = "{$a} = {$b}"; } $set = 'SET'; $set_value = implode(',', $e); } $vals = array('from', 'from_value', 'set', 'set_value', 'where', 'where_value'); foreach ($vals as $v) { if (empty($$v)) { $$v = ''; } } $sql = " {$type} {$type_value} {$from} {$from_value} {$set} {$set_value} {$where} {$where_value} "; # Here there would be something like mysql_query($sql), but i'd like PDO! PDO get me hornier. </code></pre> <p>And now? How to bind parameters? Is that possible to work it out?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T16:24:21.633", "Id": "307", "Score": "1", "body": "Code like this is why I prefer ORM offerings like Doctrine." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T16:31:33.867", "Id": "308", "Score": "2", "body": "Very usefull comment." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T20:51:54.057", "Id": "339", "Score": "0", "body": "Where's [little Bobby Tables](http://xkcd.com/327/) when we need him?" } ]
[ { "body": "<p>That query method (and the db class) has a lot of responsibilities:</p>\n\n<ul>\n<li>Do the PDO stuff, connection handling</li>\n<li>Be a query builder</li>\n<li>be a query executor</li>\n<li>Handle the params and possibly execute the same statement with different params (it would to that too)</li>\n<li>Do all the error checking</li>\n<li>maybe more i don't see</li>\n</ul>\n\n<p>Usually that functionality is handled in 2 to 3 classes, sometimes even more and not in one single function.</p>\n\n<p>And you are doing some very creepy magic to achieve all the work</p>\n\n<pre><code>foreach ($vals as $v) { if (empty($$v)) { $$v = ''; } }\n</code></pre>\n\n<p>and all that so you can write </p>\n\n<pre><code>array(\"select \" =&gt; \"something\" , ...\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>\"select something\" ...\n</code></pre>\n\n<p>Also you are using <code>mysql_real_escape_string</code> so it seems you don't want to use the pdo escaping (not binding parameters) so why try to use PDO if you limit yourself to mysql anyways ? </p>\n\n<p>So far everything i spotted thinking about it for 5 minutes. Will improve upon feedback / direction from you if it helped at all :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T18:38:17.717", "Id": "326", "Score": "0", "body": "I use mysql_real_escape_string only for the table since you cannot use binding parameter for tables. But, wait. You said you would use 2 or 3 classes? Why should you?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T20:31:36.103", "Id": "334", "Score": "1", "body": "Because packing all that functionality into one class make one darn big and complicated (read: hart do maintain, test, debug, understand, extend) class. In short: The \"once class one purpose\" principle. Many \"good oop\" books and advocates suggest that you are able to describe the purpose of a class in one sentence without saying \"and\" so you get maintainable (etc. pp. can go into detail if you want) class." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T20:34:28.720", "Id": "335", "Score": "0", "body": "You shoudn't use mysql_real_escape_string for table names though, if you use another database that might be exploitable (using a database that uses different commetents than mysql bad things COULD happen. Use a whitelist for the tablename if you want so make it save. Checking that it matches (for example) /[A-Za-z0-9_]/ will be more secure and less (maybe non) exploitable whereas mysql_real_escape_string doesn't to the right thing for this context" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T07:24:17.057", "Id": "349", "Score": "0", "body": "How could a different class for query building and query execution be any better? Using 3 classes will make you mad managing parent and inherit issues. Also it seems to me thousands of lines of code for nothings. My db class manage all the db class: one class one purpose. But I'm probably misunderstanding that." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T23:23:47.477", "Id": "1616", "Score": "0", "body": "@Charlie - a: 3 classes is far from an inheritance nightmare. b: In this instance, the classes would not be using inheritance, they simply have separate concerns, c: it's good to divide classes when they approach unmanageable levels of complexity, or have too much responsibility: http://misko.hevery.com/code-reviewers-guide/flaw-class-does-too-much/" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T18:34:21.303", "Id": "207", "ParentId": "200", "Score": "6" } } ]
{ "AcceptedAnswerId": "207", "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T14:57:14.420", "Id": "200", "Score": "9", "Tags": [ "php", "mysql", "pdo", "object-oriented", "php5" ], "Title": "Database method to query" }
200
<p>I found that in PHP (or I probably can't find it) a proper <code>is_numeric_array($array)</code> function is missing. So I created one. The problem is that I don't think it's great and I don't know how to improve it.</p> <p>Any suggestion?</p> <p><strong>My first function</strong></p> <pre><code>function is_numeric_array($array) { $i = 0; foreach ($array as $a =&gt; $b) { if (is_int($a)) { ++$i; } } if (count($array) === $i) { return true; } else { return false; } } is_numeric_array(array(0,0,0,0,0)); // true is_numeric_array(array('str' =&gt; 1, 'str2' =&gt; 2, 'str3' =&gt; 3)); // false </code></pre> <p><strong>Example</strong></p> <p>As asked, I provide an example on how this could be any useful.</p> <pre><code>function is_numeric_array($array) { # Code below } function someFunction($array) { if (is_numeric_array($array)) { $query = $array[0]; $param = $array[1]; $fetch = $array[2]; } else { $query = $array['query']; $param = $array['param']; $fetch = $array['fetch']; } # Do your sql/pdo stuff here } # This use is the same of ... someFunction(array( 'PDO SQL STATEMENT', array('param1' =&gt; 1, 'param2' =&gt; 2, 'param3' =&gt; 3), true )); # ... this one. someFunction(array( 'query' =&gt; 'PDO SQL STATEMENT', 'param' =&gt; array('param1' =&gt; 1, 'param2' =&gt; 2, 'param3' =&gt; 3), 'fetch' =&gt; true )); # To choose one form instead of the other is coder's decision # Also I know it is useless but I was just wondering why anybody actually looked forward this function </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T15:46:23.483", "Id": "450", "Score": "0", "body": "Im just curious, can you provide a use case for this?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:10:26.727", "Id": "478", "Score": "0", "body": "Done, hope you like it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T12:14:54.220", "Id": "7932", "Score": "0", "body": "They're all bad =) This is the only right one: https://gist.github.com/1272230" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-24T16:25:07.493", "Id": "103806", "Score": "0", "body": "The more I read the more confused I became; You seem to determine if an array is associative or not, Whereas I read this topic as \"determine if all array values are numeric/integers\". A Straightforward approach to an is_assoc check is exemplified here: http://stackoverflow.com/a/173479/1695680" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-24T17:01:34.663", "Id": "103817", "Score": "0", "body": "Apologies, after further consideration the linked answer is not so reliable; You'd actually want to modify the next answer: http://stackoverflow.com/a/4254008/1695680 to use 'is_int' instead of 'is_string'" } ]
[ { "body": "<p>This will drop out as soon as an element is found that is not an int, making the function more efficient for large arrays.</p>\n\n<pre><code>function is_numeric_array($array) {\n foreach ($array as $a=&gt;$b) {\n if (!is_int($a)) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T16:42:52.947", "Id": "311", "Score": "1", "body": "That doesn't do the same thing as his code does it? Unless I'm missing something this checks whether the values are ints, not the keys. Also the code will cause an error if the keys aren't ints." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T16:53:16.723", "Id": "312", "Score": "1", "body": "Also it's `return $i` instead of `return $1`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T17:08:01.470", "Id": "314", "Score": "0", "body": "Also, I'm not sure how `count` works, but it likely rewalks the array, causing you to go over it twice." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T17:27:50.113", "Id": "316", "Score": "0", "body": "...also no stop condition on while loop. Changed." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T17:28:34.233", "Id": "317", "Score": "0", "body": "And look at that - all that great thinking and someone else posted the same thing already :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T18:03:17.120", "Id": "318", "Score": "1", "body": "I would also try to `krsort($array,SORT_STRING);` first. This should move most non-numeric keys to the begining of the array. One would need to benchmark if it gives any increase in performance." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T16:28:16.500", "Id": "202", "ParentId": "201", "Score": "5" } }, { "body": "<p>Instead of using a counter to count the keys for which the condition is true, you could just return false as soon as you find a key which is not an int and return true if the loop reaches its end without finding such a key:</p>\n\n<pre><code>foreach ($array as $a =&gt; $b) {\n if (!is_int($a)) {\n return false;\n }\n}\nreturn true;\n</code></pre>\n\n<p>This has the benefit that it short-circuits (i.e. it stops iterating once it finds a key that is not an int) and gets rid of the counter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T12:14:11.490", "Id": "7931", "Score": "0", "body": "How about `array_fill(3, 5, 0)`? Do you consider that a numeric array?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-01T19:43:42.143", "Id": "125196", "Score": "2", "body": "Instead of using is_int($a) use ($a !== (int) $a) and it will be 10x faster." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T16:58:01.383", "Id": "204", "ParentId": "201", "Score": "45" } }, { "body": "<p>At first I didn't realise you wanted to check see if the keys are integers. If the reason you're doing this is to make sure the keys are 0,1,2,3,4.. etc as an indexed array and not an associative array, then you could use this:</p>\n\n<pre><code>function is_numeric_array($arr)\n{\n return array_keys($arr) === range(0,(count($arr)-1));\n}\n\n/*\n * Tests\n*/\nvar_dump(is_numeric_array(array('a', 'b', 'c'))); // true\nvar_dump(is_numeric_array(array(\"0\" =&gt; 'a', \"1\" =&gt; 'b', \"2\" =&gt; 'c'))); // true\nvar_dump(is_numeric_array(array(\"1\" =&gt; 'a', \"0\" =&gt; 'b', \"2\" =&gt; 'c'))); // false\nvar_dump(is_numeric_array(array(\"a\" =&gt; 'a', \"b\" =&gt; 'b', \"c\" =&gt; 'c'))); // false\n</code></pre>\n\n<p>Benchmark results as requested:</p>\n\n<p>Here's the code used to test the execution:</p>\n\n<pre><code>$array = array();\nfor($i=0;$i&lt;=500000;$i++)\n{\n $array[] = \"some_string\";\n}\n\n$m_initial = memory_get_usage();\nis_numeric_array($array);\n$increase = memory_get_usage() - $m_initial;\n</code></pre>\n\n<p>As you can see from the above, I tested with a linear array that had 500K strings:</p>\n\n<p>The value of <code>$increase</code> showed <strong>65032</strong> (which is in bytes). If we converted to K<b>B</b> this is around 64 rounded up. The result in KB shows <strong>63.507</strong>, which in my opinion is ok.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T18:11:40.823", "Id": "319", "Score": "0", "body": "It actually checks only values, not keys. Am i wrong?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T18:13:00.207", "Id": "320", "Score": "0", "body": "added the `$key` to that." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T18:18:31.430", "Id": "321", "Score": "0", "body": "`array_filter`'s callback only takes array values as an argument. You'd need to fetch `array_keys` first, and filter that." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T18:22:10.270", "Id": "322", "Score": "0", "body": "yea is scrapped it, I was a little in-consistence and should of done my research." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T18:31:50.220", "Id": "324", "Score": "0", "body": "Well, i'd like that the second example returns false since you, as coder, defined a specific key." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T18:34:09.923", "Id": "325", "Score": "0", "body": "Charlie, Please elaborate, your comment has got me all confused :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T19:36:29.247", "Id": "330", "Score": "0", "body": "Still no good: `var_dump(is_numeric_array(array(1 => 'a', 'b', 'c')));`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T19:37:35.163", "Id": "331", "Score": "0", "body": "The second example is not a numeric array since the keys are strings. I'd like the second example to return false." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T20:13:42.617", "Id": "332", "Score": "0", "body": "Charlie, as the index of the second example is in numeric order, the strings are automatically converted to *ints* and stored as an enumerable array, this is why the the third example returns false as there in the order of `1`,`0`,`2` and not `0`,`1`,`2`. if this is the case then it seems like you need to change the way your method requires the arrays to be." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T20:47:54.403", "Id": "337", "Score": "0", "body": "I'd love to see a large array passed in and watch memory usage... :-D" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T21:04:04.093", "Id": "342", "Score": "0", "body": "recheck the posts for some benchmark results" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-25T18:07:26.177", "Id": "205", "ParentId": "201", "Score": "6" } }, { "body": "<p>Improving a little on @sepp2k answer(+1) (removing the \"unused variable warning\" some tools will spit out):</p>\n\n<pre><code>foreach (array_keys($array) as $a)) {\n if (!is_int($a)) {\n return false;\n }\n}\nreturn true;\n</code></pre>\n\n<p>If you want to check if it's an linear array:</p>\n\n<pre><code>return array_merge($array) === $array;\n</code></pre>\n\n<p>or @RobertPitt's solution :) (Also +1 there) </p>\n\n<h2>But my main point:</h2>\n\n<p>Why do you need this, i've never had use for something like this and it <strong>might</strong> be that the solution is change and API design flaw or data structure flaw somewhere ? Doesn't have too, but might.</p>\n\n<h2>Response to OPs comment:</h2>\n\n<p>I'm building a db method for queries that needs of a 3 keys array. In case the array is Numeric the order must be: statement, parameters, fetch. In case it's not, so the coder is specifying the key string, the order can be different and two out of three required parameters could be empty.</p>\n\n<p>Ok then let my try to do that specif to your requirements :)</p>\n\n<pre><code>my_db_function(\n array(\"myquery\", array(\"params\", \"...\"), \"myfetchmode\")\n);\n// or \nmy_db_function(\n array(\"params\" =&gt; \"myquery\", \"fetchmode\" =&gt; \"myfetchmode, \"params\" =&gt; array(\"myparams\", \"...) )\n); \n</code></pre>\n\n<p>Maybe i misunderstood a little but it should get the point across how one could build that with a different check :)</p>\n\n<pre><code>function my_db_fuction($statement) {\n\n if(isset($statement[\"query\"])) { // Assoc 'Mode'\n $query = $statement[\"query\"];\n if(isset($statement[\"params\"])) { $params = $statement[\"params\"]; } \n else { $params = array(); }\n if(isset($statement[\"fetchmode\"])) { $fetchmode = $statement[\"fetchmode\"]; }\n else { $fetchmode = \"select\"; // optional param, default value here\n\n } else if(isset($statement[0]) { // Linear Array Mode\n\n $query = $statement[0];\n if(isset($statement[1])) { $params = $statement[1]; } \n else { $params = array(); }\n if(isset($statement[2])) { $fetchmode = $statement[2]; }\n else { $fetchmode = \"select\"; // optional param, default value here\n\n } else {\n // Error, misformed format\n }\n // Now we got our 3 variables :)\n}\n</code></pre>\n\n<p>That is still a pretty big code block but i didn't want to shorten it and risk worse readabilty. </p>\n\n<p>What i would do with that is create a my_db_stuff_param_helper($aParams) that will always return an array containing the 3 keys filled with the real values (or defaults if nothing was passed)</p>\n\n<pre><code> function my_db_fuction($statement) {\n $statement = my_db_parse_params($statement);\n // now e.g. $statement[\"query\"] will always be there\n }\n</code></pre>\n\n<p>something along those lines \"feels\" (subjective, i know) better than building a generic function to do the key checking. (I guess it's <strong>isset($statement[\"query\"])</strong> instead of <strong>is_numeric_array</strong> what i boilds down to :) </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T18:29:01.283", "Id": "323", "Score": "0", "body": "I need of it because i'm creating a method that, based on how it is written, must behave different ways." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T20:26:08.620", "Id": "333", "Score": "1", "body": "You are doing something that forces you to do something and because of that you need this method. I'm saying maybe if you do something different you don't need that. Sry i got no idea how i could make myself clearer but i read your answers as \"I need this because i need this\" and i'm just suggesting that maybe you don't :) And since this is codereview and not SO i though i mention it and don't just provide a code snippet with the (for me at least) obvious answer :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T07:37:47.647", "Id": "350", "Score": "0", "body": "I got what you are saying. I'm building a db method for queries that needs of a 3 keys array. In case the array is Numeric the order must be: statement, parameters, fetch. In case it's not, so the coder is specifying the key string, the order can be different and two out of three required parameters could be empty. I know it's strange and I'm going to edit it, but I was just wondering if a proper function doesn't exist." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T08:33:25.453", "Id": "354", "Score": "0", "body": "Edited my answer in response, might be a bit overblown :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:16:26.017", "Id": "482", "Score": "1", "body": "Didn't thought about this method. Thanks for providing it. But, let's face it, PHP has a lot of useless functions, why don't put `is_numeric_array()` into the core? <sarcasm> Look at that `eval()` function, isn't my `is_numeric_array()` function way more helpfull? </sarcasm>" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T18:24:34.573", "Id": "206", "ParentId": "201", "Score": "14" } }, { "body": "<p>Ok, here's a shot for consistency and proper naming conventions (Since <code>numeric</code> and <code>int</code> mean different things all together, there's little point calling one the other...):</p>\n\n<pre><code>function isNumericArray(array $array) {\n foreach ($array as $a =&gt; $b) {\n if (!is_numeric($a)) {\n return false;\n }\n }\n return true;\n}\n\nfunction isIntArray(array $array) {\n foreach ($array as $a =&gt; $b) {\n if (!is_int($a)) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>Now, for a more OO approach, I'd build a filteriterator:</p>\n\n<pre><code>class NumericFilterIterator extends FilterIterator {\n public function accept() {\n return is_numeric(parent::current());\n }\n}\n\nclass IntFilterIterator extends FilterIterator {\n public function accept() {\n return is_int(parent::current());\n }\n}\n</code></pre>\n\n<p>Then, if you just want to iterate over the integer, just do <code>$it = new IntFilterIterator(new ArrayIterator($array));</code>. If you want to verify, you can do:</p>\n\n<pre><code>$it = new IntFilterIterator(new ArrayIterator($array));\nif ($array != iterator_to_array($it)) {\n //Has a non-int element\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T01:33:25.427", "Id": "78684", "Score": "0", "body": "+1 for the difference and the `FilterIterator`. Only thing that could be improved is to only check the array values. No need to run over the whole array." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T20:31:58.340", "Id": "209", "ParentId": "201", "Score": "5" } }, { "body": "<p>If you're actually trying to determine whether it's a sequential integer array rather than associative, i.e. something that json_encode would make an array vs an object, this is probably the fastest way to to do so:</p>\n\n<pre><code>function is_normal_array($arr) {\n $c = count($arr);\n for ($i = 0; $i &lt; $c; $i++) {\n if (!isset($arr[$i])) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>...of course the fastest code is code you never run, so consider whether you really, really need to do this, and only use it where you do.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T07:24:44.013", "Id": "409", "Score": "1", "body": "This should be faster than the foreach solutions others have posted, but the algorithms don't agree perfectly. The foreach solutions return true for array(0 => 'a', 1 => 'b', 3 => 'd') whereas mine returns false." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T07:21:27.870", "Id": "258", "ParentId": "201", "Score": "2" } }, { "body": "<p>This would probably be way more efficient:</p>\n\n<pre><code>function is_numeric_array($array)\n{\n $array = array_keys($array);\n\n if ($array === array_filter($array, 'is_int'))\n {\n return true;\n }\n\n return false;\n}\n</code></pre>\n\n<hr>\n\n<p>I just noticed what you're really trying to do is not check if all the keys in an array are integers but rather if the array is indexed (non-associative), for this use <code>array_values()</code> does the trick:</p>\n\n<pre><code>function is_numeric_array($array)\n{\n return ($array === array_values($array));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-29T20:23:33.553", "Id": "301777", "Score": "0", "body": "this should be the accepted solution! array_values FTW!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T11:31:13.107", "Id": "988", "ParentId": "201", "Score": "3" } }, { "body": "<p>This is an old post, but if you're looking for a shorter but still elegant solution, use this:</p>\n\n<pre><code>return array_values($array) === $array\n</code></pre>\n\n<p>You could even use it as condition since it's pretty short too. Cheers</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-21T14:56:13.027", "Id": "163881", "ParentId": "201", "Score": "2" } } ]
{ "AcceptedAnswerId": "204", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-25T16:13:34.917", "Id": "201", "Score": "32", "Tags": [ "php", "php5", "array" ], "Title": "is_numeric_array() is missing" }
201
<p>I want to get empty string or the string value of the object</p> <p>Which code you will use and why?</p> <pre><code>value = object.to_s </code></pre> <p>or this</p> <pre><code>value = object.nil? ? "" : object </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T22:50:58.253", "Id": "345", "Score": "2", "body": "The second alternative doesn't result in a string, so I guess there's a typo?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:33:20.200", "Id": "389", "Score": "0", "body": "@TryPyPy if you are going to print `value` right after those statements, there is no difference. You just need something that `responds_to?` `to_s`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T05:55:06.670", "Id": "408", "Score": "0", "body": "I want to express in my code that there is check for nil and the object could be actually nil, so that if someone is reading my code to be aware of that. so probably the value = object || \"\" will fits best my style even that object.to_s is shorter." } ]
[ { "body": "<p>I've read in <a href=\"http://rubyglasses.blogspot.com/2007/08/actsasgoodstyle.html\" rel=\"nofollow\">here(act_as_good_style)</a> (search for <code>.nil?</code> first occurrence) that you should not check for <code>.nil?</code> unless you really want to check that, while if you want to know if the object is valued you should go for something like that</p>\n\n<pre><code>value = object ? object.to_s : ''\n</code></pre>\n\n<p>That by the way fits very well with my policy standard behavior first(exception for very short code first when else statement too long).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T11:03:54.680", "Id": "362", "Score": "1", "body": "The thing I don't get is why you'd want to explicitly handle nil when just `value = object.to_s` will do the exact same thing anyway." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:00:50.707", "Id": "380", "Score": "1", "body": "Also, this code won't work when `object === false`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:16:34.737", "Id": "384", "Score": "0", "body": "you're both right, thanks for correcting me... beh that link is not mine and written by somebody that knows what she says..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T23:25:28.187", "Id": "216", "ParentId": "214", "Score": "5" } }, { "body": "<p>If <code>object</code> is either <code>nil</code> or a string, you can just do <code>value = object || \"\"</code>.</p>\n\n<p>If it can be anything and you want to get a string, your second solution doesn't actually do what you want, since it won't turn the object into a string if it's not nil. To fix that your second solution would become <code>value = object.nil? ? object.to_s : \"\"</code>. Of course since now you're calling <code>to_s</code> in both solutions there is no reason to prefer the second over the first, so I'd go with the first.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T23:46:09.683", "Id": "347", "Score": "0", "body": "if it's a string I would definitely go for the || solution" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T18:23:24.477", "Id": "1678", "Score": "0", "body": "If object is always either nil or string, you do not need to do either of the above because nil.to_s returns \"\" . Thus all you need is object.to_s You second option (checking object.nil?) gains you absolutely nothing at all... however your first option (using object || \"\") will also work appropriately if object is *not* nil, but is false... and it's what I'd choose.... it's also shorter, which means it's easier to read. :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T18:31:05.487", "Id": "1680", "Score": "0", "body": "@Taryn: \"You second option (checking object.nil?) gains you absolutely nothing at all\" That's what I said. Note that I recommend going with `object.to_s` in that case." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T23:31:21.560", "Id": "218", "ParentId": "214", "Score": "12" } }, { "body": "<p>I would do this, personally:</p>\n\n<pre><code>value = object unless onject.nil?\n</code></pre>\n\n<p>This seems a little more expressive to me. Its something I wish we could do in C++, instead of using the ternary operator.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T18:28:01.027", "Id": "1679", "Score": "2", "body": "hmm, you may need to spell-check and logic-check that example... :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T22:04:14.340", "Id": "227", "ParentId": "214", "Score": "2" } }, { "body": "<p>I would do:</p>\n\n<p><code>\nv = object.to_s\n</code></p>\n\n<p>nil.to_s returns \"\".</p>\n\n<p>Remember nil is also an object in ruby.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T22:30:15.253", "Id": "233", "ParentId": "214", "Score": "4" } }, { "body": "<p>In your specific case, using <code>object.to_s</code>, you don't actually need to check for <code>nil</code> at all since ruby handles this for you. If the object is <code>nil</code> it will return an empty string.</p>\n\n<p>Evidence from the irb:</p>\n\n<ul>\n<li><p><code>object = nil # =&gt; nil</code></p></li>\n<li><p><code>object.to_s # =&gt; \"\"</code></p></li>\n<li><p><code>object = Object.new # =&gt; #&lt;Object:0x10132e220&gt;</code></p></li>\n<li><code>object.to_s # =&gt; \"#&lt;Object:0x10132e220&gt;\"</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T22:35:02.290", "Id": "234", "ParentId": "214", "Score": "3" } } ]
{ "AcceptedAnswerId": "218", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-25T22:41:18.287", "Id": "214", "Score": "3", "Tags": [ "ruby" ], "Title": "Avoiding null in variable assignment" }
214
<p>This is part from an <a href="https://stackoverflow.com/questions/4706151/python-3-1-memory-error-during-sampling-of-a-large-list/4706317#4706317">answer to a Stack Overflow question</a>. The OP needed a way to perform calculations on samples from a population, but was hitting memory errors due to keeping samples in memory. </p> <p>The function is based on part of <a href="http://svn.python.org/view/python/trunk/Lib/random.py?view=markup#sample" rel="nofollow noreferrer">random.sample</a>, but only the code branch using a set is present.</p> <p>If we can tidy and comment this well enough, it might be worth publishing as a recipe at the <a href="http://code.activestate.com/recipes/" rel="nofollow noreferrer">Python Cookbook</a>.</p> <pre><code>import random def sampling_mean(population, k, times): # Part of this is lifted straight from random.py _int = int _random = random.random n = len(population) kf = float(k) result = [] if not 0 &lt;= k &lt;= n: raise ValueError, "sample larger than population" for t in xrange(times): selected = set() sum_ = 0 selected_add = selected.add for i in xrange(k): j = _int(_random() * n) while j in selected: j = _int(_random() * n) selected_add(j) sum_ += population[j] # Partial result we're interested in mean = sum_/kf result.append(mean) return result sampling_mean(x, 1000000, 100) </code></pre> <p>Maybe it'd be interesting to generalize it so you can pass a function that calculates the value you're interested in from the sample?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T15:04:51.737", "Id": "800", "Score": "1", "body": "But you keep the samples in memory too, so this isn't an improvement, over the solution you gave him, namely not keeping the samples around but calculating each mean directly." } ]
[ { "body": "<p>Making a generator version of <code>random.sample()</code> seems to be a much better idea:</p>\n\n<pre><code>from __future__ import division\nfrom random import random\nfrom math import ceil as _ceil, log as _log\n\ndef xsample(population, k):\n \"\"\"A generator version of random.sample\"\"\"\n n = len(population)\n if not 0 &lt;= k &lt;= n:\n raise ValueError, \"sample larger than population\"\n _int = int\n setsize = 21 # size of a small set minus size of an empty list\n if k &gt; 5:\n setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets\n if n &lt;= setsize or hasattr(population, \"keys\"):\n # An n-length list is smaller than a k-length set, or this is a\n # mapping type so the other algorithm wouldn't work.\n pool = list(population)\n for i in xrange(k): # invariant: non-selected at [0,n-i)\n j = _int(random() * (n-i))\n yield pool[j]\n pool[j] = pool[n-i-1] # move non-selected item into vacancy\n else:\n try:\n selected = set()\n selected_add = selected.add\n for i in xrange(k):\n j = _int(random() * n)\n while j in selected:\n j = _int(random() * n)\n selected_add(j)\n yield population[j]\n except (TypeError, KeyError): # handle (at least) sets\n if isinstance(population, list):\n raise\n for x in sample(tuple(population), k):\n yield x\n</code></pre>\n\n<p>Taking a sampling mean then becomes trivial: </p>\n\n<pre><code>def sampling_mean(population, k, times):\n for t in xrange(times):\n yield sum(xsample(population, k))/k\n</code></pre>\n\n<p>That said, as a code review, not much can be said about your code as it is more or less taking directly from the Python source, which can be said to be authoritative. ;) It does have a lot of silly speed-ups that make the code harder to read.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-01-31T15:01:59.697", "Id": "485", "ParentId": "217", "Score": "2" } } ]
{ "AcceptedAnswerId": "485", "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T23:27:25.303", "Id": "217", "Score": "8", "Tags": [ "python", "random" ], "Title": "Randomly sampling a population and keeping means: tidy up, generalize, document?" }
217
<p>The requirements for this one were (<a href="https://stackoverflow.com/q/4630723/555569">original SO question</a>):</p> <ul> <li>Generate a random-ish sequence of items.</li> <li>Sequence should have each item N times.</li> <li>Sequence shouldn't have serial runs longer than a given number (longest below).</li> </ul> <p>The solution was actually drafted by another user, this is <a href="https://stackoverflow.com/questions/4630723/using-python-for-quasi-randomization/4630784#4630784">my implementation</a> (influenced by <a href="http://svn.python.org/view/python/trunk/Lib/random.py?view=markup#shuffle" rel="nofollow noreferrer">random.shuffle</a>).</p> <pre><code>from random import random from itertools import groupby # For testing the result try: xrange except: xrange = range def generate_quasirandom(values, n, longest=3, debug=False): # Sanity check if len(values) &lt; 2 or longest &lt; 1: raise ValueError # Create a list with n * [val] source = [] sourcelen = len(values) * n for val in values: source += [val] * n # For breaking runs serial = 0 latest = None for i in xrange(sourcelen): # Pick something from source[:i] j = int(random() * (sourcelen - i)) + i if source[j] == latest: serial += 1 if serial &gt;= longest: serial = 0 guard = 0 # We got a serial run, break it while source[j] == latest: j = int(random() * (sourcelen - i)) + i guard += 1 # We just hit an infinit loop: there is no way to avoid a serial run if guard &gt; 10: print("Unable to avoid serial run, disabling asserts.") debug = False break else: serial = 0 latest = source[j] # Move the picked value to source[i:] source[i], source[j] = source[j], source[i] # More sanity checks check_quasirandom(source, values, n, longest, debug) return source def check_quasirandom(shuffled, values, n, longest, debug): counts = [] # We skip the last entries because breaking runs in them get too hairy for val, count in groupby(shuffled): counts.append(len(list(count))) highest = max(counts) print('Longest run: %d\nMax run lenght:%d' % (highest, longest)) # Invariants assert len(shuffled) == len(values) * n for val in values: assert shuffled.count(val) == n if debug: # Only checked if we were able to avoid a sequential run &gt;= longest assert highest &lt;= longest for x in xrange(10, 1000): generate_quasirandom((0, 1, 2, 3), 1000, x//10, debug=True) </code></pre> <p>I'd like to receive any input you have on improving this code, from style to comments to tests and anything else you can think of. </p>
[]
[ { "body": "<p>A couple of possible code improvements that I noticed:</p>\n\n<pre><code>sourcelen = len(values) * n\n</code></pre>\n\n<p>This seems unnecessarily complicated to me. I mean, after a second of thinking the reader of this line will realize that <code>len(values) * n</code> is indeed the length of <code>source</code>, but that's still one step of thinking more than would be required if you just did <code>sourcelen = len(source)</code> (after populating <code>source</code> of course).</p>\n\n<p>That being said, I don't see why you need to store the length of <code>source</code> in a variable at all. Doing <code>for i in xrange(len(source)):</code> isn't really less readable or less efficient than doing <code>for i in xrange(sourcelen):</code>, so I'd just get rid of the variable altogether.</p>\n\n<hr>\n\n<pre><code>source = []\nfor val in values:\n source += [val] * n\n</code></pre>\n\n<p>This can be written as a list comprehension like this:</p>\n\n<pre><code>source = [x for val in values for x in [val]*n]\n</code></pre>\n\n<p>Using list comprehensions is usually considered more idiomatic python than building up a list iteratively. It is also often more efficient.</p>\n\n<p>As Fred Nurk points out, the list comprehension can also be written as</p>\n\n<pre><code>source = [val for val in values for _ in xrange(n)]\n</code></pre>\n\n<p>which avoids the creation of a temporary list and is maybe a bit more readable.</p>\n\n<hr>\n\n<pre><code>j = int(random() * (sourcelen - i)) + i\n</code></pre>\n\n<p>To get a random integer between <code>x</code> (inclusive) and <code>y</code> (exclusive), you can use <code>random.randrange(x,y)</code>, so the above can be written as:</p>\n\n<pre><code>j = randrange(i, len(source) - i)\n</code></pre>\n\n<p>(You'll also need to import <code>randrange</code> instead of <code>random</code> from the random module). This makes it more immediately obviously that <code>j</code> is a random number between <code>i</code> and <code>len(source) - i</code> and introduces less room for mistakes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T09:20:50.903", "Id": "419", "Score": "0", "body": "Alternatively: `source = [val for val in values for _ in xrange(n)]` which, for me, makes it more clear you're repeating values compared to creating a temporary list, multiplying it, and then iterating it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:33:23.913", "Id": "243", "ParentId": "219", "Score": "4" } } ]
{ "AcceptedAnswerId": "243", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-25T23:41:23.607", "Id": "219", "Score": "14", "Tags": [ "python", "random" ], "Title": "Quasi-random sequences: how to improve style and tests?" }
219
<p>I got this as an implementation of "get me the median of those values". But it sort of doesn't feel right (too long, too many branch points) so I thought I'll post it here to see what you think.</p> <pre><code>&lt;?php private function calculateMedian($aValues) { $aToCareAbout = array(); foreach ($aValues as $mValue) { if ($mValue &gt;= 0) { $aToCareAbout[] = $mValue; } } $iCount = count($aToCareAbout); sort($aToCareAbout, SORT_NUMERIC); if ($iCount &gt; 2) { if ($iCount % 2 == 0) { return ($aToCareAbout[floor($iCount / 2) - 1] + $aToCareAbout[floor($iCount / 2)]) / 2; } else { return $aToCareAbout[$iCount / 2]; } } elseif (isset($aToCareAbout[0])) { return $aToCareAbout[0]; } else { return 0; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-21T18:26:12.477", "Id": "30129", "Score": "0", "body": "`$iCount` in 1st iteration should be `$count`." } ]
[ { "body": "<p>I'm wondering if you can just compact the above to this:</p>\n\n<pre><code>private function calculateMedian($aValues) {\n $aToCareAbout = array();\n foreach ($aValues as $mValue) {\n if ($mValue &gt;= 0) {\n $aToCareAbout[] = $mValue;\n }\n }\n $iCount = count($aToCareAbout);\n if ($iCount == 0) return 0;\n\n // if we're down here it must mean $aToCareAbout\n // has at least 1 item in the array.\n $middle_index = floor($iCount / 2);\n sort($aToCareAbout, SORT_NUMERIC);\n $median = $aToCareAbout[$middle_index]; // assume an odd # of items\n\n // Handle the even case by averaging the middle 2 items\n if ($iCount % 2 == 0)\n $median = ($median + $aToCareAbout[$middle_index - 1]) / 2;\n\n return $median;\n}\n</code></pre>\n\n<p>I don't write PHP but from looking at the online manual for count:</p>\n\n<blockquote>\n <p>count() may return 0 for a variable\n that isn't set, but it may also return\n 0 for a variable that has been\n initialized with an empty array. Use\n isset() to test if a variable is set.</p>\n</blockquote>\n\n<p>But in your case, the function doesn't seem to care whether the array is empty or the variable isn't set -- 0 is returned in both cases. By checking what count returns we could eliminate some of the <code>if</code> branches.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T08:21:40.393", "Id": "352", "Score": "0", "body": "I don't like it returning 0 for empty `$aToCareAbout`. I would prefer `null` to be returned in such case. (Or perhaps an exception to be thrown?)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T08:26:03.323", "Id": "353", "Score": "0", "body": "@Mchl yeah that was one of the other points bothering me. The original code is using 0 to indicate some kind of problem. But a zero-filled array can have a valid median as well." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T08:43:22.247", "Id": "356", "Score": "2", "body": "It should be +1 for the average shouldn't it ? (Or for 2 element it will try to access [-1] ? Will provide a first iteration with all the feedback in it shortly." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T09:00:25.587", "Id": "357", "Score": "2", "body": "@edorian From looking at your original code, I assumed php arrays are 0-based, like C. So in the case of an array with 2 elements iCount is 2, middle_index would be 1, middle_index - 1 would be 0. Elements from these 2 indices are then averaged." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T09:03:54.133", "Id": "358", "Score": "2", "body": "@edorian: No, this is the correct approach. Two quick examples: **Odd number:** (3 elements, indices 0 to 2, expected = 1) Median is element `floor(3/2) == 1`. Pass. **Even number:** (4 elements, indices 0 to 3, expected = avg of 1 and 2) For 4 elements, it will use `floor(4/2) == 2`. Even amount of elements, so it uses element `2 - 1 = 1` as well. Median is average of elements 1 and 2. Pass." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T09:07:07.920", "Id": "359", "Score": "0", "body": "Thanks @Viktor and @Jonathan, must be temporary brain damage. It's a little embarrassing :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T11:37:46.743", "Id": "364", "Score": "0", "body": "@edorian: To err is human. Don't sweat it." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-26T03:37:38.067", "Id": "221", "ParentId": "220", "Score": "6" } }, { "body": "<p>The first part of your function filter out negative values. This has nothing to do with calculating the median itself, so should be moved away from this function. </p>\n\n<p>Way I would do it.</p>\n\n<p>Create <code>array_median()</code> function in a global scope (or a static method) like this:</p>\n\n<pre><code>/**\n * Adapted from Victor T.'s answer\n */\nfunction array_median($array) {\n // perhaps all non numeric values should filtered out of $array here?\n $iCount = count($array);\n if ($iCount == 0) {\n throw new DomainException('Median of an empty array is undefined');\n }\n // if we're down here it must mean $array\n // has at least 1 item in the array.\n $middle_index = floor($iCount / 2);\n sort($array, SORT_NUMERIC);\n $median = $array[$middle_index]; // assume an odd # of items\n // Handle the even case by averaging the middle 2 items\n if ($iCount % 2 == 0) {\n $median = ($median + $array[$middle_index - 1]) / 2;\n }\n return $median;\n}\n</code></pre>\n\n<p>This way we have generally available all purpose function, with naming consistent with core php functions.</p>\n\n<p>And your method would look like</p>\n\n<pre><code>/**\n * The name should probably be changed, to reflect more your business intent.\n */\nprivate function calculateMedian($aValues) {\n return array_median(\n array_filter(\n $aValues, \n function($v) {return (is_numeric($v) &amp;&amp; $v &gt;= 0);}\n // You can skip is_numeric() check here, if you know all values in $aValues are actually numeric \n )\n );\n}\n</code></pre>\n\n<p>Either within <code>calculateMedian()</code> or in the code that calls it, you should take care of catching the <code>DomainException</code> that can be thrown if the array is empty)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-26T08:39:39.397", "Id": "223", "ParentId": "220", "Score": "22" } }, { "body": "<p>Personally this is the way that I would build the function:</p>\n\n<pre><code>function calculateMedian($Values)\n{\n //Remove array items less than 1\n $Values = array_filter($Values,array($this,\"callback\"));\n\n //Sort the array into descending order 1 - ?\n sort($Values, SORT_NUMERIC);\n\n //Find out the total amount of elements in the array\n $Count = count($Values);\n\n //Check the amount of remainders to calculate odd/even\n if($Count % 2 == 0)\n {\n return $Values[$Count / 2];\n }\n\n return (($Values[($Count / 2)] + $Values[($Count / 2) - 1]) / 2);\n}\n</code></pre>\n\n<p>What changes have I done?</p>\n\n<ul>\n<li>I have used less variables, overwriting the <code>$Values</code> where needed</li>\n<li>Reduced the conditional statements to 1* from 2</li>\n<li>Made the code look more readable and understandable.</li>\n<li>I have however added a callback, which in turn removes the <code>foreach</code> and if statements but a logical check would have to be used in the callback. the callback would simple be a method in your class like so:\n<ul>\n<li><code>public function callback($value)\n{\nreturn $value &gt; 0;\n}</code></li>\n</ul></li>\n<li>Unfortunately as the native function <code>empty</code> is actually a language construct its not a valid callback, you can however use <code>return !empty($value);</code> within your callback method to also remove other entities such as <code>NULL</code>,<code>FALSE</code> etc</li>\n<li>This can be removed as stated, and placed outside the function.</li>\n</ul>\n\n<p>*Notes: I would advise you to have some kind of linear array check to make sure the arrays are based on an integer index, as our code assumes they are, a linear chack can be done like so:</p>\n\n<pre><code>if(array_keys($Values) !== range(0,($Count-1)))\n{\n return null;\n}\n</code></pre>\n\n<p>this would be added after the <code>$Count</code> value has come into play.</p>\n\n<p>Example test that I had used to test it was:</p>\n\n<pre><code>$values = array(\n 0,4,7,5,6,9,5,3,2,7,5,6,4,3,7\n);\necho calculateMedian($values);\n</code></pre>\n\n<p>which resulted in the correct answer of 5</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T19:42:07.707", "Id": "366", "Score": "3", "body": "I don't mean to nitpick, but is there a specific reason you capitalized (some of) the variable names? I think it's generally a good idea for answers to use the same variable naming conventions as the question (unless the question's naming convention contradicts the language's conventions)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T00:53:14.313", "Id": "404", "Score": "0", "body": "No reason, its just the way that I tend to write code, Im displaying the benefits of my logic, the OP would be able to change them accordingly as the capitalising is is just a naming convention I like to use." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T09:13:40.470", "Id": "417", "Score": "0", "body": "You have silently changed the meaning by converting >= 0 to > 0." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T09:17:51.690", "Id": "418", "Score": "0", "body": "Fred, I believe your on about the callback, are you saying that zero values should be within the calculation ?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T18:19:52.007", "Id": "225", "ParentId": "220", "Score": "2" } } ]
{ "AcceptedAnswerId": "223", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-26T00:28:19.200", "Id": "220", "Score": "28", "Tags": [ "php", "statistics" ], "Title": "Calculate a median" }
220
<p>According to the Doctrine <a href="http://www.doctrine-project.org/projects/orm/1.2/docs/manual/working-with-models/en#fetching-objects" rel="noreferrer">docs</a>, you should use Array hydration rather than record hydration when retrieving data for read-only purposes.</p> <p>Unfortunately, this means I have to use array syntax (as opposed to object syntax) to reference the data.</p> <pre><code>$q = Doctrine_Query::create() -&gt;from('Post p') -&gt;leftJoin('p.PostComment pc') -&gt;leftJoin('pc.User u') -&gt;where('p.post_id = ?', $id); $p = $q-&gt;fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY); ... foreach ($p['PostComment'] as $comment) { $this-&gt;Controls-&gt;Add(new CommentPanel($comment['text'], $comment['User']['nickname'], $comment['last_updated_ts'])); } </code></pre> <p>Maybe it's just me, but all of those string literals as array indexes are kinda scary. Does anyone have some ideas for cleaning this up?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T10:03:23.660", "Id": "360", "Score": "0", "body": "from what i understand if you would fetch an object you would to $comment->text; or would you do $comment->getText() ? (Not to familiar with the \"old/current\" doctrine ;) )" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T14:16:18.303", "Id": "365", "Score": "0", "body": "@edorian: It would be `$comment->text;`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T22:38:32.177", "Id": "374", "Score": "0", "body": "I believe you can use all three." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T08:40:51.857", "Id": "415", "Score": "0", "body": "I was trying to write a longer answer but it really bowls down to \"cast to stdClass (and thats already said now) if you don't like it\" but maybe i don't get your reasoning behind that looking \"scary\". The difference between -> and [''] shoudn't matter so much ?" } ]
[ { "body": "<p>Scary? In what way? I don't really get that.</p>\n\n<p>It's just syntax. If you really care, just cast the arrays as stdClass objects</p>\n\n<pre><code>foreach ( $p['PostComment'] as $comment )\n{\n $comment = (object) $comment;\n $this-&gt;Controls-&gt;Add( new CommentPanel(\n $comment-&gt;text\n , $comment-&gt;User-&gt;nickname\n , $comment-&gt;last_updated_ts\n ));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T08:38:28.693", "Id": "414", "Score": "0", "body": "He'd need to cast User to an object too, else it would be $comment->User[\"nickname\"]; But yeah, casting it was also in my mind" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T14:47:18.033", "Id": "437", "Score": "0", "body": "I guess I'm just used to other languages where a typo in a literal would not be caught until run time but a typo in a property name would be caught at compile time. But with a scripting language like PHP both will not be noticed until run time." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T20:53:38.343", "Id": "509", "Score": "2", "body": "If that's the concern, you could use define()s or constants to reference your fields, rather than string literals. But that's probably only making things worse. Object hydration may take a little more time and memory but unless you have problems with either, I'd still use it for the very reason you outline here." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:42:00.827", "Id": "247", "ParentId": "222", "Score": "5" } } ]
{ "AcceptedAnswerId": "247", "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T04:04:45.080", "Id": "222", "Score": "10", "Tags": [ "php", "doctrine" ], "Title": "Php/Doctrine array hydration" }
222
<p>I was trying to create a lock-free queue implementation in Java, mainly for personal learning. The queue should be a general one, allowing any number of readers and/or writers concurrently.</p> <p>Would you please review it, and suggest any improvements/issues you find?</p> <p>(<a href="https://stackoverflow.com/q/1634368/41283">Cross-post from StackOverflow</a>)</p> <pre><code>import java.util.concurrent.atomic.AtomicReference; public class LockFreeQueue&lt;T&gt; { private static class Node&lt;E&gt; { final E value; volatile Node&lt;E&gt; next; Node(E value) { this.value = value; } } private AtomicReference&lt;Node&lt;T&gt;&gt; head, tail; public LockFreeQueue() { // have both head and tail point to a dummy node Node&lt;T&gt; dummyNode = new Node&lt;T&gt;(null); head = new AtomicReference&lt;Node&lt;T&gt;&gt;(dummyNode); tail = new AtomicReference&lt;Node&lt;T&gt;&gt;(dummyNode); } /** * Puts an object at the end of the queue. */ public void putObject(T value) { Node&lt;T&gt; newNode = new Node&lt;T&gt;(value); Node&lt;T&gt; prevTailNode = tail.getAndSet(newNode); prevTailNode.next = newNode; } /** * Gets an object from the beginning of the queue. The object is removed * from the queue. If there are no objects in the queue, returns null. */ public T getObject() { Node&lt;T&gt; headNode, valueNode; // move head node to the next node using atomic semantics // as long as next node is not null do { headNode = head.get(); valueNode = headNode.next; // try until the whole loop executes pseudo-atomically // (i.e. unaffected by modifications done by other threads) } while (valueNode != null &amp;&amp; !head.compareAndSet(headNode, valueNode)); T value = (valueNode != null ? valueNode.value : null); // release the value pointed to by head, keeping the head node dummy if (valueNode != null) valueNode.value = null; return value; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T14:18:58.873", "Id": "434", "Score": "0", "body": "There's a race in getObject()'s head.get().next versus putObject()'s prevTailNode.next = newNode. I wish the codereview site had line numbers. After the tail.getAndSet(newNode) has occurred but before prevTailNode.next assignment has gone trhough, getObject may call head.get() and then read headNode.next which will be null at that moment, resulting in getObject() returning null incorrectly." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:10:20.043", "Id": "477", "Score": "0", "body": "@Ron I talk about how that behavior is strange in my answer, but it is at least thread-safe." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T19:52:28.577", "Id": "500", "Score": "0", "body": "@Craig Ok I see. getObject returning null is ok. I guess a performance drawback is whether the call to head.compareAndSet in getObject has any guarantees about making forward progress." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T20:45:38.703", "Id": "507", "Score": "1", "body": "@Ron That's true. Usually non-blocking structures are written to give better performance than blocking structures, but there's no guarantee that's the case here. Especially since the thread that's doing the CAS operations cannot help other threads make forward progress." } ]
[ { "body": "<p>Yes.</p>\n\n<ul>\n<li>The combination of volatile and compare-and-swap operations is enough to make sure that the Node objects are safely published.</li>\n<li>The compare-and-swap must be before the assignment to a <code>volatile</code> variable in both methods, so you're fine there. They do not need to happen atomically.</li>\n</ul>\n\n<p>The queue exhibits odd behavior. Let's say thread 1 stops in <code>putObject()</code> after the CAS but before the last assignment. Next thread 2 executes <code>putObject()</code> in its entirety. Next thread three calls <code>getObject()</code>, and it cannot see either of the first two objects, even though thread 2 is completely done. There's a small chain being built up in-memory. Only after thread 1 completes <code>putObject()</code> are both objects visible on the queue, which is somewhat surprising, and has weaker semantics than most non-blocking data structures.</p>\n\n<p>Another way of looking at the odd API is that it's nice to have a non-blocking <code>put()</code> but it's very strange to have a non-blocking <code>get()</code>. It means that the queue must be used with repeated polling and sleeping.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T13:45:35.190", "Id": "423", "Score": "0", "body": "Thanks for your comments. I didn't make the `value` field `final` to be able to set it to `null` to avoid a potential memory leak. (Check the last `if` statement in `getObject()`)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T13:47:36.780", "Id": "426", "Score": "0", "body": "As for the odd behavior, I agree with you, but that was a design decision to simplify the code and improve performance. I don't think it would matter if it's used for simple producer-consumer scenarios. What do you think?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:30:36.553", "Id": "486", "Score": "0", "body": "@Hosam I do think it's problematic on the consumer side." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T20:26:58.097", "Id": "505", "Score": "0", "body": "@Hosam: My rule of thumb is this: either `final` or `volatile`. If you won't make it `final`, at least make it `volatile`. (This is exactly what Craig said, and I want to reinforce it.)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-13T19:06:07.780", "Id": "1409", "Score": "0", "body": "@Craig: Thanks. Sorry for my late comment, but you probably know how hot it has been in Egypt during the past period. It's true that this queue would require repeated polling and sleeping. This is (IMHO) appropriate in scenarios where a simple message queue-like behavior is needed. Nevertheless, I like your idea about a non-blocking `get()`. I will think about how to implement it. Thanks again." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-13T19:08:12.770", "Id": "1410", "Score": "0", "body": "@Chris Jester-Young: I would have preferred to make it `final`, but I wanted to avoid a potential memory leak. I don't think it really matters, because it's only set twice: 1) in the constructor, and 2) when it's no longer accessible. Does this rationale make sense to you?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T05:18:47.980", "Id": "255", "ParentId": "224", "Score": "21" } }, { "body": "<p>I tweaked your code a little but I think your approach is good.</p>\n\n<p>As I alluded to in the comment, there's no guarantee of fairness between threads compareAndSetting the head, so a really unlucky thread could be stuck for a while if there are a lot of consumers.</p>\n\n<p>I don't think this data structure should hold nulls, since there's no way to distinguish between getting a null or getting from an empty queue, so I throw the NPE.</p>\n\n<p>I refactored the logic a bit in getObject to remove redundant null checks.</p>\n\n<p>And I renamed some vars to be hungarianlike.</p>\n\n<pre><code>import java.util.concurrent.atomic.AtomicReference;\n\npublic class LockFreeQueue&lt;T&gt; {\nprivate static class Node&lt;E&gt; {\n E value;\n volatile Node&lt;E&gt; next;\n\n Node(E value) {\n this.value = value;\n }\n}\n\nprivate final AtomicReference&lt;Node&lt;T&gt;&gt; refHead, refTail;\npublic LockFreeQueue() {\n // have both head and tail point to a dummy node\n Node&lt;T&gt; dummy = new Node&lt;T&gt;(null);\n refHead = new AtomicReference&lt;Node&lt;T&gt;&gt;(dummy);\n refTail = new AtomicReference&lt;Node&lt;T&gt;&gt;(dummy);\n}\n\n/**\n * Puts an object at the end of the queue.\n */\npublic void putObject(T value) {\n if (value == null) throw new NullPointerException();\n\n Node&lt;T&gt; node = new Node&lt;T&gt;(value);\n Node&lt;T&gt; prevTail = refTail.getAndSet(node);\n prevTail.next = node;\n}\n\n/**\n * Gets an object from the beginning of the queue. The object is removed\n * from the queue. If there are no objects in the queue, returns null.\n */\npublic T getObject() {\n Node&lt;T&gt; head, next;\n\n // move head node to the next node using atomic semantics\n // as long as next node is not null\n do {\n head = refHead.get();\n next = head.next;\n if (next == null) {\n // empty list\n return null;\n }\n // try until the whole loop executes pseudo-atomically\n // (i.e. unaffected by modifications done by other threads)\n } while (!refHead.compareAndSet(head, next));\n\n T value = next.value;\n\n // release the value pointed to by head, keeping the head node dummy\n next.value = null;\n\n return value;\n}\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T20:13:00.090", "Id": "503", "Score": "0", "body": "Same problem as the original code... value needs to be volatile." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:07:37.773", "Id": "516", "Score": "0", "body": "I claim it doesn't need to be volatile. Threads writing to and reading from the value field will have encountered memory fences via the AtomicReferences." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:42:56.267", "Id": "522", "Score": "0", "body": "Oh yeah! I need to read JCIP again!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-13T19:35:31.200", "Id": "1412", "Score": "0", "body": "Thanks. Throwing the NPE is a good idea, and removing the redundant `null` checks is a welcome addition. But as @Tino pointed out, the `assert` could fail in a race condition (http://codereview.stackexchange.com/questions/224/is-this-lock-free-queue-implementation-thread-safe/446#446)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T20:08:37.713", "Id": "324", "ParentId": "224", "Score": "3" } }, { "body": "<p>I don't like your 'put' routine. The 'odd behavior' others have noticed means the algorithm loses one of the main advantages of being 'lock-free': immunity from priority inversion or asynchronously-terminated threads. If a thread gets waylaid in the middle of a queue-write operation, the queue will be completely broken unless or until the queue finishes its work.</p>\n\n<p>The solution is to CompareAndSet the last node's \"next\" pointer before updating the \"tail\" pointer; if the \"last node\"'s \"next\" pointer is non-null, that means it's not the last node anymore and one must traverse links to find the real last node, repeat the CompareAndSet on it, and hope it's still the last node.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-13T19:13:01.347", "Id": "1411", "Score": "0", "body": "Thanks @supercat. Your point about asynchronously-terminated threads is certainly valuable, but I am not sure how your suggestion fixes it. Could you please explain it further with some code?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-14T00:48:16.383", "Id": "1414", "Score": "0", "body": "@Hosam: The real last item of the queue is the one whose \"next\" pointer is null. To add an item to the queue, make the real last item, i.e. the one whose \"next\" pointer is null, point to the new one. Although the queue keeps a \"last-item\" pointer, it won't always point to the very last item; it may point to an item which used to be the last item, but isn't any more. As long as code which attempts to add an item is prepared to search for the real last item, all that is required for correctness is that the \"last item\" pointer point somewhere within the queue." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-14T00:55:09.950", "Id": "1415", "Score": "0", "body": "@Hosam: Adding an item to the queue does two things: -1- It makes the real last item's \"next\" pointer point to the new item; -2- It tries to update the queue's \"last item\" pointer. If there are two simultaneous attempts to do step #1, the CompareExchange of one will succeed and the other will fail. The one whose CompareExchange fails will search for the new end of the queue and add itself after that. Note that the attempt to update the end-of-queue pointer is in a sense optional; if it never got updated, the queue would get slower and slower, but occasional failures are no problem." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T21:47:44.563", "Id": "388", "ParentId": "224", "Score": "4" } }, { "body": "<p>While OP's solution looks right for me, Ron's improvement invents a race condition:</p>\n\n<p>Thread 1 (in getObject()):</p>\n\n<pre><code>} while (!refHead.compareAndSet(head, next));\n\nT value = next.value;\n</code></pre>\n\n<p>Thread 1 is suspended here, so it did not yet execute</p>\n\n<pre><code>next.value = null;\n</code></pre>\n\n<p>We know that value!=null and refHead now is next, so refHead.get().value!=null</p>\n\n<p>Thread 2 (in getObject()):</p>\n\n<pre><code> head = refHead.get();\n assert head.value == null;\n</code></pre>\n\n<p>Here the assert bites even that everything is will be ok again after Thread 1 continues.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T02:19:54.223", "Id": "446", "ParentId": "224", "Score": "4" } }, { "body": "<p>Similar structure and operations for it to get lock free multi-producer single-consumer (MPSC) queue <a href=\"http://www.1024cores.net/home/lock-free-algorithms/queues/non-intrusive-mpsc-node-based-queue\" rel=\"nofollow\">described</a> by Dmitry Vyukov.</p>\n\n<p>I have used it as an internal queue for <a href=\"https://github.com/scalaz/scalaz/blob/scalaz-seven/concurrent/src/main/scala/scalaz/concurrent/Actor.scala#L34\" rel=\"nofollow\">Scalaz actors</a> to work with it in MPSC mode.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-30T05:55:42.897", "Id": "27956", "ParentId": "224", "Score": "2" } } ]
{ "AcceptedAnswerId": "255", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-26T11:12:35.660", "Id": "224", "Score": "48", "Tags": [ "java", "multithreading", "thread-safety", "locking", "lock-free" ], "Title": "Thread-Safe and Lock-Free - Queue Implementation" }
224
<p>In our production code, we cannot use Boost or C++0x. Formatting strings using <code>sprintf</code> or <code>stringstream</code> is annoying in this case, and this prompted me to write my own little <code>Formatter</code> class. I am curious if the implementation of this class or the use of it introduces any Undefined Behavior.</p> <p>In particular, is this line fully-defined:</p> <pre><code>Reject( Formatter() &lt;&lt; "Error Recieved" &lt;&lt; 42 &lt;&lt; " " &lt;&lt; some_code &lt;&lt; " '" &lt;&lt; some_msg &lt;&lt; "'"); </code></pre> <p>My belief is that it is OK, but I wanted peer-review.</p> <p>Three main points of concern:</p> <ol> <li>Is there a double-assignment within a single sequence point? Is it UB? </li> <li>Do I have a problem with the lifetime of temporaries?</li> <li>Does my <code>Formatter</code> class (or the intended use of it) introduce any UB?</li> </ol> <p>The <code>Formatter</code> class has both a (templatized) <code>operator&lt;&lt;</code> and an <code>operator std::string</code>. The intent is to use the <code>Formatter()</code> class as a temporary in place of a <code>std::string</code> parameter for any function taking a <code>const std::string&amp;</code>.</p> <p>Here is the class definition:</p> <pre><code>class Formatter { public: Formatter() {}; template&lt;class Field&gt; Formatter&amp; operator&lt;&lt;(Field f) { ss_ &lt;&lt; f; return *this; } operator std::string() const { return ss_.str(); } private: std::stringstream ss_; }; </code></pre> <p>And here is a complete test harness, including the above definition. You should be able to compile &amp; run as-is. Do you see any UB?</p> <pre><code>#include &lt;cstdlib&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;iostream&gt; class Formatter { public: Formatter() {}; template&lt;class Field&gt; Formatter&amp; operator&lt;&lt;(Field f) { ss_ &lt;&lt; f; return *this; } operator std::string() const { return ss_.str(); } private: std::stringstream ss_; }; void Reject(const std::string&amp; msg) { std::cout &lt;&lt; "Recieved Message: '" &lt;&lt; msg &lt;&lt; "'" &lt;&lt; std::endl; } int main() { const char&amp; some_code = 'A'; const char* some_msg = "Something"; Reject( Formatter() &lt;&lt; "Error Recieved" &lt;&lt; 42 &lt;&lt; " " &lt;&lt; some_code &lt;&lt; " '" &lt;&lt; some_msg &lt;&lt; "'"); } </code></pre>
[]
[ { "body": "<p>Looks fine. Don't worry too much and end up over-engineering a simple solution :)</p>\n\n<p>Edit:</p>\n\n<p>Actually, I would make the parameters to <code>operator&lt;&lt;</code> into const references.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T22:17:19.467", "Id": "373", "Score": "0", "body": "I agree! I was hoping there was no problem, because `Formatter` is a very small gizmo, indeed." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T22:12:59.910", "Id": "228", "ParentId": "226", "Score": "4" } }, { "body": "<p>Looks ok. The empty ctor is unnecessary; the compiler generated one will do just fine. \"Recieved\" should be spelled \"Received\" :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T22:24:55.993", "Id": "230", "ParentId": "226", "Score": "4" } }, { "body": "<p>I think you might be worried about temporary lifetime issues. (I know I have based on similar code.)</p>\n\n<p>The temporary object created as a parameter for <code>Reject</code> will have a lifetime bound to the expression it is created in. (It's in the C++ standard somewhere.) So even with your conversion operators returning values, they will all be destructed after the expression that contains <code>Reject</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T22:55:26.690", "Id": "378", "Score": "0", "body": "+1: I was also concerned about double-assignment within a single sequence point." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T22:29:10.570", "Id": "232", "ParentId": "226", "Score": "5" } }, { "body": "<h3>Just three comments:</h3>\n\n<ol>\n<li><p>I would remove the empty constructor.</p></li>\n<li><p>What about handling std::manipulators?</p></li>\n<li><p>Don't you want to pass field values by const reference?</p></li>\n</ol>\n\n<p>.</p>\n\n<pre><code> template&lt;class Field&gt; Formatter&amp; operator&lt;&lt;(Field const&amp; f)\n // ^^^^^^\n</code></pre>\n\n<h3>Your concerns:</h3>\n\n<blockquote>\n <ol>\n <li>Is there a double-assignment within a single sequence point? Is it UB? </li>\n </ol>\n</blockquote>\n\n<p>Don't see one.<br>\nLooks good.</p>\n\n<blockquote>\n <ol>\n <li>Do I have a problem with the lifetime of temporaries?</li>\n </ol>\n</blockquote>\n\n<p>No. Don't think so.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T03:43:27.183", "Id": "405", "Score": "0", "body": "What's the problem with manipulators? You can still use the templated insertion operator for them. `Formatter() << std::hex;`. Do you mean stuff like `Formatter().width(10)` ?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T05:24:55.867", "Id": "407", "Score": "0", "body": "@wilhelmtell: Actually I was thinking about std::endl. But that may be by design. Though the use of std::endl may not have much meaning in context with the Formatter object it may still confuse some users that are simply porting old code that this streamable object will not compile when used with std::endl." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T15:25:27.207", "Id": "447", "Score": "0", "body": "Manipulators will not work directly. You need to manually add support for them. Look at the [answer](http://codereview.stackexchange.com/questions/226/does-my-class-introduce-undefined-behavior/263#263) by Fred Nurk" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T19:40:08.413", "Id": "498", "Score": "0", "body": "@David Rodríguez - dribeas: Which is exactly why I mentioned it." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T12:15:48.070", "Id": "921", "Score": "0", "body": "York, I should have added some @wilhelmtell there. The comment was not about your answer, but rather about his comment. Sorry for the confusion :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T01:11:57.917", "Id": "250", "ParentId": "226", "Score": "7" } }, { "body": "<ul>\n<li>I'd use a <code>std::ostringstream</code> because you don't use (seem to need) the formatting capabilities of <code>std::istringstream</code>.</li>\n<li>What happens when formatting fails? Can you check for failure?</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T03:48:08.707", "Id": "252", "ParentId": "226", "Score": "5" } }, { "body": "<p>In addition to what's already been said, I would:</p>\n\n<ul>\n<li><p>Mark the stringstream as public. This won't affect most uses of your code, and can already be hacked around with a custom manipulator to get at the \"internal\" stream object, but it will enable those that need to access the internal stream (such as to avoid the string copy inherent in the stringstream interface), and know the specifics of their implementation that allow what they want, to do so. Of course, 0x move semantics allay much of this need, but are still Not Quite Here Yet™.</p></li>\n<li><p>Check the stream before returning the string; if it's in a failed state, throw an exception (or at least log the condition somewhere before returning a string). This is unlikely to occur for most uses, but if it does happen, you'll be glad you found out the stream is failed rather than screw with formatting while wondering why \"it just won't work\".</p></li>\n</ul>\n\n<p>Regarding double-assignment, there's no assignment at all. The sequence points should be mostly what people expect, but, exactly, it looks like:</p>\n\n<pre><code>some_function(((Formatter() &lt;&lt; expr_a) &lt;&lt; expr_b) &lt;&lt; expr_c);\n// 1 2 3\n</code></pre>\n\n<p>The operators order it as if it was function calls, so that:</p>\n\n<ul>\n<li>Formatter() and expr_a both occur before the insertion marked 1.</li>\n<li>The above, plus insertion 1, plus expr_b happen before insertion 2.</li>\n<li>The above, plus insertion 2, plus expr_c happen before insertion 3.</li>\n<li>Note this only limits in one direction: expr_c can happen after expr_a and before Formatter(), for example.</li>\n<li>Naturally, all of the above plus the string conversion occur before calling some_function.</li>\n</ul>\n\n<p>To add to the discussion on temporaries, all of the temporaries created are in the expression:</p>\n\n<pre><code>some_function(Formatter() &lt;&lt; make_a_temp() &lt;&lt; \"etc.\")\n// one temp another temp and so on\n</code></pre>\n\n<p>They will not be destroyed until the end of the full expression containing that some_function call, which means not only will the string be passed to some_function, but some_function will have already returned by that time. (Or an exception will be thrown and they will be destroyed while unwinding, etc.)</p>\n\n<p>In order to handle <a href=\"http://codepad.org/BIqNQyea\">all manipulators</a>, such as std::endl, <a href=\"http://codepad.org/NqXFei2o\">add</a>:</p>\n\n<pre><code>struct Formatter {\n Formatter&amp; operator&lt;&lt;(std::ios_base&amp; (*manip)(std::ios_base&amp;)) {\n ss_ &lt;&lt; manip;\n return *this;\n }\n Formatter&amp; operator&lt;&lt;(std::ios&amp; (*manip)(std::ios&amp;)) {\n ss_ &lt;&lt; manip;\n return *this;\n }\n Formatter&amp; operator&lt;&lt;(std::ostream&amp; (*manip)(std::ostream&amp;)) {\n ss_ &lt;&lt; manip;\n return *this;\n }\n};\n</code></pre>\n\n<p>I've used this pattern several times to wrap streams, and it's very handy in that you can use it inline (as you do) or create a Formatter variable for more complex manipulation (think a loop inserting into the stream based on a condition, etc.). Though the latter case is only important when the wrapper does more than you have it do here. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-20T11:49:35.473", "Id": "198610", "Score": "0", "body": "The danger is that `expr_c` can happen at the same time as `expr_a`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T08:06:57.033", "Id": "263", "ParentId": "226", "Score": "10" } } ]
{ "AcceptedAnswerId": "263", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-26T21:57:46.423", "Id": "226", "Score": "27", "Tags": [ "c++", "formatting" ], "Title": "Formatter class" }
226
<p>I'm creating some sort of "portfolio" website for my self (a ton of placeholder content right now...) and I was wondering if I could improve the semantics of the HTML<del>5</del> any further, especially the <code>article</code> stuff.</p> <p>I'm not completely sure if I should use <code>section</code> elements inside it. I read through a number of HTML5 "guides" and a few of the element specs, but they often have different positions on this.</p> <p>I think using sections would add to the semantics since the slides are a different "part/section" of the "article".</p> <p>Don't rant about the CSS; it's generated by LESS.</p> <p>The site can be viewed <a href="http://bonsaiden.no.de/" rel="nofollow">here</a>.</p> <p><strong>Manually formatted HTML</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;A Python Twitter Client | BonsaiDen&lt;/title&gt; &lt;link rel="shortcut icon" href="/images/favicon.ico"&gt; &lt;link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Ubuntu:regular,bold"&gt; &lt;link rel="stylesheet" href="/stylesheets/style.css"&gt; // will get copied to a local file sooner or later &lt;!--[if lt IE 9]&gt; &lt;script src="http://html5shim.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;/head&gt; &lt;body&gt; // the content &lt;article&gt; // quite some divs here &lt;div&gt; &lt;div id="content"&gt; // maybe use section? // gets replaced via ajax &lt;header data-page="/atarashii"&gt; &lt;h1 class="small"&gt;A Python Twitter Client&lt;/h1&gt; &lt;div class="external"&gt; &lt;a href="https://github.com/BonsaiDen/Atarashii"&gt;Go to Project &amp;#x27A4;&lt;/a&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; // always hate these clear things... &lt;/header&gt; &lt;div&gt; &lt;p&gt;A Twitter Client for GNOME...&lt;/p&gt; &lt;/div&gt; // ajax end &lt;/div&gt; &lt;div id="slideshow"&gt; // maybe use section? &lt;header&gt; &lt;h1 id="slideTitle"&gt;[SlideShowItem Title]&lt;/h1&gt; &lt;/header&gt; &lt;div id="slideContent"&gt; &lt;p&gt;[Slideshow Image]&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/article&gt; &lt;header&gt; // navigation, surprise! &lt;nav&gt; // really happy with this &lt;ul&gt; &lt;li class="left"&gt; &lt;h1&gt;Projects&lt;/h1&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="/garden"&gt;JavaScript Garden&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/shooter"&gt;NodeGame: Shooter&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/atarashii" class="active"&gt;Atarashii&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;h1&gt;Code&lt;/h1&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="/neko"&gt;neko.js&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/bison"&gt;BiSON.js&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;h1&gt;Web&lt;/h1&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="/stackoverflow"&gt;Stack Overflow&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/github"&gt;GitHub&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/website"&gt;The Website&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="right"&gt; &lt;h1&gt;ME&lt;/h1&gt; &lt;ul class="info"&gt; &lt;li&gt;&lt;a href="/me"&gt;Ivo Wetzel&lt;/a&gt;&lt;/li&gt; &lt;li class="simple"&gt; // div div div :/ &lt;div&gt; &lt;div id="picture"&gt; &lt;img src="images/snufkin.png" alt="Ivo Wetzel"/&gt; &lt;a href="/me"&gt;&lt;/a&gt; &lt;/div&gt; &lt;ul&gt; &lt;li class="first"&gt;&lt;a href="http://twitter.com/BonsaiDen"&gt;Twitter&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="mailto: [email protected]"&gt;E-Mail&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/header&gt; // no real content so far but a background image thingy &lt;footer&gt;&lt;/footer&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="/javascripts/page.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:30:03.630", "Id": "387", "Score": "1", "body": "Ah! Lowercase your doctype, please!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:32:40.620", "Id": "388", "Score": "0", "body": "@David I'm using jade templates (so I blame those), but a good spot :) Gonna fix that." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:52:39.337", "Id": "393", "Score": "0", "body": "Another comment,\n\nWhy do you have\n\n`<article><div>content</div><article>`\n\nYou should be able to get rid of the `<div></div>` with no side effects." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T00:08:33.337", "Id": "398", "Score": "0", "body": "@Hailwood There's a very sublte shadow fade at the top of the page and I can't get that to span over the complete page without the extra div, unless I make a header just for that and get rid of the other header." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T05:47:27.547", "Id": "50265", "Score": "0", "body": "@DavidMurdoch may I know why lowercase doctype ? I thought its case insensitive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T14:08:06.400", "Id": "50292", "Score": "0", "body": "Because uppercase is ugly, and I'm pedantic. Oh, and might save a byte or two when GZIPping. :-)" } ]
[ { "body": "<p>In my opinion A <em>section</em> element is basically an <em>important <strong>sub</strong> div</em> by this I mean,\nA section element is used to designate a notable division in your content.</p>\n\n<p>One of the best ways I have found to think about if you should use a certain element in a certain place is: </p>\n\n<p>Imagine you are using a screen reader like a blind person.\nThey cannot see images or color, so the fact that you have a different background for each part of you content makes no difference to them.</p>\n\n<p>But,\nIf suddenly the screen reader starts reading out \"<em>new section</em>\" then that makes a more sense doesn't it?</p>\n\n<p>So, in my opinion.</p>\n\n<p>You should not replace your content or slideshow div with a section.</p>\n\n<p>a section should be used inside of your content div.</p>\n\n<p>Although,</p>\n\n<p>This may be nit picking,\nbut does having a content div not take the place of where an article element should be?</p>\n\n<p><hr />\nDoes anyone else find that w3schools is full of C***?</p>\n\n<blockquote>\n <p><strong>The <code>&lt;article&gt;</code> tag defines external content.</strong><br>\n The external content could be a news-article from an external provider, or a text from a web log (blog), or a text from a forum, or any other content from an external source.</p>\n</blockquote>\n\n<p>In reality if this was the case they would have called the tag <code>&lt;external&gt;</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:26:21.377", "Id": "386", "Score": "0", "body": "The last point is a good one, problem is, the slides are more or less part of the article as the change with the article to give some overview of the project, so the should be contained in the article I guess. Maybe I could place same inside a `figure` element and make the title a `figcaption`, would that make more sense?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:18:50.440", "Id": "241", "ParentId": "239", "Score": "2" } }, { "body": "<p><code>&lt;div class=\"clear\"&gt;&lt;/div&gt;</code> can and should be replaced by the magnificent clearfix solution</p>\n\n<p>Add this to the END of your css:</p>\n\n<pre><code>/* &gt;&gt; The Magnificent CLEARFIX: http://j.mp/bestclearfix */\n.clearfix:before, .clearfix:after { content: \"\\0020\"; display: block; height: 0; visibility: hidden; }\n.clearfix:after { clear: both; }\n/* fix clearfix: blueprintcss.lighthouseapp.com/projects/15318/tickets/5-extra-margin-padding-bottom-of-page */\n.clearfix { zoom: 1; }\n</code></pre>\n\n<p>Then just add <code>class=\"clearfix\"</code> to any container that has floated elements.</p>\n\n<p>You should also check out <a href=\"http://html5boilerplate.com/\" rel=\"nofollow\">http://html5boilerplate.com/</a> if you haven't already.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:56:03.743", "Id": "394", "Score": "0", "body": "Hm, googled a bit about the float stuff and as it turns out I can also use a simple `overflow: auto` in my case, which seems to work fine so far (only used twice). Do you know of any problems with this solution?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T00:15:02.607", "Id": "399", "Score": "0", "body": "I did run into an issue with using `overflow:auto` once before but I can't remember what it was. There is also [this](http://www.impressivewebs.com/overflow-hidden-problem/). I always use `.clearfix` now, just in case." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T00:22:48.657", "Id": "400", "Score": "0", "body": "I see, I switched to `.clearfix` now." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:36:32.237", "Id": "244", "ParentId": "239", "Score": "2" } }, { "body": "<p>Your \"the content\" article tag should probably be an Aside.</p>\n\n<p>Mark Pilgrim's <a href=\"http://diveintohtml5.info/semantics.html\" rel=\"nofollow\"><strong>Dive Into HTML5</strong></a> recommends for Article tags:</p>\n\n<blockquote>\n <p>The article element represents a\n component of a page that consists of a\n self-contained composition in a\n document, page, application, or site\n and that is intended to be\n independently distributable or\n reusable, e.g. in syndication. This\n could be a forum post, a magazine or\n newspaper article, a Web log entry, a\n user-submitted comment, an interactive\n widget or gadget, or any other\n independent item of content.</p>\n</blockquote>\n\n<p>and for Aside tags:</p>\n\n<blockquote>\n <p>The aside element represents a section\n of a page that consists of content\n that is tangentially related to the\n content around the aside element, and\n which could be considered separate\n from that content. Such sections are\n often represented as sidebars in\n printed typography. The element can be\n used for typographical effects like\n pull quotes or sidebars, for\n advertising, for groups of nav\n elements, and for other content that\n is considered separate from the main\n content of the page.</p>\n</blockquote>\n\n<p>I believe ID=\"content\" should probably be a section as you proposed.</p>\n\n<p>In my opinion, he gives the best explanations for when and where each tag should be used.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:50:45.843", "Id": "392", "Score": "0", "body": "+1 Best answer yet.\nBased off your description of an aside, could the slideshow not also be considered an aside?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-26T23:57:00.827", "Id": "395", "Score": "0", "body": "Indeed the `aside` makes more sense here, I'll replace the article element with it then. @Hailwood I'm wondering about that, right now I'm planning on use a `figure` and a `figcaption` for that (the slides seem to match the description of the element that was given in the spec)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-26T23:40:57.817", "Id": "246", "ParentId": "239", "Score": "8" } }, { "body": "<p>Looking through the code, one of the no-brainers for me that jump out immediately is the the separation of the profile anchor and image. The overlay effect is important, obviously, but this can be achieved much more cleanly with a bit of CSS elbow grease: </p>\n\n<pre><code>a {\n background: #fff;\n display: block;\n height: 128px;\n width: 128px;\n}\n\na img:hover {\n opacity: 0.9;\n}\n</code></pre>\n\n<p><sup>See: <a href=\"http://www.jsfiddle.net/yijiang/Tv7AP/\" rel=\"nofollow\">http://www.jsfiddle.net/yijiang/Tv7AP/</a></sup></p>\n\n<hr>\n\n<p>Looking at the code, it <em>seems like</em> the only reason why you have a <code>div#navigation &gt; a</code> structure is for the background 'shadow'. If that is the case, you can easily get rid of the outer <code>div</code> by using either <code>box-shadow</code> or a 1px wide background image repeated along the y axis with some padding: </p>\n\n<pre><code>nav {\n -moz-box-shadow: 0 3px 0 rgba(0, 0, 0, 0.3), 0 -3px 0 rgba(0, 0, 0, 0.3);\n -webkit-box-shadow: 0 3px 0 rgba(0, 0, 0, 0.3), 0 -3px 0 rgba(0, 0, 0, 0.3);\n box-shadow: 0 3px 0 rgba(0, 0, 0, 0.3), 0 -3px 0 rgba(0, 0, 0, 0.3);\n}\n</code></pre>\n\n<hr>\n\n<p>Additionally, seeing <code>li class=\"right\"</code> makes me slightly sad, but seeing <code>li class=\"left\"</code> makes me sadder still - since the <em>only</em> reason you're using the <code>left</code> class is to avoid double borders (the right class is to give the profile section a bit more space, apparently), you can really using only one class:</p>\n\n<pre><code>nav ul li {\n border-right: 4px solid #052C4F;\n}\n\nnav ul li.right {\n border-right: 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T13:55:57.163", "Id": "428", "Score": "0", "body": "Also, just to nitpick, but isn't `a { cursor: pointer; }` a little unnecessary? ;)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:45:38.010", "Id": "491", "Score": "0", "body": "Oh, yes guess that's left in from the early stages. The img hover thing is ingenious; I've put that in. As for the last one, I tried to change it but I always had some strange offsets in there which I could not get rid of, so I'll leave the 2/2 border for now." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-12T23:16:51.657", "Id": "1390", "Score": "0", "body": "@Ivo you asked a question about HTML5 semantics and the answer you selected is only about CSS. The question and answer should be related so it helps people who are looking for the answer to the question. Stack answers help more than just asker. You should edit your question." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T13:39:23.010", "Id": "271", "ParentId": "239", "Score": "2" } }, { "body": "<p>About your \"Updated HTML\":</p>\n\n<h2><code>meta</code>-<code>charset</code> before <code>title</code></h2>\n\n<p>You should place the <code>meta</code> element with the <code>charset</code> attribute as first element in <code>head</code>; otherwise it might not be used for the <code>title</code> element.</p>\n\n<pre><code> &lt;meta charset=\"utf-8\"&gt;\n &lt;title&gt;Coding. Clean and Functional. | BonsaiDen&lt;/title&gt;\n</code></pre>\n\n<h2>Favicon</h2>\n\n<p>You could use <code>icon</code> instead of <code>shortcut icon</code> (still allowed for historic reasons, though).</p>\n\n<h2>Outline</h2>\n\n<p>A site heading is missing. Add a <code>h1</code> (containg the site name and/or site logo), probably in your <code>&lt;header&gt;&lt;/header&gt;</code>.</p>\n\n<h2>No need to use <code>header</code></h2>\n\n<p>If your <code>header</code> elements only contain a heading (<code>h1</code>-<code>h6</code>), you may omit <code>header</code> altogether. It's only useful if you add additional introductory content. However, you may keep them for consistency, of course.</p>\n\n<h2>A heading for <code>nav</code></h2>\n\n<p>If you like to structure your links in <code>nav</code> with headings, you should give it a one level higher heading like \"Navigation\" (<code>h1</code>). Then use <code>h2</code> for the other headings (or use <code>section</code> elements inside, each with <code>h1</code>). You shouldn't use a <code>ul</code> for the whole navigation, instead use a new <code>ul</code> for each sub-section.</p>\n\n<pre><code>&lt;nav&gt;\n &lt;h1&gt;Navigation&lt;/h1&gt;\n\n &lt;h2&gt;Projects&lt;/h2&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"/garden\"&gt;JavaScript&amp;nbsp;Garden&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"/shooter\"&gt;NodeGame:&amp;nbsp;Shooter&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"/atarashii\"&gt;Atarashii&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n\n &lt;h2&gt;Code&lt;/h2&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"/neko\"&gt;neko.js&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"/bison\"&gt;BiSON.js&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n\n &lt;h2&gt;Web&lt;/h2&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"/stackoverflow\"&gt;Stack&amp;nbsp;Overflow&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"/github\"&gt;GitHub&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"/website\"&gt;The&amp;nbsp;Website&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n\n &lt;h1&gt;ME&lt;/h1&gt;\n &lt;ul class=\"info\"&gt;\n &lt;li&gt;&lt;a href=\"/me\" class=\"\"&gt;Ivo Wetzel&lt;/a&gt;&lt;/li&gt;\n &lt;li class=\"simple\"&gt;&lt;a id=\"picture\" href=\"/me\" class=\"\"&gt;&lt;img src=\"images/snufkin.png\" alt=\"Ivo Wetzel\"&gt;&lt;/a&gt;\n &lt;ul&gt;\n &lt;li class=\"first\"&gt;&lt;a href=\"http://twitter.com/BonsaiDen\"&gt;Twitter&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"mailto:[email protected]\"&gt;E-Mail&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n\n&lt;/nav&gt;\n</code></pre>\n\n<p>However, I think your Twitter and E-Mail links are not part of the major navigation, so you should better move them to the site footer.</p>\n\n<h2>Main content?</h2>\n\n<p>Which is your main content of the page? Is it <code>#content</code> (\"Coding. Clean and Functional.\")? If so, why is it in <code>aside</code>? You shouldn't enclose it in <code>aside</code>! Use <code>section</code> as a direct child of <code>body</code> instead (or <code>article</code>, if applicable).</p>\n\n<p>If the slideshow is part of your main content, you shouldn't use <code>aside</code> for it either.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-03T03:46:22.833", "Id": "18170", "ParentId": "239", "Score": "3" } } ]
{ "AcceptedAnswerId": "271", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-26T22:57:09.310", "Id": "239", "Score": "16", "Tags": [ "html", "twitter" ], "Title": "Twitter client portfolio website" }
239
<p>How can I clean this up?</p> <pre><code>std::wstring LinkResolve::ResolveLink( const std::wstring&amp; source ) const { HRESULT errorCheck; wchar_t linkTarget[MAX_PATH]; wchar_t expandedTarget[MAX_PATH]; wchar_t arguments[INFOTIPSIZE]; ATL::CComPtr&lt;IPersistFile&gt; ipf; errorCheck = ipf.CoCreateInstance(CLSID_ShellLink, 0, CLSCTX_INPROC_SERVER); if (!SUCCEEDED(errorCheck)) { throw _com_error(errorCheck); } errorCheck = ipf-&gt;Load(source.c_str(), 0); ATL::CComPtr&lt;IShellLink&gt; shellLink; errorCheck = ipf-&gt;QueryInterface(&amp;shellLink); if (!SUCCEEDED(errorCheck)) { throw _com_error(errorCheck); } errorCheck = shellLink-&gt;Resolve(0, SLR_NO_UI); if (!SUCCEEDED(errorCheck)) { throw _com_error(errorCheck); } errorCheck = shellLink-&gt;GetPath(linkTarget, MAX_PATH, 0, SLGP_RAWPATH); if (!SUCCEEDED(errorCheck)) { throw _com_error(errorCheck); } ExpandEnvironmentStringsW(linkTarget, expandedTarget, MAX_PATH); errorCheck = shellLink-&gt;GetArguments(arguments, INFOTIPSIZE); if (SUCCEEDED(errorCheck)) { return std::wstring(expandedTarget) + L" " + arguments; } else { return expandedTarget; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T20:14:17.250", "Id": "602", "Score": "1", "body": "This makes me think of Haskell's maybe monad, but I don't think that will help you. Still this would totally work with it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T06:29:42.170", "Id": "43462", "Score": "0", "body": "@Tyr: Or C++14's optional<T>. :)" } ]
[ { "body": "<p>If I find my self writing the same thing over and over again I usually put it in a function somewhere. Even if that function in your case is as simple as this:</p>\n<pre><code>void check(HRESULT result) {\n if (FAILED(result)) {\n throw _com_error(result);\n }\n}\n</code></pre>\n<p>I think the code looks fairly straight forward if you reuse your error check code. I'm not familiar with the API that you are using, so I can't comment on if there is another way to use it that might result in cleaner code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T06:35:44.480", "Id": "553", "Score": "0", "body": "May I ask you to replace `!SUCCEEDED` with `FAILED`? The latter evaluates exactly to the same as `!SUCCEEDED`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-01-27T07:40:39.877", "Id": "260", "ParentId": "259", "Score": "19" } }, { "body": "<p>Personally, I'd write a simple function:</p>\n\n<pre><code>void ThrowOnFail( HRESULT hrcode )\n{\n if (FAILED(hrcode))\n throw _com_error(hrcode);\n}\n</code></pre>\n\n<p>Then the function calls become:</p>\n\n<pre><code>ThrowOnFail( ipf.CoCreateInstance(CLSID_ShellLink, 0, CLSCTX_INPROC_SERVER) );\nThrowOnFail( ipf-&gt;Load(source.c_str(), 0) );\nATL::CComPtr&lt;IShellLink&gt; shellLink;\nThrowOnFail( ipf-&gt;QueryInterface(&amp;shellLink) );\nThrowOnFail( shellLink-&gt;Resolve(0, SLR_NO_UI) );\nThrowOnFail( shellLink-&gt;GetPath(linkTarget, MAX_PATH, 0, SLGP_RAWPATH) );\n</code></pre>\n\n<p>Incidentally, you missed a check for <code>errorCheck</code> after <code>Load</code>. This becomes easier to spot with a check function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T13:58:35.347", "Id": "429", "Score": "0", "body": "Would it be possible, or reasonable, to merge the whole code block into one ThrowOnFail(...); including the CComPtr? That would reduce code duplication as well. Not extremely familiar with C++ and CComPtr." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T15:16:15.880", "Id": "444", "Score": "0", "body": "@WernerCD: No, that would not be possible. (Besides, with all those method calls you'd have a 500 character line!)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T15:19:16.637", "Id": "446", "Score": "1", "body": "Err... You know this is really why I shouldn't write code at 3AM :sigh:." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T17:48:07.167", "Id": "469", "Score": "0", "body": "Question: Does the error returned in this positively identify where the error came from?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-27T07:41:45.250", "Id": "261", "ParentId": "259", "Score": "56" } }, { "body": "<p>At least when using DirectX, I use a macro.</p>\n\n<pre><code>#define D3DCALL(a) { auto __ = a; if (FAILED(__)) DXTrace(__FILE__, __LINE__, __, WIDEN(#a), TRUE); }\n</code></pre>\n\n<p>You could get fancier and use a type with an operator=(HRESULT) to make the check.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T08:27:36.313", "Id": "411", "Score": "1", "body": "Why an everywhere-reserved name for the local variable? I'd name it _local_D3DCALL (which is reserved in the root namespace scope but not elsewhere) or similar. This macro is a good candidate for calling an (inline) function, passing (a), \\_\\_FILE\\_\\_, \\_\\_LINE\\_\\_, and #a." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T11:34:39.547", "Id": "420", "Score": "0", "body": "No idea, it's been a long time since I wrote it, it's just a sample." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T15:51:23.933", "Id": "452", "Score": "0", "body": "Some macros just for you! -> http://codereview.stackexchange.com/questions/281/the-same-if-block-over-and-over-again-oh-my-part-2-now-the-macro-monster-got :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T07:42:57.910", "Id": "262", "ParentId": "259", "Score": "6" } }, { "body": "<p>Error checks are not all the same.\nsometimes you act upon special returned HResults. sometimes there is an ELSE.\nsometime you want to log the error,sometime you don't..</p>\n\n<p>Also - although highly unlikely to be relevant in the com/atl world - calling a function has it's performance costs.</p>\n\n<p>so I prefer using if after the call, rather than calling a function.\nHow much do you save ? typing 10 chars ?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T08:24:30.213", "Id": "410", "Score": "6", "body": "The example in the question is very clear that it's the same code over and over. Not functionalising it merely creates a maintenance headache. Should the need arise to handle a specific case differently then you write specific code for it. But to use that as an excuse to not write the general function in the first place is inefficient and IMO ill-advised." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T11:50:19.833", "Id": "421", "Score": "0", "body": "if this is c++, you can always set the method inline or use a macro with the same functionality" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T14:06:37.133", "Id": "430", "Score": "0", "body": "Don't use a macro. You lose all type safeness. That's the reason for inline functions/methods." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:49:05.547", "Id": "493", "Score": "2", "body": "@MarkLoesser - There are times when macros are the right tool for the job. This is one of those times. The __FILE__ and __LINE__ expansions are very helpful in troubleshooting and would be lost if you used an inline function or method." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T08:14:40.007", "Id": "265", "ParentId": "259", "Score": "1" } }, { "body": "<p>I think you can do much of the same by using <a href=\"http://msdn.microsoft.com/en-us/library/h31ekh7e.aspx\" rel=\"nofollow\">Compiler com support</a> here is an example.</p>\n\n<pre><code>#import \"CLSID:lnkfile\" //use the clsid of the ShellLink class.\n\nIPersistFilePtr ptr = IPersistFilePtr.CreateInstance(...);\n</code></pre>\n\n<p><code>_com_ptr_t::CreateInstance()</code> will throw an exception (of type <code>_com_error</code> if the call fails)</p>\n\n<p>All other ifs in your code can be replaced by using the smart pointers generated by #import. I know I am a little skimpy on details but it has been a long time since I have touched COM.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T15:54:53.430", "Id": "453", "Score": "0", "body": "Not true according to [this](http://msdn.microsoft.com/en-us/library/k2cy7zfz.aspx); `_com_ptr_t::CreateInstance()` seems to return a `HRESULT`, and has a `throw ()` specification." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T13:59:01.980", "Id": "272", "ParentId": "259", "Score": "1" } }, { "body": "<p>I remember seeing something like this before:</p>\n\n<pre><code>class XHR\n{\npublic:\n XHR() {};\n ~XHR() {};\n\n operator HRESULT() { return hr };\n\n HRESULT&amp; operator =(const HRESULT&amp; rhs)\n {\n hr = rhs;\n if (FAILED(hr)\n throw _com_error(hr);\n }\n\nprivate:\n HRESULT hr;\n}\n</code></pre>\n\n<p>Then you can write:</p>\n\n<pre><code>std::wstring LinkResolve::ResolveLink( const std::wstring&amp; source ) const\n{\n XHR errorCheck; // instead of HRESULT errorCheck\n\n wchar_t linkTarget[MAX_PATH];\n wchar_t expandedTarget[MAX_PATH];\n wchar_t arguments[INFOTIPSIZE];\n ATL::CComPtr&lt;IPersistFile&gt; ipf;\n\n\n errorCheck = ipf.CoCreateInstance(CLSID_ShellLink, 0, CLSCTX_INPROC_SERVER);\n errorCheck = ipf-&gt;Load(source.c_str(), 0);\n\n ATL::CComPtr&lt;IShellLink&gt; shellLink;\n\n errorCheck = ipf-&gt;QueryInterface(&amp;shellLink);\n errorCheck = shellLink-&gt;Resolve(0, SLR_NO_UI);\n errorCheck = shellLink-&gt;GetPath(linkTarget, MAX_PATH, 0, SLGP_RAWPATH);\n\n ExpandEnvironmentStringsW(linkTarget, expandedTarget, MAX_PATH);\n\n try {\n errorCheck = shellLink-&gt;GetArguments(arguments, INFOTIPSIZE);\n return std::wstring(expandedTarget) + L\" \" + arguments;\n }\n catch (const XHR&amp;)\n {\n return expandedTarget;\n }\n}\n</code></pre>\n\n<p>So anytime an HRESULT that indicates failure, it will automatically convert it into a _com_error for you, and throw it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-14T08:54:56.313", "Id": "4518", "Score": "1", "body": "This is interesting (therefore I will +1 you), but if you were to ignore the type of `errorCheck` it would look as if you were ignoring errors. I think I would favor an approach that seems more explicit if you are looking at statements and merely glancing over the types." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-11T18:40:43.477", "Id": "2917", "ParentId": "259", "Score": "4" } } ]
{ "AcceptedAnswerId": "261", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-27T07:26:21.437", "Id": "259", "Score": "38", "Tags": [ "c++", "error-handling", "atl" ], "Title": "Resolving a link" }
259
<p>I'm trying to design a well defined yet simple interface for the unit of work and repository patterns. My UoW's are exposed to services and services then "get repositories" that it needs to query. I know returning <code>IQueryable&lt;T&gt;</code> for repositories is a religious war. Because repositories are only exposed to the service, all queries are performed inside the service and therefore I can test the queries. Is there anything I should change for these interfaces? All criticisms are greatly appreciated!</p> <pre><code>public interface IUnitOfWork : IDisposable { bool IsActive { get; } bool WasCommitted { get; } /// &lt;summary&gt; /// Commits all changes made on the unit of work. /// &lt;/summary&gt; void Commit(); bool WasRolledBack { get; } /// &lt;summary&gt; /// Rolls back all changes made on the unit of work. /// &lt;/summary&gt; void Rollback(); /// &lt;summary&gt; /// Returns an instance of an entity with the specified key that is attached to the unit of work without /// loading the entity from a repository. /// &lt;/summary&gt; /// &lt;param name="id"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; T Load&lt;T&gt;(int id) where T : class; void Attach&lt;T&gt;(T entity) where T : class, IIdentifiable; void Detach&lt;T&gt;(T entity) where T : class; IRepository&lt;T&gt; GetRepository&lt;T&gt;() where T : class; } public interface IRepository&lt;T&gt; where T : class { IUnitOfWork UnitOfWork { get; } void Add(T entity); void Remove(T entity); /// &lt;summary&gt; /// Returns an instance of an entity with the specified key that is attached to the unit of work by loading /// the entity from the repository. /// &lt;/summary&gt; /// &lt;param name="id"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; T Get(int id); IQueryable&lt;T&gt; All(); } </code></pre>
[]
[ { "body": "<p>Your interface breaks the <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow\">Law of Demeter</a>. Or said simply I cannot use <code>IUnitOfWork UnitOfWork { get; }</code> on <code>IRespository</code> without understanding <code>IUnitOfWork</code>.</p>\n\n<p>I would change IRespository too</p>\n\n<pre><code>public interface IRepository&lt;T&gt;\n where T : class\n{\n\n bool IsActive { get; }\n\n bool WasCommitted { get; }\n\n /// &lt;summary&gt;\n /// Commits all changes made on the unit of work.\n /// &lt;/summary&gt;\n void Commit();\n\n bool WasRolledBack { get; }\n\n /// &lt;summary&gt;\n /// Rolls back all changes made on the unit of work.\n /// &lt;/summary&gt;\n void Rollback();\n\n /// &lt;summary&gt;\n /// Returns an instance of an entity with the specified key that is attached to the unit of work without\n /// loading the entity from a repository.\n /// &lt;/summary&gt;\n /// &lt;param name=\"id\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n T Load&lt;T&gt;(int id)\n where T : class;\n\n void Attach&lt;T&gt;(T entity)\n where T : class, IIdentifiable;\n\n void Detach&lt;T&gt;(T entity)\n where T : class;\n\n IRepository&lt;T&gt; GetRepository&lt;T&gt;()\n where T : class;\n\n void Add(T entity);\n\n void Remove(T entity);\n\n /// &lt;summary&gt;\n /// Returns an instance of an entity with the specified key that is attached to the unit of work by loading\n /// the entity from the repository.\n /// &lt;/summary&gt;\n /// &lt;param name=\"id\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n T Get(int id);\n\n IQueryable&lt;T&gt; All();\n}\n</code></pre>\n\n<p>Notice how it is a copy of IUnitOfWork, is UnitOfWork really needed. </p>\n\n<p>How did you create the interface?</p>\n\n<p>This is where you should do TDD. Write the test first about what you want the code to do. Then your interface should be created in order to accomplish the test. </p>\n\n<p>For example if you call the method <code>Rollback();</code> and cannot write a test were <code>WasRollbacked</code> property was used, they you might not need the property.</p>\n\n<p>Do not put in more than needed to any interface. They interface becomes noise. I would recommend reading <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow\">Clean Code by Robert Martin</a> to understand more of these ideas in a in depth way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:48:16.300", "Id": "492", "Score": "1", "body": "I've read clean code. I'm not really sure how this even makes sense. The repository pattern is strictly responsible for being an interface to the data layer. Having `IUnitOfWork` exposed as a property on the repository might not really make sense, but I had just left it there. Putting these methods on the repository interface just doesn't make sense." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T17:52:10.953", "Id": "302", "ParentId": "276", "Score": "0" } }, { "body": "<p>I don't remember exactly where I got my implementation, but a lot of it is borrowed from the Spring Framework...</p>\n\n<p>The only three methods that my IUnitOfWork interface exposes are Initialize(), Commit(), and Rollback(). Then I inherit from that for an INhibernateUnitOfWork, which simply exposes the NHibernate Session via a property as well... I guess this part may depend on what you are using for the persistence storage mechanism...</p>\n\n<p>But what it allows me to do in my repository class then is to simply take in the unit of work as an injectable dependency. Essentially, each of my Get(id), Load(id), Find(), Save(), Update(), etc. methods just make a call against the Repository.UnitOfWork.Session property.</p>\n\n<p>In essence, it's really close to what you've already implemented... Not sure why you want the GetRepository method, but you may have some use case for that which I do not. For me, my UnitOfWork is Request lifetime object whose Initialize() and Commit() / Rollback() functionality is handled by an HTTP module hooking the BeginRequest and EndRequest events. That is, the UnitOfWork instance is only ever touched by said HTTP Module, and by the repositories that simply use it to get a reference to the current Session object.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:03:43.257", "Id": "328", "ParentId": "276", "Score": "0" } }, { "body": "<p>I think your interfaces are mostly well-defined, with a couple exceptions:</p>\n\n<p>I don't think Load, Attach and Detach should be members of IUnitOfWork, but rather IRepository. It seems that the repository that manages objects of type T would be the best place to place methods that acts on that type.</p>\n\n<p>The UnitOfWork property on IRepository does not belong there. Things that modify one repository shouldn't be allowed to go and get other repositories to modify on their own. If they need them, pass them in explicitly. Otherwise, you're hiding from potential callers the fact that your implementation actually depends on more than just the one repository, and hiding your dependencies like you're ashamed of them is one of my least favorite code smells.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T14:21:29.197", "Id": "673", "Score": "0", "body": "Good point about the UoW property, it *is* completely useless and I forgot I still had it there. The reason Attach and Detach are on the UoW is because you're not working with the repository per se: it's saying \"ok stop tracking changes\" and \"ok track changes again\". Load on the other hand, I'm not so sure about now. Do you have any other bullets against this one? I can see moving it to the repository sort of making sense (it is working with an object - but will not have its graph loaded)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T14:22:00.350", "Id": "674", "Score": "0", "body": "Also - What do you think about the `WasCommitted` etc. Do you think they're necessary?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T08:09:50.390", "Id": "411", "ParentId": "276", "Score": "3" } }, { "body": "<p>Here is how I would shape it: </p>\n\n<pre><code>public interface IEntity\n{\n GUID Id { get; }\n}\n\npublic interface IUnitOfWork&lt;TEntity&gt; where TEntity : IEntity, class \n : IDisposable\n{\n void Commit();\n void Discard();\n void Track(TEntity entity);\n void Delete(TEntity entity);\n}\n\npublic interface IRepository&lt;TEntity&gt; where TEntity : IEntity, class \n : IDisposable\n{\n IUnitOfWork&lt;TEntity&gt; UnitOfWork { get; }\n\n TEntity CreateNew();\n T FindOne(ISpecification criteria);\n IEnumerable&lt;T&gt; FindMandy(ISpecification criteria);\n IEnumerable&lt;T&gt; FetchAll();\n}\n\npublic interface ISpecification\n{\n // encapsulates everything what is needed for a query \n // this might be an SQL-statement, LINQ-functor... \n\n string CommandText { get; }\n object[] Arguments { get; set; }\n bool IsSatisfiedBy(object candidate);\n}\n</code></pre>\n\n<p>Repository itself is read only, UnitOfWork is writeonly. I can't see how this design breaks Law of Demeter. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-15T07:04:17.310", "Id": "12609", "ParentId": "276", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T14:52:33.480", "Id": "276", "Score": "25", "Tags": [ "c#", "design-patterns" ], "Title": "Interface for unit of work pattern and repository pattern" }
276
<p>I've got a flat array of &lt; 1000 items and I need to find the indices of a smaller tuple/array within the array. The tuple to find can be a varying length (generally between 2 and 5 items, order is important). </p> <p>This is my initial naive implementation. My main concerns are:</p> <ol> <li>This seems like a CS 101 problem, so I'm pretty sure I'm overdoing it. </li> <li>Readability. I can break this down into smaller methods, but it's essentially a utility function in a much larger class. I guess I could extract it into its own class, but that feels like overkill as well. As-is, it's just too long for me to grok the whole thing in one pass.</li> </ol> <p></p> <pre><code>public int[] findIndices(final Object[] toSearch, final Object[] toFind) { Object first = toFind[0]; List&lt;Integer&gt; possibleStartIndices = new ArrayList&lt;Integer&gt;(); int keyListSize = toFind.length; for (int i = 0; i &lt;= toSearch.length - keyListSize; i++) { if (first.equals(toSearch[i])) { possibleStartIndices.add(i); } } int[] indices = new int[0]; for (int startIndex : possibleStartIndices) { int endIndex = startIndex + keyListSize; Object[] possibleMatch = Arrays.copyOfRange(toSearch, startIndex, endIndex); if (Arrays.equals(toFind, possibleMatch)) { indices = toIndexArray(startIndex, endIndex); break; } } return indices; } private int[] toIndexArray(final int startIndex, final int endIndex) { int[] indices = new int[endIndex - startIndex]; for (int i = 0; i &lt; indices.length; i++) indices[i] = startIndex + i; return indices; } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T23:57:05.590", "Id": "528", "Score": "1", "body": "What about the \"overlapping\" case, i.e: should searching for \"AA\" in \"AAA\" return 0 and 1 as \"start\" indices? As it presently is in your code, it should, but if it is not a requirement (i.e. the searched-in string can be only a \"stack\" of searched-for string copies with some other strings outside and between them), it can possibly have some effect on the effectiveness of the algorithm and the size of the code implementing it." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T18:48:49.407", "Id": "600", "Score": "0", "body": "@mlvljr Overlaps not a concern in this dataset; it breaks and drops to return as soon as the search key matches" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:43:51.357", "Id": "63122", "Score": "0", "body": "This seems like a good place to use Boyer-Moore string searching." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T18:43:13.970", "Id": "63123", "Score": "0", "body": "very tempting. My fear is I will confuse the maintenance programmers though when they come back to the code and find my link to a string search algorithm in code that isn't parsing Strings (the objects are different types). If this was mission critical performance-wise, I'd make it work though. Also big +1 for dredging the answer to #1 one out of my neural off-line storage (probably tape)." } ]
[ { "body": "<p>As a quick tip, I would suggest you skip the step of finding possible start indexes.</p>\n\n<p>Instead, as you are already iterating over the whole list to find possible start indexes, then why don't you check that index right away when you find it? Would be something like:</p>\n\n<pre><code>public int[] findIndices(final Object[] toSearch, final Object[] toFind) \n{\n Object first = toFind[0];\n\n int keyListSize = toFind.length;\n for (int startIndex = 0; startIndex &lt;= toSearch.length - keyListSize; startIndex++) \n {\n if (first.equals(toSearch[startIndex])) \n {\n int endIndex = startIndex + keyListSize;\n Object[] possibleMatch = Arrays.copyOfRange(toSearch, startIndex, endIndex);\n if (Arrays.equals(toFind, possibleMatch)) {\n return toIndexArray(startIndex, endIndex);\n }\n }\n }\n\n return new int[0];\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T18:47:29.737", "Id": "599", "Score": "0", "body": "Good catch. When I started writing it I planned to map/reduce it several times to make it clear what was happening. I changed course in the middle but didn't refactor." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T15:21:18.510", "Id": "279", "ParentId": "278", "Score": "4" } }, { "body": "<p>For &lt;1000 items, unless checking each item is prohibitively expensive, I'd say Pablo has the right idea of just checking on the first pass. This eliminates O(n) from the algorithm. For a larger list, or where checking each item is expensive, something more complicated like a Boyer-Moore style algorithm like mtnygard suggests might be appropriate.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T17:11:17.220", "Id": "295", "ParentId": "278", "Score": "1" } }, { "body": "<p><strong>Edit</strong> Original code is wrong. Added better below.</p>\n\n<p>Something like this could do it in one pass (I think - I haven't checked it to death). Note that I only return the first index as the next ones can be calculated easily by just doing a new array i, i+1, ..., i+n-1 etc. Simpler (and slower) than Boyer Moore but still <em>O</em>(n):</p>\n\n<pre><code>public static &lt;T&gt; int indexOf(final T[] target, final T[] candidate) {\n\n for (int t = 0, i = 0; i &lt; target.length; i++) {\n if (target[i].equals(candidate[t])) {\n t++;\n if (t == candidate.length) {\n return i-t+1;\n }\n } else {\n t = 0;\n }\n }\n\n return -1;\n}\n</code></pre>\n\n<p><strong>Edit: This should work better, no?</strong> It's not as clean and simple, but now I'm more confident that it's actually correct. What happens is that when we fail, we backtrack and restart. </p>\n\n<pre><code>public static &lt;T&gt; int indexOf(final T[] target, final T[] candidate) {\n int t = 0, i = 0; \n while (i &lt; target.length)\n {\n if (target[i].equals(candidate[t])) {\n t++;\n if (t == candidate.length) {\n return i-t+1;\n }\n } else {\n i -= t;\n t = 0;\n }\n i++;\n } \n return -1;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T01:20:13.243", "Id": "532", "Score": "0", "body": "Fails if repeated values in search string: `indexOf(\"aaab\", \"aab\")` should return 1." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T15:15:52.917", "Id": "583", "Score": "0", "body": "Good catch. Updated accordingly." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T15:20:02.383", "Id": "584", "Score": "0", "body": "I guess it will still come out with me missing some invariant or other and making an ass of myself again... I'll shut up then." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:08:04.960", "Id": "307", "ParentId": "278", "Score": "3" } }, { "body": "<p>Here is an O(mn) solution. Given that haystack is about 1000 in length and needle is 5 or smaller, the simplest code to do the search is probably the best. But if testing for equality is expensive, there are things we can do to mitigate that, although I'm not sure switching to KMP or BM will help so much given that we're dealing with Object here.</p>\n\n<pre><code>// assumes no null entries\n// returns starting index of first occurrence of needle within haystack or -1\npublic int indexOf(final Object[] haystack, final Object[] needle) \n{\n foo: for (int a = 0; a &lt; haystack.length - needle.length; a++) {\n for (int b = 0; b &lt; needle.length; b++) {\n if (!haystack[a+b].equals(needle[b])) continue foo;\n }\n return a;\n }\n return -1;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T01:34:11.633", "Id": "533", "Score": "0", "body": "+1 for dispensing with `copyOfRange/Arrays.equals`, stopping search needle.length early, and handling repeated values in search string correctly. However, I do think a BM impl may be helpful." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T02:01:41.957", "Id": "534", "Score": "0", "body": "Thanks for your comment. I agree BM could be of benefit. I found it nonintuitive in the context of Object elements instead of chars, but it looks like a win." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T18:41:52.550", "Id": "597", "Score": "0", "body": "I'm going to go with this. I'm not sure about the readability (I usually avoid labels) but it's definitely better than mine." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T20:24:40.193", "Id": "605", "Score": "1", "body": "Should not that be `b < (needle.length + a)`?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T20:25:30.423", "Id": "606", "Score": "0", "body": "@Bert F What is `handling repeated values in search string` about?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T20:54:41.887", "Id": "610", "Score": "0", "body": "@mlvljr - people's initial stab at search algorithms often fail to handle a repeated value in the search string e.g. `indexOf(\"aaab\", \"aab\")` should return `[1]`. Some attempts will miss the possible match at `[1]` because a partial match (`[0] to `[1]`) succeeds until `[2]`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T21:00:38.697", "Id": "611", "Score": "0", "body": "@Steve the label could be avoided: move decl `int b` outside the inner loop, change `continue foo;` to `break;`, change `return a;` to `if (b >= needle.length) return a;`. Its your call on whether the result is more readable than the label." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T21:10:19.713", "Id": "612", "Score": "0", "body": "@Bert Ok, thanks. Btw, is it only me suspicious on the `needle.length + a` vs `needle.length`? Also, why not use just a separate routine like: `boolean is_at(final Object[] haystack, final Object[] needle, int haystack_index)`?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T21:18:40.030", "Id": "613", "Score": "1", "body": "@mlvljr you are right - its broke. I think the fix should be: `int b = a` should change to `int b = 0` and `haystack[b]` should be changed to `haystack[a+b]`. `b` is the index into `needle`, so `b` needs to range from `0` to `needle.length`. `a` is the index to `haystack` and the inner loop needs to add the offset `b`, so index into `haystack` should be `a+b`. I submitted an edit to fix it." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-01T01:41:45.057", "Id": "835", "Score": "1", "body": "I implemented a BM version, but its far more complex for very little performance difference (worse in some test cases)." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:19:34.823", "Id": "330", "ParentId": "278", "Score": "5" } } ]
{ "AcceptedAnswerId": "330", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-27T15:08:44.323", "Id": "278", "Score": "14", "Tags": [ "java", "array", "search" ], "Title": "Finding subtuple in larger collection?" }
278
<p>Similar piece of code to that I recently posted as:</p> <p><a href="https://codereview.stackexchange.com/questions/259/the-same-if-block-over-and-over-again-oh-my">Resolving a link</a></p> <p>I have another piece of code which cannot be as easily extracted out into a method:</p> <pre><code>#define THROW_LAST_WINDOWS_ERROR()\ WindowsApi::Exception::Throw(::GetLastError(), __FILE__, __LINE__) #define THROW_MANUAL_WINDOWS_ERROR(x)\ WindowsApi::Exception::Throw(x, __FILE__, __LINE__) Process CreateNormalProcess( ProcessSnapshot *parent, const UNICODE_STRING&amp; name, const unsigned __int32 pid, const std::vector&lt;ToolHelpThread&gt;&amp; threads ) { std::wstring nameStr(name.Buffer, name.Length/sizeof(wchar_t)); std::wstring commandLine; std::wstring mainModulePath; std::wstring error; std::vector&lt;Module&gt; modules; try { using WindowsApi::Dll::NtDll; using WindowsApi::AutoArray; HANDLE hProc = OpenProcess( PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid); if (hProc == 0) { THROW_LAST_WINDOWS_ERROR(); } //Populate the process environment block NtDll ntDll; PEB peb; AutoArray procInfoBuf = ntDll.NtQueryInformationProcess( ProcessBasicInformation, hProc, sizeof(PROCESS_BASIC_INFORMATION) ); BOOL rpmError = ReadProcessMemory( hProc, procInfoBuf.GetAs&lt;PROCESS_BASIC_INFORMATION&gt;()-&gt;PebBaseAddress, &amp;peb, sizeof(peb), 0); if (rpmError == 0) { THROW_LAST_WINDOWS_ERROR(); } RTL_USER_PROCESS_PARAMETERS procParameters; rpmError = ReadProcessMemory(hProc, peb.ProcessParameters, &amp;procParameters, sizeof(procParameters), 0); if (rpmError == 0) { THROW_LAST_WINDOWS_ERROR(); } commandLine.assign(ReadRemoteUnicodeString(hProc, procParameters.CommandLine)); mainModulePath.assign(ReadRemoteUnicodeString(hProc, procParameters.ImagePathName)); PEB_LDR_DATA ldrData; rpmError = ReadProcessMemory(hProc, peb.Ldr, static_cast&lt;void *&gt;(&amp;ldrData), sizeof(PEB_LDR_DATA), 0); if (rpmError == 0) { THROW_LAST_WINDOWS_ERROR(); } void * endPointer = static_cast&lt;void *&gt; (reinterpret_cast&lt;char *&gt;(peb.Ldr) + (reinterpret_cast&lt;char *&gt;(&amp;ldrData.InLoadOrderModuleList) - reinterpret_cast&lt;char *&gt;(&amp;ldrData))); void * currentListEntry = ldrData.InLoadOrderModuleList.Flink; while (currentListEntry != endPointer) { LDR_MODULE loaderModule; rpmError = ReadProcessMemory( hProc, currentListEntry, &amp;loaderModule, sizeof(loaderModule), 0); if (rpmError == 0) { THROW_LAST_WINDOWS_ERROR(); } std::wstring moduleName = ReadRemoteUnicodeString(hProc, loaderModule.FullDllName); modules.push_back(Module( moduleName, loaderModule.BaseAddress, loaderModule.SizeOfImage )); currentListEntry = loaderModule.InLoadOrderModuleList.Flink; } CloseHandle(hProc); } catch (const ErrorAccessDeniedException&amp;) { error.assign(L"ERROR: Could not access additional information because access " L"was denied while attempting to open the process. Are you admin? Do you " L"have SeDebugPrivilege?"); } catch (const ErrorInvalidParameterException&amp;) { error.assign(L"ERROR: The process terminated before additional information " L"could be extracted"); } catch (const ErrorPartialCopyException&amp;) { error.assign(L"ERROR: Couldn't copy a data structure from this process. Either " L"the process terminated before information extraction, or you are running " L"the 32 bit version of pevFind on a 64 bit machine."); } if (!error.empty()) { if (nameStr.empty()) { nameStr = error; } if (commandLine.empty()) { commandLine = error; } if (mainModulePath.empty()) { mainModulePath = error; } } return Process( parent, pid, nameStr, commandLine, mainModulePath, threads, modules); } </code></pre> <p>The problem here is twofold:</p> <ol> <li>I can't extract out the duplicated if blocks into a method, because it's necessary that they embed the <code>__FILE__</code> and <code>__LINE__</code>.</li> <li><p>I can't put the conditional check into a macro, because the controlled method spans multiple lines:</p> <pre><code>MYMACRO( Function( Call, Spanning, Multiple, Lines)); </code></pre> <p>doesn't seem to expand correctly.</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:12:01.247", "Id": "479", "Score": "0", "body": "So you're looking for a way to put the `if` and it's controlled block both within a single macro?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:18:36.817", "Id": "483", "Score": "0", "body": "@John: That would be one solution to the problem. I'd just like to get rid of the repeated IFs -- how is not a big deal." } ]
[ { "body": "<p>This answer is not the best one, but you could create a new variable for each time you're assigning a value to rpmError and have one if statement where the last one is to check if any of them are equal to 0.</p>\n\n<p>Note: This will not work if it is absolutely necessary that those errors are thrown before the next check.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T17:39:46.553", "Id": "588", "Score": "0", "body": "Not true. This would result in undefined behavior in several places." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:50:37.933", "Id": "314", "ParentId": "281", "Score": "1" } }, { "body": "<p>The MYMACRO call <em>should</em> be fine.</p>\n\n<pre><code>#define D3DCALL(a) { auto __ = a; if (FAILED(__)) DXTrace(__FILE__, __LINE__, __, WIDEN(#a), TRUE); }\nD3DCALL(D3DXCreateSphere(\n D3DDev.get(),\n radius,\n slices,\n slices,\n &amp;retval-&gt;Mesh._Myptr,\n &amp;retval-&gt;Adjacency._Myptr\n));\n</code></pre>\n\n<p>I use this in my own source code all the time. The main way you get problems is if you try to conditionally compile within the macro call.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:19:52.887", "Id": "331", "ParentId": "281", "Score": "5" } }, { "body": "<p>If the question is how to take something like this:</p>\n\n<pre><code>HANDLE hProc = OpenProcess(\n PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE,\n pid);\n if (hProc == 0)\n {\n THROW_LAST_WINDOWS_ERROR();\n }\n</code></pre>\n\n<p>And reduce it to a one-liner, I usually use a <code>verify</code> macro:</p>\n\n<pre><code>template&lt;class Eval&gt; RetVal Verify(Eval eval, static const string&amp; file, unsigned line)\n{\n if( !eval )\n throw MyException(error_string, file, line);\n else \n return eval;\n}\n\n#define verify(EVAL) (Verify(EVAL, __FILE__, __LINE__))\n\n// ...\n\nHANDLE hProc = verify( OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid ));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T16:33:16.150", "Id": "947", "Score": "0", "body": "Nice, but wouldn't you use `VERIFY` instead of `verify`? Macros are still danger points, and the all caps is a useful hint." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:31:53.767", "Id": "333", "ParentId": "281", "Score": "8" } }, { "body": "<p>Adapted from Charles' answer from your original post, would something like this work?</p>\n\n<pre><code>#define THROW_LAST_WINDOWS_ERROR(condition) ThrowOnFail(condition, __FILE__, __LINE__)\n\nvoid ThrowOnFail(const BOOL condition, LPCSTR file_name, const int file_line)\n{\n if (!condition)\n WindowsApi::Exception::Throw(::GetLastError(), file_name, file_line);\n}\n</code></pre>\n\n<p>Then error handling would look something like this:</p>\n\n<pre><code>THROW_LAST_WINDOWS_ERROR(ReadProcessMemory(hProc,\n procInfoBuf.GetAs&lt;PROCESS_BASIC_INFORMATION&gt;()-&gt;PebBaseAddress,\n &amp;peb,\n sizeof(peb),\n 0));\nTHROW_LAST_WINDOWS_ERROR(ReadProcessMemory(hProc,\n peb.Ldr,\n static_cast&lt;void *&gt;(&amp;ldrData),\n sizeof(PEB_LDR_DATA),\n 0));\n// ...\n while (currentListEntry != endPointer)\n {\n LDR_MODULE loaderModule;\n\n THROW_LAST_WINDOWS_ERROR(ReadProcessMemory(\n hProc,\n currentListEntry,\n &amp;loaderModule,\n sizeof(loaderModule),\n 0));\n\n // ...\n } \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:33:34.217", "Id": "334", "ParentId": "281", "Score": "1" } }, { "body": "<p>You should also have a variant for explicitly testing return values. For example, <code>CreateFile</code> will return <code>INVALID_HANDLE_VALUE</code> which is <code>!=0</code>.</p>\n\n<p>EDIT: Ah, I think I understand the question now. You want to know how to accomplish this:</p>\n\n<pre><code>int x= foo();\nif (x==error) { blah(); }\n</code></pre>\n\n<p>in a macro.</p>\n\n<p>The easiest way is to split the variable declaration and variable setting:</p>\n\n<pre><code>int x;\nif ((x= foo())==error) { blah(); }\n</code></pre>\n\n<p>which you can then wrap in a macro: </p>\n\n<pre><code>#define MYMACRO(x) if ((x)==error) { blah(); }\n</code></pre>\n\n<p>which you can then use as:</p>\n\n<pre><code>int x;\nMYMACRO(x= foo());\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T17:28:51.643", "Id": "381", "ParentId": "281", "Score": "1" } } ]
{ "AcceptedAnswerId": "331", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-27T15:45:58.250", "Id": "281", "Score": "11", "Tags": [ "c++", "macros" ], "Title": "Resolving a link - follow-up" }
281
<pre><code>void removeForbiddenChar(string* s) { string::iterator it; for (it = s-&gt;begin() ; it &lt; s-&gt;end() ; ++it){ switch(*it){ case '/':case '\\':case ':':case '?':case '"':case '&lt;':case '&gt;':case '|': *it = ' '; } } } </code></pre> <p>I used this function to remove a string that has any of the following character: \, /, :, ?, ", &lt;, >, |. This is for a file's name. This program runs fine. It simply change a character of the string to a blank when the respective character is the forbidden character. However, I have a feeling against this use of switch statement. I simply exploit the case syntax here, but this, somehow nags me. I just don't like it. Anybody else got a better suggestion of a better implementation in this case?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T17:22:02.660", "Id": "462", "Score": "0", "body": "If a char isn't forbidden, then we leave it be." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T17:30:09.770", "Id": "465", "Score": "1", "body": "Name it replaceForbiddenChars, as it replaces instead of removes and handles multiple characters." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T17:33:42.857", "Id": "466", "Score": "0", "body": "@Fred: If none of the cases in a switch-statement match, the control flow continues after the switch statement. That behavior is perfectly defined." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T17:37:52.743", "Id": "467", "Score": "0", "body": "@sepp2k: Thanks, it is well-defined. I'm not sure why I thought that, but I'll blame it on articles I've been reading about (micro-)optimizing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T23:28:05.300", "Id": "58722", "Score": "0", "body": "Seems you forgot * symbol (asterisk). It is forbidden also." } ]
[ { "body": "<p>Declare a string containing the illegal characters: <code>\"\\\\/:?\"&lt;&gt;|\"</code>. All you need to do is check if the char is in the array, so use a native function for that, or write a method <code>CharInString(char* needle, string* haystack)</code> which loops through the contents of the provided haystack to check if the needle is inside it.</p>\n\n<p>Your loop should end up looking like this:</p>\n\n<pre><code>string illegalChars = \"\\\\/:?\\\"&lt;&gt;|\"\nfor (it = s-&gt;begin() ; it &lt; s-&gt;end() ; ++it){\n bool found = illegalChars.find(*it) != string::npos;\n if(found){\n *it = ' ';\n }\n}\n</code></pre>\n\n<p>It's more maintainable and readable. You can tell if you've duplicated a character quite easily and since you can do it with <em>any</em> target string and <em>any</em> string of illegalChars you've just created for yourself a generic <code>RemoveIllegalChars(string* targetString, string* illegalChars)</code> method usable anywhere in your program.</p>\n\n<p><sub>I may be using those pointers wrong. My C++fu is weak... for now.</sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:24:15.913", "Id": "454", "Score": "0", "body": "+1, I was also going to recommend using a string to store the forbidden characters. I would add that this change makes it very easy to add the forbidden characters as a parameter to the `removeForbiddenChars` function, so that if the need should ever arise, it can be used in situations where different sets of characters are forbidden. Also you can use the `find` method to find out whether a character is in a string, so you don't necessarily need to write a `CharInString` function (or you could write is a simple wrapper around `find`)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:25:33.603", "Id": "455", "Score": "0", "body": "@sepp2k: We seem to be on the same wavelength here! :) I'll update my answer with the `find` method." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-09T02:04:41.683", "Id": "1267", "Score": "0", "body": "Maybe the file names are short and we don't call this function much, but please be aware that the proposed solution is O(n*m) on the number of characters in the string (n) and the number of illegal characters in the string (m)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:14:58.407", "Id": "285", "ParentId": "283", "Score": "23" } }, { "body": "<p>you could always use transform</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;string&gt;\n#include &lt;iostream&gt;\n\nconst std::string forbiddenChars = \"\\\\/:?\\\"&lt;&gt;|\";\nstatic char ClearForbidden(char toCheck)\n{\n if(forbiddenChars.find(toCheck) != string::npos)\n {\n return ' ';\n }\n\n return toCheck;\n}\n\nint main()\n{\n std::string str = \"EXAMPLE:\";\n std::transform(str.begin(), str.end(), str.begin(), ClearForbidden);\n std::cout &lt;&lt; str &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T00:31:23.177", "Id": "530", "Score": "0", "body": "Didn't even see this when I was just posting my answer. Yet another way to do it with a different STL algorithm :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T02:37:59.047", "Id": "540", "Score": "2", "body": "Same thing with lambda: `std::transform(str.begin(), str.end(), str.begin(), [&forbidden](char c) { return forbidden.find(c) != std::string::npos ? ' ' : c; }`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:29:40.010", "Id": "287", "ParentId": "283", "Score": "17" } }, { "body": "<p>One thing that I would change about your function (in addition to Jonathan's recommendation of using a string to store the forbidden characters), is the argument type of <code>removeForbiddenChar</code> to <code>string&amp;</code> instead of <code>string*</code>. It is generally considered good practice in C++ to use references over pointers where possible (see for example <a href=\"http://www.parashift.com/c++-faq-lite/references.html#faq-8.6\" rel=\"nofollow\">this entry</a> in the C++ faq-lite).</p>\n\n<p>One further, minor cosmetic change I'd recommend is renaming the function to <code>removeForbiddenChars</code> (plural) as that is more descriptive of what it does.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T23:06:19.563", "Id": "61538", "Score": "0", "body": "You are never checking the validity of the string * s, so if a nullptr is passed in the removeForbiddenChar function will attempt to dereference a nullptr. This implies that the caller of removeForbiddenChar should check for nullptr before calling removeForbiddenChar, but the caller won't necessarily be aware of this unless they view the internals of removeForbiddenChar. Requiring the reference to be passed in instead of a pointer conveys that your intention is: \"You MUST have a valid string in order to call removeForbiddenChar.\"" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:30:26.797", "Id": "288", "ParentId": "283", "Score": "5" } }, { "body": "<p>C comes with a helpful function <code>size_t strcspn(const char *string, const char *delimiters)</code> that you can implement this on top of. The ASCII version is pretty fast; it uses a bit vector to test for the delimiter characters.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T14:45:20.733", "Id": "579", "Score": "0", "body": "If you are looking for performance, this one is hard to beat." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:42:26.190", "Id": "335", "ParentId": "283", "Score": "4" } }, { "body": "<p>Or, here's yet another way you could do it by using all stuff from the STL:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;string&gt;\n#include &lt;iostream&gt;\n\nbool isForbidden( char c )\n{\n static std::string forbiddenChars( \"\\\\/:?\\\"&lt;&gt;|\" );\n\n return std::string::npos != forbiddenChars.find( c );\n}\n\nint main()\n{\n std::string myString( \"hell?o\" );\n\n std::replace_if( myString.begin(), myString.end(), isForbidden, ' ' );\n\n std::cout &lt;&lt; \"Now: \" &lt;&lt; myString &lt;&lt; std::endl;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T00:30:28.267", "Id": "342", "ParentId": "283", "Score": "6" } }, { "body": "<p>Solution with no conditional branching.<br>\nSwapping space for time optimization.</p>\n\n<p>Simplified algorithm:</p>\n\n<pre><code>void removeForbiddenChar(string* s)\n{\n for (string::iterator it = s-&gt;begin() ; it &lt; s-&gt;end() ; ++it)\n {\n // replace element with their counterpart in the map\n // This replaces forbidden characters with space.\n (*it) = charMap[*it];\n }\n}\n</code></pre>\n\n<p>Or the C++0x version:</p>\n\n<pre><code>void removeForbiddenChar(std::string* s)\n{\n std::transform(s-&gt;begin(), s-&gt;end(), [](char c) =&gt; {return charMap[c];});\n}\n</code></pre>\n\n<p>Just need the data:</p>\n\n<pre><code>char charMap[] =\n // The majority of characters in this array\n // map the poistion to the same character code.\n // charMap['A'] == 'A'\n // For forbidden characters a space is in the position\n // charMap['&lt;'] == ' '\n // Note: \\xxx is an octal escape sequence\n \"\\000\\001\\002\\003\\004\\005\\006\\007\"\n \"\\010\\011\\012\\013\\014\\015\\016\\017\"\n \"\\020\\021\\022\\023\\024\\025\\026\\027\"\n \"\\030\\031\\032\\033\\034\\035\\036\\037\"\n \"\\040\\041 \\043\\044\\045\\046\\047\" // replaced \\042(\") with space\n \"\\050\\051\\052\\053\\054\\055\\056 \" // replaced \\057(/) with space\n \"\\060\\061\\062\\063\\064\\065\\066\\067\"\n \"\\070\\071 \\073 \\075 \" // replaced \\072(:)\\074(&lt;)\\076(&gt;)\\077(?) with space\n \"\\100\\101\\102\\103\\104\\105\\106\\107\"\n \"\\110\\111\\112\\113\\114\\115\\116\\117\"\n \"\\120\\121\\122\\123\\124\\125\\126\\127\"\n \"\\130\\131\\132\\133 \\135\\136\\137\" // replaced \\134(\\)\n \"\\140\\141\\142\\143\\144\\145\\146\\147\"\n \"\\150\\151\\152\\153\\154\\155\\156\\157\"\n \"\\160\\161\\162\\163\\164\\165\\166\\167\"\n \"\\170\\171\\172\\173\\174\\175\\176\\177\"\n \"\\200\\201\\202\\203\\204\\205\\206\\207\"\n \"\\210\\211\\212\\213\\214\\215\\216\\217\"\n \"\\220\\221\\222\\223\\224\\225\\226\\227\"\n \"\\230\\231\\232\\233\\234\\235\\236\\237\"\n \"\\240\\241\\242\\243\\244\\245\\246\\247\"\n \"\\250\\251\\252\\253\\254\\255\\256\\257\"\n \"\\260\\261\\262\\263\\264\\265\\266\\267\"\n \"\\270\\271\\272\\273\\274\\275\\276\\277\"\n \"\\300\\301\\302\\303\\304\\305\\306\\307\"\n \"\\310\\311\\312\\313\\314\\315\\316\\317\"\n \"\\320\\321\\322\\323\\324\\325\\326\\327\"\n \"\\330\\331\\332\\333\\334\\335\\336\\337\"\n \"\\340\\341\\342\\343\\344\\345\\346\\347\"\n \"\\350\\351\\352\\353\\354\\355\\356\\357\"\n \"\\360\\361\\362\\363\\364\\365\\366\\367\"\n \"\\370\\371\\372\\373\\374\\375\\376\\377\";\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T02:04:13.407", "Id": "348", "ParentId": "283", "Score": "3" } }, { "body": "<p>Similar to <code>strcspn</code> is <code>strpbrk</code>, but instead of returning offsets, it returns a pointer to the next match and NULL if no more matches. This makes the replacement as simple as:</p>\n\n<pre><code>while ((filename = strpbrk(filename , \"\\\\/:?\\\"&lt;&gt;|\")) != NULL)\n *filename++ = '_';\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-19T18:54:31.270", "Id": "178316", "ParentId": "283", "Score": "1" } } ]
{ "AcceptedAnswerId": "285", "CommentCount": "5", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:07:55.520", "Id": "283", "Score": "23", "Tags": [ "c++", "strings" ], "Title": "Function for removing forbidden characters" }
283
<p>This is some of the code I have:</p> <pre><code>[window setLevel:kCGScreenSaverWindowLevel]; [window setOpaque:NO]; [window setStyleMask:0]; [window setBackgroundColor:[NSColor colorWithCalibratedWhite:0.0 alpha:0.3]]; [window setAlphaValue:0]; [window setFrame:[window frameRectForContentRect:[[window screen] frame]] display:YES animate:YES]; [window makeKeyAndOrderFront:self]; [[window animator] setAlphaValue:1.0]; </code></pre> <p>I was just wondering if there was any way to compact it, all of those commands to my window. Any ways to improve it too?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T17:43:53.143", "Id": "64522", "Score": "0", "body": "Off the top of my head: can any of it be done in interface builder?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:02:55.873", "Id": "64523", "Score": "0", "body": "Nope, I don't think so." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:24:15.733", "Id": "64524", "Score": "0", "body": "I'm pretty sure a number of these properties can be set in IB. I think the meat of the question is do you actually need to create this window programatically, or could you load it from a NIB?" } ]
[ { "body": "<p>This is a highly readable style, and simple. You might be able to make a loop and run through the list in some fashion, but it's unlikely to actually lower complexity, just shift it around a bit.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:04:40.660", "Id": "475", "Score": "0", "body": "It's just that for example in AppleScript (One of the first things I learnt) you can just do a 'tell' block... like \"Tell myWindow\" and then list all of the commands. It saves typing out 'window' over and over again" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:22:07.127", "Id": "484", "Score": "0", "body": "Yeah, that'd be nice." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T17:57:47.047", "Id": "304", "ParentId": "286", "Score": "4" } }, { "body": "<p>Depending on how you feel about the use of Objective-C 2.0 properties you can you can:</p>\n\n<pre><code>window.level = kCGScreenSaverWindowLevel;\n[window setOpaque:NO];\nwindow.styleMask = 0;\nwindow.backgroundColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.3];\nwindow.alphaValue = 0;\n\n[window setFrame:[window frameRectForContentRect:window.screen.frame] display:YES animate:YES];\n\n[window makeKeyAndOrderFront:self];\n[window.animator setAlphaValue:1.0];\n</code></pre>\n\n<p>I had programmed in C# for many years before taking up Objective-C and I still find the bracket notation hard to read at times. For my own readability I would would also introduce a variable for the new frame.</p>\n\n<pre><code>NSRect newFrame = [window frameRectForContentRect:window.screen.frame];\n[window setFrame:newFrame display:YES animate:YES];\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T13:01:31.183", "Id": "368", "ParentId": "286", "Score": "0" } }, { "body": "<p>If you are calling this code more than once, I would do this:</p>\n\n<p>In the <strong>implementation</strong> file:</p>\n\n<pre><code>#import \"ThisClass.h\"\n\n@interface ThisClass() {}\n - (void)doWindowStuff;\n\n@end\n\n@implementation ThisClass\n\n- (void)doWindowStuff\n{\n window.level = kCGScreenSaverWindowLevel;\n [window setOpaque:NO];\n window.styleMask = 0;\n window.backgroundColor = [NSColor colorWithCalibratedWhite:0.0 alpha:0.3];\n window.alphaValue = 0;\n\n [window setFrame:[window frameRectForContentRect:window.screen.frame] display:YES animate:YES];\n\n [window makeKeyAndOrderFront:self];\n [window.animator setAlphaValue:1.0];\n}\n\n- (void)someOtherMethods\n{\n // other code\n [self doWindowStuff];\n}\n</code></pre>\n\n<hr>\n\n<p>Note: (from experience) beware interface builder... setting some things in IB can make code harder to troubleshoot and/or read.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-12T19:43:58.240", "Id": "8925", "ParentId": "286", "Score": "1" } } ]
{ "AcceptedAnswerId": "304", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-27T16:21:45.617", "Id": "286", "Score": "4", "Tags": [ "objective-c", "cocoa" ], "Title": "Initializing a window in Cocoa" }
286
<p>I have created this code for user error logging, and I am wondering if there is anything that can be improved. The point is that this error handler would ONLY catch user errors created in-code by trigger_error(), and would display, log, and/or email the error, depending on the config settings. The error logging class is loaded by an autoloader function. For production, all error levels would be set to 0, and the user error handler would never be set, and the class would never be loaded.</p> <p><strong>Config file:</strong></p> <pre><code> // user error display level (change for production) define('LEV_USER_ERROR_DISPLAY_LEVEL', E_USER_ERROR); // user error logging level (change for production) define('LEV_USER_ERROR_LOG_LEVEL', E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE); // user error email alert level define('LEV_USER_ERROR_EMAIL_LEVEL', 0); // user error email address list (e.g. '[email protected], [email protected]') define('LEV_USER_ERROR_EMAIL_ADDRESSES', ''); </code></pre> <p><strong>Init file:</strong></p> <pre><code> // set user error handler if (LEV_USER_ERROR_LOG_LEVEL | LEV_USER_ERROR_DISPLAY_LEVEL | LEV_USER_ERROR_EMAIL_LEVEL) { set_error_handler('lev_user_error_handler::user_error_handler', LEV_USER_ERROR_LOG_LEVEL | LEV_USER_ERROR_DISPLAY_LEVEL | LEV_USER_ERROR_EMAIL_LEVEL); } </code></pre> <p><strong>Error logging class file:</strong></p> <pre><code>&lt;?php // user error handler class lev_user_error_handler { // user error handler public static function user_error_handler($error_level, $message, $file_name, $line_number) { if ((LEV_USER_ERROR_LOG_LEVEL | LEV_USER_ERROR_DISPLAY_LEVEL) == 0) return true; switch ($error_level) { case E_USER_ERROR: if (LEV_USER_ERROR_DISPLAY_LEVEL &amp; E_USER_ERROR) { echo '[' . date('Y-m-d h:i:s') . '] User Level Error: "' . $message . '", File: "'.$file_name.'", Line: '.$line_number.'&lt;br /&gt;'; } if (LEV_USER_ERROR_LOG_LEVEL &amp; E_USER_ERROR) { error_log('[' . date('Y-m-d h:i:s') . '] User Error: "' . $message . '", File: "'.$file_name.'", Line: '.$line_number.', Request: "' . $_SERVER['ORIG_PATH_INFO'] . "\"\n", 3, 'application/logs/user_error_log.txt'); } if (LEV_USER_ERROR_EMAIL_LEVEL &amp; E_USER_ERROR) { error_log('[' . date('Y-m-d h:i:s') . '] User Error: "' . $message . '", File: "'.$file_name.'", Line: '.$line_number.', Request: "' . $_SERVER['ORIG_PATH_INFO'] . '"', 1, LEV_USER_ERROR_EMAIL_ADDRESSES, 'From: no-reply@' . preg_replace('/^.+?\./i', '', $_SERVER['SERVER_NAME'])); } die; break; case E_USER_WARNING: if (LEV_USER_ERROR_DISPLAY_LEVEL &amp; E_USER_WARNING) { echo '[' . date('Y-m-d h:i:s') . '] User Level Warning: "' . $message . '", File: "'.$file_name.'", Line: '.$line_number.'&lt;br /&gt;'; } if (LEV_USER_ERROR_LOG_LEVEL &amp; E_USER_WARNING) { error_log('[' . date('Y-m-d h:i:s') . '] User Warning: "' . $message . '", File: "'.$file_name.'", Line: '.$line_number.', Request: "' . $_SERVER['ORIG_PATH_INFO'] . "\"\n", 3, 'application/logs/user_error_log.txt'); } if (LEV_USER_ERROR_EMAIL_LEVEL &amp; E_USER_WARNING) { error_log('[' . date('Y-m-d h:i:s') . '] User Error: "' . $message . '", File: "'.$file_name.'", Line: '.$line_number.', Request: "' . $_SERVER['ORIG_PATH_INFO'] . '"', 1, LEV_USER_ERROR_EMAIL_ADDRESSES, 'From: no-reply@' . preg_replace('/^.+?\./i', '', $_SERVER['SERVER_NAME'])); } break; case E_USER_NOTICE: if (LEV_USER_ERROR_DISPLAY_LEVEL &amp; E_USER_NOTICE) { echo '[' . date('Y-m-d h:i:s') . '] User Level Notice: "' . $message . '", File: "'.$file_name.'", Line: '.$line_number.'&lt;br /&gt;'; } if (LEV_USER_ERROR_LOG_LEVEL &amp; E_USER_NOTICE) { error_log('[' . date('Y-m-d h:i:s') . '] User Notice: "' . $message . '", File: "'.$file_name.'", Line: '.$line_number.', Request: "' . $_SERVER['ORIG_PATH_INFO'] . "\"\n", 3, 'application/logs/user_error_log.txt'); } if (LEV_USER_ERROR_EMAIL_LEVEL &amp; E_USER_NOTICE) { error_log('[' . date('Y-m-d h:i:s') . '] User Error: "' . $message . '", File: "'.$file_name.'", Line: '.$line_number.', Request: "' . $_SERVER['ORIG_PATH_INFO'] . '"', 1, LEV_USER_ERROR_EMAIL_ADDRESSES, 'From: no-reply@' . preg_replace('/^.+?\./i', '', $_SERVER['SERVER_NAME'])); } break; default: // call PHP internal error handler return false; } // do not call PHP internal error handler return true; } } ?&gt; </code></pre>
[]
[ { "body": "<p>Personally I think that working with 50% native and 50% your code does not work very well, because of things such as trigger_error does not allow custom bits to be sent.</p>\n\n<p>That being said if you named your class <code>Error</code> and created it to be abstract that implements a logger interface (optional) you would be able to do more with it.</p>\n\n<p>Creating custom constants such as <code>LOG</code>,<code>SHOW_ERROR</code>,<code>SEND_MAIL</code> combined with a custom static function would be a better option, as doing things such as:</p>\n\n<pre><code>Error::Trigger(\"Cannot divide by 0\", Error::LOG | Error::SHOW_ERROR);\n</code></pre>\n\n<p>makes more sense to have specific control over errors.</p>\n\n<p>Here's a small example how I would improve the above</p>\n\n<pre><code>abstract class Error\n{\n public const LOG = 0;\n public const SEND_MAIL = 1;\n public const SHOW_ERROR = 2;\n /*...*/\n\n public static function Monitor(){}; /*Used for set_error_handler*/\n\n public static function Trigger($Message,$bits = Error::LOG | Error::SEND_MAIL,$Context = false)\n {\n if($bits &amp; Error:LOG)\n {\n //Log it\n }\n\n if($bits &amp; Error:SEND_MAIL)\n {\n //Send it\n }\n\n /*Lastly*/\n if($bits &amp; Error:LOG)\n {\n //Show it\n }\n }\n}\n</code></pre>\n\n<p>you would then bind the Monitor to the error_reportng and call the Error::Trigger depending on what type of error has been triggered, or you could extend the class and run the parent static method</p>\n\n<pre><code>class ErrorHandler extends Error\n{\n public fucntion Monitor(/*...*/)\n {\n parent::Trigger(/*...*/);\n }\n}\n</code></pre>\n\n<p>And allow your class to handle <strong>all</strong> errors as you then have more control over the decision on what to do.</p>\n\n<p>you can then set the default error handling to a combination of options such as:</p>\n\n<pre><code> define(\"DEFAULT_ERROR_HANDLING\",Error:log | Error::SEND_MAIL);\n</code></pre>\n\n<p>and change <code>$bits</code> in the parameter section of trigger to <code>$bits = DEFAULT_ERROR_HANDLING</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T20:51:49.680", "Id": "508", "Score": "0", "body": "I definetly like the idea of a custom trigger method to allow for more control over each trigger. My concern is that if error handling is turned off in the config, I would like to avoid loading the class at all, but without using native functionality, I am not sure how I would accomplish this. Any advice?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:01:09.703", "Id": "514", "Score": "0", "body": "this can be accomplished by creating a function in the root scope, so that instead of `Error::Trigger` you would have `TriggerError` function and within that function check if errors are turned on, as well as check if the class is loaded, then you can pass the params to the actual object" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:47:38.700", "Id": "312", "ParentId": "294", "Score": "3" } }, { "body": "<h2>Preface:</h2>\n\n<p>I'm not going to talk about alternatives to trigger_error for now.</p>\n\n<p>Edit: Someone else did, perfect ! :)</p>\n\n<h2>About the config:</h2>\n\n<p>I assume those settings are what you are using in development ? </p>\n\n<p>If so: I'd like to advice against that. You should always produce at least E_NOTICE free code and only logging those errors to a file isn't going to help you achieve that.</p>\n\n<p>Why ?</p>\n\n<p>The E_NOTICE error you are going to see mostly is <strong>$asd is an undefined variable</strong>. That will point you to errors in your code very quickly and you don't have to think about (\"why doesn't it work, i put the value into the function\") or similar problems coming from typos. Maybe your IDE warns you about those but let php do it too.</p>\n\n<h2>Init:</h2>\n\n<p>Usually an error handler isn't a static function. I'm not sure what php version will throw an E_STRICT warning.</p>\n\n<p>Also <code>\"class::function\"</code> is not the best way to pass a callback. <a href=\"http://de3.php.net/manual/en/language.pseudo-types.php#language.types.callback\" rel=\"nofollow\">(See here for php callbacks)</a> </p>\n\n<p>You might want to use <code>set_error_handler(\"class\", \"function\");</code>. That help if you decide you don't want to use a static function but an object because it works the same way <code>set_error_handler($obj, \"function\");</code></p>\n\n<h2>The handler:</h2>\n\n<p>You are repeating</p>\n\n<pre><code>'[' . date('Y-m-d h:i:s') . '] User Error: \"' . $message . '\", File: \"'.$file_name.'\", Line: '.$line_number.'\n</code></pre>\n\n<p>many times there. Put that into an extra method. It will help you if you want to change the logfile name or the date or something like that.</p>\n\n<p>Also it helps with the distinction you are already makeing betten the 2 log files.</p>\n\n<h2>Displaying errors ?</h2>\n\n<p>You should <em>never</em> display errors in production. I'd use <code>ini_get(\"display_errors\")</code> to figure out how the server is configure and honor that at all costs.</p>\n\n<h2>If you don't want the errors displayed in development (maybe many ajax calls ?)</h2>\n\n<p><a href=\"http://getfirebug.com/\" rel=\"nofollow\">Look into firebug.</a> It lets you see the errors if you got the firefox plugin installed without cluttering the pages output.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T20:56:02.813", "Id": "510", "Score": "0", "body": "You are definitely right about the needless repeating, I will fix that asap. One note, E_NOTICE errors would not be handled by the custom error handler, only user level errors (E_USER_...) would be handled by this class. All other errors would be handled by the native error handler and use its settings." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T20:59:23.013", "Id": "513", "Score": "0", "body": "Also, you are right, I should definetly look in to honoring the ini setting." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:49:20.077", "Id": "313", "ParentId": "294", "Score": "1" } } ]
{ "AcceptedAnswerId": "312", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T16:58:46.913", "Id": "294", "Score": "6", "Tags": [ "php", "error-handling", "php5" ], "Title": "User error logging" }
294
<p>I've just started learning CSS/HTML a week ago and I made a quick site today. It looks pretty good, but I think that I reused/wrote some really messy CSS. This is because I haven't used the <code>float</code> property in CSS too well, so I keep using <code>position:relative</code> and <code>top</code> to offset the <code>float</code>.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>/* General Elements* / body { background: #53777a; font-family: Garamond, Baskerville, "Baskerville Old Face", "Hoefler Text", "Times New Roman", serif; } h1 { font-size: 28pt; } h2 {} p {} a:link { color: black; text-decoration: none; } a:visited { color: purple; text-decoration: none; } a:hover { color: green; text-decoration: underline; } a:active { color:yellow; text-decoration: none; } /* Curvy Shapes */ #wrapper, #footer { -moz-border-radius-bottomright: 50px; -moz-border-radius-topleft: 50px; -moz-border-radius-topright: 50px; -moz-border-radius-bottomleft: 50px; border-bottom-right-radius: 50px; border-top-left-radius: 50px; border-top-right-radius: 50px; border-bottom-left-radius: 50px; } #links { -moz-border-radius-bottomright: 50px; -moz-border-radius-bottomleft: 50px; border-bottom-right-radius: 50px; border-bottom-left-radius: 50px; } #header { -moz-border-radius-topleft: 50px; -moz-border-radius-topright: 50px; border-top-left-radius: 50px; border-top-right-radius: 50px; } /* Structure */ #wrapper { width: 900px; margin: 0 auto; margin-top: 30px; overflow: auto; background: #E0E4CC; padding: 20px; -moz-border-radius-bottomright: 50px; -moz-border-radius-topleft: 50px; -moz-border-radius-topright: 50px; -moz-border-radius-bottomleft: 50px; border-bottom-right-radius: 50px; border-top-left-radius: 50px; border-top-right-radius: 50px; border-bottom-left-radius: 50px; } #header { text-align: center; background: #ECD078; padding: 4px; } #links { width: 900px; background-color: #A7DBD8; position: relative; top: -20px; text-align: center; } #links ul { list-style-type: none; padding: 5px; } #links li{ display: inline; font-size: 14pt; padding: 20px; } .sidebar_left { float: left; width: 180px; margin-left: 10px; position: relative; top: -10px; text-align: justify; line-height: 150%; } #post { float: right; width: 680px; margin-left: 0px; margin-right: 10px; position: relative; top: -25px; text-align: justify; line-height: 150%; } #post b { font-size: 18pt; text-decoration: underline; } #content { float: right; width: 680px; margin-left: 0px; margin-right: 10px; position: relative; top: -25px; text-align: justify; text-indent: 25px; line-height: 150%; } #social { float: right; } #footer { width: 890px; background: #A7DBD8; float: left; padding: 5px; text-align: right; } #footer b { margin-left: 10px; } /* End Structure */ /*images*/ .navimg { width: 2px; height: 20px; } #tree { width: 175px; height: 200px; float: right; margin-left: 20px; margin-top: 24px; } #blackwhite { width: 200px; height: 125px; float: left; margin-right: 20px; margin-top: 10px; } #quickshot { width: 125px; height: 100px; display: block; margin-left: auto; margin-right: auto; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"&gt; &lt;head&gt; &lt;title&gt;Kevin Li&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="css/style.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="wrapper"&gt; &lt;div id="header"&gt; &lt;h1&gt;Kevin Li&lt;/h1&gt; &lt;/div&gt; &lt;div id="links"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Biography&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Portfolio&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Blog&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Images&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Contact Me&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="sidebar_left"&gt; Lorem ipsum dolor sit amet...&lt;br /&gt; &lt;/div&gt; &lt;div id="post"&gt; &lt;b&gt;Introduction&lt;/b&gt;&lt;br /&gt; &lt;i&gt;Thursday, January 27, 2011&lt;/i&gt; &lt;/div&gt; &lt;br /&gt; &lt;div id="content"&gt; &lt;img id="tree" src="images/c2_i6.png" /&gt; &lt;p&gt; Lorem ipsum dolor sit amet...&lt;br /&gt; &lt;br /&gt; &lt;img id="blackwhite" src="images/c3_i7.png" /&gt; Ut venenatis diam nunc...&lt;br /&gt; &lt;br /&gt; &lt;/p&gt; &lt;/div&gt; &lt;div id="footer"&gt; &lt;b&gt;Copyright 2010 Kevin Li&lt;/b&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>By the way, I know it doesn't validate. I am working on that now.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:36:55.407", "Id": "488", "Score": "10", "body": "Could you post the relevant HTML and CSS for us to see? Most people are not going to follow your link." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T23:48:07.970", "Id": "617", "Score": "3", "body": "we have a policy of requiring the important bits of the code to be in the post.. it's fine to post a \"see more\" link but not showing *any* code at all is disallowed. I also think generic requests to \"review my website!\" are a bit too broadly scoped as that encompasses html, css, design.. etc.." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T00:19:20.933", "Id": "620", "Score": "0", "body": "@Jeff: Since he specifically mentioned the messiness of the CSS, I it should be added to the question as well (though it does make the question rather crowded)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T03:49:42.333", "Id": "631", "Score": "1", "body": "the XML prolog before the doctype makes IE6 trigger the quirks mode" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T16:09:04.680", "Id": "62596", "Score": "0", "body": "You have some alt parameters you havent specified too" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T03:30:33.917", "Id": "62597", "Score": "0", "body": "The first line is not needed and I wouldn't do one attribute per line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T20:53:42.487", "Id": "68789", "Score": "0", "body": "I think this could use a better title to describe what you want feedback on. Just saying \"after a week of learning HTML\" is not very descriptive and sets up too much of a \"pat on the back\" type of environment." } ]
[ { "body": "<p>Your CSS doesn't handle what happens if the reader closes down the window to smaller than your planned size.</p>\n\n<pre><code>Test: resize window to less than 900px.\nResults: Window is cut off.\n</code></pre>\n\n<p>This is a design issue, more than a coding issue.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T17:53:49.703", "Id": "303", "ParentId": "296", "Score": "3" } }, { "body": "<p>I didn't look at your site, as I can't afford to click on random links right now.</p>\n\n<p>However, I add <code>overflow: hidden;</code> to the parent element to make sure it wraps its immediate floated child elements. Take my example and try it with and with out the overflow.</p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;div id=\"page\"&gt;\n &lt;div id=\"main\"&gt;main content&lt;/div&gt;\n &lt;div id=\"side\"&gt;side content&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>div#page{\n overflow: hidden;\n background-color: #ccc;\n}\n\ndiv#main{\n float: left;\n}\n\ndiv#side{\n float: right;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T18:00:12.207", "Id": "305", "ParentId": "296", "Score": "1" } }, { "body": "<p>A few quick comments looking through the source:</p>\n\n<p>You did very well in structuring things semantically. I only see a few <code>&lt;br /&gt;</code> or <code>&lt;b&gt;</code> tags. That said, you probably want to include more semantic markup for some things, e.g.,</p>\n\n<pre><code>&lt;div id=\"post\"&gt;\n &lt;b&gt;Introduction&lt;/b&gt;&lt;br /&gt;\n &lt;i&gt;Thursday, January 27, 2011&lt;/i&gt;\n&lt;/div&gt;\n&lt;br /&gt;\n&lt;div id=\"content\"&gt;\n</code></pre>\n\n<p>If I were to rework it, I would do:</p>\n\n<pre><code>&lt;div id=\"post\"&gt;\n &lt;h1&gt;Introduction&lt;/h1&gt;\n &lt;h2&gt;Thursday, blah blah&lt;/h2&gt;\n&lt;/div&gt;\n&lt;div id=\"content\"&gt;\n</code></pre>\n\n<p>Then your CSS will style those elements:</p>\n\n<pre><code>div#post h1 { ... }\ndiv#post h2 { ... }\n</code></pre>\n\n<p>For your images, unless you need a javascript id selector, I'd probably make them a class, rather than unique ID's. It looks like your images will all be styled similarly, so why not group them using a class? Or just override the CSS defaults for the image tag.</p>\n\n<p>Finally, you should probably use a CSS reset. Browsers all use different defaults, so the only sensible thing is to use a reset so that all styling attributes start out the same across all browsers. Eric Meyer is the CSS guru, he has his reset at <a href=\"http://meyerweb.com/eric/tools/css/reset/\">http://meyerweb.com/eric/tools/css/reset/</a> (along with more explanation about why to use it).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T02:22:27.073", "Id": "539", "Score": "0", "body": "might want to wrap your tags in ``` otherwise things dont show up..." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T08:48:22.730", "Id": "564", "Score": "0", "body": "Are there such tags as `or` tags?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T01:30:05.107", "Id": "624", "Score": "0", "body": "I would question the semantics here. <strong> could work as well. <em> should also be used over <i>. I would personally never remove unique identifiers from elements, as the flexibility of being able to style/jQuery a specific element is more efficient than navigating through a list. But a class is a good idea if styles will be reused for many images." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-20T00:48:49.473", "Id": "72682", "Score": "0", "body": "@VisionarySoftwareSolutions I think you mistook the first piece of code for an answer, I was using it as an input. OP, as you can see there are lots of good ways of doing it. As you progress, you'll develop your own style. I recommend that you be try to develop a consistent style - eg, if you prefer #post instead of div#post, that's fine, but be consistent." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T20:28:20.107", "Id": "325", "ParentId": "296", "Score": "17" } }, { "body": "<p>A few semantic issues:</p>\n\n<ol>\n<li><p><strong>Do not use <code>&lt;b&gt;</code> tags.</strong><br>\nIf you must, you can use <code>&lt;strong&gt;</code>, or even better, <code>&lt;span class=\"bold\"&gt;&lt;/span&gt;</code>, and then style the class in your CSS.</p></li>\n<li><p><strong>Do not use <code>&lt;i&gt;</code> tags.</strong><br>\nIf you must, you can use <code>&lt;em&gt;</code>, or even better, <code>&lt;span class=\"italic\"&gt;&lt;/span&gt;</code>, and then style the class in your CSS.</p></li>\n<li><p><strong>Do not use <code>&lt;br /&gt;</code> tags for spacing.</strong><br>\nIf you require spacing, use <code>margin-bottom</code> or <code>padding-bottom</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T03:12:47.973", "Id": "543", "Score": "1", "body": "Why is <span> better than <i> or <b>? I don't see what semantic value is obtained by replacing those tags." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T03:17:24.223", "Id": "544", "Score": "0", "body": "Probably because the W3C says its better to use CSS. I can see the pros and cons.. various levels of bold, different color bold, etc. http://www.w3schools.com/tags/tag_phrase_elements.asp" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T03:27:40.120", "Id": "545", "Score": "4", "body": "But that's not a semantic issue. Unless a different class is used, I don't see how \"bold\" tells anything more _about_ the content (as opposed to telling about the presentation) than <b>." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T11:25:50.533", "Id": "567", "Score": "0", "body": "I have suggested that semantic be replaced with good-practice." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T12:23:18.523", "Id": "569", "Score": "7", "body": "@Kevin You do realise that the W3Schools have absolutely nothing to do with the W3C?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T01:32:58.347", "Id": "625", "Score": "1", "body": "Good call on identifying things that shouldn't be done. The rationale, however, is lacking. The point of <strong> and <em> is not to get bold text and italicized text. You can overwrite the default behavior with CSS. The point is to add semantic meaning so that intelligent queries can be done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T07:29:47.070", "Id": "16039", "Score": "0", "body": "http://w3fools.com. I'd probably use h1 or h2 for the header instead of `<b>`, and a `<div class=\"post-meta\">` for the date (and possible other stuff about the post)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-07T22:16:37.557", "Id": "139184", "Score": "0", "body": "A better idea is to use <span class=\"keyword\"></span>, or whatever that special element is. Why does it deserve highlighting? Author Name? First mention of person in article? Sound bite phrase which summarizes the point of the paragraph? That you might define all these as bold in the css is fine, that's where it wants to be." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T02:20:54.187", "Id": "350", "ParentId": "296", "Score": "2" } }, { "body": "<p>A couple notes:</p>\n\n<p><strong>Use HTML5</strong></p>\n\n<ol>\n<li>Instead of <code>&lt;div id=\"header\"&gt;</code> consider using an <code>&lt;header&gt;</code> </li>\n<li>Instead of <code>&lt;div id=\"post\"&gt;</code> consider using <code>&lt;article&gt;</code></li>\n<li>Instead of <code>&lt;div class=\"sidebar_left\"&gt;</code> use <code>&lt;aside&gt;</code>. Also, you should NOT use \"style specific\" classes such as \"left\", \"red\", etc because it's very easily overridable in CSS and no-longer relevant. I would also suggest sticking with a convention for CSS that uses dashes instead of underscores. When you look through your JavaScript it will be more legible (underscores mean JS, dashes mean selectors or DOM). </li>\n<li>Instead of <code>&lt;div id=\"footer\"&gt;</code> use <code>&lt;footer&gt;</code></li>\n<li>Instead of <code>&lt;div id=\"content\"&gt;</code> use <code>&lt;section&gt;</code> or <code>&lt;div id=\"main\" role=\"main\"&gt;</code>. You should use <code>role</code> to provide more context.</li>\n<li>Anchors with hashes: I'm not sure why you are using a hash in your anchors (ex: <code>&lt;a href=\"#\"&gt;Contact Me&lt;/a&gt;</code>). I see developers use it to simply enable a pointer cursor. If this is the case you should instead use:</li>\n</ol>\n\n<p><strong>HTML</strong></p>\n\n<pre><code>&lt;a&gt;Contact Me&lt;/a&gt; \n</code></pre>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>a { cursor: pointer;}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T20:55:48.483", "Id": "68791", "Score": "1", "body": "There is no point to add `a { cursor: pointer;}`. The practice of using `<a href=\"#\">Link</a>` is common sense to all of us that a url will be inserted later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-31T14:29:38.793", "Id": "366425", "Score": "0", "body": "Note that this question was posted in 2011, before HTML5 was available." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T23:56:16.647", "Id": "38599", "ParentId": "296", "Score": "1" } }, { "body": "<p>Here is some code golf tips, that can improve performance and code readability:</p>\n\n<p>This:</p>\n\n<pre><code>#wrapper, #footer {\n -moz-border-radius-bottomright: 50px;\n border-bottom-right-radius: 50px;\n -moz-border-radius-topleft: 50px;\n border-top-left-radius: 50px;\n -moz-border-radius-topright: 50px;\n border-top-right-radius: 50px;\n -moz-border-radius-bottomleft: 50px;\n border-bottom-left-radius: 50px;\n}\n</code></pre>\n\n<p>could be just this:</p>\n\n<pre><code>#wrapper, #footer {\n border-radius: 50px;\n -moz-border-radius: 50px;\n}\n</code></pre>\n\n<p>or if the values differ:</p>\n\n<pre><code>#elem {\n border-radius: 50px 0 25px 10px; /* Top 50px, Right 0, Bottom 25px, Left 10px */\n /* or */\n border-radius: 50px 0; /* Top &amp; Bottom 50px, Right &amp; Left 0 */\n}\n</code></pre>\n\n<p>This rule also applies when you are using margin's or padding's, example:</p>\n\n<pre><code>margin: 0 auto;\nmargin-top: 30px;\n</code></pre>\n\n<p>could be:</p>\n\n<pre><code>margin: 30px auto 0;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-05T01:29:46.673", "Id": "38600", "ParentId": "296", "Score": "1" } }, { "body": "<p><strong>Leave out empty CSS rules</strong></p>\n\n<p>In your example, you have these</p>\n\n<pre><code>h2 {}\n\np {}\n</code></pre>\n\n<p>You can have one file for development that has those so you can work on them later. But in your production file, leave those out to reduce your file size. It also makes your files more readable when you submit them for review. </p>\n\n<p><strong>Do not use <code>&lt;br&gt;</code> tags for spacing</strong></p>\n\n<pre><code>&lt;br /&gt;\n&lt;img id=\"blackwhite\" src=\"images/c3_i7.png\" /&gt; Ut venenatis diam nunc...&lt;br /&gt;\n&lt;br /&gt;\n</code></pre>\n\n<p>If you want to create white space around images. You could do something like </p>\n\n<pre><code>img { margin: 6px; }\n</code></pre>\n\n<p>You could of course make that margin anything you want. Or you could pass down rules based on how you want them to display at certain cases. </p>\n\n<p><strong>Use <code>class</code> instead of <code>id</code> more often.</strong> </p>\n\n<p>In that same element you have this </p>\n\n<p></p>\n\n<p><code>blackwhite</code> is not something that sounds like it would describe a specific element in a document. But as a matter fact, it looks like you are creating a blog considering how there is a \"post.\" And because you will have many images on this page, you should make this classes. </p>\n\n<p><strong>Use absolute paths</strong></p>\n\n<p>The <code>images/c3_i7.png</code> in <code>&lt;img id=\"blackwhite\" src=\"images/c3_i7.png\" /&gt;</code> would become <code>/images/c3_i7.png</code> which is good on a server because it helps prevent errors if things get moved around. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T21:14:15.810", "Id": "40781", "ParentId": "296", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-27T17:17:24.273", "Id": "296", "Score": "16", "Tags": [ "beginner", "html", "css" ], "Title": "Personal website, done after one week of learning HTML and CSS" }
296
<p>I am in the process of learning Clojure. I am fairly new to functional programming and would like to know if my code smells or if there are any performance implications with my approach.</p> <pre><code>; Returns the the given sequence with the given item appended to it. (defn snoc [xs x] (concat xs [x])) ; Returns the Fibonacci sequence up to the highest number less than max. (defn fib [max] (loop [a 1, b 1, acc [1]] (if (&gt; b max) acc (recur b (+ a b) (snoc acc b))))) ; Project Euler Problem 2: Attempt A (defn pe2a [] (reduce + (filter even? (fib 4000000)))) </code></pre> <p>For <a href="http://projecteuler.net/index.php?section=problems&amp;id=2">reference</a>:</p> <blockquote> <p>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</p> <p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</p> <p>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-24T21:08:12.427", "Id": "63121", "Score": "0", "body": "You can generate the even-valued terms directly, rather than generating all terms and discarding the odd ones. The direct approach takes a bit less time to generate the sequence up to four million." } ]
[ { "body": "<pre><code>(defn snoc [xs x] (concat xs [x]))\n</code></pre>\n\n<p>There is a reason <code>snoc</code> is not defined by default in clojure: Since appending at the end of a singly linked list takes O(n) time, this is actually quite expensive. When building up non-lazy lists tail-recursively in a functional language, you often build the list the wrong way around (using <code>cons</code> instead of <code>snoc</code>) and then reverse it at the end to avoid that cost.</p>\n\n<p>However in this case there is actually a nicer way: by using a lazy sequence rather than a strict list, we can avoid the need for <code>loop</code>/<code>recur</code> and save the cost of building up the list. We can also separate the logic of creating the Fibonacci numbers from the logic which decides how many numbers we want by first creating a lazy sequence containing all Fibonacci numbers and then using <code>take-while</code> to take those less than the given maximum. This will lead to the following code:</p>\n\n<pre><code>;; A lazy sequence containing all fibonacci numbers\n(def fibs\n (letfn\n [(fibsrec [a b]\n (lazy-seq (cons a (fibsrec b (+ a b)))))]\n (fibsrec 1 1)))\n\n;; A function which returns all fibonacci numbers which are less than max\n(defn fibs-until [max]\n (take-while #(&lt;= % max) fibs))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T20:12:14.960", "Id": "502", "Score": "0", "body": "I think I have broken part your code well enough. Just to be sure, what does the `%` do? From what I can see, it represents the parameter that is implicitly being passed into the anonymous function." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T20:18:49.960", "Id": "504", "Score": "1", "body": "@Jeremy: That's right. `#(<= % max)` is just a short way to write `(fn [x] (<= x max))`, i.e. a function which takes an argument and then checks whether that argument is less than or equal to `max`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T19:15:11.683", "Id": "316", "ParentId": "300", "Score": "13" } }, { "body": "<p>I'm not sure if this belongs as a comment here but I built my solution in clojure as well. The Fibonacci numbers are generated as an infinite sequence as per Halloway's \"Programming in Clojure\" p. 136. I then sum using using a list comprehension</p>\n\n<pre><code>;;Programming in Clojure p. 136\n\n(defn fibo [] (map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))\n\n(defn proj-euler2 [] \n (reduce + (for [x (fibo) :when (even? x) :while (&lt; x 4000000)] x)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-03T18:19:24.853", "Id": "586", "ParentId": "300", "Score": "5" } }, { "body": "<p>Rather than writing snoc, just use conj.</p>\n\n<pre><code>(conj [1 2] 3)\n</code></pre>\n\n<p>returns </p>\n\n<pre><code>[1 2 3]\n</code></pre>\n\n<p>Note that this <em>only</em> works for vectors.</p>\n\n<pre><code>(conj (list 1 2) 3)\n</code></pre>\n\n<p>returns </p>\n\n<pre><code>(3 1 2)\n</code></pre>\n\n<p>Finally, if there were performance implications, you could use a transient vector and persist it at the last possible moment.</p>\n\n<p>P.S. I like Dave's solution.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T10:04:07.383", "Id": "3868", "ParentId": "300", "Score": "2" } } ]
{ "AcceptedAnswerId": "316", "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T17:43:18.330", "Id": "300", "Score": "25", "Tags": [ "functional-programming", "project-euler", "clojure", "fibonacci-sequence" ], "Title": "Project Euler Problem 2 in Clojure" }
300
<p>I wrote a BST in C a while back and may use it at some point. </p> <pre><code> search_tree tree_make_empty( search_tree tree ) { if ( tree != NULL ) { tree_make_empty( tree-&gt;left ); tree_make_empty( tree-&gt;right ); free( tree ); } return NULL; } tree_position tree_find( CHAR_DATA *target, search_tree tree ) { if ( tree == NULL ) return NULL; if ( target &lt; tree-&gt;hatedata-&gt;target_char ) return tree_find( target, tree-&gt;left ); else if ( target &gt; tree-&gt;hatedata-&gt;target_char ) return tree_find( target, tree-&gt;right ); else return tree; } search_tree tree_insert( HATE_DATA *hatedata, search_tree tree ) { if ( tree == NULL ) { tree = (HATE_NODE * ) malloc( sizeof( HATE_NODE ) ); if ( tree == NULL ) bug( "tree_insert: out of space!" ); else { tree-&gt;hatedata = hatedata; tree-&gt;left = tree-&gt;right = NULL; } } else if ( hatedata-&gt;target_char &lt; tree-&gt;hatedata-&gt;target_char ) tree-&gt;left = tree_insert( hatedata, tree-&gt;left ); else if ( hatedata-&gt;target_char &gt; tree-&gt;hatedata-&gt;target_char ) tree-&gt;right = tree_insert( hatedata, tree-&gt;right ); return tree; } tree_position tree_find_min( search_tree tree ) { if ( tree == NULL ) return NULL; else if ( tree-&gt;left == NULL ) return tree; else return tree_find_min( tree-&gt;left ); } search_tree tree_delete( HATE_DATA *hatedata, search_tree tree ) { tree_position pos; if ( tree == NULL ) bug( "tree_delete: not found" ); else if ( hatedata-&gt;target_char &lt; tree-&gt;hatedata-&gt;target_char ) tree-&gt;left = tree_delete( hatedata, tree-&gt;left ); else if ( hatedata-&gt;target_char &gt; tree-&gt;hatedata-&gt;target_char ) tree-&gt;right = tree_delete( hatedata, tree-&gt;right ); else if ( tree-&gt;left &amp;&amp; tree-&gt;right ) { pos = tree_find_min( tree-&gt;right ); tree-&gt;hatedata = pos-&gt;hatedata; tree-&gt;right = tree_delete( tree-&gt;hatedata, tree-&gt;right ); } else { pos = tree; if ( tree-&gt;left == NULL ) tree = tree-&gt;right; else if ( tree-&gt;right == NULL ) tree = tree-&gt;left; free( pos ); } return tree; } HATE_DATA *tree_retrieve( tree_position pos ) { return pos-&gt;hatedata; } </code></pre> <p>...</p> <pre><code> struct hate_data { CHAR_DATA *target_char; int hate_amount; }; struct hate_node { HATE_DATA *hatedata; search_tree left; search_tree right; }; </code></pre> <p>...</p> <pre><code>mob-&gt;hatedata = tree_make_empty( NULL ); </code></pre> <p>Example use:</p> <pre><code>if ( IS_NPC(victim) ) { HATE_DATA *hatedata; tree_position P; if( ( P = tree_find( ch, victim-&gt;hatedata )) == NULL || tree_retrieve( P )-&gt;target_char != ch ) { int test; hatedata = (HATE_DATA * ) malloc( sizeof( HATE_DATA ) ); hatedata-&gt;target_char = ch; test = number_range( 1, 50 ); hatedata-&gt;hate_amount = test; victim-&gt;hatedata = tree_insert( hatedata, victim-&gt;hatedata ); ch_printf( ch, "It should now hate you for %d.\n\r", test ); } else { hatedata = tree_retrieve(tree_find( ch, victim-&gt;hatedata )); ch_printf(ch, "You are already hated for %d!\n\r", hatedata-&gt;hate_amount ); } } </code></pre> <p>Do you have any suggestions? Does it look okay? Are there any ways to optimize it?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T07:44:59.120", "Id": "560", "Score": "0", "body": "I would say it is not going to work (if CHAR_DATA* is a string). You are comparing pointers. So unless all the data is static the comparisons using < and > are meaningless." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T18:19:15.037", "Id": "590", "Score": "0", "body": "It's a pointer to a struct." } ]
[ { "body": "<p>In <code>tree_find</code> and <code>tree_find_min</code> [edit: and even in <code>tree_insert</code>] you're not really gaining anything from using recursion. For example, I think <code>tree_find_min</code> would probably be clearer something like:</p>\n\n<pre><code>tree_position tree_find_min( search_tree tree )\n{\n if ( tree == NULL )\n return NULL;\n while (tree-&gt;left != NULL)\n tree = tree-&gt;left;\n return tree;\n}\n</code></pre>\n\n<p>As a side-benefit, this may also be faster with some compilers. In code like:</p>\n\n<pre><code> HATE_DATA *hatedata;\n\n /* ... */\n\n hatedata = (HATE_DATA * ) malloc( sizeof( HATE_DATA ) );\n</code></pre>\n\n<p>I'd change it to look more like:</p>\n\n<pre><code> hatedata = malloc(sizeof(*hatedata));\n</code></pre>\n\n<p>The cast accomplishes nothing useful in C, and can cover up the bug of forgetting to <code>#include &lt;stdlib.h&gt;</code> to get the proper prototype for <code>malloc</code>. Using <code>sizeof(*hatedata)</code> instead of <code>sizeof(HATE_DATA)</code> means that changing the type only requires changing it in one place (where you've defined the variable), instead of everywhere you've done an allocation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T13:14:43.817", "Id": "7176", "Score": "0", "body": "+1 a) True for not gaining much, but recursion vs iteration readability is sometimes just matter of taste. So I believe it is subjective. I believe that more skilled programmer will recognize the pattern. b) what You did to malloc is good, it hides the type which can change ... one can make macro out of it then" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T19:18:01.680", "Id": "317", "ParentId": "311", "Score": "6" } }, { "body": "<p>Using the comparison than operators <code>&lt;</code> and <code>&gt;</code> on pointers seems a bit redundant.</p>\n\n<p>Depending on how the heap is working you may end up with a tree that looks like a list.<br>\nWithout understand the properties of HATE_DATA it is imposable to know if this is a good or even valuable usage of theses operators.</p>\n\n<p>If the data inside the pointer <code>target_char</code> has some intrinsic property that would allow you to do a more meaningful comparison then you can define/use a function to do the comparison or you can document the properties of HATE_DATA that make using these operators meaningful in this context.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T19:54:45.647", "Id": "322", "ParentId": "311", "Score": "2" } }, { "body": "<p>An even better way to do the malloc is with this macro (simplified version of g_new in GLib):</p>\n\n<pre><code>#define my_new(type, count) ((type*)malloc (sizeof (type) * (count)))\n</code></pre>\n\n<p>The advantages of this are:</p>\n\n<ul>\n<li>less typing, more clarity</li>\n<li>assignment to the wrong type will be a compiler warning</li>\n<li>you can't accidentally sizeof() the wrong thing</li>\n</ul>\n\n<p>Also, of course, malloc can return NULL. The easiest way to deal with that is to make a wrapper function that handles it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:44:13.223", "Id": "336", "ParentId": "311", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-27T18:47:23.210", "Id": "311", "Score": "4", "Tags": [ "performance", "c" ], "Title": "How does this Binary Search Tree look?" }
311
<p>Oftentimes I find myself wanting the total number of rows returned by a query even though I only may display 50 or so per page. Instead of doing this in multiple queries like so:</p> <pre><code>SELECT first_name, last_name, (SELECT count(1) FROM sandbox.PEOPLE WHERE trunc(birthday) = trunc(sysdate) ) as totalRows FROM sandbox.PEOPLE WHERE trunc(birthday) = trunc(sysdate); </code></pre> <p>It has been recommended to me to do this:</p> <pre><code>SELECT first_name, last_name, count(*) over () totalRows FROM sandbox.PEOPLE WHERE trunc(birthday) = trunc(sysdate); </code></pre> <p>I am just looking for what is better as far as performance and if performance is a wash. Does this really improve readability of SQL? It is certainly cleaner/easier to write.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T20:56:27.947", "Id": "511", "Score": "2", "body": "Do you have a specific question?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T20:58:51.533", "Id": "512", "Score": "0", "body": "Really don't think this belongs here. Probably better on SO." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:12:17.577", "Id": "517", "Score": "1", "body": "@Mark: Maybe Programmers.SE? There's nothing wrong with the code. I assume @Scott wants to know which is better?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T21:25:52.240", "Id": "519", "Score": "0", "body": "@Jeremy: programmers makes sense to me." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T23:09:21.063", "Id": "616", "Score": "0", "body": "The second query looks better; performance-wise I expect it's a wash. How are you doing your pagination?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-03T03:11:00.227", "Id": "994", "Score": "0", "body": "Many people might find the analytic functions to be esoteric, so from a maintainability perspective it's a strike against the second option. In any event, doesn't it seem cheesy to repeat the same figure in every row? How about issuing two queries within the same transaction? If you have an index on birthday the count might be satisfied without needing to go to the table." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-03T03:23:02.967", "Id": "995", "Score": "0", "body": "I found a relevant thread on OTN. http://forums.oracle.com/forums/thread.jspa?threadID=2162934" } ]
[ { "body": "<p>The latter query will be much more efficient-- it only requires hitting the table once. You can do a quick test yourself to confirm this.</p>\n\n<p>I'll create a simple two-column table with 1 million rows where the second column is one of 10 distinct values</p>\n\n<pre><code>SQL&gt; create table t (\n 2 col1 number,\n 3 col2 number\n 4 );\n\nTable created.\n\nSQL&gt; insert into t\n 2 select level, mod(level,10)\n 3 from dual\n 4 connect by level &lt;= 1000000;\n\n1000000 rows created.\n</code></pre>\n\n<p>Now, I'll run two different queries that retrieve 10% of the data. I've set SQL*Plus to not bother displaying the data but to display the query plan and the basic execution statistics. With the first query, note that the query plan shows that Oracle has to access the table twice and then do a sort and aggregate. The query does ~10,000 consistent gets which is a measure of the amount of logical I/O being done (note that this is independent of whether data is cached so it is a much more stable measure-- if you run the same query many times, the consistent gets figure will fluctuate very little)</p>\n\n<pre><code>SQL&gt; set autotrace traceonly;\nSQL&gt; select col1\n 2 ,(select count(*) from t where col2=3)\n 3 from t\n 4 where col2 = 3;\n\n100000 rows selected.\n\n\nExecution Plan\n----------------------------------------------------------\nPlan hash value: 3335345748\n\n---------------------------------------------------------------------------\n| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |\n---------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 85706 | 2176K| 525 (3)| 00:00:07 |\n| 1 | SORT AGGREGATE | | 1 | 13 | | |\n|* 2 | TABLE ACCESS FULL| T | 85706 | 1088K| 525 (3)| 00:00:07 |\n|* 3 | TABLE ACCESS FULL | T | 85706 | 2176K| 525 (3)| 00:00:07 |\n---------------------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n\n 2 - filter(\"COL2\"=3)\n 3 - filter(\"COL2\"=3)\n\nNote\n-----\n - dynamic sampling used for this statement (level=2)\n\n\nStatistics\n----------------------------------------------------------\n 32 recursive calls\n 1 db block gets\n 10465 consistent gets\n 0 physical reads\n 176 redo size\n 2219528 bytes sent via SQL*Net to client\n 73850 bytes received via SQL*Net from client\n 6668 SQL*Net roundtrips to/from client\n 0 sorts (memory)\n 0 sorts (disk)\n 100000 rows processed\n</code></pre>\n\n<p>On the other hand, with the analytic function approach, the query plan shows that we only have to hit the table once. And we only have to do ~1,900 consistent gets-- less than 20% of the logical I/O that the first query had to do.</p>\n\n<pre><code>SQL&gt; select col1,\n 2 count(*) over ()\n 3 from t\n 4 where col2 = 3;\n\n100000 rows selected.\n\n\nExecution Plan\n----------------------------------------------------------\nPlan hash value: 2291049666\n\n---------------------------------------------------------------------------\n| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |\n---------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 85706 | 2176K| 525 (3)| 00:00:07 |\n| 1 | WINDOW BUFFER | | 85706 | 2176K| 525 (3)| 00:00:07 |\n|* 2 | TABLE ACCESS FULL| T | 85706 | 2176K| 525 (3)| 00:00:07 |\n---------------------------------------------------------------------------\n\nPredicate Information (identified by operation id):\n---------------------------------------------------\n\n 2 - filter(\"COL2\"=3)\n\nNote\n-----\n - dynamic sampling used for this statement (level=2)\n\n\nStatistics\n----------------------------------------------------------\n 4 recursive calls\n 0 db block gets\n 1892 consistent gets\n 0 physical reads\n 0 redo size\n 2219510 bytes sent via SQL*Net to client\n 73850 bytes received via SQL*Net from client\n 6668 SQL*Net roundtrips to/from client\n 1 sorts (memory)\n 0 sorts (disk)\n 100000 rows processed\n</code></pre>\n\n<p>Now, to be fair, you probably won't cut out 80% of your consistent gets moving to the analytic function approach using this particular query because it is likely that far fewer than 10% of the rows in your <code>PEOPLE</code> table have a birth date of today. The fewer rows you return, the less the performance difference will be.</p>\n\n<p>Since this is Code Review, the analytic function approach is much easier to maintain over time because you don't violate the <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">DRY principle</a> and you have to remember to make all the same changes to your inline query that you make in the main query. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T21:53:49.470", "Id": "39813", "Score": "1", "body": "If the total data set is very large and an estimate of the total number of rows is acceptable then a subquery with a sample clause might be handy: \"(select count(*) *100 from t sample(1) where col2=3)\"" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T04:12:16.923", "Id": "3738", "ParentId": "326", "Score": "8" } } ]
{ "AcceptedAnswerId": "3738", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-27T20:48:43.133", "Id": "326", "Score": "6", "Tags": [ "sql", "oracle" ], "Title": "Returning total number of rows in query" }
326
<p>This JS function is intended to retrieve or place a value into an object with the nested keys as a string.</p> <p>For example</p> <pre><code>var obj = {a: {b: [4]}}; parse_obj_key(obj, "a.b.0") should equal 4. parse_obj_key(obj, "a.c", 2) should add another element to "a" named "c" with value 2. </code></pre> <p>The method works, but I'd like to clean it up if possible (or a more polished implementation which is publicly available). I'd also love to know of any edge-case failures which can be found.</p> <pre><code>function parse_obj_key(obj, loc, val){ var _o = obj; while (true){ var pos = loc.indexOf('.'); if (!_o || typeof _o != 'object'){ $.log("Invalid obj path: " + loc + "\n" + JSON.stringify(obj)); return null; } if (pos === -1){ if (val){ _o[loc] = val; return obj; } else { if (!isNaN(parseInt(loc))) loc = parseInt(loc); return _o[loc]; } } var part = loc.substring(0, pos); var loc = loc.substring(pos + 1); if (!isNaN(parseInt(part))) part = parseInt(part); if (!(part in _o)){ if (val) _o[part] = new object; else return null; } _o = _o[part]; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T13:25:46.623", "Id": "574", "Score": "0", "body": "I would suggest providing two different methods, one to get and one to set values (maybe both calling a common private method to retrieve the property)." } ]
[ { "body": "<p>Here is what's wrong with your code:</p>\n\n<ul>\n<li><p>Do not use variable names like <code>_o</code>. Get an editor with good auto-completion.</p></li>\n<li><p><code>typeof _o != 'object'</code> does not do what you think it does: <code>typeof([1,2]) // \"object\"</code>.\nIn general, doing those kinds of checks is a code smell.</p></li>\n<li><p><code>if (!isNaN(parseInt(loc))) loc = parseInt(loc);</code>. Confusing and not needed.<br>\nJavaScript: <code>['a', 'b'][\"1\"] // 'b'</code>. Same goes for the other <code>isNaN</code></p></li>\n<li><p><code>in</code>. Do not do that check. <code>null</code> is a value, but what you want to return is the lack of value. It is <code>undefined</code> in JavaScript, and it is what will be returned if there is no value.</p></li>\n<li><p>Consider using <code>split</code> instead of <code>indexOf</code> and <code>substring</code>. It is much faster and makes the code more readable.</p></li>\n</ul>\n\n<p>So, here is a neat version for you:</p>\n\n<pre><code>function chained(obj, chain, value){\n var assigning = (value !== undefined);\n // split chain on array and property accessors\n chain = chain.split(/[.\\[\\]]+/); \n // remove trailing ']' from split \n if (!chain[chain.length - 1]) chain.pop();\n // traverse 1 level less when assigning\n var n = chain.length - assigning; \n for (var i = 0, data = obj; i &lt; n; i++) {\n data = data[chain[i]];\n // if (data === undefined) return; // uncomment to handle bad chain keys \n }\n\n if (assigning) {\n data[chain[n]] = value;\n return obj;\n } else {\n return data; \n }\n}\n</code></pre>\n\n<p>Blogged: <a href=\"http://glebm.blogspot.com/2011/01/javascript-chained-nested-assignment.html\" rel=\"nofollow\">http://glebm.blogspot.com/2011/01/javascript-chained-nested-assignment.html</a></p>\n\n<p>Please come up with further improvements :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T13:19:53.187", "Id": "573", "Score": "0", "body": "Could you elaborate on how your solution is an improvement with regards to OP's code?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T09:45:04.537", "Id": "659", "Score": "0", "body": "@Eric Done. Feel free to add more." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T17:09:36.440", "Id": "680", "Score": "2", "body": "I mostly agree with your comments, except \"Do not use strict comparison\". I would rather suggest to use strict comparison all the time, trying to focus on \"The Good Parts\" (c) of JavaScript rather than its quirks. +1" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T23:19:21.773", "Id": "714", "Score": "0", "body": "I used _o to signify that it's a temporary var just to be mashed about in the loop, e.g. that it only meaningful for it's ref to the real obj. I intended the typeof to work the way it did, I want to know if it's an array or an object (e.g. not a primitive), will it not work for this purpose?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T05:36:06.797", "Id": "731", "Score": "0", "body": "I was not completely correct about your use of typeof. It will work for checking whether something is a primitive or not. However, if you try `parse_obj_key(\"awesome_string\", \"length\")` it won't work because `\"object\"` is not the same as something that responds to methods. Cheers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-13T21:27:32.523", "Id": "6096", "Score": "0", "body": "I agree with Eric. `==` and `!=` are evil. `0 == '' // true 0 == '0' // true '0' == '' // false!` or `' \\t\\r\\n\\f' == 0 // true` or even `',,,,,,' == Array(('i' <3, 'js', 'on a scale of 1 to 10, js is a ', 7))` although that exploits more than just `==`..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-09T13:16:35.453", "Id": "46751", "Score": "0", "body": "I, too, agree with Eric. How is `===` not embracing the language? You just have to _know_ that `domNode.property === 123` will always be false, so use ` === '123'`. Using `== 123` isn't embracing the language IMO, it's just relying on type coercion, which is slower and, in some times, making life harder: `dateInput == new Date()`... Besides, `aVar === +(aVar)` is _very_ common in JS" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-09T15:43:19.417", "Id": "46756", "Score": "0", "body": "I removed the `==` bit, as you are all right :)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T04:15:38.687", "Id": "353", "ParentId": "340", "Score": "3" } }, { "body": "<p>I know little about javascript, and thought yours solution is fine.\nglebm's code seems not working for <code>parse_obj_key(obj, \"a.c.c.c\", 2)</code></p>\n\n<p>I trying to modify your code to a recursion style, and it works, the \"new object\" goes wrong on my firefox, so I change it to = {}</p>\n\n<pre><code>function parse_obj_key(obj, loc, val) {\n if(!obj || typeof obj != 'object') {\n alert(\"error\")\n return null\n }\n var pos = loc.indexOf('.');\n var part = loc.substring(0, pos);\n var endpart = loc.substring(pos+1);\n\n if (!isNaN(parseInt(part)))\n part = parseInt(part);\n\n if (pos === -1) {\n if (val) {\n obj[loc] = val\n return obj\n }\n else\n return obj[loc]\n }\n\n if (val) {\n if (!(part in obj)) \n obj[part] = {}\n\n parse_obj_key(obj[part], endpart, val)\n return obj\n }\n else {\n return parse_obj_key(obj[part], endpart, val)\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T09:10:19.520", "Id": "656", "Score": "0", "body": "I much prefer a recursive style like this to \"while (true)\" if you can get away with it. I would say, though, that you might want to consider refactoring the validation of `obj` into a separate method. `parse_obj_key` would validate the arguments, then call into the recursive helper function. That way the arguments are re-validated on every recursion. Not a big problem in this instance, but a pattern to consider for deeper recursion or move complex argument validation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T07:40:59.673", "Id": "358", "ParentId": "340", "Score": "0" } }, { "body": "<p>My code is based off glebm's, but I've changed it so that array lookups must always use the <code>.</code> syntax. I made a few other tweaks such as creating an object chain if assigning to a nested key that doesn't yet exist.</p>\n\n<pre><code>function parse_obj_key(obj, key, value){\n var is_assigning = (value !== undefined);\n key = key.split('.'); \n\n var data = obj;\n var length = key.length - is_assigning;\n\n for (var i = 0; i &lt; length; i++) {\n var child = data[key[i]];\n var has_child = (child !== undefined);\n\n if (!has_child &amp;&amp; !is_assigning) {\n $.log(\"Invalid obj path: \" + key + \"\\n\" + JSON.stringify(obj));\n return null;\n }\n\n if (!has_child) {\n child = {};\n data[key[i]] = child;\n }\n\n data = child;\n }\n\n if (is_assigning) {\n data[key[i]] = value;\n } else {\n return data; \n }\n}\n</code></pre>\n\n<p>If you're trying to create an optional parameter, you should check if it is undefined using <code>if (param !== undefined)</code>, rather than just <code>if (param)</code>, otherwise you'll have trouble setting falsy values such as <code>false</code>, <code>null</code>, <code>0</code> and <code>\"\"</code>.</p>\n\n<p>One of the things that allows this code to be much shorter is the observation that in javascript, <code>arr['a']['b'][0]</code> is the same as <code>arr['a']['b']['0']</code> - that is to say, array lookup using an integer is no different from array lookup using a string that contains a number. This avoids the need to parse the numbers like you do.</p>\n\n<p>The other major saver is the use of split rather than indexing, which makes it easy to <code>for</code> loop over the parts of the key.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T09:47:48.993", "Id": "660", "Score": "0", "body": "Your code fails to return `null` on `parse_obj_key({a: null}, 'a')`. Replacing `(!child)` with `child !== undefined` might fix it. Cheers" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T10:17:51.520", "Id": "738", "Score": "0", "body": "Cheers. I should listen to my own advice :P" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T09:04:34.990", "Id": "412", "ParentId": "340", "Score": "0" } } ]
{ "AcceptedAnswerId": "353", "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T23:39:15.980", "Id": "340", "Score": "6", "Tags": [ "javascript", "parsing" ], "Title": "Javascript Object Placement / String Parsing Method" }
340
<p>This works but there must be a better way:</p> <pre><code>txtBox.InputScope = new InputScope { Names = { new InputScopeName { NameValue = InputScopeNameValue.Text } } }; </code></pre>
[]
[ { "body": "<p>I'm not really sure what you want from this, if all you want is to make it more readable, then a few well placed new-lines will make a world of difference. If you want to reduce the amount of code, I don't think there is much room for that other than switching constructors for <code>InputScopeName</code>.</p>\n\n<pre><code>txtBox.InputScope = new InputScope\n{\n Names =\n {\n new InputScopeName(InputScopeNameValue.Text)\n }\n};\n</code></pre>\n\n<p>Note: <code>Text</code> does not appear to be a <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.input.inputscopenamevalue.aspx\" rel=\"nofollow\">valid member</a> of <code>InputScopeNameValue</code>, but ill keep it for the sake of consistency with the question.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-09T10:06:30.763", "Id": "705", "ParentId": "341", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-27T23:57:41.817", "Id": "341", "Score": "3", "Tags": [ "c#" ], "Title": "Better way of setting input scope on text box in WP7" }
341
<p>I started out with the best of intentions, but this form got hacky real fast.</p> <p>It's purpose is to serve as a create new Student form. Also, if you want to view an existing Students information.</p> <p>Think of it as the CRU of CRUD.</p> <p>Here it is:</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Tutomentor.Branding; using Tutomentor.Data.Repositories; namespace Tutomentor.UI.Students { public partial class StudentInformation : Form { StudentRepository repo = new StudentRepository(); bool IsCreating = false; Student student; public StudentInformation() { InitializeComponent(); LoadComboBoxes(); LoadBranding(); IsCreating = true; } public StudentInformation(int studentID) { InitializeComponent(); LoadComboBoxes(); LoadBranding(); student = repo.FindStudent(studentID); LoadStudentInformation(student); } private void LoadComboBoxes() { cmbGrade.DisplayMember = "Name"; cmbGrade.ValueMember = "ID"; cmbGradeParalelo.DisplayMember = "Name"; cmbGradeParalelo.ValueMember = "ID"; GradeRepository repo = new GradeRepository(); cmbGrade.DataSource = repo.FindAllGrades(); } private void LoadStudentInformation(Student student) { cmbGrade.SelectedValue = student.GradeParalelo.Grade.ID; cmbGradeParalelo.SelectedValue = student.IDGrade; txtRude.Text = student.RUDE.ToString(); txtNombrePadre.Text = student.FatherName; txtProfesionPadre.Text = student.FatherProfession; txtCelularPadre.Text = student.MobilePhoneFather; txtLugarDeTrabajoPadre.Text = student.PlaceofWorkFather; txtNombreMadre.Text = student.MotherName; txtProfesionMadre.Text = student.MotherProfession; txtCelularMadre.Text = student.MobilePhoneMother; txtLugarDeTrabajoMadre.Text = student.PlaceofWorkMother; txtObservaciones.Text = student.Observations; txtNombre.Text = student.Name; txtApellidoPaterno.Text = student.FatherLastName; txtApellidoMaterno.Text = student.MotherLasteName; dtpFechaNacimiento.Value = Convert.ToDateTime(student.DateOfBirth); txtLugarNacimiento.Text = student.PlaceOfBirth; SetSex(student.Sex); txtCarnet.Text = student.Carnet; txtTelefono.Text = student.Telephone; txtCelular.Text = student.MobilePhone; txtDireccion.Text = student.Address; } private void SetSex(string p) { if (p == "M") { sexoMasculino.Checked = true; sexoFemenino.Checked = false; } else { sexoMasculino.Checked = false; sexoFemenino.Checked = true; } } private void LoadBranding() { this.Text = "Tutomentor - Agregando nuevo alumnos."; this.BackColor = Brand.PrimaryColor; panelBorderLeft.BackColor = Brand.HeaderColor; panelBorderRight.BackColor = Brand.HeaderColor; panelSeparator1.BackColor = Brand.SeparatorColor; } private void cmbGrade_SelectedIndexChanged(object sender, EventArgs e) { LoadGradeParalelos(); } private void LoadGradeParalelos() { GradeParaleloRepository repo = new GradeParaleloRepository(); Int64 gradeID = Convert.ToInt64(cmbGrade.SelectedValue); cmbGradeParalelo.DataSource = repo.FindAllGradeParalelos().Where(g =&gt; g.IDGrade == gradeID); } private void btnSave_Click(object sender, EventArgs e) { SaveInformation(); } private void SaveInformation() { if (IsCreating) { Student newStudent = new Student(); Int64 gradeId = Convert.ToInt64(cmbGradeParalelo.SelectedValue); newStudent.IDGrade = gradeId; newStudent.RUDE = Convert.ToInt64(txtRude.Text); /*Parents information.*/ newStudent.FatherName = txtNombrePadre.Text; newStudent.FatherProfession = txtProfesionPadre.Text; newStudent.MobilePhoneFather = FormatPhoneNumber(txtCelularPadre.Text); newStudent.PlaceofWorkFather = txtLugarDeTrabajoPadre.Text; newStudent.MotherName = txtNombreMadre.Text; newStudent.MotherProfession = txtProfesionMadre.Text; newStudent.MobilePhoneMother = FormatPhoneNumber(txtCelularMadre.Text); newStudent.PlaceofWorkMother = txtLugarDeTrabajoMadre.Text; /*newStudent information*/ newStudent.Name = txtNombre.Text; newStudent.FatherLastName = txtApellidoPaterno.Text; newStudent.MotherLasteName = txtApellidoMaterno.Text; newStudent.DateOfBirth = dtpFechaNacimiento.Value.ToShortDateString(); newStudent.PlaceOfBirth = txtLugarNacimiento.Text; newStudent.Sex = sexoMasculino.Checked ? sexoMasculino.Text : sexoFemenino.Text; newStudent.Telephone = FormatPhoneNumber(txtTelefono.Text); newStudent.MobilePhone = FormatPhoneNumber(txtCelular.Text); newStudent.Address = txtDireccion.Text; newStudent.Carnet = FormatPhoneNumber(txtCarnet.Text); newStudent.Observations = txtObservaciones.Text; repo.Add(newStudent); repo.Save(); MessageBox.Show("Se guardo el registro exitosamente.", "Exito!", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); ClearForm(); } else { Int64 gradeId = Convert.ToInt64(cmbGradeParalelo.SelectedValue); student.IDGrade = gradeId; student.RUDE = Convert.ToInt64(txtRude.Text); /*Parents information.*/ student.FatherName = txtNombrePadre.Text; student.FatherProfession = txtProfesionPadre.Text; student.MobilePhoneFather = FormatPhoneNumber(txtCelularPadre.Text); student.PlaceofWorkFather = txtLugarDeTrabajoPadre.Text; student.MotherName = txtNombreMadre.Text; student.MotherProfession = txtProfesionMadre.Text; student.MobilePhoneMother = FormatPhoneNumber(txtCelularMadre.Text); student.PlaceofWorkMother = txtLugarDeTrabajoMadre.Text; /*student information*/ student.Name = txtNombre.Text; student.FatherLastName = txtApellidoPaterno.Text; student.MotherLasteName = txtApellidoMaterno.Text; student.DateOfBirth = dtpFechaNacimiento.Value.ToShortDateString(); student.PlaceOfBirth = txtLugarNacimiento.Text; student.Sex = sexoMasculino.Checked ? sexoMasculino.Text : sexoFemenino.Text; student.Telephone = FormatPhoneNumber(txtTelefono.Text); student.MobilePhone = FormatPhoneNumber(txtCelular.Text); student.Address = txtDireccion.Text; student.Carnet = FormatPhoneNumber(txtCarnet.Text); student.Observations = txtObservaciones.Text; repo.Save(); MessageBox.Show("Se guardo el registro exitosamente.", "Exito!", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); this.Close(); } } private string FormatPhoneNumber(string p) { return p.Insert(3, "-"); } private void btnClear_Click(object sender, EventArgs e) { ClearForm(); } private void ClearForm() { Action&lt;Control.ControlCollection&gt; func = null; func = (controls) =&gt; { foreach (Control control in controls) if (control is TextBox) (control as TextBox).Clear(); else func(control.Controls); }; func(Controls); } } } </code></pre> <p>I don't know how to improve this class because every line of code is needed.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T01:16:03.153", "Id": "531", "Score": "1", "body": "I like to line up the equal signs. It makes the code easier to read for me." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T09:38:12.610", "Id": "64487", "Score": "0", "body": "You don't need to pass student to LoadStudentInformation if you're storing it in a class variable." } ]
[ { "body": "<p>Look at your code within this block inside the <code>SaveInformation</code> method.</p>\n\n<pre><code>if (IsCreating) \n{\n // code here\n}\nelse\n{\n // and here\n}\n</code></pre>\n\n<p>Start refactoring with this. How many lines of code are actually different here? Outside of a different object name (<code>newStudent</code> vs. <code>student</code>), there are not very many. Looks to me like you can create a method with the <code>Student</code> object as a parameter so that you can populate each of the relevant attributes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T01:20:27.110", "Id": "344", "ParentId": "343", "Score": "4" } }, { "body": "<p>You can simplify SaveInformation:</p>\n\n<pre><code>private void SaveInformation()\n{\n if (IsCreating)\n {\n Student newStudent = new Student();\n repo.Add(newStudent);\n }\n\n Int64 gradeId = Convert.ToInt64(cmbGradeParalelo.SelectedValue);\n newStudent.IDGrade = gradeId;\n newStudent.RUDE = Convert.ToInt64(txtRude.Text);\n\n /*Parents information.*/\n newStudent.FatherName = txtNombrePadre.Text;\n newStudent.FatherProfession = txtProfesionPadre.Text;\n newStudent.MobilePhoneFather = FormatPhoneNumber(txtCelularPadre.Text);\n newStudent.PlaceofWorkFather = txtLugarDeTrabajoPadre.Text;\n\n newStudent.MotherName = txtNombreMadre.Text;\n newStudent.MotherProfession = txtProfesionMadre.Text;\n newStudent.MobilePhoneMother = FormatPhoneNumber(txtCelularMadre.Text);\n newStudent.PlaceofWorkMother = txtLugarDeTrabajoMadre.Text;\n\n /*newStudent information*/\n newStudent.Name = txtNombre.Text;\n newStudent.FatherLastName = txtApellidoPaterno.Text;\n newStudent.MotherLasteName = txtApellidoMaterno.Text;\n newStudent.DateOfBirth = dtpFechaNacimiento.Value.ToShortDateString();\n newStudent.PlaceOfBirth = txtLugarNacimiento.Text;\n newStudent.Sex = sexoMasculino.Checked ? sexoMasculino.Text : sexoFemenino.Text;\n newStudent.Telephone = FormatPhoneNumber(txtTelefono.Text);\n newStudent.MobilePhone = FormatPhoneNumber(txtCelular.Text);\n newStudent.Address = txtDireccion.Text;\n newStudent.Carnet = FormatPhoneNumber(txtCarnet.Text);\n newStudent.Observations = txtObservaciones.Text;\n\n repo.Save();\n MessageBox.Show(\"Se guardo el registro exitosamente.\",\n \"Exito!\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Information,\n MessageBoxDefaultButton.Button1);\n\n if (IsCreating)\n {\n ClearForm();\n }\n else\n {\n this.Close();\n }\n}\n</code></pre>\n\n<p>The second one is a style thing. Some people like this others hate it. </p>\n\n<pre><code> private void SetSex(string p)\n {\n sexoMasculino.Checked = (p == \"M\");\n sexoFemenino.Checked = !sexoMasculino.Checked;\n }\n</code></pre>\n\n<p>Additional note: It is unclear from the given text if p will have already been sanitized. As a result (and depending on expected usage) you want to also check for \"m\" (if this is a possibility).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T02:41:45.293", "Id": "541", "Score": "0", "body": "I see no reason to hate the Boolean thing unless you really don't understand Boolean logic. Besides, it reads nicely: `sexoMasculino.Checked` gets whether `p` equals `\"M\"`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T08:39:53.110", "Id": "563", "Score": "0", "body": "I like the first line of the SetSex function: the `= (p == \"M\")` part. I would have used an If-statement. I think I will learn many useful coding idioms on this site. I wonder if it works in other languages." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T12:09:05.800", "Id": "568", "Score": "0", "body": "There is a problem with the case, though. What if the sex was passed as \"m\"? You must compare both cases or normalize first. a || between them might be reasonable. However it seems calling Equals is more efficient because the == operator calls that function in the end, so why not cut the middle man?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T12:49:13.343", "Id": "571", "Score": "1", "body": "@Voulnet: Thinking of efficiency here is a macro optimization. Until we can show that this is an efficiency bottleneck clarity is the only goal. Weather == or Equal is more clear is style. I prefer ==." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T21:55:50.360", "Id": "29662", "Score": "0", "body": "@LokiAstari Does visual studio offer any way to automatically align equals signs (or protect them during automatic reformatting)? I used to align mine back when all layout/alignment was manual; but stopped because the value of being able to fix idents/wrap long lines automatically was more beneficial than any manually inserted whitespace to align code into columns." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T01:24:11.757", "Id": "345", "ParentId": "343", "Score": "10" } }, { "body": "<p>Sorry folks, I cannot comment on anyone's reply because of my points. But I would refactor Martin York's SetSex() method to look like this: </p>\n\n<pre><code>private void SetSex(string p)\n{\n sexoMasculino.Checked = p.Equals(\"m\", StringComparison.OrdinalIgnoreCase);\n sexoFemenino.Checked = !sexoMasculino.Checked; \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T07:41:22.027", "Id": "559", "Score": "1", "body": "You would only redactor my version? Not the original version? :-(" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T11:12:17.863", "Id": "566", "Score": "1", "body": "@cod3-monk3y, how about ` = ((p == \"m\") || (p == \"M\"))`? Is it not more efficient than the method call?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T16:43:01.713", "Id": "587", "Score": "0", "body": "@Martin York You already refactored the original version, so you should take the credit for that. I wanted to comment but couldn't because of my points. @Geoffrey I don't know how efficient it is, but it looks more elegant and is more readable. If I've to be so much concerned about efficiency that I've to start thinking about calling function, I would better use assembly and not a high level language." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-26T02:17:02.877", "Id": "16458", "Score": "1", "body": "Whether or not it needs to be a case insensitive comparison depends upon how the incoming value is set, and what it means. Perhaps \"m\" should result in false, or more likely, perhaps it's impossible." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T03:54:59.730", "Id": "352", "ParentId": "343", "Score": "6" } }, { "body": "<pre><code>public StudentInformation()\n {\n InitializeComponent();\n LoadComboBoxes();\n LoadBranding();\n IsCreating = true;\n }\n\n public StudentInformation(int studentID)\n {\n InitializeComponent();\n LoadComboBoxes();\n LoadBranding();\n\n student = repo.FindStudent(studentID);\n LoadStudentInformation(student);\n\n }\n</code></pre>\n\n<p>can be refactored to,</p>\n\n<pre><code>// default IsCreating to true\nbool IsCreating = true;\n\npublic StudentInformation()\n {\n InitializeComponent();\n LoadComboBoxes();\n LoadBranding();\n }\n\n public StudentInformation(int studentID) : this()\n {\n IsCreating = false;\n student = repo.FindStudent(studentID);\n LoadStudentInformation(student);\n }\n</code></pre>\n\n<p>Also there is lot of code in your Form control class which should be part of controller (MVC) / presenter (MVP) like using those repositories also save information should be with controller part to notify the model to save data.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T10:38:25.383", "Id": "361", "ParentId": "343", "Score": "3" } }, { "body": "<p>One could also argue that you're mixing a lot of presentation code with business logic (creation/modification of data). Don't do that. <a href=\"http://en.wikipedia.org/wiki/Separation_of_presentation_and_content\" rel=\"nofollow\">Separate presentation from content</a>.</p>\n\n<p>Have the form call a ViewModel/Controller style of object that handles saving student information and contains the repository. Then the form code can focus purely on presentational elements, and the other object can handle validation, modification, etc. <a href=\"http://insideria.com/2010/10/pragmatic-design-patterns-sepa.html\" rel=\"nofollow\">Separation of concerns</a> is good, young padawan.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T01:56:04.840", "Id": "399", "ParentId": "343", "Score": "2" } }, { "body": "<p>First of all you have to use separate class for Business Logic (to save information) and then you should use that class object and add ALL text values as parameters in SaveInformation function rather than using textbox value directly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T10:49:43.723", "Id": "7017", "ParentId": "343", "Score": "3" } } ]
{ "AcceptedAnswerId": "345", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T01:09:00.223", "Id": "343", "Score": "14", "Tags": [ "c#", ".net", "winforms" ], "Title": "Form to create new students or view existing student information" }
343
<p>It's clever, but makes me vomit a little:</p> <pre><code>file = '0123456789abcdef123' path = os.sep.join([ file[ x:(x+2) ] for x in range(0,5,2) ]) </code></pre>
[]
[ { "body": "<p>Is there are reason you're not just doing:</p>\n\n<pre><code>path = os.sep.join([file[0:2], file[2:4], file[4:6]])\n</code></pre>\n\n<p>I think that my version is a little easier to parse (as a human), but if you need to extend the number of groups, your code is more extensible.</p>\n\n<p>Edit: and if we're looking for things that are easy to read but not necessarily the best way to do it...</p>\n\n<pre><code>slash = os.sep\npath = file[0:2] + slash + file[2:4] + slash + file[4:6]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T02:00:30.617", "Id": "347", "ParentId": "346", "Score": "10" } }, { "body": "<p>I have no idea what you're trying to do here, but it looks like you're splitting a string into groups of two a specified number of times? Despite the magic constants, etc. there's really no better way to <strong>do</strong> it, but I think there's certainly a better way to format it (I'm assuming these are directories since you're using os.sep):</p>\n\n<p>The below is I think a more clear way to write it:</p>\n\n<pre><code>file = '0123456789abcdef123'\ndir_len = 2\npath_len = 3\n\npath = os.sep.join(file[ x:(x+2) ] for x in range(0, dir_len * path_len-1, dir_len))\n</code></pre>\n\n<p>Note that the [] around the list comprehension is gone - it's now a <a href=\"http://linuxgazette.net/100/pramode.html\" rel=\"nofollow\">generator</a>. For this example it really doesn't matter which one you use, but since this is Code Review generators are another Python concept you should look at.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T02:20:27.817", "Id": "349", "ParentId": "346", "Score": "2" } } ]
{ "AcceptedAnswerId": "349", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T01:28:04.327", "Id": "346", "Score": "0", "Tags": [ "python" ], "Title": "Generating filesystem paths from a fixed string" }
346
<p>I wrote a bunch of Ruby code for a book project I've just finished. One criticism is that it is fine code but not very "ruby like". I agree my style was simplified for communication reasons, and although it's procedural code, it still feels "ruby-like" to me. </p> <p>For the representative example below, any ideas on making it more "Ruby like"?</p> <pre><code># Genetic Algorithm in the Ruby Programming Language # The Clever Algorithms Project: http://www.CleverAlgorithms.com # (c) Copyright 2010 Jason Brownlee. Some Rights Reserved. # This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.5 Australia License. def onemax(bitstring) sum = 0 bitstring.size.times {|i| sum+=1 if bitstring[i].chr=='1'} return sum end def random_bitstring(num_bits) return (0...num_bits).inject(""){|s,i| s&lt;&lt;((rand&lt;0.5) ? "1" : "0")} end def binary_tournament(pop) i, j = rand(pop.size), rand(pop.size) j = rand(pop.size) while j==i return (pop[i][:fitness] &gt; pop[j][:fitness]) ? pop[i] : pop[j] end def point_mutation(bitstring, rate=1.0/bitstring.size) child = "" bitstring.size.times do |i| bit = bitstring[i].chr child &lt;&lt; ((rand()&lt;rate) ? ((bit=='1') ? "0" : "1") : bit) end return child end def crossover(parent1, parent2, rate) return ""+parent1 if rand()&gt;=rate point = 1 + rand(parent1.size-2) return parent1[0...point]+parent2[point...(parent1.size)] end def reproduce(selected, pop_size, p_cross, p_mutation) children = [] selected.each_with_index do |p1, i| p2 = (i.modulo(2)==0) ? selected[i+1] : selected[i-1] p2 = selected[0] if i == selected.size-1 child = {} child[:bitstring] = crossover(p1[:bitstring], p2[:bitstring], p_cross) child[:bitstring] = point_mutation(child[:bitstring], p_mutation) children &lt;&lt; child break if children.size &gt;= pop_size end return children end def search(max_gens, num_bits, pop_size, p_crossover, p_mutation) population = Array.new(pop_size) do |i| {:bitstring=&gt;random_bitstring(num_bits)} end population.each{|c| c[:fitness] = onemax(c[:bitstring])} best = population.sort{|x,y| y[:fitness] &lt;=&gt; x[:fitness]}.first max_gens.times do |gen| selected = Array.new(pop_size){|i| binary_tournament(population)} children = reproduce(selected, pop_size, p_crossover, p_mutation) children.each{|c| c[:fitness] = onemax(c[:bitstring])} children.sort!{|x,y| y[:fitness] &lt;=&gt; x[:fitness]} best = children.first if children.first[:fitness] &gt;= best[:fitness] population = children puts " &gt; gen #{gen}, best: #{best[:fitness]}, #{best[:bitstring]}" break if best[:fitness] == num_bits end return best end if __FILE__ == $0 # problem configuration num_bits = 64 # algorithm configuration max_gens = 100 pop_size = 100 p_crossover = 0.98 p_mutation = 1.0/num_bits # execute the algorithm best = search(max_gens, num_bits, pop_size, p_crossover, p_mutation) puts "done! Solution: f=#{best[:fitness]}, s=#{best[:bitstring]}" end </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T07:17:46.503", "Id": "555", "Score": "6", "body": "Looked at your book, algorithm-wise - good explanations. but you should've asked a rubyist to take a look at the code before it got published :(" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T07:47:26.340", "Id": "561", "Score": "2", "body": "I'm just agreeing all over the place with you glebm. It's a bit insulting really. Like if I wrote a book on Middle East politics and US foreign policy but didn't bother to consult with experts on the matter. Oh well, at least the book is free in PDF form." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T08:33:39.590", "Id": "562", "Score": "4", "body": "It is time for the second edition." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T12:55:57.877", "Id": "572", "Score": "0", "body": "Please format your code using the code button in the format bar, not pre-tags. The way it is now, some of the code won't display because of `<` and `>` characters in it." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T05:46:46.240", "Id": "635", "Score": "0", "body": "Agreed, I should have got more ruby people to look at the book before I published it. I simply ran out of time, and in your eyes, it makes the work less professional. To be fair, it is not a ruby book, it is an AI book. From this perspective, the use of rubyisms is important but should be metered by the requirements of good communication (ability for non-ruby people to parse and port to their preferred language). The book is on github, I'd love to see a ruby-purist version of the sample code!!!! In fact, I'd really love to link to a \"jason\" and \"purist\" versions of each algorithm on the web." } ]
[ { "body": "<p>An easy one is to remove the <code>return</code> at the end of each method. Ruby automatically does a return of the last value. It's actually an extra method call to use <code>return</code>.</p>\n\n<p><strike>The only time you specifically need to use return is</strike> You don't even need to use return if you are returning multiple values:</p>\n\n<pre><code>def f\n [1,2]\nend\n\na,b = f\n</code></pre>\n\n<p>Again, using <code>return</code> costs an extra method call and those add up. If you can optimize your code by not using them you've just given yourself some free optimization.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T05:41:18.240", "Id": "550", "Score": "0", "body": "Ok, thanks. In this case, I think it would only apply to the \"onemax\", \"random_bitstring\", and \"point_mutation\" functions." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T05:44:46.023", "Id": "551", "Score": "1", "body": "No remove it on EVERY function. For instance in the `reproduce` method change the last line from `return children` to just `children`. The only time you need to use return in Ruby is if you are returning multiple values, e.g. `def f() return 1,2 end a,b = f()`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T07:13:03.343", "Id": "554", "Score": "0", "body": "better return multiple values like this: `def f() [1, 2] end`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T07:32:13.053", "Id": "557", "Score": "0", "body": "@glebm Agreed, I stand corrected. Return isn't even needed with multiple return values." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T05:38:41.173", "Id": "355", "ParentId": "354", "Score": "5" } }, { "body": "<p>Ruby library is quite powerful:</p>\n\n<p><code>onemax(bitstring)</code> can be simply <code>bitstring.count('1')</code></p>\n\n<p><code>random_bitstring(num_bits)</code> is probably better off implemented as <code>rand(2**num_bits).to_s(2)</code></p>\n\n<p>The first thing to check out is this <a href=\"http://ruby-doc.org/core-2.0/Enumerable.html\" rel=\"nofollow\">http://ruby-doc.org/core-2.0/Enumerable.html</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T05:51:32.227", "Id": "637", "Score": "0", "body": "Thanks for pointing out the count method - your onemax is excellent. I really do need to read the API more. The suggestion for random_bitstring, although elegant, I find difficult to parse. Granted mine is worse, but I feel like that a non-ruby person could figure out my version from reading a \"quick start language guide\", yours would require the API open in another tab. I am finding this case far less clear cut. Thanks again for the feedback!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T07:03:32.667", "Id": "357", "ParentId": "354", "Score": "7" } }, { "body": "<p>First a note on your general design: You use hashmaps to represent members of the population. I'd rather recommend you create a little class to represent them:</p>\n\n<pre><code>class Individual\n include Comparable\n\n attr_reader :bitstring, :fitness\n\n def initialize(bitstring)\n @bit_string = bitstring\n @fitness = onemax(bitstring)\n end\n\n def &lt;=&gt;(other)\n fitness &lt;=&gt; other.fitness\n end\nend\n</code></pre>\n\n<p>You'll now use <code>Individual.new(bitstring)</code> to create a new individual (which will automatically calculate its own fittness) and <code>individual.bitstring</code> and <code>individual.fitness</code> to get an individual's bitstring or fitness respectively.</p>\n\n<p>This has the benefit that now the logic of how to calculate an individuals fitness lives in the <code>Individual</code> class instead of in multiple place in the <code>search</code> method. This is a more natural place for it and makes it easier to find and change should you ever decide to use a different fitness function.</p>\n\n<p>Also note that I included Comparable, implementing <code>&lt;=&gt;</code> based on fitness. This means that you can now compare individuals to each other such that an individual is greater than another if and only if its fitness is greater. This allows you to use <code>&gt;</code> on two individuals as well as methods like <code>max</code> to get the individual with the greatest fitness out of an array of individuals. It also allows you to call <code>sort</code> on array of individuals without passing a block. This will simplify your code in some places.</p>\n\n<hr>\n\n<p>In a comment you mentioned that you don't want to use classes. However I still think that it would greatly improve your design to have the logic for creating new individuals and calculating their fitness in one single place, so you should at least factor it out into a method like this:</p>\n\n<pre><code>def create_individual(bitstring)\n {:bitstring =&gt; bitstring, :fitness =&gt; onemax(bitstring)}\nend\n</code></pre>\n\n<hr>\n\n<p>Now some notes on particular pieces of code:</p>\n\n<pre><code>bitstring.size.times {|i| sum+=1 if bitstring[i].chr=='1'}\n</code></pre>\n\n<p>As has already been mentioned, this can easily be replaced with a call to <code>count</code>. However as a general note I want to point out that it's good practice to avoid index-based loops wherever possible, so if <code>count</code> did not exist, I'd write the above like this:</p>\n\n<pre><code>bitstring.each_char {|c| sum+=1 if c == '1'}\n</code></pre>\n\n<p>Or for 1.8.6 compability:</p>\n\n<pre><code>bitstring.each_byte {|b| sum+=1 if b.chr == '1'}\n</code></pre>\n\n<hr>\n\n<pre><code>(0...num_bits).inject(\"\"){|s,i| s&lt;&lt;((rand&lt;0.5) ? \"1\" : \"0\")}\n</code></pre>\n\n<p>When dealing with <code>inject</code>, it's usually a good idea to keep the function simple, so it's more easily understandable. Often you can separate the logic of generating the elements from the logic of combining them, by using <code>map</code> before <code>inject</code>. This would make your code look like this:</p>\n\n<pre><code>(0...num_bits).map {|i| (rand&lt;0.5) ? \"1\" : \"0\"}.inject(\"\") {|s,i| s&lt;&lt;i}\n</code></pre>\n\n<p>Now there's two things to notice here:</p>\n\n<ol>\n<li>Whenever you call <code>map</code> on a range from 0 to some size, you might rather want to use <code>Array.new(size) {block}</code> which creates an array of the given size by calling the block <code>size</code> times.</li>\n<li>The smaller <code>inject</code> is now much easier to understand, but happens to be equivalent to calling <code>join</code>, so let's just do that.</li>\n</ol>\n\n<p>So your code becomes:</p>\n\n<pre><code>Array.new(num_bits) { (rand&lt;0.5) ? \"1\" : \"0\" }.join\n</code></pre>\n\n<p>This way you create a temporary array, which you didn't before, but on the other hand your code became much more understandable, so that little inefficiency should be worth it.</p>\n\n<hr>\n\n<pre><code>(pop[i][:fitness] &gt; pop[j][:fitness]) ? pop[i] : pop[j]\n</code></pre>\n\n<p>Thanks to the <code>Individual</code> class this now looks like this:</p>\n\n<pre><code>(pop[i] &gt; pop[j]) ? pop[i] : pop[j]\n</code></pre>\n\n<p>This isn't much different, but note that it now has the form <code>(x &gt; y) ? x : y</code>, which incidentally means \"the maximum of two objects\". In other words we can simplify this code by using the <code>max</code> method:</p>\n\n<pre><code>[ pop[i], pop[j] ].max\n</code></pre>\n\n<hr>\n\n<pre><code>bitstring.size.times do |i|\n bit = bitstring[i].chr\n</code></pre>\n\n<p>Again this should be <code>bitstring.each_char do |bit|</code> or <code>bitstring.each_byte do |b| bit = b.chr</code>.</p>\n\n<hr>\n\n<pre><code>\"\"+parent1 if rand()&gt;=rate\n</code></pre>\n\n<p><s>I'm not sure what the <code>\"\"+</code> is supposed to do here. Remove it. Note that <code>\"\"+x</code> is not a way to turn <code>x</code> into a string in ruby (like it would be in e.g. Java). Calling <code>\"\"+x</code> when <code>x</code> is not a string (or \"duck-string\"), will cause a type error.</s></p>\n\n<p>The fact that you're using <code>\"\"+</code> to create a copy is less than obvious (thus the above paragraph). If you use the <code>dup</code> method, whose sole purpose it is to create a copy, instead, it will be much more understandable.</p>\n\n<hr>\n\n<p>I'd also change the <code>crossover</code> method to return an individual rather than a string, which makes the code a bit simpler.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T06:05:08.283", "Id": "640", "Score": "0", "body": "Some great suggestions, thank-you for taking the time. I especially love the random bitstring suggestion. Regarding the use of the object, I explicitly chose a procedural paradigm for presentation although agree having objects can make the organization of the code much better. I had to drop each_char (and a few other funcs) for 1.8.6 support. The \"\"+parent1 was to make a quick copy of the string object (overly cautious, i know). Thanks again!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T11:50:57.137", "Id": "662", "Score": "0", "body": "@jasonb: If you can't use `each_char`, use `each_byte` at least (it will be the same except that you get an integer, which you need to call `chr` on). That's still better than iterating over the indices. To create a copy of an object, you should use `dup`, which makes it clear to the reader what you're doing." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T11:54:18.660", "Id": "664", "Score": "0", "body": "@jasonb: Even for procedural code it's still bad design to have the fitness code in several places inside the `search` method. If you don't want to use classes, I'd at least recommend a `create_individual` method which takes a bitstring and returns a hash with the bitstring and the fitness. This way the fitness calculation still takes place in a single location." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T13:41:09.987", "Id": "372", "ParentId": "354", "Score": "22" } }, { "body": "<p>I'm currently going through the book and yes, as admitted it's not the most Ruby-esque code I've ever seen, but I think it does achieve the main objectives of what it was set out to accomplish and I don't think the Ruby gets in the way of that.</p>\n\n<p>The thing I've noticed most when trying to following along, run, and even augment some of the methods was the general flow. There's a few things I can't say \"YOU SHOULD DO IT THIS WAY THUS SAYETH THE RUBY\" but it would just \"feel\" more comfortable if:</p>\n\n<ul>\n<li><p>The configurations were done at the beginning of the file in a Hash. As far as using a Hash, you see Hash configs a lot in Ruby, many times due to the use and reading of .yml config files so I guess I just expect configs to be done in a Hash. (If this were an application, I'd say put the configs in a .yml file, but I understand the desire to have the full solution encapsulated in a single file.)</p></li>\n<li><p>The \"search\" method definition were at the beginning of the file, right under a Hash outlining the config. (The calling of the search method still happens at the bottom in your if <strong>FILE</strong> section.)</p></li>\n</ul>\n\n<p>Ok so the at the beginning thing is definitely debatable, but I just found myself dropping in to each of these files, scrolling to the bottom, reading the config, scrolling up a little and reading the \"search\" method to get a high level view of what's going on, then scrolling to the top again to dig into the supporting methods.</p>\n\n<p>Another debatable style I've enjoyed in both reading and writing Ruby is using a space to pad the beginning and end of an inline block.</p>\n\n<p>So</p>\n\n<pre><code>children.sort!{|x,y| y[:fitness] &lt;=&gt; x[:fitness]}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>children.sort!{ |x,y| y[:fitness] &lt;=&gt; x[:fitness] }\n</code></pre>\n\n<p>Yeah it's a small thing and some people will say anything that adds extra keystrokes to typing is bad, but I find it much more readable.</p>\n\n<p>Also just now noticing some inconsistent spacing when using operators...and as you can probably guess, I vote for more spacing in most situations. ;)</p>\n\n<pre><code>def crossover(parent1, parent2, rate)\n return \"\"+parent1 if rand()&gt;=rate\n point = 1 + rand(parent1.size-2)\n return parent1[0...point]+parent2[point...(parent1.size)]\nend\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>def crossover(parent1, parent2, rate)\n return \"\" + parent1 if rand() &gt;= rate\n point = 1 + rand(parent1.size-2)\n return parent1[0...point] + parent2[point...(parent1.size)]\nend\n</code></pre>\n\n<p>And now I'm getting nit picky...so I'm done for now.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T04:51:47.667", "Id": "449", "ParentId": "354", "Score": "4" } } ]
{ "AcceptedAnswerId": "372", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T05:33:47.420", "Id": "354", "Score": "18", "Tags": [ "ruby", "genetic-algorithm" ], "Title": "Genetic algorithm for Clever Algorithms project" }
354
<p>I'm new to Hibernate so I need some advice/direction on doing Transactions.</p> <p>I have a DAO like</p> <pre><code>public class MyDao extends HibernateDaoSupport implements IMyDao { @Override public Foo getFoo(int id) { return (Foo)getHibernateTemplate().load(Foo.class, id); } } </code></pre> <p>With this setup (using HibernateDaoSupport), will Hibernate/Spring handle transactions for me? Some of the examples I see say yes, others show using</p> <pre><code>Transaction tx = getHibernateTemplate().getSessionFactory().getCurrentSession().beginTransaction(); </code></pre> <p>to get a Transaction in every DAO method.</p> <p>Right now I'm assuming my minimal DAO is correct but I want to do a "larger" transaction that includes a couple of Hibernate calls in one method. Would I use the manual Transaction method there? Do I have to use it everywhere? Thanks.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T14:04:41.497", "Id": "577", "Score": "0", "body": "Belongs on stackoverflow?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T15:04:44.883", "Id": "580", "Score": "2", "body": "Yup, the question here is clearly not \"does it make my ass look fat\", but \"does it work\" (see this meta answer : http://meta.codereview.stackexchange.com/questions/138/how-is-this-site-different-from-stackoverflow/141#141 )" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T19:09:09.853", "Id": "601", "Score": "0", "body": "I was torn on whether this belongs on SO or not since what I have might be right, I just want to know if it's the right way of doing it or not. I'm fine with moving it though." } ]
[ { "body": "<p>In general, you should never handle transactions in dao code, as you never know where the transaction boundary is. You should let whoever wants to control the transactions control them.</p>\n\n<p>Code that starts and commits a transaction in every dao method is likely to be problematic.</p>\n\n<p>Btw: not very keen at all on 'dao' but as you use it, so will i.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T23:18:03.980", "Id": "435", "ParentId": "356", "Score": "2" } }, { "body": "<p>I would personally introduce spring and their hibernate support into your application then you can use there hibernate transaction manager and define transactions in the xml file and then forget about them in the actual code</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T18:08:50.037", "Id": "808", "Score": "0", "body": "I actually have Spring set up and I thought using the HibernateDaoSupport would handle transactions automatically. I'll look into any needed xml changes, thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T16:53:23.513", "Id": "486", "ParentId": "356", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T05:55:18.000", "Id": "356", "Score": "2", "Tags": [ "java", "hibernate" ], "Title": "Hibernate transaction advice" }
356
<p>I want to write an Android <a href="http://developer.android.com/reference/android/widget/ListAdapter.html" rel="nofollow"><code>ListAdapter</code></a> to serve data from a database that look like this:</p> <pre><code>CREATE TABLE note (_id integer primary key autoincrement, content text not null) CREATE TABLE tag (_id integer primary key autoincrement, name text not null); CREATE TABLE relation (_id integer primary key autoincrement, noteid integer not null, tagid integer not null, idx integer not null); </code></pre> <p>I use this database to store notes and their associated tags as an ordered list. One requirement of the ListAdapter is that it must be able to update the ListView contents if the underlying data changes. I can query all the notes in the database with this query:</p> <pre><code>SELECT note._id AS noteid, note.content, relation.idx AS tagidx, tag.name FROM note LEFT JOIN relation ON (relation.noteid = note._id) LEFT JOIN tag ON (tag._id = relation.tagid) ORDER BY noteid, tagidx; </code></pre> <p>Which will give me results looking like this (null values shown for clarity):</p> <pre><code>0|foo bar baz|0|x 1|hello world|null|null 2|one more nn|0|yy 2|one more nn|1|y </code></pre> <p>As you can see, a note with more than one tag will be located on more than one row in the result. This means that I can't look at the cursor size to determine the number of notes, I need to traverse the entire Cursor to get a count. I don't want to do that.</p> <p>The solution I have come up with so far is to use two cursors: one with the query mentioned above and one with a query containing the number of rows in the notes table (<code>select count(*) from notes</code>). In the constructor I call <code>intializeCursors()</code>:</p> <pre><code>private void initializeCursors() { notesCursor.moveToFirst(); countCursor.moveToFirst(); count = countCursor.getInt(0); } </code></pre> <p>I have implemented <code>getItem()</code> like this:</p> <pre><code>public Note getItem(int position) { // notes is a List of notes that we have already read. if (position &lt; notes.size()) { return notes.get(position); } int cursorPosition = notes.size(); while (cursorPosition &lt;= position) { // Creates a note by reading the correct number of rows. Note note = NotesDb.noteFrom(notesCursor); notes.add(note); ++cursorPosition; } return notes.get(position); } </code></pre> <p>The adapter assumes that the cursors are being managed by some <a href="http://developer.android.com/reference/android/app/Activity.html" rel="nofollow"><code>Activity</code></a> that has called <a href="http://developer.android.com/reference/android/app/Activity.html#startManagingCursor(android.database.Cursor)" rel="nofollow"><code>startManagingCursor()</code></a> on them.</p> <p>So far so good, I guess. The problem is now how to handle the cursor being <a href="http://developer.android.com/reference/android/database/Cursor.html#requery()" rel="nofollow">requeried</a>. Since I have two cursors I need to register listeners for both of them and when I have received <a href="http://developer.android.com/reference/android/database/DataSetObserver.html#onChanged()" rel="nofollow"><code>onChange()</code></a> for both of them I can <code>initializeCursors()</code> and notify any listeners registered to my <a href="http://developer.android.com/reference/android/widget/ListAdapter.html" rel="nofollow"><code>ListAdapter</code></a> of a change in the its data.</p> <p>The requery scenario is the actual reason that I needed two cursors in the first place. I have not figured out a way to count the number of notes in a required cursor other than asking the database using another cursor.</p> <p>This is the best I have so far. I want to check the sanity of this approach with this group. :-) Is this two cursor approach too complicated? Perhaps I have missed some part of the API that solves this nicely for me?</p>
[]
[ { "body": "<p>I would suggest using the built-in <a href=\"http://developer.android.com/reference/android/widget/CursorAdapter.html\" rel=\"nofollow\">CursorAdapter</a> together with a <a href=\"http://developer.android.com/reference/android/database/sqlite/SQLiteCursor.html\" rel=\"nofollow\">SQLiteCursor</a>. You should be able to construct even your more complex query using the <a href=\"http://developer.android.com/reference/android/database/sqlite/SQLiteQueryBuilder.html\" rel=\"nofollow\">SQLiteQueryBuilder</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-13T12:00:42.330", "Id": "2926", "ParentId": "359", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T07:56:03.023", "Id": "359", "Score": "7", "Tags": [ "java", "android", "sqlite" ], "Title": "Android ListAdapter design advice" }
359
<p>Should my class pass parameters internally or reference class level scoped variables?</p> <p>I'm not sure on the best approach or style for procedure calls that have parameters. Should I go with the class level scoped variables?</p> <pre><code>public class YouOweTheGovernment { public float AmountToPay { get; private set; } public float ArbitraryTaxRate { get; private set; } public float Salary { get; private set; } public YouOweTheGovernment(float taxRate, float salary) { this.ArbitraryTaxRate = taxRate; this.Salary = salary; CalculateAmount(); } private void CalculateAmount() { this.AmountToPay = (this.Salary * (this.ArbitraryTaxRate / 100)); } } </code></pre> <p>Or explicitly pass parameters into a procedure?</p> <pre><code>public class YouOweTheGovernment { public float AmountToPay { get; private set; } public float ArbitraryTaxRate { get; private set; } public float Salary { get; private set; } public YouOweTheGovernment(float taxRate, float salary) { this.ArbitraryTaxRate = taxRate; this.Salary = salary; CalculateAmount(this.Salary, this.ArbitraryTaxRate); } private void CalculateAmount(float salary, float taxRate) { this.AmountToPay = (salary * (taxRate / 100)); } } </code></pre> <p>In my contrived example I think the first is clearer, but as a class grows in size and complexity it would make it harder to track what is coming from where.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-16T09:28:50.150", "Id": "134117", "Score": "2", "body": "Don't use binary floating point numbers (`float`/`double`) for money. Either use integers or `decimal`." } ]
[ { "body": "<p>Since this is Code Review, I will first start with mentioning that you are not validating the logical correctness of your numbers, salary can't be negative, for example (Unless you're an evil employer). You may have left it out to shorten the question, but consider it a reminder.</p>\n\n<p>If the Calculate amount function does just this single line, then a better approach for you is to take its line <code>this.AmountToPay = (salary * (taxRate / 100));</code> and put it in the constructor as well. If it is one line, why call a function, load a stack frame and store registers? Just inline that line of logic in the constructor itself, this way <code>AmountToPay</code> will be initialized with the values from the constructor's arguments, so its access will be faster because it's a local variable (beating the first example), and the logic that updates the <code>AmountToPay</code> will not need a function call including stacking up arguments (beating the second example).</p>\n\n<p>If, however, you plan on creating more than one constructor, then keep all the shared code in one place (An <code>init()</code> function).\nFor example suppose we wanted another constructor which also took your loans, then you might do this.</p>\n\n<pre><code>YouOweTheGov(float taxRate, float salary, float loans)\n{\n... Process logic relating to loans..\ninit(taxRate,salary); // this function updates ArbitraryTaxRate,Salary,AmountToPay\n}\n</code></pre>\n\n<p>Keep the shared logic in one place, don't call a function if it does a very small piece of code at the constructor because of function preparation overhead (and construction will happen a lot, especially when passing or returning objects!), but rather add the code in the constructor itself. If you have more than one constructor then keep all shared code in a function (don't repeat code!)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T01:47:08.953", "Id": "626", "Score": "2", "body": "You could also use constructor chaining over an init() method. It'll make you look cool at cocktail parties.http://www.csharp411.com/constructor-chaining/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T21:25:11.230", "Id": "43931", "Score": "0", "body": "@Orca; you had to comment `init()`. Wasn't the OP's method descriptive enough? It isn't self describing enoygh to reveal intent, so anyone new to this code would say 'what's init doing?', waste time seeing its assignments. With OP's, you know instantly. For your other point, the 'overhead' of a 16 bit function call, on a 3Ghz processor..; would you seriously go back to a client and say you think its a performance bottleneck in the system to calculate tax because you are calling a method? Properties ARE methods in the CLR, so you've already called 2 methods by assigning their initial values." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T11:54:52.367", "Id": "363", "ParentId": "362", "Score": "5" } }, { "body": "<p>I try to use <strong>class level scoped variables</strong> unless there is a specific reason not to. My reasoning for this is that it feels cleaner from an API standpoint.</p>\n\n<p>Some of the reasons I would pass explicit parameters:</p>\n\n<ul>\n<li>Increase the re-usability of the method.</li>\n<li>Make it clear to sub-types what variables are required for the method.</li>\n<li>Decouple the method from the specifics of the containing type.</li>\n</ul>\n\n<p>I would guess (hope) that there is much more reasoned and academic writing on this topic but I'm far enough removed from my collegiate days to have no idea what the name of that topic would be. As such, I tend to choose based on what \"feels\" right. If a method exists simply to clean up another method and/or encapsulate some bit of logic I tend to use a class-level scoped variable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T21:01:36.653", "Id": "43928", "Score": "0", "body": "Clean Code by Robert C. Martin spends a whole chapter on this. Functions ideally have no parameters (nomadic), 1 (monadic) or 2 (dyadic). When using 3 (triadic), you should review why and consider grouping them together in another class. Why? If these 3 have an association here, there /might/ be other associations. Params types don't count as they are arrays. Constructors with large amounts of params should be switched to properties and used as DTOs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-14T19:33:32.630", "Id": "347739", "Score": "0", "body": "I agree - as long as good object-oriented principles (SOLID) are being followed. In many cases, I've run into a God Class with so many class-scoped variables, it's like the global pollution of C/BASIC days past." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T14:31:21.287", "Id": "375", "ParentId": "362", "Score": "7" } }, { "body": "<p>In addition to the suggestions posted already, I'd recommend going a step farther with your <code>CalculateAmount</code> method:</p>\n\n<pre><code>public class YouOweTheGovernment\n{\n public float AmountToPay { get; private set; }\n public float ArbitraryTaxRate { get; private set; }\n public float Salary { get; private set; }\n\n public YouOweTheGovernment(float taxRate, float salary)\n {\n this.ArbitraryTaxRate = taxRate;\n this.Salary = salary;\n\n this.AmountToPay = CalculateAmount(this.Salary, this.ArbitraryTaxRate);\n }\n\n private float CalculateAmount(float salary, float taxRate)\n { \n return (salary * (taxRate / 100));\n }\n}\n</code></pre>\n\n<p>Since this removes the side effect assignment, the constructor reads cleaner and that method can be reused more easily. If you don't want an immutable object, you'll have to recalculate every time the <code>salary</code> and <code>taxRate</code> change. But it looks like you do since you have the setters private.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T14:58:13.230", "Id": "376", "ParentId": "362", "Score": "3" } }, { "body": "<p>Don't store what you can calculate:</p>\n\n<pre><code>public class YouOweTheGovernment\n{\n public float AmountToPay\n {\n get { return Salary * (ArbitraryTaxRate / 100); }\n }\n public float ArbitraryTaxRate { get; private set; }\n public float Salary { get; private set; }\n\n public YouOweTheGovernment(float taxRate, float salary)\n {\n this.ArbitraryTaxRate = taxRate;\n this.Salary = salary;\n }\n}\n</code></pre>\n\n<p>Your <code>AmountToPay</code> field is basically a cache, and caching is notoriously problematic. Case in point: even your tiny code here has a cache invalidation bug. If you change the tax rate or salary, you aren't recalculating the amount to pay.</p>\n\n<p>Every time you add a field, ask yourself \"does this field store unique information that no other field stores?\" If the answer is no, don't create the field. The less state you have, the easier it is to understand your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T20:27:54.353", "Id": "607", "Score": "0", "body": "I see what you're saying and it's something I hadn't considered. Although your code calculates the AmountToPay each time, the salary could still change leaving the same bug? also to change the salary the constructor would need to be called again thus creating a new object?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T20:48:21.133", "Id": "609", "Score": "0", "body": "You can't call the constructor again for the same object, Rob. If your design must provide for the salary or taxrate to be changed after construction, then make the setter public instead of private. You must make sure that any value dependent on this change (in this case AmountToPay) must change too, to be in a consistent sane state, which this answer provides. Notice that if salary and taxrate shouldn't change after construction, then you'd be better of caching AmountToPay after construction for faster access." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T08:17:00.450", "Id": "654", "Score": "0", "body": "my comment was poorly worded, I was trying to say that your example would also have the same invalidation bug you mention but that bug doesn't really exist in this example as the salary and taxRate can only be set when the object is created, theses values can never become out of sync with the AmountToPay. I do think the code is cleaner if the AmountToPay is always calculated." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T18:28:40.230", "Id": "811", "Score": "0", "body": "@Rob: If the salary changed, subsequent calls to `AmountToPay` would take the new salary into account. There's no caching, so there's no cache invalidation to worry about." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T18:30:21.210", "Id": "812", "Score": "2", "body": "@Voulnet: You're not better off caching AmountToPay for faster access. Caching adds complexity to the code. Even though this class is simple now, it may not be in the future, and cache invalidation bugs are some of the hardest to find. The simple solution is to not cache in the first place. If your profiler has revealed performance problems, then it may make sense to cache. In that case, the cached data should be clearly marked as such." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-01T08:45:07.790", "Id": "842", "Score": "0", "body": "Yes, controlling cache consistency is difficult. However my condition to the asker regarding caching was clear: If he was sure those values don't change after construction." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T18:43:01.800", "Id": "382", "ParentId": "362", "Score": "9" } }, { "body": "<p>The second <code>CalculateAmount</code> method is evil. If a class invariant is supposed to be that <code>AmountToPay</code> is the amount of tax due for Salary and <code>ArbitraryTaxRate</code>, calling <code>CalculateAmount</code> with anything other than those parameters would break the class invariant. If you want to pass <code>Salary</code> and <code>ArbitraryTaxRate</code> to a method, then that method should either:</p>\n\n<ol>\n<li>Be a function which returns the calculated amount but does not disturb anything in the class, or</li>\n<li>Set the backing fields for <code>Salary</code> and <code>ArbitraryTaxRate</code> to the indicated values, and update <code>AmountToPay</code> appropriately.</li>\n</ol>\n\n<p>If you use the first approach, you could opt to make the function static. It's possible that changes in tax rules might require the function to make use of instance variables that weren't in the original parameter list. Such a change could be problematic if the function were public (suggesting that perhaps it shouldn't be static) but shouldn't pose any difficulty if it's private.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T22:03:22.830", "Id": "390", "ParentId": "362", "Score": "5" } }, { "body": "<p>I'd also want to add something else that others didn't.</p>\n\n<p>I'd rather remove the <code>private set</code> in all your properties because what private setter really says is that your value of that properties might change in the class somewhere else, which obviously is not the case. </p>\n\n<p>So instead of leaving the wrong intentions you can make all the properties get only and initialize them in the constructor, this way you will be more explicit in your meaning. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-14T22:47:30.713", "Id": "182824", "ParentId": "362", "Score": "1" } } ]
{ "AcceptedAnswerId": "375", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T11:14:15.870", "Id": "362", "Score": "13", "Tags": [ "c#", "comparative-review", "classes", "finance" ], "Title": "\"Do you owe the government?\" classes" }
362
<p>I've built a custom control that generates a tab style navigation. Each page might have different tabs to display, the aim was to modularise it so I can make global changes to all the tabs.</p> <p><strong>TabMenu.ascx</strong></p> <pre><code>&lt;%@ Control Language="C#" AutoEventWireup="true" CodeFile="TabMenu.ascx.cs" Inherits="TabMenu" %&gt; &lt;asp:Panel runat="server" ID="TabMenuWrapper" CssClass="tabWrapper"&gt; &lt;/asp:Panel&gt; </code></pre> <p><strong>TabMenu.ascx.cs</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Collections; public partial class TabMenu : System.Web.UI.UserControl { public string TabGroup { get; set; } // The tab group this control belongs to public int SelectedTab { get; set; } // Index of selected tab protected void Page_Load(object sender, EventArgs e) { ArrayList tabCollection = new ArrayList(); MenuTab myTab; // Artorking tab group if (this.TabGroup.ToLower() == "artwork") { myTab = new MenuTab() { linkURL = "artworkHome.aspx", linkText = "First!" }; tabCollection.Add(myTab); myTab = new MenuTab() { linkURL = "artworkHome.aspx", linkText = "Second!" }; tabCollection.Add(myTab); myTab = new MenuTab() { linkURL = "artworkHome.aspx", linkText = "3rd!" }; tabCollection.Add(myTab); myTab = new MenuTab() { linkURL = "artworkHome.aspx", linkText = "Fourth!" }; tabCollection.Add(myTab); } // Add tabs to the page for (int i = 0; i &lt; tabCollection.Count; i++) { MenuTab thisTab = ((MenuTab)(tabCollection[i])); thisTab.CreateTab(); if (i == this.SelectedTab) { thisTab.tabPanel.CssClass = "tab tabSelected"; } TabMenuWrapper.Controls.Add(thisTab.tabPanel); } TabMenuWrapper.Controls.Add(new Panel(){CssClass = "clear"}); } } // A menu tab public class MenuTab { public string linkURL; public string linkText; public HyperLink tabLink; public Panel tabPanel; // Create internal controls public void CreateTab() { this.tabLink = new HyperLink() { NavigateUrl = this.linkURL, Text = this.linkText }; this.tabPanel = new Panel() { CssClass = "tab" }; this.tabPanel.Controls.Add(this.tabLink); } } </code></pre> <p>Used as follows:</p> <pre><code>&lt;CrystalControls:TabMenu runat="server" ID="TopMenu" TabGroup="Artwork" SelectedTab="1" /&gt; </code></pre> <p>And renders like:</p> <pre><code>&lt;div class="tab"&gt; &lt;a href="Controls/artworkHome.aspx"&gt;First!&lt;/a&gt; &lt;/div&gt;&lt;div class="tab tabSelected"&gt; &lt;a href="Controls/artworkHome.aspx"&gt;Second!&lt;/a&gt; &lt;/div&gt;&lt;div class="tab"&gt; &lt;a href="Controls/artworkHome.aspx"&gt;3rd!&lt;/a&gt; &lt;/div&gt;&lt;div class="tab"&gt; &lt;a href="Controls/artworkHome.aspx"&gt;Fourth!&lt;/a&gt; &lt;/div&gt;&lt;div class="clear"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Is this a good design?</p>
[]
[ { "body": "<p>Yes the design looks good but it would be really better if you could replace that ArrayList with a Generic Collection.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T17:03:20.863", "Id": "379", "ParentId": "364", "Score": "4" } }, { "body": "<p>It might be better to render the control as an unordered list. This is more semantically correct and normal practice for menu-type controls (which tabs are, if you think about it).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T20:53:58.727", "Id": "384", "ParentId": "364", "Score": "5" } }, { "body": "<p>Step:</p>\n\n<ul>\n<li>Open a Blank Default.aspx page from visual studio 2005.</li>\n<li>Go to the solution explorer and right click on to the Default.aspx and then click on the Add New Item.</li>\n<li>After that you have to select the Web User Control.ascx file from add new item dialog box.</li>\n<li>That page will be the same like as default asp page draw your user control on that page.</li>\n<li><p>Code on the User Control.ascx page:</p>\n\n<pre><code>&lt;%@ Control Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"WebUserControl.ascx.cs\" Inherits=\"WebUserControl\" %&gt;\n&lt;table style=\"width: 330px\"&gt;\n &lt;tr&gt;\n &lt;td style=\"height: 148px\" align=\"center\"&gt;\n &lt;asp:Label ID=\"Label1\" runat=\"server\" Text=\"Thanks To awadh Sir\" Font-Bold=\"True\" Font-Size=\"XX-Large\" ForeColor=\"Red\" Visible=\"False\"&gt;&lt;/asp:Label&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td style=\"height: 55px\" align=\"center\"&gt;\n &lt;asp:Button ID=\"Button1\" runat=\"server\" Text=\"Button\" OnClick=\"Button1_Click\" /&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table&gt;\n</code></pre></li>\n</ul>\n\n<p>For more details please check out this link...</p>\n\n<p><a href=\"http://www.mindstick.com/Articles/535bd817-c3c1-46dd-be9c-f14e42c7db78/?Creating%20User%20Define%20Control%20in%20ASP%20.Net\" rel=\"nofollow\">http://www.mindstick.com/Articles/535bd817-c3c1-46dd-be9c-f14e42c7db78/?Creating%20User%20Define%20Control%20in%20ASP%20.Net</a></p>\n\n<p>Thanks</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-06T10:08:28.587", "Id": "7526", "ParentId": "364", "Score": "2" } } ]
{ "AcceptedAnswerId": "384", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T12:15:44.040", "Id": "364", "Score": "10", "Tags": [ "c#", "asp.net" ], "Title": "ASP.net custom user control design" }
364
<p>I've had to make several functions to turn some structures into strings. I am a still green when it comes C so I am unsure if I am doing this a very awkward way. The system I am coding for does not have snprintf, I know that would be far more elegant, however I cannot use it. Any advice?</p> <pre><code>int device_to_string(char* const asString, pDevice dev, size_t maxLength) { char* ipAsString; size_t actualLength; struct in_addr addr; if (dev == NULL) { return NULL_ERROR; } addr.s_addr = dev-&gt;ip; ipAsString = inet_ntoa(addr); actualLength = strlen("name=") + strlen(dev-&gt;name) + strlen("&amp;ip=") + strlen(ipAsString) + strlen("&amp;mac=") + strlen(dev-&gt;mac) + strlen("&amp;type=") + strlen(dev-&gt;type) + 1; if (actualLength &gt; maxLength) { return SIZE_ERROR; } strncat(asString, "name=", strlen("name=")); strncat(asString, dev-&gt;name, strlen(dev-&gt;name)); strncat(asString, "&amp;ip=", strlen("&amp;ip=")); strncat(asString, ipAsString, strlen(ipAsString)); strncat(asString, "&amp;mac=", strlen("&amp;mac=")); strncat(asString, dev-&gt;mac, strlen(dev-&gt;mac)); strncat(asString, "&amp;type=", strlen("&amp;type=")); strncat(asString, dev-&gt;type, strlen(dev-&gt;type)); asString[actualLength] = '\0'; return NO_ERROR; } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T12:39:07.527", "Id": "570", "Score": "0", "body": "I assume that since your system doesn't have `snprintf` that you also don't have `sprintf` (http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/)?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T14:03:37.537", "Id": "576", "Score": "2", "body": "Is it possible that you might have characters that need to be URL encoded?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T14:11:54.487", "Id": "578", "Score": "0", "body": "@Michael, good point I hadn't thought of that." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T16:23:05.927", "Id": "135358", "Score": "0", "body": "I really like sprintf(). If it were me, I'd look at implementing my own simple version. It would make the code in your main routine look so much cleaner." } ]
[ { "body": "<p>Yeah, without <code>snprintf</code> and <code>sprintf</code> it gets a bit tedious, but I think this code is actually quite clear. You use your horizontal and vertical whitespace very well, and it's clear what you're doing with each block of code. You have also controlled for any possible issues that might come up (null pointer, insufficient buffer length, etc). Maybe there's a more concise way to do it, but in terms of clarity and maintainability I think this code will suffice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T12:36:22.930", "Id": "367", "ParentId": "365", "Score": "5" } }, { "body": "<p>One thing I would personally do would be to move the string concatenation into its own function since I see you have repeated the same 2 lines multiple times:</p>\n\n<pre><code>strncat(asString, \"name=\", strlen(\"name=\"));\nstrncat(asString, dev-&gt;name, strlen(dev-&gt;name));\n</code></pre>\n\n<p>I'd have something like:</p>\n\n<pre><code>void addParam( char *paramString, const char *paramName, const char *paramValue )\n{\n strncat( paramString, paramName, strlen( paramName );\n strncat( paramString, paramValue, strlen( paramValue );\n}\n</code></pre>\n\n<p>Reduces the length of your function and makes it slightly cleaner, imho.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T14:58:38.637", "Id": "377", "ParentId": "365", "Score": "5" } }, { "body": "<p>There's a bigger-picture issue here; this kind of manual string manipulation is a Bad Idea. It's guaranteed to be buggy, often with security consequences.</p>\n\n<p>You ought to use (preferred) or at least implement a string utility class. Here are a couple examples:</p>\n\n<ul>\n<li><a href=\"http://git.gnome.org/browse/glib/tree/glib/gstring.h\" rel=\"nofollow\">http://git.gnome.org/browse/glib/tree/glib/gstring.h</a></li>\n<li><a href=\"http://cgit.freedesktop.org/dbus/dbus/tree/dbus/dbus-string.h\" rel=\"nofollow\">http://cgit.freedesktop.org/dbus/dbus/tree/dbus/dbus-string.h</a></li>\n<li><a href=\"ftp://vsftpd.beasts.org/users/cevans/untar/vsftpd-2.3.2/str.h\" rel=\"nofollow\">ftp://vsftpd.beasts.org/users/cevans/untar/vsftpd-2.3.2/str.h</a></li>\n</ul>\n\n<p>This way all your string code will be much more concise, and entire classes of bugs eliminated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T04:17:56.680", "Id": "727", "Score": "0", "body": "He's using C -- a class isn't an option." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T14:54:08.330", "Id": "743", "Score": "0", "body": "Classes aren't built into the language, but certainly you can and should use classes anyway. All three links I posted have an example for strings. GLib has many many more examples in it, too. A class is just some data plus some methods. You don't have to have syntactic sugar for it. GLib even gives you the means to do virtual functions and so on." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T15:08:18.223", "Id": "744", "Score": "0", "body": "To be clear, all three links have an example *in C*" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T16:09:54.307", "Id": "416", "ParentId": "365", "Score": "2" } }, { "body": "<p>Given the specification of <code>strncat()</code>, you are misusing it; if you must use a concatenation operation, simply use <code>strcat()</code>.</p>\n\n<p>For reference, the C standard says:</p>\n\n<blockquote>\n <p>§7.21.3.2 The <code>strncat</code> function</p>\n \n <p><strong>Synopsis</strong></p>\n\n<pre><code>#include &lt;string.h&gt;\nchar *strncat(char * restrict s1, const char * restrict s2, size_t n);\n</code></pre>\n \n <p><strong>Description</strong></p>\n \n <p>The <code>strncat</code> function appends not more than <code>n</code> characters (a null character and\n characters that follow it are not appended) from the array pointed to by <code>s2</code> to the end of\n the string pointed to by <code>s1</code>. The initial character of <code>s2</code> overwrites the null character at the\n end of <code>s1</code>. A terminating null character is always appended to the result.<sup>261)</sup> </p>\n \n <p><sup>261)</sup> Thus, the maximum number of characters that can end up in the array pointed to by <code>s1</code> is <code>strlen(s1)+n+1</code>.</p>\n</blockquote>\n\n<p>Now, don't get me wrong - what you are doing is safe, because you've previously checked the length, but making <code>strncat()</code> do the donkey work of checking the length is really pointless. You are also not telling the whole truth to <code>strncat()</code>; there is more space in the target buffer than you are admitting. That is safe, but it is a bit wasteful.</p>\n\n<hr>\n\n<p>I suggest using a simple function such as:</p>\n\n<pre><code>char *copy_string(char *target, const char *source)\n{\n strcpy(target, source);\n return(target + strlen(source));\n}\n\ntarget = asString;\ntarget = copy_string(target, \"name=\");\ntarget = copy_string(target, dev-&gt;name);\ntarget = copy_string(target, \"&amp;ip=\");\ntarget = copy_string(target, ipAsString);\ntarget = copy_string(target, \"&amp;mac=\");\ntarget = copy_string(target, dev-&gt;mac);\ntarget = copy_string(target, \"&amp;type=\");\ntarget = copy_string(target, dev-&gt;type);\n</code></pre>\n\n<p>One advantage of this is that it avoids quadratic behaviour. As your output string grows longer, the <code>strncat()</code> operation gradually has to skip over more and more characters each time it is called. With long enough strings, this can become a measurable overhead. It is a nuisance that <code>strcpy()</code> et al return the start address of the string instead of the address of the null at end of the string; it means you end up scanning it twice - once to copy, once to determine the length.</p>\n\n<hr>\n\n<p>That notation is still a bit tedious to use. I have previously created variable-length argument list functions like this:</p>\n\n<pre><code>#include &lt;stdarg.h&gt;\n\nchar *vstrcpy(char *buffer, size_t buflen, ...)\n{\n const char *arg;\n char *bufend = buffer + buflen;\n char *target = buffer;\n va_list args;\n\n va_start(args, buflen);\n while ((arg = va_arg(args, const char *)) != 0)\n {\n size_t arglen = strlen(arg);\n if (target + arglen &gt;= bufend)\n return(0);\n strcpy(target, arg);\n target += arglen;\n }\n return(target);\n}\n\ntarget = vstrcpy(asString, maxLength, \"name=\", dev-&gt;name,\n \"&amp;ip=\", ipAsString,\n \"&amp;mac=\", dev-&gt;mac,\n \"&amp;type=\", dev-&gt;type, (const char *)0);\nif (target == 0)\n ...something went wrong despite your pre-computation...\n</code></pre>\n\n<p>Note that you must provide an explicit cast to that final end marker; you would be invoking undefined behaviour on Windows 64 (as a specific example) if you omitted the cast. This is as notationally convenient as the equivalent <code>snprintf()</code> (it requires you to write a null pointer at the end instead of a format string consisting of repeated <code>%s</code> operations near the beginning), and it is as safe. You can decide on the best return value - I've chosen NULL to indicate that there wasn't enough space and a pointer to the final null if there is enough room. You could mimic <code>snprintf()</code> more closely if you calculated the full length that would be required, just making sure to skip the copying when you've reached the end of the string. You probably then need to use offsets rather than pointers because although you are guaranteed to be able to evaluate <code>buffer + buflen</code>, you are not guaranteed to be able to evaluate <code>buffer + buflen + 1</code>. That design leads to:</p>\n\n<pre><code>#include &lt;stdarg.h&gt;\n\nsize_t vstrcpy(char *buffer, size_t buflen, ...)\n{\n const char *arg;\n char *target = buffer;\n size_t offset = 0;\n va_list args;\n\n va_start(args, buflen);\n while ((arg = va_arg(args, const char *)) != 0)\n {\n size_t arglen = strlen(arg);\n if (offset + arglen &lt; buflen)\n strcpy(target + offset, arg);\n offset += arglen;\n }\n return(offset);\n}\n\nlen = vstrcpy(asString, maxLength, \"name=\", dev-&gt;name,\n \"&amp;ip=\", ipAsString,\n \"&amp;mac=\", dev-&gt;mac,\n \"&amp;type=\", dev-&gt;type, (const char *)0);\n\nif (len &gt;= maxLength)\n ...something went wrong despite your pre-computation...\n</code></pre>\n\n<p>This only copies whole arguments that fit. If there are 20 characters left in the buffer but the next string is 30 characters long, then the 20 characters are left unused. You still get told the actual length of the space required, though, and are guaranteed no overflow. If you have different requirements (such as copying as much as possible, even if it means a partial argument copy), then modify the code to do as you require. In my book, if the strings don't fit where I'm trying to place them, I've screwed up.</p>\n\n<hr>\n\n<p>I'm not sure if modern optimizing compilers pre-compute <code>strlen(\"string constant\")</code>. If they don't, you can get a small benefit from using <code>sizeof(\"string constant\")-1</code> instead, where the <code>-1</code> accounts for the terminal null that <code>sizeof()</code> includes in the size it returns.</p>\n\n<hr>\n\n<p>This example is not big enough to benefit from a table-driven approach to assembling the string. Occasionally, if the structures have enough elements in them, you can use a table-driven approach with the <code>offsetof()</code> macro identifying the start locations of the string members in the data structure. You might need to encode the types for mixed types (such as the IP address, or numbers that have to be converted to a string before printing). It is those complications that mean you need a considerable number of elements in the structures before you use the technique.</p>\n\n<p>In outline, for a structure that only contains null terminated strings, you can do:</p>\n\n<pre><code>struct description\n{\n const char *tag;\n size_t offset;\n};\n\nstatic const struct description dev_desc[] =\n{\n { \"name=\", offsetof(pDevice, name) },\n { \"&amp;ip=\", offsetof(pDevice, ip) }, // Taking liberties here!\n { \"&amp;mac=\", offsetof(pDevice, mac) },\n { \"&amp;type=\", offsetof(pDevice, type) },\n};\nenum { DEV_DESC_SIZE = sizeof(dev_desc) / sizeof(*dev_desc) };\n\nsize_t offset = 0;\nfor (size_t i = 0; i &lt; DEV_DESC_SIZE; i++)\n{\n offset = vstrcpy(&amp;asString[offset], maxLength - offset,\n dev_desc[i].tag, ((char *)&amp;dev + dev_desc[i].offset),\n (const char *)0);\n if (offset &gt; maxLength)\n break;\n}\n</code></pre>\n\n<p>This iterates through the fields in the structure <code>dev</code> using the control information from the descriptor array <code>dev_desc</code>. The expressions get more complex if you have to deal with other types than just character strings. If you ever have the misfortune to deal with structures with hundreds of elements, though, this can be a life-saver since you reduce the code to a simple loop and a simple table which encapsulates the complexity of the structure. (I see <a href=\"https://codereview.stackexchange.com/users/489/jerry-coffin\">Jerry Coffin</a> gave an answer using some of this idea, but I think my version has some merits over his.)</p>\n\n<hr>\n\n<p>Your final assignment buys you nothing:</p>\n\n<pre><code> asString[actualLength] = '\\0';\n</code></pre>\n\n<p>The null was inserted by the final <code>strncat()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T10:29:11.240", "Id": "458", "ParentId": "365", "Score": "4" } } ]
{ "AcceptedAnswerId": "367", "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T12:26:13.537", "Id": "365", "Score": "8", "Tags": [ "c", "strings" ], "Title": "Struct to web style string" }
365
<p>I've been doing a simple Tic-Tac-Toe with PHP, generating only HTML code.</p> <p>A few notes:</p> <ul> <li>I didn't bother yet to give an AI to the opponents (the Os), and it is intentional. </li> <li>There is no CSS style to it, I intend to append it with a css file. </li> <li>tictactoe.php is naturally the name of the script itself, so each links are refering to the page itself.</li> </ul> <p>Now I don't know if I did everything correctly, here are my concern:</p> <ul> <li>If I want to expand the functionalities of the game in the future (adding javascript, opponent AIs, new game features), I fear that the structure of the code is not adapted for it. Should I change my code so it is Object Oriented? <strong>EDIT</strong> I have in mind to add new feature to the game, like powers who would change the state of the board, like rewind to a previous state and; some css and javascript in a non-intrusive way and add some way to check if options are disabled (like javascript/flash), or check for the version of the browser for html5/css3 features.</li> <li>As for now, it is easy to "cheat" and directly introduce the wished board state. I would like to prevent that, and if possible without using javascript, as I want the game to be playable also without it.</li> </ul> <pre><code>&lt;table&gt; &lt;?php //Determine if a player as aligned three of its symbols and return the id of the player (1 //for X Player, -1 for O Player(Computer)). Otherwise return 0; function isWinState($board){ $winning_sequences = '012345678036147258048642'; for($i=0;$i&lt;=21;$i+=3){ $player = $board[$winning_sequences[$i]]; if($player == $board[$winning_sequences[$i+1]]){ if($player == $board[$winning_sequences[$i+2]]){ if($player!=0){ return $player; } } } } return 0; } //Player O plays its turn at random function OsTurn($board){ if(in_array(0,$board)){ $i = mt_rand(0,8); while($board[$i]!=0){ $i = mt_rand(0,8); } $board[$i]=-1; } return $board; } $winstate = 0; $values = array(); if(empty($_GET['values'])){ //initializing the board $values = array_fill(0,9,0); //determine who begins at random if(mt_rand(0,1)){ $values = OsTurn($values); } }else{ //get the board $values = explode(',',$_GET['values']); //Check if a player X won, if not, player 0 plays its turn. $winstate = isWinState($values); if($winstate==0){ $values = OsTurn($values); } //Check if a player 0 won $winstate = isWinState($values); } //Display the board as a table for($i=0;$i&lt;9;$i++){ //begin of a row if(fmod($i,3)==0){echo '&lt;tr&gt;';} echo '&lt;td&gt;'; //representation of the player token, depending on the ID if($values[$i]==1){ echo 'X'; }else if($values[$i]==-1){ echo 'O'; }else{ //If noone put a token on this, and if noone won, make a link to allow player X to //put its token here. Otherwise, empty space. if($winstate==0){ $values_link = $values; $values_link[$i]=1; echo '&lt;a href="tictactoe.php?values='.implode(',',$values_link).'"&gt;&amp;nbsp;&lt;/a&gt;'; }else{ echo '&amp;nbsp;'; } } echo '&lt;/td&gt;'; //end of a row if(fmod($i,3)==2){echo '&lt;/tr&gt;';} } ?&gt; &lt;/table&gt; &lt;?php //If someone won, display the message if($winstate!=0){ echo '&lt;p&gt;&lt;b&gt;Player '.(($winstate==1)?'X':'O').' won!&lt;/b&gt;&lt;/p&gt;'; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T13:59:25.403", "Id": "575", "Score": "4", "body": "Brings back memories - TTT was one of the first games I built in C." } ]
[ { "body": "<p>There isn't really a reason to make this \"more object-oriented\" if you don't need to. To add more AI constructs, for example, you can do:</p>\n\n<pre><code>switch ($aiLevel) {\n case 1: $values = $OsTurn($values);\n case 2: $values = $betterAi($values);\n case 3: $values = $unbeatableAi($values);\n}\n</code></pre>\n\n<p>Adding more features could be done in a similiar manner. I'm not sure exacly wht you have in mind, so I can only make some general comments. Break down everything into functions, and make sure that it's easy to see the flow of the program. The way you've structured your code is good. It should not be difficult to add more features if you use similiar style.</p>\n\n<p>CSS won't affect your script; it just changes how the page looks. You'll just need to be sure you use the right elements when outputting html. Javascript may be trickier, but there are many ways of doing that including form elements (possibly hidden) and page submits. There may be other ways that I'm not aware of as I'm not primarily a web programmer.</p>\n\n<p>I believe when you are talking about cheating, you're saying that you can send a winning board value set to the script by typing the URL yourself. To prevent this you need a way to preserve state. A cookie would be an easy way to start; store the current state of the board in it after every page call, and check that the only change was the placing of another piece. A more robust, but somewhat more involved, solution would be to use session variables to store the state. This would avoid the \"cookys are bad\" problem and the possibility that someone might fake the cooky!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T15:05:47.843", "Id": "581", "Score": "0", "body": "See my comment for precision on what I plan to do. Also do I need to use cookie? I have a superstitious \"fear\" of cookies, (discussing if cookies are evil belongs to programmers.se, so I'll check into it), but could I not obtain a similar result with session variables?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T15:07:53.643", "Id": "582", "Score": "0", "body": "Yes, you could. That would probably be a better solution too." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-01T12:30:00.640", "Id": "852", "Score": "0", "body": "One other question, I had always the impression that one could only do effective unit testing on OO code. But in case I'm mistaking, what would be the unit-test you would do on such a code? Testing some winning board would be one I thought of, especially some board where there is an empty line checked before the winning line, but there is surely more to it. Should add this question to the OP? Or should I make it this own question?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-01T13:30:37.803", "Id": "853", "Score": "0", "body": "No, you don't need OO to unit test. In many ways straight procedural code is easier - there are often fewer dependencies so you don't need to mock as much. As for how to test it, all of your non-printing functions can be tested. You've given an example of testing `isWinState()`; the same could be applied to `OsTurn()`. Of course, this only works for a deterministic AI." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T13:58:39.723", "Id": "373", "ParentId": "366", "Score": "10" } }, { "body": "<ul>\n<li>Regardless of whether you choose to use procedural or object-oriented syntax, you should definitely make a distinct separation in your script between the &quot;processing&quot; and &quot;displaying&quot; parts. In other words, don't park you function declarations inside your html table.</li>\n<li>To defend your script from users hand-crafting/hacking the board layout, you could use SESSION variables to store the previous plays, then only submit the new play on each page load. This will help you to validate that the new play is available on the board.</li>\n<li>I don't recommend the use of <code>-1</code>, <code>0</code>, and <code>1</code> to mark the game board -- it is not instantly intuitive to other programmers. Furthermore, you have to translate these values into <code>X</code>, <code>O</code>, <code>&amp;nbsp;</code>. I recommend using the values <code>X</code>, <code>O</code>, and <code> </code>(space) so that all characters are repesented by a single-byte. This new structure will allow you to pass the whole board as a nine-character string without imploding.</li>\n<li>When presenting the board/table, use <code>array_chunk()</code> to avoid modulus-based conditions.</li>\n<li>See this other tic-tac-toe review of mine that shows how to concisely and directly assess a game board using regex: <a href=\"https://codereview.stackexchange.com/a/243502/141885\">https://codereview.stackexchange.com/a/243502/141885</a></li>\n<li>Rather than asking php to make looped guesses in <code>OsTurn()</code>, I recommend that you create an array of the available spaces on the board and make a single random selection from that pool to avoid unproductive guesses.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-13T09:49:17.033", "Id": "243814", "ParentId": "366", "Score": "2" } } ]
{ "AcceptedAnswerId": "373", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T12:30:47.890", "Id": "366", "Score": "16", "Tags": [ "php", "game", "tic-tac-toe" ], "Title": "Simple Tic-Tac-Toe PHP/Pure HTML" }
366
<p>In our console app, the parsing of application arguments is done like so:</p> <pre><code>using System.Linq; namespace Generator { internal class Program { public static void Main(string[] args) { var param1 = args.SingleOrDefault(arg =&gt; arg.StartsWith("p1:")); if (!string.IsNullOrEmpty(param1)) { param1 = param1.Replace("p1:", ""); } //... } } } </code></pre> <p>It's supposed to be called like this:</p> <blockquote> <pre><code>`Generator.exe p1:somevalue` </code></pre> </blockquote> <p>Is there a better/simpler way to parse arguments?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-24T11:22:49.830", "Id": "58715", "Score": "0", "body": "Also, [the FubuCore library](https://github.com/DarthFubuMVC/fubucore) has a pretty powerful and self-documenting command line args parser, that I briefly described [here](http://stackoverflow.com/a/6314555/390819)" } ]
[ { "body": "<p>You could use foreach for iterating through the agruments and then for your argument with index 1 you could use regular expression to retrieve parsed text after p1: </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T18:36:29.500", "Id": "595", "Score": "1", "body": "I was hoping to avoid using loops. As for Regex, I think it would be too much, the pattern is quite simple." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T13:34:13.460", "Id": "370", "ParentId": "369", "Score": "1" } }, { "body": "<p>With such an implementation you will have to repeat yourself for each param.</p>\n\n<p>Alternative: </p>\n\n<pre><code>var parsedArgs = args\n .Select(s =&gt; s.Split(new[] {':'}, 1))\n .ToDictionary(s =&gt; s[0], s =&gt; s[1]);\nstring p1 = parsedArgs[\"p1\"];\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T18:19:29.583", "Id": "591", "Score": "1", "body": "+1: I would have used '='. And check that arguments are prefixed with '--'. And what about where the value is the next argument not in the same argument?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T18:38:56.457", "Id": "596", "Score": "0", "body": "@Martin why would you prefix arguments with '--'?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T20:15:38.073", "Id": "603", "Score": "1", "body": "@frennky: Its sort of a standard for command line arguments (--<longName> or -<shortName>). It separates flags (which modify behavior) from inputs/outputs. But re-reading your original question I was over generalizing and this is not what you want." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T20:22:39.550", "Id": "604", "Score": "0", "body": "@frennky - I agree with Martin, if you are writing an application which somebody (except you) will use then you should read about console argument standarts. As far as I know '--' is kind of *nix style, in windows it is more about slashes." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T13:38:52.283", "Id": "371", "ParentId": "369", "Score": "23" } }, { "body": "<p>I'd recommend taking advantage of the excellent <a href=\"http://tirania.org/blog/archive/2008/Oct-14.html\">Mono.Options</a> module. It's a single <code>.cs</code> file you can drop in to your solution and get full-featured parsing of GNU getopt-style command lines. (Things like <code>-x -y -z</code>, which is equivalent to <code>-xyz</code>, or <code>-k value</code>, or <code>--long-opt</code>, and so forth.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-13T16:40:38.310", "Id": "368645", "Score": "0", "body": "from 2018: Microsoft added their own code to the file. Now you **CAN NOT** use it as a separated file. Thanks MS. [This is the latest tag without MS's intervention I've found](https://github.com/mono/mono/blob/mono-5.0.1.1/mcs/class/Mono.Options/Mono.Options/Options.cs)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-12T20:32:16.220", "Id": "408748", "Score": "2", "body": "@maxkoryukov I don't get your logic. It's still licensed under the MIT license, which explicitly says it can be copied in part or in whole, as long as the license is included with it. So as of this writing in 2019 you can still take [this file](https://raw.githubusercontent.com/mono/mono/master/mcs/class/Mono.Options/Mono.Options/Options.cs) on its own. Unless you have something about irrationally avoiding everything Microsoft has ever touched, in which case you should know that StackExchange runs on Microsoft software." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T16:54:42.627", "Id": "408935", "Score": "0", "body": "@NicHartley, you are right, it is still **MIT-licensed**. Sorry, but I _don't remember_ what I meant then, so I can't explain my comment now... Yes, I don't like the MS-development way and their style in the software world, overall. But who am I )))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T17:00:13.497", "Id": "408936", "Score": "0", "body": "@maxkoryukov urgh, sorry for my tone there -- I genuinely didn't mean any sarcasm, but rereading my comment it _really_ sounded like it. And yeah, it's perfectly fair to dislike Microsoft. My issue is just with people avoiding everything they've ever had contact with, even indirectly by someone becoming a developer for them, because of some \"taint\" that they have, and (as it's been MIT-licensed the whole time) that's what I immediately jumped to. I guess I like imagining the worst of people. Sorry :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-14T17:44:05.807", "Id": "408947", "Score": "1", "body": "@NicHartley don't apologize;) there was an error in my comment (and it is still there) — I can't explain that comment in any other way. And I don't know why I wrote that comment. `Mono.Options` is still a decent piece of C# code, in spite of the fact of MS interventions" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T21:34:05.680", "Id": "387", "ParentId": "369", "Score": "27" } }, { "body": "<p>There's a <a href=\"https://stackoverflow.com/q/491595/4794\">related question on Stack Overflow</a>. There, the consensus seems to be <a href=\"http://tirania.org/blog/archive/2008/Oct-14.html\" rel=\"nofollow noreferrer\">Mono.Options</a> as already suggested here by <a href=\"https://codereview.stackexchange.com/questions/369/is-there-a-better-way-to-parse-console-application-arguments/387#387\">josh3736</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T17:00:26.053", "Id": "2032", "Score": "0", "body": "Read further down the list of answers on that SO question and you'll see that http://ndesk.org/Options has 2x the upvotes of the accepted answer." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T18:00:19.140", "Id": "2039", "Score": "1", "body": "Actually, the answer you refer to says \"I would strongly suggest using NDesk.Options (Documentation) and/or Mono.Options (same API, different namespace).\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T22:03:45.450", "Id": "391", "ParentId": "369", "Score": "4" } }, { "body": "<p>I usually don't use complex command line arguments, so I use a <a href=\"http://dotnetfollower.com/wordpress/2012/03/c-simple-command-line-arguments-parser/\" rel=\"nofollow\">very Simple Command Line Arguments Parser</a>, but it can be used as a foundation for your own application specific parameter presenter.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-22T15:24:25.260", "Id": "10248", "ParentId": "369", "Score": "2" } }, { "body": "<p>Please check solution from link. IT uses linq. It short and reuseble in my opinion. Provides extension method so you just do somethink like:</p>\n\n<pre><code>args.Process(\n () =&gt; Console.WriteLine(\"Usage is switch1=value1,value2 switch2=value3\"),\n new CommandLine.Switch(\"switch1\",\n val =&gt; Console.WriteLine(\"switch 1 with value {0}\",\n string.Join(\" \", val))),\n new CommandLine.Switch(\"switch2\",\n val =&gt; Console.WriteLine(\"switch 2 with value {0}\",\n string.Join(\" \", val)), \"s1\"));\n }\n</code></pre>\n\n<p>for details please visit <a href=\"http://lukasz-lademann.blogspot.com/2013/01/c-command-line-arguments-parser.html\" rel=\"nofollow\">my blog</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-19T09:58:33.497", "Id": "20703", "ParentId": "369", "Score": "-2" } } ]
{ "AcceptedAnswerId": "387", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T13:13:39.513", "Id": "369", "Score": "31", "Tags": [ "c#", "parsing", "console" ], "Title": "Parsing console application arguments" }
369
<p>Here is the skeleton of my (first!) Django app:</p> <pre><code># models.py class Task(models.Model): description = models.CharField(max_length = 200) ... # forms.py class AddTaskForm(forms.ModelForm): class Meta: model = Task </code></pre> <p>I then created two views using <code>AddTaskForm</code>: one to create a new instance, the other to edit an existing one. I was able to refactor those two views (and the function they call) into one, but I'm not sure I got the best possible result...</p> <pre><code># urls.py: (r'^yata/add_task/$', 'yata.views.edit'), (r'^yata/(?P&lt;task_id&gt;\d+)/edit/$', 'yata.views.edit'), # views.py def edit(request, task_id = None): t = get_object_or_404(Task, pk=task_id) if task_id else None if request.method == 'POST': form = AddTaskForm(request.POST, instance=t) if form.is_valid(): form.save() return HttpResponseRedirect('/yata/') else: form = AddTaskForm(instance = t) # Either the form was not valid, or we've just created it d = {'form': form} if task_id: # The template needs the id to decide if the form's action # is .../add_task or .../{{id}}/edit d['id'] = t.id return render_to_response('yata/edit.html', d, context_instance=RequestContext(request)) </code></pre> <p>And here is the corresponding part of the template:</p> <pre><code># edit.html {% if id %} &lt;form action="/yata/{{ id }}/edit/" method="post"&gt; {% else %} &lt;form action="/yata/add_task/" method="post"&gt; {% endif %} {{ form.as_p }} &lt;input type="submit" value="Save!" /&gt; &lt;/form&gt; </code></pre> <p>Is there a better Django idiom to handle this 'add or create' issue? Or can this be considered a correct way?</p>
[]
[ { "body": "<p>I have looked at your code and I think that it actually looks pretty clean and straight forward. However, I would suggest that you make it more DRY by using <a href=\"http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse\" rel=\"nofollow\">reverse()</a> to figure out what action to assign to the form.</p>\n\n<p>views.py:</p>\n\n<pre><code>if task_id:\n action = reverse(edit, args=[task_id])\nelse:\n action = reverse(edit)\nd['action'] = action\n</code></pre>\n\n<p>edit.html:</p>\n\n<pre><code>&lt;form action=\"{{ action }}\" method=\"post\"&gt;\n {{ form.as_p }}\n &lt;input type=\"submit\" value=\"Save!\" /&gt;\n&lt;/form&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T07:52:06.830", "Id": "653", "Score": "0", "body": "And, additionally, it helps separating concerns: the view is not supposed to contain the application's logic... Great! Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T22:49:48.980", "Id": "392", "ParentId": "374", "Score": "2" } }, { "body": "<p>You don't need set \"action\" for form directly.</p>\n\n<pre><code># views.py\ndef edit(request, task_id = None):\n t = get_object_or_404(Task, pk=task_id) if task_id else None\n\n form = AddTaskForm(request.POST or None, instance=t)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/yata/')\n\n return render_to_response('yata/edit.html', {'form': form}, \n context_instance=RequestContext(request))\n\n# edit.html\n&lt;form action=\"\" method=\"post\"&gt;\n {{ form.as_p }}\n &lt;input type=\"submit\" value=\"Save!\" /&gt;\n&lt;/form&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T20:31:40.057", "Id": "1831", "ParentId": "374", "Score": "2" } } ]
{ "AcceptedAnswerId": "392", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T14:08:51.607", "Id": "374", "Score": "11", "Tags": [ "python", "django" ], "Title": "An idiom to use the same view function to create or edit an object?" }
374
<p><strong>Goal:</strong> To create a countdown to our next available live stream.</p> <p><strong>Details:</strong> We live stream six times a week all (PST). 1. Sunday at 8:00 a.m. 2. Sunday at 10:00 a.m. 3. Sunday at 12:00 p.m. 4. Sunday at 6:30 p.m. 5. Wednesday at 7:00 p.m. 6. Saturday at 10:00 a.m.</p> <p><strong>My approach:</strong> I check what day it is and what time it is then create the countdown to the next stream. </p> <p>I'm sure what I have done can be cleaned up and improved, so tell me how.</p> <pre><code>&lt;?php // Countdown Stuff $year = date(Y); $month = date(m); $month_day = date(d); $day = date(w); $hour = date(G); $min = date(i); $addDay = 0; // It's Sunday if ( $day == 0 ) { if ( $hour &lt; 8 ) { $hour = 8; $min = 0; } else if ( $hour &lt; 10 ) { $hour = 10; $min = 0; } else if ( $hour &lt; 12 ) { $hour = 12; $min = 0; } else if ( $hour &lt;= 18 &amp;&amp; $min &lt; 30 ) { $hour = 18; $min = 30; } else { $addDay = 3; $hour = 19; $min = 0; } } // It's Monday else if ( $day == 1 ) { $addDay = 2; $hour = 19; $min = 0; } // It's Tuesday else if ( $day == 2 ) { $addDay = 1; $hour = 19; $min = 0; } // It's Wednesday else if ( $day == 3) { if ( $hour &lt; 19 ) { $hour = 19; $min = 0; } else { $addDay = 3; $hour = 10; $min = 0; } } // It's Thursday else if ( $day == 4 ) { $addDay = 2; $hour = 10; $min = 0; } // It's Friday else if ( $day == 5 ) { $addDay = 1; $hour = 10; $min = 0; } // All that's left is Saturday else { if ( $hour &lt; 10 ) { $hour = 10; $min = 0; } else { $addDay = 1; $hour = 8; $min = 0; } } $build_date = $year . '-' . $month . '-' . $month_day . ' ' . $hour . ':' . $min . ':00'; $date = new DateTime($build_date); if ( $addDay ) { $date-&gt;modify("+$addDay day"); } $date = strtotime($date-&gt;format("Y-m-d G:i:s")); $now = strtotime("now"); $count = $date - $now; ?&gt; &lt;script type="text/javascript"&gt; var myTime = &lt;?=$count?&gt;; $('#countdown').countdown({ until: myTime}); &lt;/script&gt; </code></pre>
[]
[ { "body": "<p>I don't have time to look over everything, but I noticed you only set <code>$min</code> to something other than <code>0</code> once. You could add the following above <code>$build_date</code>, and then remove all the <code>$min = 0;</code>s, and you'd clear up a few lines:</p>\n\n<pre><code>if($min == date('i')) {\n $min = 0;\n}\n</code></pre>\n\n<p>If it didn't change, which would only happen when you set it to <code>30</code> in that one instance, then set it to <code>0</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T21:59:45.143", "Id": "389", "ParentId": "383", "Score": "4" } }, { "body": "<p>A few things that jumped out.</p>\n\n<p>In your date() calls you are passing constants instead of strings e.g. you use date(Y) as opposed to date('Y'), this issues a notice error. PHP will assume that you meant a string, but it is best to be explicit.</p>\n\n<p>The getdate() function will gives you all that information instead of calling date() 6 times.</p>\n\n<p>For what you are wanting to do, I would recommend taking a look at the mktime() function. Once you calculate the next live stream time from your current time, simply pass those values to mktime() and do a time() - mktime() and thats how many seconds you have until the event. mktime produces a UNIX timestamp, so you can pass that to the date() function or into a DateTime object to format, change timezone, etc.</p>\n\n<p>If you are going to have a lot of if/elseif statements like that, it would be cleaner to use a switch statement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-28T22:56:44.060", "Id": "393", "ParentId": "383", "Score": "3" } }, { "body": "<p>Of course, now if your company decides to change streams from Sunday at 8:00am to Tuesday at 2, you're going to have to go in and hack this code. And if you mess up a ';' or '?php' or junior developer passes \"NO WAY\" to strtotime()?</p>\n\n<p>Evolve your approach. You should be storing the stream times externally; either in a file or a database. You should be querying those times, doing a strtotime() difference between them and now, then taking the minimum positive element and displaying that. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T01:25:02.493", "Id": "397", "ParentId": "383", "Score": "2" } }, { "body": "<p>To add to Andrew's answer about taking advantage of what type of timestamps can be creating using strtotime(), your code can be reduced to around 25 lines...</p>\n\n<pre><code>&lt;?php\n\n$schedule = array(\n 'this Sunday 8am',\n 'this Sunday 10am',\n 'this Sunday 12pm',\n 'this Sunday 6:30pm',\n 'this Wednesday 7pm',\n 'this Saturday 10am'\n );\n\n$current_time = strtotime('now');\nforeach ($schedule as &amp;$val) {\n $val = strtotime($val);\n // fix schedule to next week if time resolved to the past\n if ($val - $current_time &lt; 0) $val += 604800; \n }\nsort($schedule);\n$countdown = $schedule[0] - $current_time;\n\n?&gt;\n\n&lt;script type=\"text/javascript\"&gt;\n var myTime = &lt;?php echo $countdown; // just personally prefer full tags ?&gt;;\n $('#countdown').countdown({ until: myTime}); \n&lt;/script&gt;\n</code></pre>\n\n<p>To add to visionary-software-solutions' answer, it would be best to store the schedule in a database or a separate xml/text/json/etc type file. This way, you can have staff simply use an internal webform to change schedules instead of having the PHP dev hard-code the changes every time. In that webpage, you can allow staff to only select a weekday and time, and have the page translate that into a string usable by <code>strtotime()</code> in this countdown script.</p>\n\n<p>Edit: fixed <code>strtotime()</code> values. Careful with \"this day\" vs \"next\". For some insight into what type of strings <code>strtotime()</code> can take, see: <a href=\"http://www.gnu.org/software/tar/manual/html_node/Date-input-formats.html\">http://www.gnu.org/software/tar/manual/html_node/Date-input-formats.html</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T05:28:32.003", "Id": "402", "ParentId": "383", "Score": "11" } } ]
{ "AcceptedAnswerId": "402", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T19:52:59.890", "Id": "383", "Score": "11", "Tags": [ "php", "datetime" ], "Title": "Checking date & time in PHP" }
383
<p>I would like to solicit advice on everyone's thoughts on how best to combat the <a href="http://en.wikipedia.org/wiki/Anemic_Domain_Model" rel="nofollow">Anemic Domain Model anti-pattern</a> when building out a system based on web services.</p> <p>One of our goals is to build a set of core web services that expose the most basic services we reuse repeatedly in our organization, which is the creating of domain models. Right now we have a small library that we share and reuse but as we grow our team it would be much nicer to centralize these basic services. Over time our systems are going to change as some of the data may come from the cloud (Salesforce.com or AWS) so we're <strong>not just isolating basic DAO code in a web service but also application integration</strong>.</p> <p>For example, our customer data comes from the accounting, CRM, and order processing systems. Configuration is a real pain because every app that ships needs to be bundled with the core library and configuration on each system. I would like to centralize the creation of models, ala, SOA, but retain a rich model higher up in the Service Layer / Facade.</p> <p>If you think in general that this is a bad I'd be interested in hearing why!</p> <p>My thought is to define a domain object <code>Employee</code> that has an <code>EmployeeService</code> injected. At runtime the <code>EmployeeService</code> implementation is an <code>EmployeeWebServiceClientImpl</code> that implements said interface. <code>EmployeeWebServiceClientImpl</code> uses a web service proxy to the server.</p> <p>On the server-side of the web service we have <code>EmployeeWebService</code> invoking <code>EmployeeDao</code> to query the database. Could just as easily be a class calling out to Salesforce.com to get data. We would share a library that contained the domain model and interface so you would deserialize the web service response directly into a class that contained the needed business logic.</p> <p>Below is some example code in order from client to server:</p> <pre><code>//Example of client public static void main(String[] args) { try { Employee employee = Employee.getEmployee("james"); if (employee.isEligibleForRaise()) { System.out.println("Give that man a raise!"); } } catch (RuntimeException e) { System.out.println("Oh no!"); } } //Employee Domain Object public class Employee { private String name; private String username; private static EmployeeService service; public static Employee getEmployee(String username) { return service.getEmployee(username); } public static List&lt;Employee&gt; getAllEmployees() { return service.getAllEmployees(); } public boolean isEmployeeEligibleForRaise() { //business logic here return true; } //Getters &amp; Setters ... } //EmployeeWebServiceClientImpl public class EmployeeWebServiceClientImpl implements EmployeeService { //A client web service proxy to our core basic services BaseWebServiceProxy proxy; @Override public Employee getEmployee(String username) { return proxy.getEmployee(username); } @Override public List&lt;Employee&gt; getAllEmployees() { return proxy.getAllEmployees(); } } //On the server-side we have EmployeeWebService public class EmployeeWebService implements EmployeeService { EmployeeDao employeeDao; @Override public List&lt;Employee&gt; getAllEmployees() { return employeeDao.getAllEmployees(); } @Override public Employee getEmployee(String username) { return employeeDao.getEmployee(username); } } </code></pre> <p>Is that making sense? Basically the plan is to keep core business logic in the <code>Employee</code> domain object but isolate the data access logic in a web service.</p> <p>Thoughts?</p>
[]
[ { "body": "<p>You're adding a lot of complexity here. Plus, you're going against the point of a <a href=\"http://martinfowler.com/eaaCatalog/serviceLayer.html\" rel=\"nofollow\">Service Layer</a> and Domain Model. Your Domain Model should probably use either <a href=\"http://martinfowler.com/eaaCatalog/activeRecord.html\" rel=\"nofollow\">Active Record</a> or <a href=\"http://martinfowler.com/eaaCatalog/dataMapper.html\" rel=\"nofollow\">Data Mapper</a>. </p>\n\n<p>The point of a Service Layer is to act as an end point (API) that holds common business logic that deals with integration of domain model objects. Your service layer should just query repositories and delegate calls to process business logic to your domain model (which should hold as much business logic as possible). Injecting it into your domain model adds persistence concerns, which it should not care about. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T03:33:46.640", "Id": "630", "Score": "0", "body": "Am only talking about the two inner-most circles of ServiceLayer: Domain Model and Datasource. My example above is trivial. In practice my model is called from SL/Facade. I had ActiveRecord in mind but it is not as simple as the example on Martin's site. We rarely talk directly to a db. Our data is behind vendor API's (CRM, HR, Project Mgmt etc..), ActiveDirectory, & DB. To create our model we talk to 6-7 different systems. Motivation is to create basic set of services that create the model from a central server (ala SOA) yet still have rich model in the Service Layer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T01:42:43.187", "Id": "398", "ParentId": "395", "Score": "3" } }, { "body": "<p>Let's not get pattern tastic.</p>\n\n<p>You have an employee, that's good.</p>\n\n<p>Then you have a way to find them from various sources? Let's call that <code>Employees</code>. Then you are able to perhaps get them and find them. So you have <code>Employees.findByName()</code> - where you expect that there is one, and returns an Employee or throws. Then you might have a <code>queryByName()</code> where you don't know if there is one at all, which might return a list or iterable.</p>\n\n<p>Then you have some different implementations. I personally think that Impl is a terrible thing. It adds more letters without actually telling you more about the implementation. Wr decided the interface was Employees, so now we have maybe an <code>HttpEmployees</code> or a <code>HibernateEmployees</code>, see we implemented the interface, gave more information about the implementation, but didn't need to use Impl.</p>\n\n<p>You've made a bit of an error by putting the <code>EmployeeService</code> (what I called <code>Employees</code>) in the <code>Employee</code> class. The <code>Employee</code> should not know about keeping records on the Employee.</p>\n\n<p>In addition, you should be very wary of static methods here, in this case you would be saying that in a particular application, employees can only be found from one source , because you have a static. Why not instantiate those things that need to use the Employees interface with a particular implementation... </p>\n\n<p>One more thing... <code>getAllEmployees()</code> is unlikely to be useful. Many companies have tens or hundreds of thousands of employees.....</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T19:36:52.407", "Id": "753", "Score": "0", "body": "I disagree with the notion that static methods for finders is bad and that \"Employee should not know about keeping records of Employee.\" Those two patterns are how modern ORM tools like ActiveRecord(Ruby) and GORM(Groovy) do it. Besides, having Employee now how to insert/update/delete itself is classic EAA Active Record pattern. See an example of GORM for what I mean: http://grails.org/doc/1.0.x/guide/5.%20Object%20Relational%20Mapping%20(GORM).html" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T13:47:13.360", "Id": "794", "Score": "0", "body": "The static method introduces tight coupling, which can make unit testing difficult (you won't be able to use a mock Employee, for example). Ruby can get away with it because it is so dynamic (a test can change the Employee class to MockEmployee at runtime)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T13:48:48.770", "Id": "795", "Score": "0", "body": "Also, unless you're using a very nice ORM (meaning, if you'll have any code that is using SQL directly, I would put that in a DAO, and have your object model use the DAO." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T17:21:30.907", "Id": "806", "Score": "0", "body": "I see two mocking strategies: 1) separate Employee interface from implementation so you can mock Employee and 2) mock EmployeeService inside Employee used in static finders. Niether are hindered from the use of static finder methods." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-29T23:10:47.623", "Id": "434", "ParentId": "395", "Score": "1" } }, { "body": "<p>You will have a hard day to \"combat\" this design. My view on this subject: People either want to get around semantics, do not care about it or even don't know that such thing exists.</p>\n\n<p>As the \"Anemic Domain Model\" does not care about encapsulation it is easy to get around semantics. You do not need to think about where attributes and algorithms are located \"best\". You can easily pass the structures around that you need at a certain location to do whatever you want with it.</p>\n\n<p>I have to explain \"best\" because this is the main point I always struggling with other developers. </p>\n\n<p>I suggest to read the next paragraph too if you get a bad impression on my view here. First of all I want to mention that for me there is for one special requirement only ONE (the \"best\") solution. The point is: If you talk about code quality and what kind of code is better everybody implicitly say \"There is one best solution\". If you do not do this: ANY sugestions about \"improving\" code would be totally subjective.</p>\n\n<p>On the other side WE ALL have cognitive trouble at some point of complexity and/or the programming languge hinders us to express the semantic properly. That is why I am convinced that we nearly NEVER reach the point of the \"best\" implementation. BUT I am also convinced that we can evaluate the path through trial and error and falsification. Nothing else is done in in science. They try to produce good models of reality. And they want to be as close as possible because they want to make forecasts with these models that will be beneficial for the society. But to do that they have to be clear in semantics.</p>\n\n<p>One thing a want to mention on which assumption my statements are made if I talk about \"reality\":</p>\n\n<blockquote>\n <p>I think that we share and experience ONE reality we have to deal with. The other thing is that we all have different perceptions of reality. And our goal should be to determine the best methods to explain reality.</p>\n</blockquote>\n\n<p>We developers try to produce models od reality as well. But there are developers that do not care about reality as there are people who do not care about the reality that science try to evaluate and describe. The point is: We as developers can make up fiction in the programm in our programming languages as long as the interfaces produce beneficial results to those who hired us. We can unneccessarily iterate over a collection twice but returning the correct result. We can build up huge structure and destroy them instantly. I have to admit that my models are bad in contrast to the models that science produce. Doens't matter if it the fault of the programming language or my cognitive troubles.</p>\n\n<p>So we as developers build models... May goal is it to have the model matching best with reality AND the code we produce matching best the model. Currently object-orientated paradigm is seen as the best paradigm to model real world elements. You have a car in reality, you create a model of a car, finally you get an object of class \"Car\" in your object-oriented language. A car in reality can be started, so you may have a model of starting engine of your car that may result in a method \"startEngine()\".</p>\n\n<p>And here comes the problem: The more specific AND the more abstract the things are we have to model: I think we get cognitive troubles. This unfortunately also correlates with the persons perceptions on reality.</p>\n\n<p>We have one great advantage over the management: We can only be tracked by other developers that are familar with the our code. This has been discovered at a point of time when software came up that could not be developed by one developer alone. Collaboration was neccessary. The problem: The different perceptions of reality of the different developers (persons).</p>\n\n<p>Todays approaches to solve this problem are to have experience, IT expertise AND high social competence.</p>\n\n<p>I personally do not care about social competence when I answer questions here. So I put out the sharpest sword have to argue with to pass it to you: The SOLID-principles together with the Law of Demeter.</p>\n\n<p>I am convinced under the assumption I made (reality, semantics etc.) these principles will improve code quality on the semantic level and reveal things that compromise reality so you are able to adjust your model to fit reality better.</p>\n\n<p>The SOLID-principles will lead to a domain model that clearly is NOT an \"Anemic Domain Model\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-02-05T13:39:07.643", "Id": "154501", "ParentId": "395", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-28T23:26:01.420", "Id": "395", "Score": "11", "Tags": [ "java", "design-patterns" ], "Title": "Pattern Against Anemic Domain Model" }
395
<p>I've made a SPL-based class named "Recordset" that wraps both MySQLi_STMT and MySQLi_Result objects and allows treating either as a 3-dimensional array. It requires PHP5.3+.</p> <p>I'm pretty bummed about the slow foreach loop over my Recordset object, by the slower internal seek and fetch speeds within Recordset, and by the fact that nothing can even compare to the old <code>while ($MySQLI_STMT-&gt;fetch()) {}</code>. I've already cached certain result information, such as num_rows and class name, and try to avoid chaining internal function calls, which speeds things up considerably. Unfortunately, this cuts down on proper internal data validation checks. The constant data_seek calls do slow things a little. I'd like for this to work better. Any suggestions or insight how to speed up foreach loops and internal row fetching?</p> <p>Here's excerpts of the important parts...</p> <pre><code>class Recordset implements Iterator, ArrayAccess, Countable { private $MySQLi_set; // MySQLi_STMT or MySQLi_Result object private $MySQLi_set_type; // cache of MySQLi_STMT or MySQLi_Result object type to avoid repeat instanceof calls private $field_metadata; // array of field info objects returned by query private $num_rows; // cache row count to avoid repeat mysqli_x-&gt;num_rows call private $bind_row; // binding array for MySQLi_STMT results private $pointer; // for tracking iterations over records in query function __construct($sql) { $bind_params = func_get_args(); array_shift($bind_params); try { if (count($bind_params) === 0) { // expecting MYSQLI_Result obj returned, replace code as necessary $this-&gt;MySQLi_set = DB_Main::query($sql); } else { // expecting MySQLi_STMT obj returned, replace code as necessary $this-&gt;MySQLi_set = DB_Main::statement($sql, $bind_params); } } catch (Exception $e) { throw new RuntimeException(((count($bind_params)) ? 'Statement' : 'Query') . ' failed: ' . $e-&gt;getMessage(), $e-&gt;getCode(), $e); } // cache name of object to avoid repeat instanceof calls $this-&gt;MySQLi_set_type = get_class($this-&gt;MySQLi_set); if ($this-&gt;MySQLi_set_type === 'mysqli_result') { // set $this-&gt;field_metadata to array of field info objects $this-&gt;field_metadata = $this-&gt;MySQLi_set-&gt;fetch_fields(); } else if ($this-&gt;MySQLi_set_type === 'mysqli_stmt') { // Set up special handling for MySQLi_STMT objects // set $this-&gt;field_metadata to array of field info objects used later for result bindings for MySQLi_STMT object $result_metadata = $this-&gt;MySQLi_set-&gt;result_metadata(); $this-&gt;field_metadata = $result_metadata-&gt;fetch_fields(); $result_metadata-&gt;free_result(); unset($result_metadata); // store results to allow object to act as a countable, seekable array if (!$this-&gt;MySQLi_set-&gt;store_result()) throw new RuntimeException('MySQLi_STMT Result failed to store. Error: ' . $this-&gt;MySQLi_set-&gt;error); // because bind_result() cannot bind to an object or array, use the 'call_user_func_array()' technique instead $this-&gt;bind_row = array(); $bind_row2 = array(); foreach($this-&gt;field_metadata as $field) $bind_row2[$field-&gt;name] =&amp; $this-&gt;bind_row[$field-&gt;name]; if (!call_user_func_array(array($this-&gt;MySQLi_set, 'bind_result'), $this-&gt;bind_row)) throw new RuntimeException($this-&gt;MySQLi_set-&gt;error); if ($this-&gt;MySQLi_set-&gt;error) throw new RuntimeException($this-&gt;MySQLi_set-&gt;error); } else { throw new RuntimeException('No MySQLi_STMT or MySQLi_Result object to work with. Class: ' . $this-&gt;MySQLi_set_type . ' attempted.'); } // cache row count to avoid constant calls to MySQLi_x-&gt;num_rows $this-&gt;num_rows = $this-&gt;MySQLi_set-&gt;num_rows; // if rows were returned, set internal pointer to 0 if ($this-&gt;num_rows &gt; 0) $this-&gt;pointer = 0; } function fetchRow($offset = null) { // private function internally using regular fetch() methods to progress through records // sets $this-&gt;bind_row to an associative array of the next record for MySQLi_STMT wrapped objects $this-&gt;MySQLi_set-&gt;data_seek((($offset !== null) ? (int) $offset : $this-&gt;pointer)); if ($this-&gt;MySQLi_set_type === 'mysqli_result') return $this-&gt;MySQLi_set-&gt;fetch_assoc(); // else this is a MySQLi_STMT object $fetch_status = $this-&gt;MySQLi_set-&gt;fetch(); if ($fetch_status === true) return $this-&gt;bind_row; else if ($fetch_status === null) return null; // no more rows // MySQLi_STMT row fetch failed throw new RuntimeException('Error fetching row: . ' . $this-&gt;MySQLi_set-&gt;error); } function count() {return $this-&gt;num_rows;} function current() {return $this-&gt;fetchRow();} function key() {return $this-&gt;pointer;} function next() {$this-&gt;pointer++;} function rewind() {$this-&gt;pointer = 0;} function valid() {return $this-&gt;offsetExists($this-&gt;pointer);} function offsetExists($offset) { // Part of the ArrayAccess interface. Used to determine if the selected record in the set actually exists or is out of bounds. // Example: 'isset($Recordset[22])' returns true if there were 23 or more records returned from the query. return ((int) $offset &lt; $this-&gt;num_rows AND (int) $offset &gt;= 0); } function offsetGet($offset) { // Part of the ArrayAccess interface. Used to retrieve the assoc array of the chosen record in line. // allow index referencing without altering "internal array pointer" // Example: 'print_r($Recordset[22])' prints the 23rd record returned by the query. if (!((int) $offset &lt; $this-&gt;num_rows AND (int) $offset &gt;= 0)) throw new OutOfBoundsException('Out of range of result set.'); return $this-&gt;fetchRow($offset); } } </code></pre> <p>The code is roughly 200 lines long, so instead of making a giant post, here's a pastebin link... <a href="http://pastebin.com/n17MuEzf" rel="noreferrer">http://pastebin.com/n17MuEzf</a></p> <p><b>Use...</b></p> <p>Objects are created by passing in an sql query string. For handling prepared statements, simply pass in additional arguments as the prepared binding parameters. In those cases, there is a behind-the-scenes <code>bind_param</code> going on generating the MySQLi_STMT object to be wrapped. That part isn't included here, so for the purposes of this post, pretend it's magic.</p> <p>For example to automatically handle the query as a prepared statement and output rows:</p> <pre><code>$recordset = new Recordset("SELECT * FROM tblComments WHERE(parentBlogID = ?)", 2); if (count($recordset) &gt; 0) { foreach ($recordset as $record) echo $record['commentText'] . '&lt;br&gt;'; } else echo "No records returned."; </code></pre> <p><b>Advantages...</b></p> <ul> <li>Allows accessing result rows by array key (<code>echo $Recordset[295]['title'];</code>) or by foreach loops (<code>foreach ($Recordsetas $rec) {echo $rec['title'];}</code>).</li> <li>Allows you to get a row by index number without interfering with the internal result pointer. In other words, right in the middle of a foreach loop, you can do <code>$x = $Recordset[259]['ID'];</code> without causing the internal result row pointer to jump out of order.</li> <li>Allows exchanging this class out for regular 3-dimensional arrays of result dumps.</li> <li>Avoids duplication of result binding code for every statement throughout an application.</li> <li>Lets you still access functions and properties of the wrapped MySQLi object directly (<code>$Recordset->attr_get(1)</code>).</li> <li>Would allow plugging in automatic output filters or template handling.</li> </ul> <p><b>Tests...</b></p> <p>Here's some speed tests iterating over 10000 records from a localhost table with 6 columns. This test was done with prepared statement results either wrapped in Recordset or not. Timing is measured starting before and ending after each entire loop call..</p> <p><b>With Recordset...</b></p> <ul> <li><code>foreach($Recordset as $rec) {$x = $rec;}</code> ... <br> 0.1033s</li> <li><code>for ($i = 0, $count = count($Recordset); $i &lt; $count; $i++) {$x = $Recordset[$i];}</code> ... <br> 0.0445s</li> <li><code>for ($i = 0, $count = count($Recordset); $i &lt; $count; $i++) {$x = $Recordset-&gt;fetchRow($i);}</code> ... <br> 0.0344 s</li> <li><code>while ($x = $Recordset[$i]) {$i++; if (!isset($Recordset[$i])) break;}</code> ... <br> 0.0542 s</li> </ul> <p><b>Without Recordset, but still using the "bind to array" technique and pre-storing results...</b></p> <ul> <li><code>for ($i=0, $count=MySQLI_STMT-&gt;num_rows; $i &lt; $count; $i++)) {$MySQLI_STMT-&gt;fetch(); $x = $bind_row;}</code> ...<br> 0.0414 s</li> <li><code>while ($MySQLI_STMT-&gt;fetch()) {$x = $bind_row;}</code> ... <br> 0.009 s</li> </ul>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T17:26:20.997", "Id": "682", "Score": "0", "body": "Please put the relevant code in the question. We are trying to discourage pastebins as they segment the website. Also, not everyone is going to be able to click on your link if they are at work." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T17:38:10.453", "Id": "684", "Score": "0", "body": "@Mark Loeser: might be difficult, but let me see how I can shrink the code without having this post become a book." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T04:36:19.803", "Id": "729", "Score": "1", "body": "So I can't self-answer, but one thing I'm already finding is that the more internally chained function calls there are (ie calling `$this->offsetExists($this->pointer)` to avoid duplication in the `valid()` method), the slower it gets. Just changing that line to `return ($this->pointer !== null AND $this->pointer < $this->num_rows AND $this->pointer >= 0);` shaves a little over 0.1s off the foreach test time." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-19T04:47:26.457", "Id": "1580", "Score": "2", "body": "Still can't self-answer, but taking from a comment on PHP's man page on Mysqli classes, apparently you can extend them. Who knew? So, I've scrapped this idea and extended Mysqli_stmt to auto-handle param and result binding on construct. So I now have a simple old-school query-like api for parametrized statements with a simple `fetch_assoc` method. Array interface doesn't seem so important anymore." } ]
[ { "body": "<p>bob-the-destroyer withdrew the question in a comment above:</p>\n\n<blockquote>\n <p>taking from a comment on PHP's man page on Mysqli classes, apparently\n you can extend them. Who knew? So, I've scrapped this idea and\n extended Mysqli_stmt to auto-handle param and result binding on\n construct. So I now have a simple old-school query-like api for\n parametrized statements with a simple fetch_assoc method. Array\n interface doesn't seem so important anymore.</p>\n</blockquote>\n\n<p>(just posting this so this question doesn't show up as \"unaswered\" any more</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-20T20:24:22.947", "Id": "8013", "ParentId": "401", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T03:33:00.837", "Id": "401", "Score": "7", "Tags": [ "php", "php5", "mysqli", "spl" ], "Title": "MySQLi_Recordset: blending SPL and Statement/Query results" }
401
<p>Theme-swap functionality will be done via a better-looking <code>&lt;div&gt;</code> at the top of the page, but for right now, it's just thrown on the button. The theme preference should persist through page refreshes through the use of cookies. </p> <p>I'm going to do five different themes, each in two different sizes, since the site is very bad in <code>800x600</code> and still quite bad in <code>1024x768</code>.</p> <p>Let me know if it breaks or simply doesn't work. I've noticed a bug that happens once in a blue moon, but I think that's because the browser might be doing parallel work and one script gets too far ahead of the other. I'll have to research it more, but I think it's good enough right now to ask for opinions.</p> <p>The page will eventually display via <code>&lt;noscript&gt;</code> for those that don't have JavaScript turned on but for right now, it'll just display a message that says:</p> <blockquote> <p>Please turn JavaScript on!</p> </blockquote> <p>How it works:</p> <ol> <li>Non-JavaScript page is displayed with <code>&lt;noscript&gt;</code></li> <li>If JavaScript is enabled, it loads the theme-preference from cookies.</li> <li>JavaScript then applies the preferred theme via AJAX fetching the appropriate theme (<code>skin[x].html</code>) and the content of the page (<code>[page_name.html]</code>).</li> </ol> <p>The code isn't perfect yet, and I'll definitely have to remove the use of another person's image as the background for the second skin, but it's almost done. About half of the code deals with merely re-positioning the elements when the window is resized. For the sake of brevity, some code is not shown. I apologize for its length.</p> <h3>index.html:</h3> <pre><code>&lt;script type="text/javascript"&gt; window.onresize = function() { setContentPositions(); setJSMenuPositions(); } $('html').addClass('js'); &lt;/script&gt; &lt;script type="text/javascript"&gt; $().ready(function() { getThemeInfo(); AJAX_LoadResponseIntoElement("mybody", "skin1.txt", function() { AJAX_LoadResponseIntoElement("contentdiv", "index.txt", initPage); }); if (themeSelect&gt;1) { themeSwapNoInc();} }); &lt;/script&gt; </code></pre> <h3>funcs.js:</h3> <pre><code>function getThemeInfo() { themeSelect=checkCookie(); } function themeSwap() { themeSelect++; if (themeSelect&gt;2 || themeSelect&lt;1) {themeSelect=1;} $('html').addClass('js'); switch(themeSelect) { case 1: AJAX_LoadResponseIntoElement("mybody", "skin1.txt", function() { AJAX_LoadResponseIntoElement("contentdiv", "index.txt", initPage); }); document.body.style.backgroundImage="url(http://www.solarcoordinates.com/images/bg2b.png)"; document.body.style.backgroundRepeat="repeat-x"; break; case 2: AJAX_LoadResponseIntoElement("mybody", "skin2.txt", function() { AJAX_LoadResponseIntoElement("contentdiv", "index.txt", initPage); }); document.body.style.backgroundImage="url(http://www.constantcollide.com/wp-content/themes/killerbrown/images/texture.jpg)"; document.body.style.backgroundRepeat="repeat"; break; } setCookie("themeSelection",themeSelect,365); } function themeSwapNoInc() { themeSelect--; themeSwap(); } function initPage() { $('#vertnav .kwicks').kwicks({ defaultKwick:0, max : 205, spacing : 3, isVertical : true }); setContentPositions(); replaceCSSMenu(); showContainer(); setJSMenuPositions(); } function showContainer() { $('html').removeClass('js'); } function AJAX_LoadResponseIntoElement (elementId, fetchFileName, cfunc) { var XMLHRObj; if (window.XMLHttpRequest) { XMLHRObj=new XMLHttpRequest(); } else { XMLHRObj=new ActiveXObject("Microsoft.XMLHTTP"); } XMLHRObj.onreadystatechange=function() { if (XMLHRObj.readyState==4 &amp;&amp; XMLHRObj.status==200) { document.getElementById(elementId).innerHTML=XMLHRObj.responseText; cfunc(); } } XMLHRObj.open("GET",fetchFileName,true); XMLHRObj.send(); } function findLeft(obj) { var curleft = 0; if (obj.offsetParent) { do {curleft += obj.offsetLeft;} while (obj = obj.offsetParent);} else { curleft += obj.offsetLeft; } return curleft; } function findTop(obj) { var curtop = 0; if (obj.offsetParent) { do {curtop += obj.offsetTop;} while (obj = obj.offsetParent);} else { curtop += obj.offsetTop; } return curtop; } function findmyparent(e) { var srcElement = e.srcElement ? e.srcElement : e.target; if (srcElement.className.search("jsmenu")==-1 &amp;&amp; srcElement.className.search("kwick")==-1 &amp;&amp; srcElement.className!="vertnav" &amp;&amp; srcElement.className!="active") { document.getElementById("jsmenu" + lastindex).style.display="none"; submenuvisible=false; } } function getContentHeight() { return window.innerHeight; } function getContentWidth() { return window.innerWidth; } function setContentPositions() { var DOMheight = getContentHeight()? getContentHeight(): window.document.body.parentElement.clientHeight; var DOMwidth = getContentWidth()? getContentWidth(): window.document.body.parentElement.clientWidth; var y_lbound, x_lbound, x_ubound; var container_ymod, container_ymin; var container_xmod, container_xmax, container_xmin; var content_xmod, content_xmax, content_xmin; switch (themeSelect) { case 1: y_lbound=727; x_lbound=910; x_ubound=1400; container_ymod=-240; container_ymin=487; container_xmod=-240; container_xmax=1160; container_xmin=670; content_xmod=-490; content_xmax=910; content_xmin=420; break; case 2: y_lbound=710; x_lbound=910; x_ubound=1400; container_ymod=-178; container_ymin=532; container_xmod=-300; container_xmax=1100; container_xmin=610; content_xmod=-350; content_xmax=1050; content_xmin=560; break; default: } // end switch if (DOMheight &gt; y_lbound) { document.getElementById('containerdiv').style.height = (DOMheight+container_ymod) + 'px'; } else { document.getElementById('containerdiv').style.height = container_ymin + 'px'; } if (DOMwidth &gt; x_lbound) { if (DOMwidth &lt; x_ubound) { document.getElementById('containerdiv').style.width = (DOMwidth+container_xmod) + 'px'; document.getElementById('contentdiv').style.width = (DOMwidth+content_xmod) + 'px'; } else { document.getElementById('containerdiv').style.width = container_xmax +'px'; document.getElementById('contentdiv').style.width = content_xmax + 'px'; } } else { document.getElementById('containerdiv').style.width = container_xmin + 'px'; document.getElementById('contentdiv').style.width = content_xmin + 'px'; } } </code></pre> <h3>jsmenucontent.js:</h3> <pre><code>function setJSMenuPositions() { var popupleft = findLeft(document.getElementById('kwick1'))+168; var popuptop = findTop(document.getElementById('kwick1')); document.getElementById('jsmenu0').style.left = popupleft + "px"; document.getElementById('jsmenu0').style.top = popuptop -12+ "px"; document.getElementById('jsmenu1').style.left = popupleft + "px"; document.getElementById('jsmenu1').style.top = popuptop +33+ "px"; document.getElementById('jsmenu2').style.left = popupleft + "px"; document.getElementById('jsmenu2').style.top = popuptop +77+ "px"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T13:26:48.247", "Id": "670", "Score": "4", "body": "You use jQuery for the DOM but then don't use it to handle ajax in a cross-browser compliant manner for you? I would use `$.ajax` rather then messing with XMLHRObj manually. If your going to bother including jQuery then you might aswell use it more. It makes your life easier." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T18:13:26.640", "Id": "696", "Score": "1", "body": "@Micheal - There's several discussions about that on meta. :P. And in addition to what Raynos mentioned, you should try out a jQuery plugin (http://www.electrictoolbox.com/jquery-cookies/) for handling cookies." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T02:47:14.287", "Id": "901", "Score": "0", "body": "Have you read http://www.alistapart.com/articles/bodyswitchers/? Without going too much details, your method is over-engineered, you should be using jQuery *properly* (and update it - the version you're using is 3 major versions behind!) and you should try not to copy code from W3Schools." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T03:33:14.193", "Id": "902", "Score": "0", "body": "No, I haven't read the article... I will, though, thanks for the link. I'm assuming that, by \"over-engineered,\" you mean that I did too much myself and could've used more jQuery. I guess I won't know what you mean until I read the article... which I'll do later tonight." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T03:35:22.600", "Id": "903", "Score": "0", "body": "RE W3S: I read their articles for reference at times (along with others,) but with the exception of the AJAX fetch function, no code here, to my knowledge, has anything in common with any code found on W3S. The AJAX fetch function has slight differences, but is nonetheless rather similar to what is found on W3S. It's also similar to almost every AJAX fetch function ever posted on the internet (that I've seen, at any rate... I've looked over about 30 examples) so I don't see that as a problem(?)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-03T17:26:15.043", "Id": "1020", "Score": "0", "body": "Just a quick note, you'll want to \"debounce\" window.onresize because many browsers call the event every tick of the resize (while the user is dragging) which could cause your event handler to fire hundreds/thousands of times as a user drags the edge of the window. Reference: http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/ and http://paulirish.com/2009/throttled-smartresize-jquery-event-handler/" } ]
[ { "body": "<p>This may just be me nit picking.</p>\n\n<p>But using this approach I can see getting very very messy.\nIf you decide to have say 40 theme's. That's a heck of a lot of javascript!\nand especially if you decide that you are going to support things like mobile or tablet.</p>\n\n<p>You are changing the look of your page using javascript.\nYou would be better off in my opinion to have:</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"..\\css\\themes\\th1.css\" id=\"themesheet\" type=\"text/css\" /&gt; \n</code></pre>\n\n<p>in your html have</p>\n\n<pre><code>&lt;select id=\"theme\"&gt;\n &lt;option value=\"th1\" selected=\"selected\"&gt;Theme One&lt;/option&gt;\n &lt;option value=\"th2\"&gt;Theme Two&lt;/option&gt;\n&lt;/select&gt;\n</code></pre>\n\n<p>then in your javascript have</p>\n\n<pre><code>$('#theme').change(function(){\n var link = '..\\css\\themes\\{name}.css';\n link = link.replace('{name}', $(this).val());\n $('#themesheet').attr('href', link); \n});\n</code></pre>\n\n<p>This way you are only changing the css sheet instead of coding in the style changes for every theme.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T05:29:11.570", "Id": "775", "Score": "0", "body": "I'm assuming that you are referring to switch/case portions of themeSwap(). Yes, I plan to redo that, and yes, the theme swaps will be done via CSS replacements. If skin[x].txt is not already 100% CSS-driven, it will be, and then I'll change the themeSwap() function to work via CSS swaps: main.css is going to be changed to \"skin1.css\" and a swap to skin[x] will replace it with \"skin[x].css\". And yes, I plan on making a skin for mobile devices as well. Thanks for letting me know that jQuery can do this, though. I'm new to both JS and jQuery and don't yet know what all jQuery can do for me." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T22:00:13.963", "Id": "470", "ParentId": "403", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-29T05:37:09.230", "Id": "403", "Score": "3", "Tags": [ "javascript", "jquery", "ajax" ], "Title": "Skin/theme swap" }
403
<p>I'm thinking about how to do a color transition for a line in WPF. I'm looking for this to be as simple and succinct as possible, and also the "correct" way in the WPF world.</p> <p>This is what I have, taking the line from it's previous color to <code>Colors.LightGreen</code> in 0.1 seconds.</p> <pre><code>Line TargetLine = GetMyTargetLine(); var s = new Storyboard(){ Duration = new Duration(TimeSpan.FromSeconds(0.1f)) }; s.Children.Add(new ColorAnimation(Colors.LightGreen, s.Duration)); Storyboard.SetTarget(s.Children[0], TargetLine); Storyboard.SetTargetProperty(s.Children[0], new PropertyPath("Stroke.Color")); s.Begin(); </code></pre> <p>And it is functional. Is this the proper way to do it in the WPF mindset? It just seems very clunky and verbose way to express what I want to do. Thoughts?</p> <p><strong>Edit:</strong> With Snowbear's advice I can at least get it to 4 lines. The entire context of the storyboard is right here so I don't think it's a big deal to reference the only child by index. If it were any more complex than this I'd agree that it should be a named variable.</p> <pre><code> Line TargetLine = GetMyTargetLine(); var story = new Storyboard() { Children = { new ColorAnimation(color, new Duration(TimeSpan.FromSeconds(0.1))) } }; Storyboard.SetTarget(story.Children[0], TargetLine); Storyboard.SetTargetProperty(story.Children[0], new PropertyPath("Stroke.Color")); story.Begin(); </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T05:39:30.943", "Id": "633", "Score": "1", "body": "By the way I don't yet have the 150 rep to tag this properly so if anyone wants to step in it'd be appreciated." } ]
[ { "body": "<p>1) I believe it is not a good practice to give variables one-letter names. <code>Storyboard story = ...</code><br>\n2) I believe you can specify <code>Duration</code> in <code>ColorAnimation</code> only. And do not set it for <code>Storyboard</code>.<br>\n3) I would introduce variable for <code>ColorAnimation</code> because <code>s.Children[0]</code> looks weird to me when I know that it is <code>ColorAnimation</code>.<br>\n4) Strangely you are using <code>0.1f</code> where parameter is double anyway.<br>\n5) I would consider using object and collection initializers for <code>Storyboard.Children</code>.<br>\n6) Optionally I would think on removing storyboard variable and start it immediatly after constructing.</p>\n\n<p>Result: my code looks differently, but readability changes are subjective: </p>\n\n<pre><code>Line TargetLine = line;\n\nvar duration = new Duration(TimeSpan.FromSeconds(0.1));\nvar colorAnimation = new ColorAnimation(Colors.LightGreen, duration);\nStoryboard.SetTarget(colorAnimation, TargetLine);\nStoryboard.SetTargetProperty(colorAnimation, new PropertyPath(\"Stroke.Color\"));\n\nnew Storyboard {Children = {colorAnimation}}.Begin();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T18:21:54.340", "Id": "425", "ParentId": "404", "Score": "5" } }, { "body": "<p>No need for a storyboard:</p>\n\n<pre><code>var colourAnimation = new ColorAnimation(Colors.Red, new Duration(TimeSpan.FromSeconds(0.1)));\nline.Stroke.ApplyAnimationClock(SolidColorBrush.ColorProperty, colourAnimation.CreateClock()); \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-23T05:11:07.800", "Id": "3072", "ParentId": "404", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T05:39:15.903", "Id": "404", "Score": "9", "Tags": [ "c#", "wpf" ], "Title": "Animating the color of a line in WPF" }
404
<p>Consider the following method that I have for checking write permissions on a directory path:</p> <pre><code>/// &lt;summary&gt; /// Check existence and write permissions of supplied directory. /// &lt;/summary&gt; /// &lt;param name="directory"&gt;The directory to check.&lt;/param&gt; protected static void CheckPermissions(string directory) { if (!Directory.Exists(directory)) { throw new DirectoryNotFoundException(String.Format(JobItemsStrings.Job_DirectoryNotFound, directory)); } // Check permissions exist to write to the directory. // Will throw a System.Security.SecurityException if the demand fails. FileIOPermission ioPermission = new FileIOPermission(FileIOPermissionAccess.Write, directory); ioPermission.Demand(); } </code></pre> <p>When running FxCop, this code throws up a <strong>"CA2103 - Review imperative security"</strong> warning, albeit with a certainty of 25%, with this info:</p> <blockquote> <p>"Use of imperative demands can lead to unforeseen security problems. The values used to construct a permission should not change within the scope of the demand call. For some components the scope spans from the demand call to end of the method; for others it spans from the demand call until the component is finalized. If the values used to construct the permission are fields or properties, they can be changed within the scope of the demand call. This can lead to race conditions, mutable read-only arrays, and problems with boxed value types."</p> </blockquote> <p>Bascially, is FxCop being over-cautious, or am I doing it wrong?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T17:28:39.467", "Id": "683", "Score": "1", "body": "This is probably a question better suited for StackOverflow based on the FAQs guidelines for what is an applicable question." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T17:45:29.647", "Id": "688", "Score": "0", "body": "@Mark: Hmm, well the FAQ says \"If you are looking for specific feedback about… Code correctness, ..., Security issues in a code snippet, etc … then you are in the right place!\" I figured my question was a pretty good fit for that. But, if it is felt that it better suited for SO, then fair enough. :)" } ]
[ { "body": "<p>This FxCop warning is basically asking you to make sure (\"Review\") that that non-constant you are passing (<code>directory</code>) to the security permission does not change while the permission is in effect. Basically, FxCop isn't sure if it is possible for the code (or some rogue module that a hacker has put in place) to do something like the following:</p>\n\n<ol>\n<li>Set <code>directory</code> to \"c:\\Temp\\\"</li>\n<li><code>.Demand()</code></li>\n<li><code>&lt;untrusted&gt;</code><strong>Set <code>directory</code> to \"c:\\Windows\\System32\\\"</strong><code>&lt;/untrusted&gt;</code></li>\n<li>Write something into a file contained in <code>directory</code>.</li>\n</ol>\n\n<p>In this particular case, since <code>directory</code> is a non-ref parameter, it is not possible for another module outside your call-descendants to modify it. Thus, what you need to check for:</p>\n\n<ul>\n<li>Anything in this method assigning a value to <code>directory</code></li>\n<li>Anything in this method that passes <code>directory</code> by reference (<code>ref</code>/<code>out</code>/unsafe pointers)</li>\n</ul>\n\n<p><em>Disclaimer: I am not a code security expert and have no formal training as such. I may have missed entire classes of things to look for here. If you are dealing with code that has real-world security implications, I highly suggest you hire a consultant who does, rather than take what I wrote above as gospel.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T13:47:17.723", "Id": "739", "Score": "0", "body": "Thanks, you have clarified what I thought. This does not have Earth-shattering implications - I just want to gracefully handle any circumstance where the permissions don't allow writing by popping a MessageBox." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T10:21:54.583", "Id": "457", "ParentId": "413", "Score": "3" } }, { "body": "<p>When working with files, checking before an operation can be useful, but you still always need to handle relevant exceptions (e.g. <code>FileNotFoundException</code>, <code>IOException</code>). </p>\n\n<p>The permissions (or existence) of a file/directory may change between the time you check and time the operation is invoked (<code>new FileIOPermission(...)</code> in this case). This situation is more common than it seems. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T19:29:55.777", "Id": "564", "ParentId": "413", "Score": "0" } } ]
{ "AcceptedAnswerId": "457", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-29T09:56:55.847", "Id": "413", "Score": "2", "Tags": [ "c#", "security", "file-system" ], "Title": "Directory write permissions check" }
413
<p>I have a stored procedure that looks up an article based on the article's title. But I also need to increment a column in the same table that counts the number of times the article has been viewed.</p> <p>Trying to be as efficient as possible, I wanted a way to do this without performing multiple lookups. Someone pointed out the newer OUTPUT clause, which I've used below.</p> <p>I'm just wondering if I'm using it in the most efficient way, if I really made it faster, and if there are any other optimizations that could be employed.</p> <pre><code>DECLARE @Slug VARCHAR(250) -- Stored procedure argument -- declare @UpdatedArticle table variable DECLARE @UpdatedArticle TABLE ( ArtID INT, ArtUserID UNIQUEIDENTIFIER, ArtSubcategoryID INT, ArtTitle VARCHAR(250), ArtHtml VARCHAR(MAX), ArtDescription VARCHAR(350), ArtKeywords VARCHAR(250), ArtLicenseID VARCHAR(10), ArtViews BIGINT, ArtCreated DATETIME2(7), ArtUpdated DATETIME2(7) ); UPDATE Article SET ArtViews = ArtViews + 1 OUTPUT INSERTED.ArtID, INSERTED.ArtUserID, inserted.ArtSubcategoryID, INSERTED.ArtTitle, INSERTED.ArtHtml, INSERTED.ArtDescription, INSERTED.ArtKeywords, INSERTED.ArtLicenseID, INSERTED.ArtViews, INSERTED.ArtUpdated, INSERTED.ArtCreated INTO @UpdatedArticle WHERE ArtSlugHash = CHECKSUM(@Slug) AND ArtSlug = @Slug AND ArtApproved = 1 SELECT a.ArtID, a.ArtUserID, a.ArtTitle, a.ArtHtml, a.ArtDescription, a.ArtKeywords, a.ArtLicenseID, l.licTitle, a.ArtViews, a.ArtCreated, a.ArtUpdated, s.SubID, s.SubTitle, c.CatID, c.CatTitle, sec.SecID, sec.SecTitle, u.UsrDisplayName AS UserName FROM @UpdatedArticle a INNER JOIN Subcategory s ON a.ArtSubcategoryID = s.SubID INNER JOIN Category c ON s.SubCatID = c.CatID INNER JOIN [Section] sec ON c.CatSectionID = sec.SecID INNER JOIN [User] u ON a.ArtUserID = u.UsrID INNER JOIN License l ON a.ArtLicenseID = l.LicID </code></pre> <p>This is used in an ASP.NET application using SQL Server 2008.</p>
[]
[ { "body": "<p>I would optimize by not storing meta data along with the data. How does the view count really affect the article itself? Not at all.</p>\n\n<p>It's a different thing... So store it in a different place.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T00:54:15.560", "Id": "716", "Score": "1", "body": "I'm not sure I follow. How would it be more efficient if I moved the view count to another table? The existing query needs five joins. Why would it be worth needing another join just to keep that data in a separate table? I'd be curious to how that makes it better. (Aside from the fact that I do consider view counts to be an attribute of the article.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T00:17:35.607", "Id": "436", "ParentId": "415", "Score": "0" } }, { "body": "<p>You could do it all in one step, like this.</p>\n\n<pre><code>CREATE PROCEDURE dbo.IncrementArtViews (@Slug varchar(250)) AS\n\nUPDATE a\nSET ArtViews = ArtViews + 1\nOUTPUT a.ArtID, a.ArtUserID, a.ArtTitle, a.ArtHtml, a.ArtDescription,\n a.ArtKeywords, a.ArtLicenseID, l.licTitle, a.ArtViews, a.ArtCreated, \n a.ArtUpdated, s.SubID, s.SubTitle, c.CatID, c.CatTitle, sec.SecID, \n sec.SecTitle, u.UsrDisplayName AS UserName\nFROM dbo.Article a\n INNER JOIN dbo.Subcategory s ON a.ArtSubcategoryID = s.SubID\n INNER JOIN dbo.Category c ON s.SubCatID = c.CatID\n INNER JOIN dbo.[Section] sec ON c.CatSectionID = sec.SecID\n INNER JOIN dbo.[User] u ON a.ArtUserID = u.UsrID\n INNER JOIN dbo.License l ON a.ArtLicenseID = l.LicID\nWHERE a.ArtSlugHash = CHECKSUM(@Slug)\n AND a.ArtSlug = @Slug\n AND a.ArtApproved = 1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T23:37:49.363", "Id": "1828", "Score": "0", "body": "I like it. I don't understand it, and will need to study it, but I will use this approach if it works like that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-17T18:14:26.953", "Id": "282499", "Score": "0", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-17T18:15:32.853", "Id": "282500", "Score": "0", "body": "@Mast This answer is from '11. I'd just leave it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-17T18:18:22.280", "Id": "282501", "Score": "0", "body": "@SimonForsberg Which is why I upvoted it. However, I don't want the answerer to get the wrong idea. New answers should follow new rules." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T22:28:54.907", "Id": "1017", "ParentId": "415", "Score": "1" } }, { "body": "<p>Create a view. Update a row in the view, and output the columns.</p>\n\n<pre><code>CREATE VIEW dbo.ArticleView AS\n SELECT a.ArtID, a.ArtUserID, a.ArtTitle, a.ArtHtml, a.ArtDescription,\n a.ArtKeywords, a.ArtLicenseID, l.licTitle, a.ArtViews, a.ArtCreated, \n a.ArtUpdated, s.SubID, s.SubTitle, c.CatID, c.CatTitle, sec.SecID, \n sec.SecTitle, u.UsrDisplayName AS [UserName]\n FROM dbo.Article a\n INNER JOIN dbo.Subcategory s ON a.ArtSubcategoryID = s.SubID\n INNER JOIN dbo.Category c ON s.SubCatID = c.CatID\n INNER JOIN dbo.[Section] sec ON c.CatSectionID = sec.SecID\n INNER JOIN dbo.[User] u ON a.ArtUserID = u.UsrID\n INNER JOIN dbo.License l ON a.ArtLicenseID = l.LicID\nGO\n\nCREATE PROCEDURE dbo.IncrementArtViews (@Slug varchar(250)) AS\n UPDATE dbo.ArticleView\n SET ArtViews = ArtViews + 1\n OUTPUT ArtID, ArtUserID, ArtTitle, ArtHtml, ArtDescription,\n ArtKeywords, ArtLicenseID, licTitle, ArtViews, ArtCreated, \n ArtUpdated, SubID, SubTitle, CatID, CatTitle, SecID, \n SecTitle, [UserName]\n WHERE ArtSlugHash = CHECKSUM(@Slug)\n AND ArtSlug = @Slug\n AND ArtApproved = 1\nGO\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T16:12:51.643", "Id": "1023", "ParentId": "415", "Score": "1" } } ]
{ "AcceptedAnswerId": "1017", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T15:45:27.830", "Id": "415", "Score": "7", "Tags": [ "sql", "sql-server", "lookup" ], "Title": "Return Data and Update Row without Multiple Lookups?" }
415
<p>This system has to manage students, teachers, staff and grading. This is for production and is not a school assignment. As such, please let me know if I can improve on any aspect. :)</p> <p>My main concern is automation. I'd like my software to be able to run regardless if I still exist. </p> <p>I'm using SQLite as the database:</p> <pre><code>create table User ( ID integer primary key autoincrement, Username string, Password string ); create table Area ( ID integer primary key autoincrement, Name string ); create table Subject ( ID integer primary key autoincrement, Name string, Abbreviation string, IDArea integer references Area(ID) ); create table Level ( ID integer primary key autoincrement, Name string, Principle string ); create table Grade ( ID integer primary key autoincrement, Name string, IDLevel integer references Level(ID), Observation string ); create table StaffType ( ID integer primary key autoincrement, Name string ); create table Staff ( ID integer primary key autoincrement, IDStaffType integer references StaffType(ID), Name string, LastNameFather string, LastNameMother string, DateOfBirth string, PlaceOfBirth string, Sex string, Carnet string, Telephone string, MobilePhone string, Address string, FatherName string, MotherName string, FatherContact string, MotherContact string, FatherPlaceOfWork string, MotherPlaceOfWork string, DateOfHiring string, YearsOfService string, Formation string, Specialty string, Category string, Salary string ); create table GradeParalelo ( ID integer primary key autoincrement, IDGrade integer references Grade(ID), IDStaff integer references Staff(ID), Name string ); create table Student ( ID integer primary key autoincrement, IDGradeParalelo integer references GradeParalelo(ID), Rude string, Name string, LastNameFather string, LastNameMother string, DateOfBirth string, PlaceOfBirth string, Sex string, Carnet string, Telephone string, MobilePhone string, Address string, FatherName string, MotherName string, FatherMobilePhone string, MotherMobilePhone string, FatherProfession string, MotherProfession string, FatherPlaceOfWork string, MotherPlaceOfWork string, Observations string ); create table Attendance ( ID integer primary key autoincrement, IDStudent integer references Student(ID), Attended string, Date string ); create table SubjectGrade ( ID integer primary key autoincrement, IDGrade integer references Grade(ID), IDSubject integer references Subject(ID) ); create table ScoreRecord ( ID integer primary key autoincrement, IDSubject integer references Subject(ID), IDStudent integer references Student(ID), FirstTrimester integer, SecondTrimester integer, ThirdTrimester integer, FinalGrade integer, Year string ); </code></pre> <p><a href="https://i.stack.imgur.com/gUAbT.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/gUAbT.jpg" alt="Entity/Relationship diagram"></a></p> <p>Any glaring room for improvement?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T22:09:21.320", "Id": "709", "Score": "0", "body": "Are you sure sqlite is what you want to use? What do you expect the number of concurrent users to be (reading & writing)? What are expected # of rows in each table? How will you handle audit trail, delete/undelete, edit/undo? Don't store passwords as plain text. Any idea up front what kinds of reports you'll be running? It's pretty clear for staff & students you will need to adjust the fields from time to time; it may be worth it to come up with a general mechanism for extensibility there." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T00:57:13.843", "Id": "717", "Score": "0", "body": "Concurrent users: 2. Each table will have at MAXIMUM 5 million rows, and that's REALLY stretching it." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T23:55:23.607", "Id": "983", "Score": "1", "body": "I don't have time for a full review right now, but a quick note besides those I've seen below: I feel \"Observation\" as seen in various tables may benefit from being stored in a separate table for each (ie: StudentObservations) with timestamps and perhaps user auditing. In general I would think User roles (for who/what they can and can't change) would be pretty important for a school too, though this sounds like a pretty small setup." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T01:24:11.730", "Id": "62327", "Score": "1", "body": "I would suggest to set all columns which should not contain NULL values to \"non null\"." } ]
[ { "body": "<p>Comments</p>\n\n<ol>\n<li><p>All your ID (unique ID's) are called ID (this is OK and it works for you)<br>\nBut I have found when you start doing joins this may become hard to read. Thus I like to name the unique key after the table. eg <code>User_ID</code> on the User Table etc.</p></li>\n<li><p>To make the Identifiers easier to read either use camel case or separate words with _<br>\nIdentifiers like <code>IDArea</code> run together a bit much. So <code>IdArea</code> or <code>ID_Area</code> or <code>Id_Area</code> (Remember pick a style and be consistent though).</p></li>\n<li><p>The Staff table has a lot of information in it a lot of which could be NULL.<br>\nI would rather have a Person table to hold people information. Then a relationship table to hold relations ships between people. This way when your DB is expanded (and in a Business environment this will happen) you can express other relationships between staff.</p></li>\n<li><p>Related to Staff. Like Staff I would keep the personal details of Student in the Person table. Note. I would still keep a seprate table (or view) for Staff/Student that has a link into the Person table.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T17:22:10.833", "Id": "681", "Score": "1", "body": "Regarding point #1, I use Entity Framework, so in my code I go: .FindAllStudents().Where(s=>s.ID == parameterID); Like that. :P" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T18:21:57.590", "Id": "810", "Score": "1", "body": "Point #1 is a swings and roundabouts thing. If you always call your primary key ID then you know that ID is always your primary key - there's convention over configuration benefits that arise as a consequence to offset the potential SQL issues (though I'd suggest that tableID = table.ID is fairly clear)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T19:02:09.907", "Id": "817", "Score": "0", "body": "@Murph: This is a code review all points are subjective. And on simple queries then ID is fine. But once you start writing complex multiple nested queries (which is what happens in the real world) that extend past 2 three pages the extra clarity does actually bye you some benefit." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T19:25:07.923", "Id": "818", "Score": "0", "body": "everything is a compromise, you give up one thing to gain another. And I've *done* complex queries (-:" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T17:11:14.260", "Id": "420", "ParentId": "418", "Score": "11" } }, { "body": "<p>I appreciate that all the names you choose for tables and fields are understandable and self-explanatory. Only \"GradeParalelo\" does not make sense to me.</p>\n\n<p>Nevertheless, I would suggest adding short comments to describe fields and tables. Include the motivation for design decisions that required complex thinking, especially if you expect the system to be maintained by different people.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T18:07:30.890", "Id": "694", "Score": "2", "body": "It's because it's in Spanglish :P Basically, here in Bolivia you can have many 'instances' of a grade. And a student belongs to a single instance of a grade." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T17:24:56.687", "Id": "421", "ParentId": "418", "Score": "2" } }, { "body": "<p>Some things that jumped out</p>\n\n<p>take martin york's suggestion and be consistent as much as possible, user identifying primary key names like <code>user_id</code> as opposed to <code>id</code> for every table as it will make it less confusing for those writing/maintaining the SQL. For foreign keys, I would suggest table first e.g. <code>area_id</code> as opposed to <code>IdArea</code> as it flows better with natural language.</p>\n\n<ul>\n<li><p>Looking at your ERD, there are places where it is failing to get to <a href=\"http://en.wikipedia.org/wiki/Database_normalization\" rel=\"nofollow\">3NF</a> (which is a level of database normalization you should strive for when possible)</p></li>\n<li><p>Use proper field types, looks like you are using string a lot, things like date of hire should be actual timestamp/datetime column, gender can be enum, etc.</p></li>\n<li><p>All the contact/phone information in the staff and student tables can be places in more appropriate phone/contact tables as those are one to many relationships.</p></li>\n<li><p>Your attendance table...looks like it either states that a student attended school a particular day or not...seems like this would be something more on the per class level, as a student could attend a half day and such.</p></li>\n<li><p>Is it possible for a staff member to have more than one staff type, if so you should have an associative table to link staff to staff types</p></li>\n<li><p>Instead of years of service in staff, could you not just use the date of hire column to figure that out instead of every year updating the year of service column.</p></li>\n</ul>\n\n<p>Those are some things I noticed, hope it helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-29T18:07:44.667", "Id": "424", "ParentId": "418", "Score": "12" } }, { "body": "<p>There seems to be duplication, I'm just going to put changes for each table in a separate answer.</p>\n\n<p>Staff Table</p>\n\n<ol>\n<li><p>The mother and father contact information could be put into a separate table. That way you are not limited if someone has different contacts</p>\n\n<pre><code>contact_id, contact_name, relationship, contact_number, contact_address, fk=staff_id\n</code></pre></li>\n<li><p>Can a Staff have more than one StaffType? Like can a teacher be a coach? If so the table must be altered. Will all types have a specialty? </p></li>\n<li><p>Regarding <code>DateOfHiring</code> and <code>YearsOfService</code>, the length of service can be deduced using the current date and the <code>DateOfHiring</code>.</p></li>\n<li><p>I don't see a way to deactivate a staff member. What happens when they are terminated? Dropping their record is not a good solution. You may want to consider adding a termination date to the table.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-30T08:48:25.597", "Id": "452", "ParentId": "418", "Score": "2" } }, { "body": "<p>I agree with all of the other's observations above, but I will touch on a few particular points:</p>\n\n<ol>\n<li><p>You could definitely do some additional normalization. There are places where this may come down to a conscious decision NOT to fully normalize (there can be some reasons not to . . . Depending on your problem space), but overall, when I begin to see the same field names appearing in multiple tables (other than PK/FK relationships), I become suspicious. An example (which Martin York touches on, but I will take a step further) is all of the \"People\" fields. Note the level of duplication between the \"Staff\" table and the \"Student\" table with regard to Mothers/Fathers/Workplaces/Professions. Mothers and fathers are people. Staff are also people. Students are people. </p></li>\n<li><p>I notice you have an \"Observations\" field in your student table. I strongly recommend you define an \"Observations\" table with a foreign key to the \"Students\" table with the following fields (The Staff_ID is to record who made the observation). Over time, observations will accumulate, and it will be helpful to know when, and who made them:</p></li>\n</ol>\n\n<p>Observations Table: Observation_ID, Student_ID, Observation_Date, Observation, Staff_ID </p>\n\n<ol start=\"3\">\n<li><p>I agree with the notion that there should be a separate \"Contact_Info\" table. Further, I am betting you will want to send the student (or the student's parents) mail from time-to-time. I would include an \"Addresses\" table for this purpose. I won't pretend to know how it works in Bolivia, but in the United States, schools like to mail out report cards (although, parents ALSO can track their student's progress over the internet these days ...). </p></li>\n<li><p>Staff salaries can change. While you may decide it is acceptable to overwrite this value, this is another area where correct normalization indicates a Staff-Salaries table, which includes fields for ID, Salary, and Effective_Date. </p></li>\n</ol>\n\n<p>How far you take the normalization process can be tricky, but as one or more of the other commenters observed, you should always shoot for 3NF. I promise you, from my own painful experience, that when your boss decides he wants a report showing staff salary increases over a five-year period, you will be glad you did. </p>\n\n<p>While it often happens that there is a conscious, design-based decision to \"de-normalize\" a table, the decision should documented for those who may need to maintain your database in the future, when you are no longer there. </p>\n\n<p>Hope that helps!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-01-30T09:36:26.533", "Id": "455", "ParentId": "418", "Score": "5" } }, { "body": "<p>One thing which immediately jumped out to me is this:</p>\n\n<pre><code>LastNameFather string,\nLastNameMother string,\nFatherName string,\nMotherName string,\nFatherContact string,\nMotherContact string,\nFatherPlaceOfWork string,\nMotherPlaceOfWork string,\n</code></pre>\n\n<p>Your design assumes that every student will have exactly 1 mother and exactly 1 father. I can tell you now that will not be the case. Students with divorced parents may have two mothers and two fathers, all of whom will want to have their contact info listed. Some students may have gay or lesbian parents, and thus two fathers or two mothers. Some students may have <em>neither</em>, and instead may have a legal guardian who is neither their father nor mother.</p>\n\n<p>One solution to this would be to have a table for a \"person\", and link people to each student. Identify whether that person is a father or mother (or non-parental guardian). This will also simplify having siblings: you can have the same mother, father, etc. for multiple students. </p>\n\n<p>For the majority of students, this won't be an issue, but for more than you might think, it will. Do those families and your management a favor by making it easy to handle various family scenarios!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T14:49:09.753", "Id": "742", "Score": "0", "body": "I'll keep that in mind for the next iteration. I'll create a table \"Guardian\", with IDStudent, IDGuardianType(parent, guardian, etc.) and Name, Contact Info, etc." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T17:11:00.400", "Id": "749", "Score": "0", "body": "Do keep in mind the possibility that a child will have two mothers or two fathers on their birth certificate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-13T15:20:15.580", "Id": "416503", "Score": "0", "body": "Be aware that not everyone fits the neat firstname+lastname pattern that's proposed, too. That *might* be adequate for the students, but their parents are less likely to all come from the local culture." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T09:51:48.460", "Id": "456", "ParentId": "418", "Score": "26" } }, { "body": "<p>All tables use automatically assigned <em>sequences</em> as keys, this is not proper data modelling. Many people do that and forget about the actual/business/real world <em>Primary Keys</em>. You don't want to allow multiple users/areas/subjects with the same name, thus you must add Unique Constraints on <code>User.username</code>, <code>Area.name</code>, <code>Subject.name</code>, <code>Subject.Abbreviation</code>, etc.</p>\n\n<p>The <code>ID</code> in <code>SubjectGrade</code> is useless, it's never used/referenced, the logical key is <code>IDGrade,IDSubject</code>.</p>\n\n<p>Similar for <code>ScoreRecord</code>: <code>IDSubject, IDStudent</code> instead of <code>ID</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-28T12:03:59.543", "Id": "124084", "ParentId": "418", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-29T16:30:59.507", "Id": "418", "Score": "37", "Tags": [ "sql", "sqlite" ], "Title": "Database design for a school system" }
418
<p>While researching ways to convert back and forth between <code>std::wstring</code> and <code>std::string</code>, I found <a href="http://social.msdn.microsoft.com/Forums/en/Vsexpressvc/thread/0f749fd8-8a43-4580-b54b-fbf964d68375">this conversation</a> on the MSDN forums.</p> <p>There were two functions that, to me, looked good. Specifically, these:</p> <pre><code>std::wstring s2ws(const std::string&amp; s) { int len; int slength = (int)s.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len); std::wstring r(buf); delete[] buf; return r; } std::string ws2s(const std::wstring&amp; s) { int len; int slength = (int)s.length() + 1; len = WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, 0, 0, 0, 0); char* buf = new char[len]; WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, buf, len, 0, 0); std::string r(buf); delete[] buf; return r; } </code></pre> <p>However, the double allocation and the need to delete the buffer concern me (performance and exception safety) so I modified them to be like this:</p> <pre><code>std::wstring s2ws(const std::string&amp; s) { int len; int slength = (int)s.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); std::wstring r(len, L'\0'); MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, &amp;r[0], len); return r; } std::string ws2s(const std::wstring&amp; s) { int len; int slength = (int)s.length() + 1; len = WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, 0, 0, 0, 0); std::string r(len, '\0'); WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, &amp;r[0], len, 0, 0); return r; } </code></pre> <p>Unit testing indicates that this works in a nice, controlled environment but will this be OK in the vicious and unpredictable world that is my client's computer?</p>
[]
[ { "body": "<p>I don't do any Windows development, so I can't comment on the <code>WideCharToMultiByte</code> part being safe.</p>\n\n<p>The one thing I would say though is to ensure you are using the proper types for everything. For example, <code>string.length()</code> returns a <code>std::string::size_type</code> (most likely a <code>size_t</code>, the constructor also takes a <code>std::string::size_type</code>, but that one isn't as big of a deal). It probably won't ever bite you, but it is something to be careful of to ensure you don't have any overflows in other code you may be writing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T09:15:19.157", "Id": "736", "Score": "1", "body": "Well, it returns a `std::string::size_type`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T15:41:28.377", "Id": "745", "Score": "0", "body": "@Jon: True, but I've never it seen it not be equal to the representation of a `size_t`. I'll modify the answer though, thanks for your feedback." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T22:02:46.747", "Id": "757", "Score": "2", "body": "@Jon: `std::string::size_type` is always a `std::size_t`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T23:28:42.033", "Id": "763", "Score": "0", "body": "@GMan: I was just being pedantic out of boredom. SGI says it's \"an unsigned integral type that can represent any nonnegative value of the container's distance type\"—that is, `difference_type`—and that both of these must be `typedef` s for existing types, but this doesn't imply that `size_type` has to be equivalent to `size_t`. Is there something else at work here?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T05:31:34.937", "Id": "776", "Score": "1", "body": "@Jon: I'm not sure why SGI matters. The *standard* says `std::string::size_type` is `allocator_type::size_type`, and the default allocator's `size_type` is `std::size_t`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T07:10:51.307", "Id": "780", "Score": "0", "body": "@GMan: Alright, that's what I was looking for. SGI doesn't matter, except of course when it does. But hey, `size_type` is the first one in the chain, for all it matters. Or the last, depending on where you're standing." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T17:49:15.337", "Id": "422", "ParentId": "419", "Score": "3" } }, { "body": "<p>I've only briefly looked over your code. I haven't worked with std::string much but I've worked a lot with the API.</p>\n\n<p>Assuming you got all your lengths and arguments right (sometimes making sure the terminator and wide vs multibyte lengths are all right can be tricky), I think you're on the right track. I think the first routines you posted unnecessarily allocate an additional buffer. It isn't needed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T22:56:40.853", "Id": "433", "ParentId": "419", "Score": "-1" } }, { "body": "<p>One thing that may be an issue is that it assumes the string is ANSI formatted using the currently active code page (CP_ACP). You might want to consider using a specific code page or CP_UTF8 if it's UTF-8.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T19:49:27.960", "Id": "819", "Score": "0", "body": "This may be a silly question but, how can I tell? For my usage these will typically be filenames." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-01T01:30:57.983", "Id": "833", "Score": "0", "body": "How do you obtain the filenames? That will determine the correct code page to use." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-05T16:31:30.893", "Id": "1112", "Score": "0", "body": "@Jere.Jones: One way is to check if the string is valid UTF-8. If not, assume it's ANSI." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-05T21:33:04.090", "Id": "1125", "Score": "1", "body": "@dan04: ANSI requires that a code page is specified. http://en.wikipedia.org/wiki/Code_page." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-20T20:46:58.430", "Id": "358867", "Score": "1", "body": "Further note: The [MSDN documentation](https://msdn.microsoft.com/en-us/library/windows/desktop/dd374130(v=vs.85).aspx) recommends not using CP_ACP for strings intended for permanent storage, because the active page may be changed at any time" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-24T23:29:22.773", "Id": "393929", "Score": "0", "body": "CP_UTF8 https://docs.microsoft.com/es-es/windows/desktop/Intl/code-page-identifiers" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T16:05:31.277", "Id": "463", "ParentId": "419", "Score": "6" } }, { "body": "<p>I would, and have, redesign your set of functions to resemble casts:</p>\n\n<pre><code>std::wstring x;\nstd::string y = string_cast&lt;std::string&gt;(x);\n</code></pre>\n\n<p>This can have a lot of benefits later when you start having to deal with some 3rd party library's idea of what strings should look like.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T18:53:42.243", "Id": "816", "Score": "1", "body": "I love the syntax. Can you share the code?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-05T18:21:41.183", "Id": "1118", "Score": "1", "body": "Oooh. That looks nice. How would one do that? Just make a template with specializations to convert between the various string types?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-05T03:20:49.413", "Id": "8806", "Score": "1", "body": "@Billy someone posted a codereview question for string_cast implementation [on here](http://codereview.stackexchange.com/questions/1205/c-string-cast-template-function/1466#1466) if you guys are interested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-13T23:55:53.637", "Id": "445083", "Score": "0", "body": "Why, though? I think I prefer to have functions `to_string` and `to_wstring`, similar to the standard library (in my own namespace of course)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T18:17:21.010", "Id": "488", "ParentId": "419", "Score": "12" } }, { "body": "<p>I'd recommend changing this:</p>\n\n<pre><code>int len;\nint slength = (int)s.length() + 1;\nlen = WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, 0, 0, 0, 0);\n</code></pre>\n\n<p>...to this:</p>\n\n<pre><code>int slength = (int)s.length() + 1;\nint len = WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, 0, 0, 0, 0);\n</code></pre>\n\n<p>Slightly more concise, <code>len</code>'s scope is reduced, and you don't have an uninitialised variable floating round (ok, just for one line) as a trap for the unwary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-02T16:24:04.177", "Id": "556", "ParentId": "419", "Score": "5" } }, { "body": "<p>No, this is dangerous! The characters in a std::string may not be stored in a contiguous memory block and you must not use the pointer <code>&amp;r[0]</code> to write to any characters other than that character! This is why the <code>c_str()</code> function returns a <code>const</code> pointer.</p>\n\n<p>It might work with MSVC, but it will probably break if you switch to a different compiler or STL library.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-05T13:59:20.287", "Id": "8808", "Score": "3", "body": "-1: Wrong: http://stackoverflow.com/questions/2256160/how-bad-is-code-using-stdbasic-stringt-as-a-contiguous-buffer" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-05T01:46:54.117", "Id": "5816", "ParentId": "419", "Score": "-3" } }, { "body": "<p><strong>Actually <em>my</em> unit testing shows that your code is wrong!</strong></p>\n\n<p>The problem is that you include the zero terminator in the output string, which is not supposed to happen with <code>std::string</code> and friends. Here's an example why this can lead to problems, especially if you use <code>std::string::compare</code>:</p>\n\n<pre><code>// Allocate string with 5 characters (including the zero terminator as in your code!)\nstring s(5, '_');\n\nmemcpy(&amp;s[0], \"ABCD\\0\", 5);\n\n// Comparing with strcmp is all fine since it only compares until the terminator\nconst int cmp1 = strcmp(s.c_str(), \"ABCD\"); // 0\n\n// ...however the number of characters that std::string::compare compares is\n// someString.size(), and since s.size() == 5, it is obviously not equal to \"ABCD\"!\nconst int cmp2 = s.compare(\"ABCD\"); // 1\n\n// And just to prove that string implementations automatically add a zero terminator\n// if you call .c_str()\ns.resize(3);\nconst int cmp3 = strcmp(s.c_str(), \"ABC\"); // 0\nconst char term = s.c_str()[3]; // 0\n\nprintf(\"cmp1=%d, cmp2=%d, cmp3=%d, terminator=%d\\n\", cmp1, cmp2, cmp3, (int)term);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-30T13:01:45.993", "Id": "180694", "Score": "0", "body": "I found the addition of the terminator annoying too: it also broke a string addition in my case. I ended up adding the boolean parameter `includeTerminator` to both methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-12T00:53:12.097", "Id": "444815", "Score": "0", "body": "@reallynice see: [FlagArgument (martinfowler.com)](https://www.martinfowler.com/bliki/FlagArgument.html)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-03T17:35:18.177", "Id": "23393", "ParentId": "419", "Score": "12" } }, { "body": "<p>It really depends what codecs are being used with <code>std::wstring</code> and <code>std::string</code>.</p>\n\n<p>This answer assumes that the <code>std::wstring</code> is using a UTF-16 encoding, and that the conversion to <code>std::string</code> will use a UTF-8 encoding.</p>\n\n<pre><code>#include &lt;codecvt&gt;\n#include &lt;string&gt;\n\nstd::wstring utf8ToUtf16(const std::string&amp; utf8Str)\n{\n std::wstring_convert&lt;std::codecvt_utf8_utf16&lt;wchar_t&gt;&gt; conv;\n return conv.from_bytes(utf8Str);\n}\n\nstd::string utf16ToUtf8(const std::wstring&amp; utf16Str)\n{\n std::wstring_convert&lt;std::codecvt_utf8_utf16&lt;wchar_t&gt;&gt; conv;\n return conv.to_bytes(utf16Str);\n}\n</code></pre>\n\n<p>This answer uses the STL and does not rely on a platform specific library.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-24T09:02:49.213", "Id": "349386", "Score": "0", "body": "This is the best answer because is the only working. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T15:48:07.800", "Id": "434892", "Score": "0", "body": "https://dbj.org/c17-codecvt-deprecated-panic/ ... my shameless plug might help ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-12T00:59:34.990", "Id": "444816", "Score": "0", "body": "@DBJDBJ Your proposed solution is by no means a replacement to `wstring_convert` from <codecvt>. You kind of down-play the problem by saying the approach is \"_somewhat controversial_\" - in my opinion, it's much more than that. It's wrong. I have uses of `wstring_convert` which your solution cannot replace. It cannot convert true unicode strings like `\"おはよう\"`, as it's not a true conversion; it's a cast. Consider making that more explicit in your text ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-12T15:17:45.560", "Id": "444910", "Score": "0", "body": "@Marc.2377 -- well ,I think I have placed plenty of warnings in that text. I even have mentioned the \"casting\" word. there is even a link to \"that article\" ... Many thanks for reading in any case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-12T16:15:12.507", "Id": "444916", "Score": "0", "body": "FFWD to 2019 -- `<codecvt>` is deprecated" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-11T07:14:52.263", "Id": "146738", "ParentId": "419", "Score": "10" } }, { "body": "<p>When we're using <code>std::string</code> and <code>std::wstring</code>, we need <code>#include &lt;string&gt;</code>.</p>\n\n<p>There's no declaration of <code>MultiByteToWideChar()</code> or <code>WideCharToMultiByte()</code>. Their names suggest they might be some thin wrapper around <code>std::mbstowcs()</code> and <code>std::wcstombs()</code> respectively, but without seeing them, it's hard to be sure.</p>\n\n<p>It would be much simpler and easier to understand if we used the standard functions to convert between null-terminated multibyte and wide-character strings.</p>\n\n<p>Depending on the use case, a <code>std::codecvt&lt;wchar_t, char, std::mbstate_t&gt;</code> facet might be more appropriate. Then there's very little code to be written, and in particular, no need to guess at the possible output length.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-10T17:21:16.237", "Id": "217212", "ParentId": "419", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-29T17:04:41.087", "Id": "419", "Score": "40", "Tags": [ "c++", "strings", "converting" ], "Title": "Converting between std::wstring and std::string" }
419
<p>Having coded in Java and C# for quite some years, I'm currently learning Ruby. I'm working my way through the <a href="http://rubykoans.com/" rel="noreferrer">Ruby Koans tutorial</a>. At some point, you are to implement a method that calculates the game-score of a dice-game called Greed.</p> <p>I came up with this recursive Java/C#-like method. It passes all the supplied unit tests, so technically it's correct. </p> <p>Now I'm wondering: Is this good Ruby code? If not, how would a "Rubyist" write this method? And possibly: Why? I'm also not so happy about the amount of duplicate code but can't think of a better Rubyish way.</p> <pre><code>def score(dice) #dice is an array of numbers, i.e. [3,4,5,3,3] return 0 if(dice == [] || dice == nil) dice.sort! return 1000 + score(dice[3..-1]) if(dice[0..2] == [1,1,1]) return 600 + score(dice[3..-1]) if(dice[0..2] == [6,6,6]) return 500 + score(dice[3..-1]) if(dice[0..2] == [5,5,5]) return 400 + score(dice[3..-1]) if(dice[0..2] == [4,4,4]) return 300 + score(dice[3..-1]) if(dice[0..2] == [3,3,3]) return 200 + score(dice[3..-1]) if(dice[0..2] == [2,2,2]) return 100 + score(dice[1..-1]) if(dice[0] == 1) return 50 + score(dice[1..-1]) if(dice[0] == 5) return 0 + score(dice[1..-1]); end </code></pre> <p><strong>Some background (if needed)</strong></p> <pre><code># Greed is a dice game where you roll up to five dice to accumulate # points. A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fours is 400 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) =&gt; 1150 points # score([2,3,4,6,2]) =&gt; 0 points # score([3,4,5,3,3]) =&gt; 350 points # score([1,5,1,2,4]) =&gt; 250 points # # More scoring examples are given in the tests below: class AboutScoringProject &lt; EdgeCase::Koan def test_score_of_an_empty_list_is_zero assert_equal 0, score([]) end def test_score_of_a_single_roll_of_5_is_50 assert_equal 50, score([5]) end def test_score_of_a_single_roll_of_1_is_100 assert_equal 100, score([1]) end def test_score_of_a_single_roll_of_1_is_100 assert_equal 200, score([1,1]) end def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores assert_equal 300, score([1,5,5,1]) end def test_score_of_single_2s_3s_4s_and_6s_are_zero assert_equal 0, score([2,3,4,6]) end def test_score_of_a_triple_1_is_1000 assert_equal 1000, score([1,1,1]) end def test_score_of_other_triples_is_100x assert_equal 200, score([2,2,2]) assert_equal 300, score([3,3,3]) assert_equal 400, score([4,4,4]) assert_equal 500, score([5,5,5]) assert_equal 600, score([6,6,6]) end def test_score_of_mixed_is_sum assert_equal 250, score([2,5,2,2,3]) assert_equal 550, score([5,5,5,5]) end def test_score_of_a_triple_1_is_1000A assert_equal 1150, score([1,1,1,5,1]) end def test_score_of_a_triple_1_is_1000B assert_equal 350, score([3,4,5,3,3]) end def test_score_of_a_triple_1_is_1000C assert_equal 250, score([1,5,1,2,4]) end end </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T22:19:14.650", "Id": "710", "Score": "1", "body": "The second revision of the code looks good to me. Using a hash is a nice idea (though it doesn't make use of the fact that for `[x,x,x]` with `x != 1` the score is `x*100`, but I guess for 5 numbers doing so would be more noise than helpful)." } ]
[ { "body": "<p>There are a few issues with the code:</p>\n\n<ol>\n<li>Do not check for <code>== nil</code> when it is not specified as a valid value for the method. Here,checking for it and returning 0 might mask another problem.</li>\n<li>Do not use return statements unless necessary. In ruby, almost everything is an expression, and methods return the value of the last expression. Here you can use <code>if...elsif</code>, or <code>case</code> instead of a series of <code>if</code> statement.</li>\n<li>Do not modify parameters that come into your function (<code>dice.sort!</code>).</li>\n<li>Do not use recursion if it makes the code less readable.</li>\n</ol>\n\n<p>Here is a version of the code with the advice above applied:</p>\n\n<pre><code>def score(dice)\n score = 0\n counts = dice.each_with_object(Hash.new(0)) { |x, h| h[x] += 1 }\n (1..6).each do |i|\n if counts[i] &gt;= 3 \n score += (i == 1 ? 1000 : 100 * i)\n counts[i] = [counts[i] - 3, 0].max\n end\n score += counts[i] * (i == 1 ? 100 : 50)\n end\n score\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T19:34:51.033", "Id": "699", "Score": "2", "body": "Recursion is not the opposite of straight forward. I found the OP's approach quite straight forward - just very repetitive." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T19:42:58.287", "Id": "700", "Score": "0", "body": "It's not the opposite of straight forward in general. However, in this case I believe it is." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T20:05:13.387", "Id": "701", "Score": "1", "body": "Since coming to ruby, I've actually dropped my rule of \"one and only one return\" per method. I often have more than a single return statement in a method." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T21:08:46.153", "Id": "704", "Score": "0", "body": "What I am talking about is not multiple return points, but the usage of `return` keyword" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T21:14:49.013", "Id": "706", "Score": "0", "body": "Thanks for your review! It helped me quite a bit. I'm exceited to see thing like: \"(1..6).each do |i|\" ... Thanks. As for the recursion, to me it still seems a natural thing to do here. I nearly never use recusion but here it seemed to make it so very easy. Is recursion per se \"non-Ruby\"?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T05:29:57.087", "Id": "730", "Score": "0", "body": "No, recursion is alright :) But for this task it's just not approptiate! You are welcome!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T15:43:45.620", "Id": "803", "Score": "0", "body": "Uber Noob to Ruby... why is using the return keyword not good?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-08T17:54:12.380", "Id": "1229", "Score": "0", "body": "Return is normally OK, but in Ruby is not necessary at the end of a method - in this case it was a bit wasteful." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T07:44:20.450", "Id": "1764", "Score": "2", "body": "A great review. This clued me into a [bug I had to go fix](https://github.com/BinaryMuse/rforce-wrapper/commit/eaa7e28) after I read it. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-03T04:35:13.090", "Id": "98368", "Score": "0", "body": "Is there a reason you make a count variable instead of using Array#count like this: `dice.count(i)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-03T12:28:01.933", "Id": "98453", "Score": "0", "body": "@addison `Array#count` walks the entire array for every `i`, we only walk it once" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-29T18:46:52.523", "Id": "426", "ParentId": "423", "Score": "12" } }, { "body": "<p>@glebm has some very good points. I want to also introduce a different style. Here is how I would approach this problem.</p>\n\n<pre><code>def score dice\n dice.group_by(&amp;:to_i).inject(0) do |score, combo| \n score + combos_score(*combo) + ones_score(*combo) + fives_score(*combo)\n end\nend\n\ndef combos_score dice_value, dice_with_value\n number_of_bonues = [dice_with_value.size - 2, 0].max\n\n bonus_for(dice_value) * number_of_bonues\nend\n\ndef bonus_for dice_value\n dice_value == 1 ? 1000 : dice_value * 100\nend\n\ndef ones_score dice_value, dice_with_value\n return 0 if dice_value != 1 || dice_with_value.size &gt; 2\n\n dice_with_value.size * 100\nend\n\ndef fives_score dice_value, dice_with_value\n return 0 if dice_value != 5 || dice_with_value.size &gt; 2\n\n dice_with_value.size * 50\nend\n</code></pre>\n\n<p>I like that </p>\n\n<ol>\n<li>Logic for each scoring scenario is isolated together</li>\n<li>There isn't a need to build a special Hash that would calculate the score.</li>\n<li>Use of the built in Enumerable#group_by to grab similar die together</li>\n<li>Small methods that are easy to test</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-24T05:23:37.290", "Id": "42640", "ParentId": "423", "Score": "2" } } ]
{ "AcceptedAnswerId": "426", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-29T17:57:54.140", "Id": "423", "Score": "24", "Tags": [ "ruby", "programming-challenge", "dice" ], "Title": "Ruby Koans' Greed Task" }
423
<p>I have been developing this class, and was wondering if anyone had any thoughts on how I can improve the performance of it.</p> <pre><code>&lt;?php class Something { private $APIUsername, $APIPassword; private $APIurl = 'somesite.com'; function __construct ($APIUsername = '', $APIPassword = '') { try { if (!$APIUsername || !$APIPassword) { throw new Exception('You must specify a valid API username and password.'); } $this-&gt;APIUsername = $APIUsername; $this-&gt;APIPassword = $APIPassword; } catch (Exception $e) { die($e-&gt;getMessage()); } } /* * Authenticate Account */ public function authenticate ($EmailAddress, $Password) { try { $data['EmailAddress'] = $EmailAddress; $data['Password'] = $Password; $data = $this-&gt;setJSON($data); $result = $this-&gt;fetch('authenticate', $data); } catch (Exception $e) { $result = $e-&gt;getMessage(); } return $result; } /* * Get Contacts */ public function contacts ($EmailAddress, $Password, $PIN) { try { $data['EmailAddress'] = $EmailAddress; $data['Password'] = $Password; $data['PIN'] = $PIN; $data = $this-&gt;setJSON($data); $result = $this-&gt;fetch('contacts', $data); } catch (Exception $e) { $result = $e-&gt;getMessage(); } return $result; } /* * Get Transactions */ public function transactions ($EmailAddress, $Password, $PIN) { try { $data['EmailAddress'] = $EmailAddress; $data['Password'] = $Password; $data['PIN'] = $PIN; $data = $this-&gt;setJSON($data); $result = $this-&gt;fetch('transactions', $data); } catch (Exception $e) { $result = $e-&gt;getMessage(); } return $result; } /* * Validate PIN */ public function validatepin ($EmailAddress, $Password, $PIN) { try { $data['EmailAddress'] = $EmailAddress; $data['Password'] = $Password; $data['PIN'] = $PIN; $data = $this-&gt;setJSON($data); $result = $this-&gt;fetch('validatepin', $data); } catch (Exception $e) { $result = $e-&gt;getMessage(); } return $result; } /* * Get Account Balance */ public function balance ($EmailAddress, $Password) { try { $data['EmailAddress'] = $EmailAddress; $data['Password'] = $Password; $data = $this-&gt;setJSON($data); $result = $this-&gt;fetch('balance', $data); } catch (Exception $e) { $result = $e-&gt;getMessage(); } return $result; } /* * Get Account Information */ public function account_information ($EmailAddress, $Password) { try { $data['EmailAddress'] = $EmailAddress; $data['Password'] = $Password; $data = $this-&gt;setJSON($data); $result = $this-&gt;fetch('account_information', $data); } catch (Exception $e) { $result = $e-&gt;getMessage(); } return $result; } /* * Send Money */ public function send ($EmailAddress, $Password, $PIN, $DestinationID, $Amount, $Notes = '', $FundsSource = '') { try { $data['EmailAddress'] = $EmailAddress; $data['Password'] = $Password; $data['PIN'] = $PIN; $data['DestinationID'] = $DestinationID; $data['Amount'] = $Amount; $data['Notes'] = urlencode($Notes); $data['FundsSource'] = $FundsSource; $data = $this-&gt;setJSON($data); $result = $this-&gt;fetch('send', $data); } catch (Exception $e) { $result = $e-&gt;getMessage(); } return $result; } /* * Send (Sender Assumes Transaction Costs) */ public function send_assume_costs ($EmailAddress, $Password, $PIN, $DestinationID, $Amount, $Description = '') { try { $data['EmailAddress'] = $EmailAddress; $data['Password'] = $Password; $data['PIN'] = $PIN; $data['DestinationID'] = $DestinationID; $data['Amount'] = $Amount; $data['Description'] = urlencode($Description); $data = $this-&gt;setJSON($data); $result = $this-&gt;fetch('send_assume_costs', $data); } catch (Exception $e) { $result = $e-&gt;getMessage(); } return $result; } /* * Set JSON Data */ private function setJSON ($data) { $a = array(); $a['APIUsername'] = $this-&gt;APIUsername; $a['APIPassword'] = $this-&gt;APIPassword; foreach ($data as $key =&gt; $value) { $a[$key] = $value; } return json_encode($a); } /* * Helper method that talks to teh API */ private function fetch($APIMethod, $data) { $c = curl_init($this-&gt;APIurl.$APIMethod); curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); curl_setopt($c, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json')); curl_setopt($c, CURLOPT_POSTFIELDS, $data); $returned = curl_exec($c); if ($returned === false) { throw new Exception(curl_error($c)); return; } curl_close($c); if (json_decode($returned)) { return $returned; } else { throw new Exception('Invalid Service Request.'); return; } } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T01:41:12.257", "Id": "719", "Score": "0", "body": "like agentile, I originally answered with \"combine all methods into one\". agentile actually proposes a better way than I though. My question would be, what area of performance are you looking at specifically? Is this a frequently trafficked script? Are you focusing on the curl call and the lag of external connections? Are your `setJSON` and `fetch` methods used _outside_ your class at all?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T10:10:04.810", "Id": "737", "Score": "0", "body": "Note, that this class is accessing remote resources via cUrl, so most of the time is spend on sending/receiving data, not on actual PHP processing here. There's hardly anything you can do to speed this up." } ]
[ { "body": "<p>Some things I noticed.</p>\n\n<p>It seems like a lot/all of your public functions are simply doing the same thing, setting the functions params into an array, calling <code>setJSON</code> which simply appends the <code>APIusername</code> and <code>APIpassword</code> and then you fetch and catch any errors. You could have one method that does this and only methods that differ from this logic would do something else.</p>\n\n<p>looks like you can just use PHP's <code>compact()</code> function for most of what you are doing.</p>\n\n<p>For <code>setJSON()</code>, instead of looping through <code>$data</code> and remaking the same array, why not just add <code>$data['APIUsername'] = $this-&gt;APIUsername;</code> and <code>$data['APIPassword'] = $this-&gt;APIPassword;</code> and then return the <code>json_encode($data)</code></p>\n\n<p>For your <code>fetch()</code> method, you could get rid of the curl requirement and just use streams in PHP using a combination of <code>stream_context_create()</code> and <code>file_get_contents()</code>.</p>\n\n<p>I think it also might be useful to glance over this articles about <a href=\"http://phpadvent.org/2009/exceptional-php-by-brandon-savage\" rel=\"nofollow\">Exceptions</a> .</p>\n\n<p>If you really are just passing along data with the username and password attached, you may just want to just use the magic <code>__call</code> method, that will check an array of acceptable API methods to call and then take the params, compact, add username and password, and then call your fetch method with this data and return. Example below.</p>\n\n<pre><code>&lt;?php\nclass API {\n protected $_api_methods = array(\n 'balance' =&gt; array('EmailAddress', 'Password'),\n );\n\n private $_api_username;\n private $_api_password;\n private $_api_url = 'someurl.com';\n\n public function __construct($username, $password)\n {\n if (!$username || !$password) {\n throw new APIException('You must provide API credentials');\n }\n\n $this-&gt;_api_username = $username;\n $this-&gt;_api_password = $password;\n }\n\n public function __call($method_name, $arguments)\n {\n if (!in_array($method_name, array_keys($this-&gt;_api_methods)) {\n throw new APIException(\"$method_name is not a valid API method\");\n }\n\n $data = $this-&gt;setJSON($method_name, $arguments);\n return $this-&gt;fetch($method_name, $data);\n }\n\n protected function setJSON($method_name, $data)\n {\n if (empty($data)) {\n throw new APIException('No data provided');\n }\n\n $data = array_combine($this-&gt;_api_methods[$method_name], $data);\n\n $data['api_username'] = $this-&gt;_api_username;\n $data['api_password'] = $this-&gt;_api_password;\n\n return json_encode($data);\n }\n\n protected function fetch($method, $data)\n {\n $context = stream_context_create(array(\n 'http' =&gt; array(\n 'method' =&gt; 'GET',\n 'timeout' =&gt; 5,\n ),\n ));\n\n try {\n $ret = file_get_contents($this-&gt;_api_url . $method, false, $context); \n } catch (APIException $e) {\n $ret = $e-&gt;getMessage();\n }\n\n return $ret;\n }\n}\n\nclass APIException extends Exception {}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-30T00:46:52.277", "Id": "439", "ParentId": "427", "Score": "2" } }, { "body": "<p>I think with \"performance\" you mean the cost of keeping a PHP session open as long as the CURL request waits for an answer. If it is about \"speed in PHP\" or \"loading time\" etc. then please don't get me wrong, but PHP is a farm horse, it never will make a good racehorse.</p>\n\n<p>Technically there is no way to speed up remote API calls, as you always need to wait for that. The CURL library should usually performs very well, however I am not an expert when it comes to PHP+CURL.</p>\n\n<p>The only thing I spot is that you disable SSL certificate checking. Doing that allows for MITM attacks, so perhaps this is not a good idea (SSL without verify is like a condom with a hole).</p>\n\n<p>What comes into my mind is that it always is not a good idea to keep RPC calls with a longer duration around, so I would recommend to change that into more phases. However that voids your class, as the complete framework has to be rewritten.</p>\n\n<p>I cannot show you code, but here is the idea:</p>\n\n<ol>\n<li><p>When the user submits the RPC to your app, the app stores the request (into some database table) and returns immediately, so the user can see something like \"processing\" on the page.</p></li>\n<li><p>In the background some task picks up the request which is stored (in the database) and processes it. The result then is saved (in the database).</p></li>\n<li><p>The client side then polls (or waits, retries, whatever) until the result is available.</p></li>\n</ol>\n\n<p>The \"funny\" thing about this is, that this takes even longer because of the handling of the background job. However as the user can see some progress the waiting experience is better.</p>\n\n<p>Perhaps you can even do it completely asynchronous, so if the user transfers money you see some \"scheduled tasks\" list, so the user can continue to do other things (this probably involves Ajax). And then, when the result is available, the \"scheduled task\" blinks (or whatever, you get the idea) such that the user can look into the result.</p>\n\n<p>All is a design issue: Think about a DoS situation, where 1000 users click onto the \"send money\" button in the same second (perhaps after some TV add ran). Your web server then needs to keep open 1000 sessions until all the 1000 CURL requests are done in parallel. The API side usually will have some DoS prevention and reject 980 CURL requests, because you are only allowed to have 20 requests open simultaneously with the same API key (this is quite common).</p>\n\n<p>So you have to serialize the requests anyway. Doing this from within PHP (like from within your class) is a pain in the a** (starvation problems, aborting manually. debugging concurrency, etc.), but with the background tasks it is easy: If you only have, say, 10 concurrent processors of stored requests, there never will be any problem with reaching the API request limit.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T19:19:40.767", "Id": "750", "Score": "0", "body": "Thanks for all the input. \"Improve the performance\" was pretty vague. I was looking for ways to make the class run more efficient; if all possible. Looks like I have some ready to do. Thanks again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-30T01:10:40.023", "Id": "442", "ParentId": "427", "Score": "0" } } ]
{ "AcceptedAnswerId": "439", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-29T19:31:05.860", "Id": "427", "Score": "6", "Tags": [ "php", "object-oriented", "php5" ], "Title": "JSON API for some bank account" }
427
<p>I wrote the following little shell script and published it on <a href="https://github.com/Basphil/random-xkcd-wallpaper/" rel="nofollow" title="My github repo">GitHub</a>. In the repo there's also a README file that explains how to use it in more detail.</p> <p>This is the first time I open-sourced/published something I wrote, so I'm interested whether you think that this code is ready for the public. </p> <p>Some pointers, but feel free to add your own thoughts:</p> <ol> <li>Does it look professional? If not, what would need to be done?</li> <li>Are the comments too much? Was it ok to publish it, although I know that under some circumstances it doesn't work (I wrote about that in the README)?</li> </ol> <p></p> <pre><code># random xkcd wallpaper: gets a random xkcd comic from xkcd.com and sets it as the desktop background. #!/bin/bash # /random/comic redirects to random comic. Wget gets the index.html of the comic. wget http://dynamic.xkcd.com/random/comic/ echo $(pwd) #Searches the line in the index.html file that points to the url where the actual comic is placed. #The image urls are of the form: http://imgs.xkcd.com/comics/.'name of comic'.(png | jpg) url=$(cat index.html | grep -o -m 1 http://imgs.xkcd.com/comics/.*\.png) #Assuming picture format is .png. Gets the name of the image file by only matching what comes after the last forward slash. name_pic=$(echo $url | grep -o [^/]*\.png) is_png=1 #Sets url and name_pic in the case of the picture being in .jpg format. if [ -z "$url" ] then url=$(cat index.html | grep -o -m 1 http://imgs.xkcd.com/comics/.*\.jpg) name_pic=$(echo $url | grep -o [^/]*\.jpg) is_png=0 fi #Downloads the image and saves it under its appropriate name. wget --output-document="$name_pic" "$url" #Sets the desktop background gconftool-2 --set --type=string /desktop/gnome/background/picture_filename $(pwd)/"$name_pic" #Cleans up rm index.html #For some reason, if the image is moved to fast (e.g without a wait) the background does not get set. sleep 1 #The current wallpaper can always be found under "current_xkcd_wallpaper.png" or "current_xkcd_wallpaper.jpg". Also prevents cluttering the directory with images. #If you want to keep all the pictures you downloaded, uncomment the following lines. #Cleans up. Makes sure that there is only one current_xkcd_wallpaper image file. #rm current_xkcd_wallpaper.* rm current_xkcd_wallpaper.* if [ $is_png = 1 ] ; then mv $(pwd)/"$name_pic" $(pwd)/current_xkcd_wallpaper.png else mv $(pwd)/"$name_pic" $(pwd)/current_xkcd_wallpaper.jpg fi </code></pre>
[]
[ { "body": "<pre><code>#!/bin/bash\n</code></pre>\n\n<p>The shebang line has no effect unless it's on the very first line, so you should put it before the copyright notice.</p>\n\n<pre><code>echo $(pwd)\n</code></pre>\n\n<p><code>echo $(command)</code> is almost always the same as just writing <code>command</code> (the exception being that <code>echo</code> adds a newline at the end if the command doesn't already produce one, but that's not the case here). So you can just change the above to <code>pwd</code>.</p>\n\n<pre><code>cat index.html | grep -o -m 1 http://imgs.xkcd.com/comics/.*\\.png\n</code></pre>\n\n<p>That's useless use of <code>cat</code>. If you want to grep through a file, you can just pass the filename as the last argument - no need to <code>cat</code> and pipe. (The same goes for later places in the code where you do the same with .jpg).</p>\n\n<pre><code>gconftool-2 --set --type=string /desktop/gnome/background/picture_filename $(pwd)/\"$name_pic\"\n</code></pre>\n\n<p>I think it'd be a good idea to make the command to change the wallpaper configurable, so non-GNOME users can use your script too.</p>\n\n<p>Also I'm not sure why you set the image to be the wallpaper <em>before</em> renaming it. I think it'd make more sense to do so afterwards (that might also solve your issue of having to <code>sleep</code>).</p>\n\n<hr>\n\n<p>On a general note you might take care to gracefully handle already existing files. For example if the script is called in a directory where an index.html already exists (which is not that unlikely), your script will a) not work and b) delete that index.html, which its owner might not appreciate.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T22:45:17.250", "Id": "712", "Score": "0", "body": "Those are all valid points which I will incorporate. I especially appreciate the remark about deleting files. Thats really important :-) I set the image before renaming it, because gconftool does not change the background if the name of the image stays the same, even though the file changed. Seems to be a bug." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T22:59:38.453", "Id": "713", "Score": "1", "body": "@Basil: [This mailing list post](http://mail.gnome.org/archives/nautilus-list/2005-March/msg00073.html) suggests unsetting and then resetting the key. That seems cleaner than using the old filename and then sleeping." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T23:02:40.673", "Id": "762", "Score": "0", "body": "I tried this when I wrote the first version of this script. I didn't work for some reason, thats why I download it to a different file name each time. It just loads the same image again otherwise. But your right, this would be nicer if it worked." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T21:19:40.550", "Id": "430", "ParentId": "428", "Score": "14" } }, { "body": "<p>Sorry, this might sound harsh, but I really think GPLv3 is plain overkill for your code.\nAnd this even might sound harsher: What you want to archive can be done in a 3-liner, so I think Public Domain would fit far better.</p>\n\n<p>I do not want to show you up as everybody starts as beginner, and basically it's your idea which counts, the implementation itself is mostly an exercise for the reader. So continue learning shell, it's tremendously powerful!</p>\n\n<p>An elaborated example which basically does what your script does, it borrows some details from your script:</p>\n\n<pre><code>#!/bin/bash\n\ncd \"`dirname \"$0\"`\" || exit\n\n[ 0 = \"$#\" ] &amp;&amp;\nset -- gconftool-2 --set --type=string /desktop/gnome/background/picture_filename\n\nurl=\"`curl -sL http://dynamic.xkcd.com/random/comic/ | grep -om1 'http://imgs.xkcd.com/comics/[^.]*\\.[a-z]*'`\"\nimg=\"$PWD/xkcd-wallpaper.${url##*.}\"\n\ncurl -so \"$img\" --fail \"$url\" &amp;&amp;\n\"$@\" \"$img\"\n</code></pre>\n\n<p>I wrapped the lines just for better readability. Note that every programmer has a set of favorite tools and ways, and one always can learn something from each other. Like I learned \"grep -o\" from your script today (I usually use sed, but grep -o is far more elegant in this context).</p>\n\n<p>The nice thing on Unix is that you can chain things so easily and flexibly. There is no need to squeeze everything into one monolithic script. The better way would be to create two scripts as building blocks and then join them together.</p>\n\n<p>One pulls the picture. Second installs the picture on gnome. Like this:</p>\n\n<p>xkcd-pull.sh:</p>\n\n<pre><code>#!/bin/bash\n\nurl=\"`curl -sL http://dynamic.xkcd.com/random/comic/ | grep -om1 'http://imgs.xkcd.com/comics/[^.]*\\.[a-z]*'`\"\n\nimg=\"/tmp/xkcd-wallpaper.${url##*.}\"\nimg=\"${1:-$img}\"\n\ncurl -so \"$img\" --fail \"$url\" &amp;&amp; echo \"$img\"\n</code></pre>\n\n<p>set-gnome-wp.sh</p>\n\n<pre><code>#!/bin/bash\n\nexec gconftool-2 --set --type=string /desktop/gnome/background/picture_filename \"$@\"\n</code></pre>\n\n<p>And then join that together, for example on the commandline:</p>\n\n<pre><code>img=\"`./xkcd-pull.sh`\" &amp;&amp; ./set-gnome-wp.sh \"$img\"\n</code></pre>\n\n<p>Following this pattern you can easily extend it for KDE or perhaps even adapt it to Cygwin under Windows. Please note that these snippets even contain some extra bloat, which might come handy later on.</p>\n\n<p>As you can see easily, doing it this way there is nothing left which you cannot look up in a manual. So all creativity left is your idea \"XKCD -> Wallpaper\" while the implementation is \"trivial\".</p>\n\n<p>(I did not test the code snippets here. Maybe there still is a typo in it. My contributed code is Public Domain.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T22:42:45.333", "Id": "759", "Score": "0", "body": "Thanks for the input. As already mentioned, this is the first thing I open sourced, so I wanted to put a license on it :) But I see your point. \nI also appreciate the bash specific comments, was my first script, lots more to learn!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T05:47:15.830", "Id": "3085", "Score": "0", "body": "The kind of license you choose is orthogonal to the length of the code and the matureness of the developer. Having said that, I like to nitpick on the backticks, which are deprecated. $(...) is better because it can easily be nested, and is better readable, even in poor fonts." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-10T08:44:43.117", "Id": "70913", "Score": "0", "body": "You are right! But typing 2 backticks involves 2 keypresses of just a lonely single key, while you usually have 5 keypresses of 4 different keys to enter `$(` and `)`. And moreover, we program because we are lazy, right? So using `$(..)` everywhere means wasting entropy. Which is bad as we know: Entropy never can drop. (SCNR as I am German `<- triple irony`)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T00:33:20.820", "Id": "437", "ParentId": "428", "Score": "13" } }, { "body": "<p>As well as the other problems already outlined, your code gets a file 'index.html', which could clobber any file of the same name in the current directory. Maybe it would be a good idea to create a new directory so that you don't mess things up?</p>\n\n<p>It would also be a good idea to make sure that the debris is removed even if the script is interrupted. You do that with 'trap'. I recommend trapping HUP, INT, QUIT, PIPE and TERM signals:</p>\n\n<pre><code>trap \"rm -f index.html; exit 1\" 0 1 2 3 13 15\n\n...other actions...\n\nrm -f index.html\ntrap 0\n</code></pre>\n\n<p>The <code>trap 0</code> at the end ensures that your script can exit successfully - very important. You can make your trap actions as complex as necessary - and should aim to keep them as simple as possible. One advantage of creating a directory for intermediate files is that you can simply remove that directory to clean up.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T14:22:57.320", "Id": "741", "Score": "1", "body": "+1 for creating a new folder. It is good practice to create a hidden folder named after your app in the user's home folder for this purpose, e.g. ~/.yourappname" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T03:03:22.130", "Id": "68541", "Score": "1", "body": "Even better: avoid writing `index.html` to disk at all. Just pipe it into your code for processing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T08:48:34.717", "Id": "453", "ParentId": "428", "Score": "7" } } ]
{ "AcceptedAnswerId": "437", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-29T20:54:09.183", "Id": "428", "Score": "13", "Tags": [ "bash", "http", "shell" ], "Title": "Was this shell script ready for open-source? (Random XKCD wallpaper)" }
428
<p>This weekend I've been having one heck of a time getting WPF Ribbon v4 working with MVVM and Prism (using unity). After much trial and error, I believe I have it working. I was hoping someone could take a look at it and give me some feedback.</p> <p>RibbonRegionAdapter.cs</p> <pre><code>public class RibbonRegionAdapter : RegionAdapterBase&lt;Ribbon&gt; { private Ribbon _ribbonTarget; public RibbonRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory) : base(regionBehaviorFactory) { } protected override void Adapt(IRegion region, Ribbon regionTarget) { _ribbonTarget = regionTarget; region.Views.CollectionChanged += delegate { foreach (RibbonTab tab in region.Views.Cast&lt;RibbonTab&gt;()) { if (!_ribbonTarget.Items.Contains(tab)) { _ribbonTarget.Items.Add(tab); } } }; } protected override IRegion CreateRegion() { return new SingleActiveRegion(); } } </code></pre> <p>BootStrapper.cs - To register our regionAdapter</p> <pre><code> protected override RegionAdapterMappings ConfigureRegionAdapterMappings() { RegionAdapterMappings mappings = base.ConfigureRegionAdapterMappings(); if (mappings != null) { mappings.RegisterMapping(typeof(Ribbon), this.Container.Resolve&lt;RibbonRegionAdapter&gt;()); } return mappings; } </code></pre> <p>CarRibbonTab.xaml</p> <pre><code>&lt;ribbon:RibbonTab x:Class="CarManager.Modules.CarModule.Views.CarRibbonTab" xmlns:ribbon="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" Header="Officers"&gt; &lt;ribbon:RibbonGroup Header="New"&gt; &lt;/ribbon:RibbonGroup&gt; &lt;ribbon:RibbonGroup Header="Manage"&gt; &lt;ribbon:RibbonButton Label="Make" LargeImageSource="..\Resources\make.png" /&gt; &lt;ribbon:RibbonButton Label="Inventory" LargeImageSource="..\Resources\Inventory.png" /&gt; &lt;ribbon:RibbonButton Label="Assignments" /&gt; &lt;/ribbon:RibbonGroup&gt; &lt;/ribbon:RibbonTab&gt; </code></pre> <p>CarRibbonTab.cs - Code behind for the View</p> <pre><code>public partial class CarRibbonTab: RibbonTab { public CarRibbonTab() { InitializeComponent(); } } </code></pre> <p>Shell.xaml - Just showing the ribbon control</p> <pre><code>&lt;ribbon:Ribbon DockPanel.Dock="Top" Title="CarManager" prism:RegionManager.RegionName="RibbonRegion"&gt; &lt;ribbon:Ribbon.ApplicationMenu&gt; &lt;ribbon:RibbonApplicationMenu SmallImageSource="Images\Icon.png"&gt; &lt;ribbon:RibbonApplicationMenuItem Header="Exit" ImageSource="Images\ExitIcon.png"/&gt; &lt;/ribbon:RibbonApplicationMenu&gt; &lt;/ribbon:Ribbon.ApplicationMenu&gt; &lt;/ribbon:Ribbon&gt; </code></pre> <p>CarModule.cs - registering the view with the region </p> <pre><code> public class CarModule: IModule { private readonly IRegionManager _regionManager; private readonly IUnityContainer _container; public MenuItemViewModel MenuItem; public CarModule(IUnityContainer container, IRegionManager regionManager) { _container = container; _regionManager = regionManager; } public void Initialize() { //Ribbon _container.RegisterType&lt;Object, CarRibbonTab&gt;("CarRibbonTab"); _regionManager.AddToRegion("RibbonRegion", _container.Resolve&lt;CarRibbonTab&gt;()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T05:55:15.417", "Id": "41653", "Score": "0", "body": "Scott, could you please tell in which problem scenario you have used RibbonRegionAdapter, or Why we need to have one when developing Apps using Ribbon control with prism ?" } ]
[ { "body": "<p>Not sure whether we have many Prism specialists on Code Review and I haven't worked with it for a while, so maybe my comments are incorrect at points. </p>\n\n<ol>\n<li>I do not really like the way you're handling <code>region.Views.CollectionChanged</code> event. This event provides a lot of information in eventArgs but you're ignoring it. Firstly you do not handle removing views at all. Secondly instead of iterating through all views every time I would use those from <code>eventArgs</code> (<code>NewItems</code> property). </li>\n<li>I believe generally it is better to have views isolated from regions in terms of concrete types. Your view is not isolated since it has to inherit <code>RibbonTab</code> class. Maybe it is not an issue here and I'm not sure whether it should be changed somehow, it just looks strange to me.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T23:55:48.173", "Id": "715", "Score": "0", "body": "Thank you for your suggestions. I'll make some changes. I'm a little confused on your point 2 however and was hoping you could provide a better explanation or an example of what you mean." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T14:12:38.833", "Id": "740", "Score": "0", "body": "@Scott - regarding second point. Take a look at this `TabControlRegionAdapter` implementation: https://compositewpf.svn.codeplex.com/svn/V2/trunk/CAL/Silverlight/Composite.Presentation/Regions/TabControlRegionAdapter.cs and especially `PrepareContainerForItem` method. It doesn't force views to be of type `TabItem`, istead it wraps them if they are not. This is correct behavior for `Region` IMO. But you instead forcing all you views to be inheritors of `RibbonTab`. It *may* make sense but I'm not sure it does in your scenario." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-29T22:08:56.670", "Id": "432", "ParentId": "429", "Score": "7" } }, { "body": "<p>One note for anyone else researching this issue: The modules in this application need to be WPF User Control Library projects. Simply replace the XAML in the empty UserControl objects with @Scott's Ribbon Tab XAML shown above. There is no need to wrap the <code>RibbonTab</code> object in a <code>UserControl</code>.</p>\n\n<p>In this specific case, I don't share @Snowbear's concern about deriving the Ribbon Tab 'view' from a <code>RibbonTab</code> control. I agree with his point in a more general situation, but the Ribbon Tab that we are inserting into the Ribbon isn't really a view, per se. In other words, it's not a composite of several different UI controls meant to present a UI or a part of a UI to a user. The Ribbon Tab is a lot more specific than that--it is literally a <code>RibbonTab</code> object--a single control--and it can be nothing else.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-22T20:14:34.153", "Id": "927", "ParentId": "429", "Score": "0" } }, { "body": "<p>I'm late to this party, but I'm unclear on why a custom region adapter is even required. Why can't you just use the built-in ones? To my mind all the areas in the ribbon one might want to expose already have appropriate adapters.</p>\n\n<ul>\n<li><code>RibbonRegion</code> => <code>SelectorRegionAdapter</code> (each item would be a <code>RibbonTab</code>)</li>\n<li><code>RibbonTabRegion</code> => <code>ItemsControlRegionAdapter</code> (each item typically a <code>RibbonGroup</code>)</li>\n<li><code>RibbonApplicationMenuRegion</code> => <code>ItemsControlRegionAdapter</code> (each item typically a <code>RibbonApplicationMenuItem</code>)</li>\n<li><code>RibbonApplicationMenuAuxiliaryPanelRegion</code> => <code>ContentControlRegionAdapter</code></li>\n<li>etcetera</li>\n</ul>\n\n<p>I can imagine extending the built-in regions to apply custom sorting logic or the like, but your adapter does not do this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-05T15:37:20.237", "Id": "4599", "ParentId": "429", "Score": "1" } }, { "body": "<p>The Custom <code>RibbonRegionAdapter</code> is good. I used this one. But the problem I am facing is as follows.\nsay, 1 of my module need to show multiple ribbon tabs(<code>Tab1</code> &amp; <code>Tab2</code>) in the same <code>ribbon_region</code> when it is got loaded, not the only <code>CarTab</code>.</p>\n\n<p>For that I have written this code:</p>\n\n<pre><code>var tab1= new Uri(\"Tab1\", UriKind.Relative);\nregionManager.RequestNavigate(\"RibbonRegion\", tab1);\n\nvar tab2= new Uri(\"Tab2\", UriKind.Relative);\nregionManager.RequestNavigate(\"RibbonRegion\", tab2);\n</code></pre>\n\n<p>Now the issue is, the <code>Tab1</code> is getting overlaped by <code>Tab2</code> and only the <code>Tab2</code> is showing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-02T14:48:22.470", "Id": "6473", "ParentId": "429", "Score": "1" } }, { "body": "<p>A better approach would be to build the tabs first then assign the tabs to the Content property of the hosting control. That should prevent the overlapping which I believe is caused by you making two requestnavigate calls.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-13T20:41:07.347", "Id": "9993", "ParentId": "429", "Score": "2" } } ]
{ "AcceptedAnswerId": "432", "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-29T21:10:01.687", "Id": "429", "Score": "21", "Tags": [ "c#", "wpf" ], "Title": "MVVM, WPF Ribbon V4, with Prism" }
429
<p>I am working on a project where I have to calculate the totals of a transaction. Unfortunately, coupons have proven to be quite an issue. There are four types of coupons: transaction percentage, transaction dollar amounts, item percentage and item dollar amounts.</p> <p>I ended-up with this beast of a method, and was wondering if it is clear why I'm doing each part in the way I am. Are my comments are detailed enough? Is my code is more-or-less readable? Is there a way to simplify any of it?</p> <pre><code>private static Totals CalculateTotals(List&lt;Item&gt; items, List&lt;Coupon&gt; coupons, List&lt;Payment&gt; payments) { // Local vars, totals gets returned. Totals totals = new Totals(); decimal subtotal = 0; decimal workingSubtotal = 0; decimal discounts = 0; decimal tax = 0; decimal paid = 0; decimal taxRate = (Initialization.Location.TaxRate ?? 0); // Get the subtotal before any discounts. items.ForEach(i =&gt; subtotal += (i.Price ?? 0)); // An ItemCoupon takes a whole amount or percentage off of a single Item. // It can take it off of the most expensive, or least. Nothing in the middle. foreach (var coupon in coupons.OfType&lt;ItemCoupon&gt;()) { // new Item to hold the item to be discounted. Item item; // Find which item to discount. if (coupon.DiscountMostExpensive) { item = items.OrderByDescending(i =&gt; i.Price).FirstOrDefault(); } else // Otherwise, Discount LEAST Expensive. { item = items.OrderByDescending(i =&gt; i.Price).LastOrDefault(); } // Remove it from the list, before editing the price. items.Remove(item); // Set new price of item based on the type of coupon. (Percent, or whole dollar.) if (coupon.PercentageCoupon) { item.Price = Utils.CalculatePercentage(item.Price, coupon.DiscountPercentage); } else { item.Price = (item.Price ?? 0) - (coupon.DiscountAmount ?? 0); } // Add the item back to the list, with the new price. items.Add(item); } // Now that the single items have been discounted, let's get a wroking subtotal. items.ForEach(i =&gt; workingSubtotal += (i.Price ?? 0)); // A TransactionCoupon takes a whole amount or percentage off of the entire transaction. // To simplfy tax caculation--and because some items are non-taxable, // oh and, because we don't want any one item going below zero--we // split the discount over all the items, evenly. foreach (var coupon in coupons.OfType&lt;TransactionCoupon&gt;()) { if (coupon.PercentageCoupon) { // If it is a Percentage Coupon, simply take said percentage of off each item. items.ForEach(i =&gt; i.Price = Utils.CalculatePercentage(i.Price, coupon.DiscountPercentage)); } else { // If it is a whole amount, get each items percent of the of the subtotal, and discount them equally. // This would look way too confusing using lambda. foreach (var item in items) { decimal discount = (item.Price ?? 0) * ((coupon.DiscountAmount ?? 0) / workingSubtotal); item.Price = item.Price - discount; } } } // Let's get the new-new-new subtotal. workingSubtotal = 0; items.ForEach(i =&gt; workingSubtotal += (i.Price ?? 0)); // Calculate the total discounts. discounts += (subtotal - workingSubtotal); // Set tax for order. (This must be done after ALL discounts have been applied) foreach (var item in items.Where(i =&gt; i.Taxable)) { tax += ((item.Price ?? 0) * taxRate); } // Get the total amount paid. payments.ForEach(p =&gt; paid += p.Amount); // Add all the results to the Totals struct. totals.Subtotal = subtotal; // Never return the workingSubtotal; totals.Discounts = discounts; totals.Tax = tax; totals.Paid = paid; totals.Total = ((workingSubtotal + tax) - paid); return totals; } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T06:19:49.790", "Id": "733", "Score": "3", "body": "I dont know c#, but too many comments?" } ]
[ { "body": "<p>The first thing that I noticed is that you're using <code>?? 0</code> a lot. If you could restructure your code to ensure that the prices won't be <code>null</code> that would allow you to remove those, which would clean up your code a bit.</p>\n\n<p>Further you're often using the pattern:</p>\n\n<pre><code>int foo = 0;\n//...\nitems.ForEach(i =&gt; foo += (i.Price ?? 0));\n</code></pre>\n\n<p>This can be simplified using LINQ's <code>Sum</code> method to:</p>\n\n<pre><code>int foo = items.Sum(i =&gt; i.Price ?? 0);\n</code></pre>\n\n<p>(Or just <code>i.Price</code> instead of <code>i.Price ?? 0</code> if you heed my earlier suggestion).</p>\n\n<pre><code>// Remove it from the list, before editing the price.\nitems.Remove(item);\n</code></pre>\n\n<p>Unless <code>item</code> is a value-type, you don't need to delete and re-add it to change it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T01:52:52.007", "Id": "722", "Score": "0", "body": "Good call on all points! Didn't even think of .Sum. I also hate all of the ?? 0, but price is nullable in the database for other reasons. Both you and Saeed were correct about removing/re-adding Item. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-15T21:09:32.633", "Id": "134043", "Score": "0", "body": "Think of **?? 0** as a design issue instead of code restructuring. For example the `Item` constructor will set \"null in the database\" integers to zero. With defined default state I can use `??` to convert `null` (method / constructor parameters) to something concrete w/out requiring other code to guess what I just made. Thus, the design is coalescing error and exception handling to higher levels. Significantly, complex composite objects behave better because we don't have a \"sometimes null, sometimes not\" quandary for every. method. or. constructor. call." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T00:52:22.213", "Id": "440", "ParentId": "438", "Score": "8" } }, { "body": "<p>A few comments:</p>\n\n<ul>\n<li>Please avoid comments that tell you \"what\" the code is doing. There is no reason to have a comment that says \"The next line of code will add two numbers\", when I can just look at the next line and see the two numbers being added. Comments should be used to explain \"why\", not \"what\".</li>\n<li>Generally, clean code shouldn't require too many comments other than method headers. A common pattern to look for is if you have a comment followed by several lines of code, you should probably take that block of code and refactor it into a separate method with a descriptive name, with the comment becoming the method header.</li>\n<li>Use helper methods. The CalculateTotals() method should be just a few lines that calls into other methods like CalculatePreDiscountSubtotal(), CalculateItemDiscounts(), CalculateTransactionDiscounts(), and CalculateStatistics(). That makes it much easier to understand the overall flow of CalculateTotals(), while also making each of the smaller pieces easier to understand and debug.</li>\n<li>Why are you removing item from the list, modifying it, and then re-adding it? You should be able to just modify the object while it's in the list.</li>\n<li>In the item loop, do you really want to sort the items on each iteration? Not only is there a perf optimization to be made by pulling it out of the loop, the logic here is possibly broken. Did you intend to re-sort the items every time with discounts applied, or by original price? In other words, if you have two coupons that apply to the most expensive item, do you want them to potentially apply to the same item? Do you apply them one at a time with whatever item is most expensive after all coupons processed so far? Or do you want to apply them to the two most expensive items? Note that in the second to last option, the order in which you process the coupons might matter.</li>\n<li>I would recommend not modifying the Price of an Item. Instead, I would add a Discount member to Item and increment that.</li>\n<li>When calculating the price for a non-percentage coupon, your code will potentially make the price of an item negative, which is probably not what you want.</li>\n<li>Why not keep track of the transaction discount separately rather than trying to equally subtract it from each item in the order? It would more closely match the actual problem domain, and simplify the code a great deal. Not to mention that the code as is can set the price of an item to a negative number.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T01:50:51.167", "Id": "721", "Score": "0", "body": "Thanks for all the feed back. Points one, two and three are hand-in-hand. As the method grew, I found the need to be more verbose. I had thought about breaking it in to small methods, but wasn't sure where to best break it. Both you and sepp2k were correct, there was no reason to remove/re-add the item. The list does actually need resoreted on each coupon. I want the current highest item to be discounted (though, I did forget to order the coupons, thanks!) I didn't notice the non-percentage issue, thanks again! As for the last one, it just made tax a nightmare." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T02:11:46.900", "Id": "723", "Score": "0", "body": "Why would it make tax a nightmare? Can't you just take the item subtotal after applying item coupons, subtract the transaction discount, and then apply tax?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T02:47:02.907", "Id": "725", "Score": "0", "body": "No, because some items are non-taxable. That is why I can't just subtotal less discounts. If that were the case this would have only been a few lines. Just add up all the discounts, and be done with it." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T03:03:28.600", "Id": "726", "Score": "0", "body": "Ah, I missed that point. In that case, you could use your same approach, but on the totals rather than item prices. In other words, calculate your transaction discount, your discounted item subtotal, and your discounted taxable item subtotal, and then calculate tax based on the ratio between transaction discount and taxable item subtotal. In any case, I would personally not modify item prices for either item or transaction discounts, and instead track the discounts separately." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T01:08:02.680", "Id": "441", "ParentId": "438", "Score": "12" } }, { "body": "<p>I would seperate the coupon discount logic into a seperate class. Have a CouponBase class, that has a function .ApplyCouponToItem(Item item). Then you can have a PercentageCoupon class and a WholeAmountCoupon class, and each one can override that function to do what it needs to do. This way, your code won't be cluttered with discount logic and will be better decoupled in the face of future changes to coupons.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T03:51:50.773", "Id": "448", "ParentId": "438", "Score": "2" } }, { "body": "<p>Most of these were already mentioned but I'd like to add:</p>\n<ol>\n<li><p><strong>Get rid of <code>item.Price ?? 0</code></strong>. Looks like you finally missed this construction in <code>TransactionCoupon</code> loop for non-percentage coupons.</p>\n<p>You have there:</p>\n<pre><code> item.Price = item.Price - discount;\n</code></pre>\n</li>\n<li><p><strong>Use <code>Sum</code> instead of <code>ForEach</code></strong>. It has two advantages - works on IEnumerable and allows more easily understand that in this particular line you need only sum of items being iterated, but not something that was in accumulator before.</p>\n</li>\n<li><p><strong>Do not introduce all you variables (unless you write in C) in the beginning of the methods</strong>. It is usually recommended to introduce variable right before it's first use. It will allow you to join variable declaration and it's assignment, which also improves readability. And in this case you will be able to use object-initializer for <code>total</code> variable, which (IMO) is better than direct property assignment you're doing in last lines.</p>\n</li>\n<li><p>Too many parentheses here:</p>\n<pre><code> totals.Total = ((workingSubtotal + tax) - paid);\n</code></pre>\n</li>\n<li><p>Any reason to take parameters as <code>List</code> instead of <code>IEnumerable</code>?</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-30T14:04:30.650", "Id": "461", "ParentId": "438", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-30T00:40:52.877", "Id": "438", "Score": "12", "Tags": [ "c#", "linq", "finance" ], "Title": "Calculating totals of a transaction" }
438
<p>I'm working on a simple star rating system, and before I move on to actually "tallying" the votes, which I figure I'll just do with <code>$.ajax</code>, I wanted to make sure what I've done so far has been done as well as it can be.</p> <p><strong>JavaScript</strong></p> <pre><code>//max number of stars var max_stars = 5; //add images to the ratings div function fill_ratings() { var $rating = $("#rating"); if($rating.length) { for(i = 1; i &lt;= max_stars; i++) { $rating.append('&lt;img id="' + i + '"src="star_default.png" /&gt;'); } } } //variables... var hovered = 0; var has_clicked = false; var star_clicked = 0; function handle_ratings() { if(has_clicked == true) { for(i = 1; i &lt;= star_clicked; i++) { $('#rating img#' + i).attr('src', 'star.png'); } } $('#rating img').hover(function() { hovered = Number($(this).attr('id')); for(i = 1; i &lt;= max_stars; i++) { if(i &lt;= hovered) { $('#rating img#' + i).attr('src', 'star.png'); } else { $('#rating img#' + i).attr('src', 'star_default.png'); } } }).click(function() { //if they click a star, only set the stars to grey that are after it. star_clicked = Number($(this).attr('id')); has_clicked = true; for(i = 1; i &lt;= star_clicked; i++) { $('#rating img#' + i).attr('src', 'star.png'); //handle the vote here. eventually. } }).mouseout(function() { //if they haven't clicked a star, set all stars to grey. if(has_clicked !== true) { $('#rating img').attr('src', 'star_default.png'); } else { //show their rating for(i = 1; i &lt;= max_stars; i++) { if(i &lt;= star_clicked) { $('#rating img#' + i).attr('src', 'star.png'); } else { $('#rating img#' + i).attr('src', 'star_default.png'); } } } }); } $(function() { fill_ratings(); handle_ratings(); }); </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;div id="ratings"&gt;&lt;/div&gt; </code></pre> <p>The code works, but I was wondering if anyone notices any code that I can improve. Also, is there anything wrong with the way it...looks? Should I be commenting more, indenting differently, or any other "formatting" type things?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-04T18:24:52.837", "Id": "137410", "Score": "0", "body": "Using Namespaces for your global variables as well as methods is a good practice." } ]
[ { "body": "<p>The obvious improvement to the code you have here is that you should package it up as a jQuery plugin, to improve code reusability and reduce the number of global variables created. </p>\n\n<p>You'll also want to use a <code>class</code> instead of <code>id</code>, to improve reusability (if you chose not to change this to a plugin), and to store as much information on the element themselves, instead of using global variables to store information, to create less coupled functions. </p>\n\n<p>Otherwise, going down the code line by line: </p>\n\n<p><strong>Inside the <code>fill_ratings</code> function:</strong></p>\n\n<pre><code>$rating.append('&lt;img id=\"' + i + '\"src=\"star_default.png\" /&gt;');\n</code></pre>\n\n<p>You are creating elements with <code>id</code> attribute starting with a number. This is illegal before HTML5. Also, you can create elements in a more 'jQuery' manner with this syntax instead: </p>\n\n<pre><code>$('&lt;img&gt;', {\n id: 'star-' + i,\n src: 'star_default.png'\n}).appendTo($rating);\n</code></pre>\n\n<p>The main benefit of this is that now you have a reference to element you just created. You can then push it to an array, to reuse later, instead of creating new jQuery objects by attempting to select the same elements again later in the code. </p>\n\n<p><strong>Variable declaration</strong> - mostly a style suggestion, but you can avoid multiple <code>var</code>s by using the comma operator:</p>\n\n<pre><code>var hovered = 0, \n has_clicked = false, \n star_clicked = 0;\n</code></pre>\n\n<p><strong>Don't use <code>$(this)</code> to get element attributes</strong>: </p>\n\n<pre><code>$(this).attr('id');\n</code></pre>\n\n<p>is about 97% slower than </p>\n\n<pre><code>this.id;\n</code></pre>\n\n<p>the latter is less verbose and much much more efficient. </p>\n\n<p><strong>Inside each of the event handlers attached to <code>#rating img</code></strong> - instead of looping through all <code>#rating img</code> element, like you're doing: </p>\n\n<pre><code> for (i = 1; i &lt;= max_stars; i++) {\n if (i &lt;= hovered) {\n $('#rating img#' + i).attr('src', 'star.png');\n } else {\n $('#rating img#' + i).attr('src', 'star_default.png');\n }\n }\n</code></pre>\n\n<p>We can always use the information already given (the current element triggering the event) to do the processing. The above code, for instance, can be written as: </p>\n\n<pre><code>$(this).prevAll().attr('src', 'star.png');\n</code></pre>\n\n<p>thereby reducing the all those lines into one, and removing a variable. Most of the other event handlers can be similarly rewritten. </p>\n\n<p><strong>Type coercion to <code>Number</code></strong> can be done without using <code>Number</code> - just append a <code>+</code> in front of the variable. In your case, it is completely unnecessary, since you're coercing it back to <code>String</code> again after joining it to another string in the selector passed to the jQuery selector </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T04:21:28.217", "Id": "728", "Score": "0", "body": "Thanks for all the info, I'll start looking into converting it to a plugin and updating/fixing everything you mentioned. I accepted your answer, but if anyone has anything to add - please do!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T03:00:32.030", "Id": "447", "ParentId": "444", "Score": "14" } }, { "body": "<p>Some automation can help a lot nowadays:</p>\n\n<p>Google's own <strong><a href=\"http://code.google.com/closure/compiler/\" rel=\"nofollow\">Closure Compiler</a></strong> from Google </p>\n\n<blockquote>\n <p>is a tool for making JavaScript\n download and run faster. It parses\n your JavaScript, analyzes it, removes\n dead code and rewrites and minimizes\n what's left. It also checks syntax,\n variable references, and types, and\n warns about common JavaScript\n pitfalls.</p>\n</blockquote>\n\n<p>There's a <a href=\"http://closure-compiler.appspot.com\" rel=\"nofollow\">online version</a> of this tool too, a Firebug plugin, and is already part of <a href=\"http://code.google.com/speed/page-speed/\" rel=\"nofollow\">PageSpeed</a> and there's also a <a href=\"http://code.google.com/closure/utilities/\" rel=\"nofollow\">JavaScript Linter</a> as part of these <a href=\"http://code.google.com/closure/\" rel=\"nofollow\">Closure Tools</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-21T13:18:25.513", "Id": "1367", "ParentId": "444", "Score": "2" } } ]
{ "AcceptedAnswerId": "447", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-30T01:55:18.230", "Id": "444", "Score": "13", "Tags": [ "javascript", "jquery" ], "Title": "Simple star rating system" }
444
<p>Can I make my template syntax simpler? I'm hoping to eliminate the <code>if</code> and maybe also the <code>for</code> block. </p> <p>This worked in the shell but I can't figure out the template syntax.</p> <pre><code>recipes[0].recipephotos_set.get(type=3).url </code></pre> <p>model.py</p> <pre><code>class Recipe(models.Model): .... class RecipePhotos(models.Model): PHOTO_TYPES = ( ('3', 'Sub Featured Photo: 278x209'), ('2', 'Featured Photo: 605x317'), ('1', 'Recipe Photo 500x358'), ) recipe = models.ForeignKey(Recipe) url = models.URLField(max_length=128,verify_exists=True) type = models.CharField("Type", max_length=1, choices=PHOTO_TYPES) </code></pre> <p>view.py</p> <pre><code>recipes = Recipe.objects.filter(recipephotos__type=3) </code></pre> <p>template.html</p> <pre><code>{% for recipe in recipes %} {% for i in recipe.recipephotos_set.all %} {% if i.type == '3' %} {{ i.url }} {% endif %} {% endfor %} &lt;a href="/recipe/{{ recipe.recipe_slug }}/"&gt;{{ recipe.recipe_name }}&lt;/a&gt;&lt;/li&gt; {% empty %} </code></pre>
[]
[ { "body": "<p>I'll refer you to a <a href=\"https://stackoverflow.com/questions/223990/how-do-i-perform-query-filtering-in-django-templates\">Stack Overflow post</a> that pretty much nails the answer.</p>\n\n<p>I assume that you want to display all recipes that have \"Sub Featured Photos\".</p>\n\n<p>The call <code>recipes = Recipe.objects.filter(recipephotos__type=3)</code> will give you a queryset of recipes that have at least one photos with type 3. So far so good. Note, that this code is in the views.py file and not in the template. Like the StackOverflow post mentioned, you should put the filtering code in your view or model.</p>\n\n<p>Personally I'd prefer writing a function for your model class:</p>\n\n<pre><code>class Recipe(models.Model):\n (...)\n def get_subfeature_photos(self):\n return self.recipephotos_set.filter(type=\"3\")\n</code></pre>\n\n<p>And access it in the template like this:</p>\n\n<pre><code>{% for recipe in recipes %}\n {% for photo in recipe.get_subfeature_photos %}\n {{ photo.url }}\n {% endfor %}\n (...)\n{% endfor %}\n</code></pre>\n\n<p>Please note that the function is using <code>filter()</code> for multiple items instead of <code>get()</code>, which only ever returns one item and throws a <code>MultipleObjectsReturned</code> exception if there are more.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-30T08:06:38.763", "Id": "451", "ParentId": "445", "Score": "9" } } ]
{ "AcceptedAnswerId": "451", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-30T01:57:55.443", "Id": "445", "Score": "6", "Tags": [ "python", "django", "django-template-language" ], "Title": "Django query_set filtering in the template" }
445
<p>I have the following method:</p> <pre><code>private void removeUnnecessaryLines(List&lt;ScatterViewItem&gt; list) { List&lt;Line&gt; remove = new List&lt;Line&gt;(); foreach (Line line in lines) { SourceFile destination = (line.Tag as Call).getCallee(); foreach (ScatterViewItem svi in list) { SourceFile test = svi.Tag as SourceFile; if (test.Equals(destination)) { remove.Add(line); } } } foreach (Line l in remove) { lines.Remove(l); Dependencies.Children.Remove(l); } } </code></pre> <p>As you can see, there is a lot of iteration and casting. Is there a simple way to improve that?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T16:24:33.983", "Id": "747", "Score": "0", "body": "This looks like C# (though you should mention that in the tags). Can you use LINQ?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T16:26:34.233", "Id": "748", "Score": "0", "body": "@sepp2k yes it is c# and i could use linq" } ]
[ { "body": "<p>The most obvious improvement would be to use LINQ's <code>Where</code> method to filter the <code>lines</code> list instead of building up a list of to-be-deleted items and then deleting them. In addition to being easier to read and understand it will have the benefit of its runtime not being quadratic in the length of <code>lines</code>.</p>\n\n<p>You can also use the <code>List&lt;T&gt;.RemoveAll</code> method which also takes a predicate like <code>Where</code> (though the predicate specifies the items to be removed, so it's in a way the opposite of <code>Where</code>), but modifies the list in-place, like your solution did.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T20:48:25.070", "Id": "754", "Score": "0", "body": "Would that work if returning a new list was not an option?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T22:51:39.363", "Id": "760", "Score": "0", "body": "@Sean: It would if reassigning `lines` is an option (i.e. you could reassign lines to the result of Where + ToList). If that is also not an option, then no, I'm afraid it won't work for you. Though I'd have to ask why it isn't an option. I'd suspect that any such restriction would be the result of a design flaw (though of course I would not presume to say for sure without knowing the design)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T02:02:00.650", "Id": "772", "Score": "0", "body": "Your right, it generally would be the result of a design flaw. Unfortunately with third party controls it might not be my design. But assuming that reassigning lines is a possibility it is definitely the best option." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T16:31:40.450", "Id": "464", "ParentId": "462", "Score": "13" } }, { "body": "<ol>\n<li>I would not insist on replacing <code>lines.Remove</code> with <code>lines = lines.Where(...)</code>. I believe this replacement is subjective since you will still need to remove the same lines from <code>Dependencies.Children</code> collection. Instead I would modify <code>foreach</code> statement. </li>\n<li>If you do not checking <code>test == null</code> then instead of <code>test = svi.Tag as SourceFile</code>, I would use <code>test = (SourceFile)svi.Tag</code>. Resharper says the same. </li>\n<li>Second nested <code>foreach</code> is definitely a <code>Contains</code> statement </li>\n<li>Rename <code>remove</code> -> <code>linesToRemove</code> since <code>remove</code> is not a noun</li>\n<li><code>IEnumerable&lt;&gt;</code> for method parameter, not <code>List&lt;&gt;</code> </li>\n<li>Better name for <code>list</code> parameter? It doesn't clear what is that parameter used for from method signature </li>\n<li>Why not <code>UpperCamelCase</code>? </li>\n</ol>\n\n<p>Result: </p>\n\n<pre><code>private static void RemoveUnnecessaryLines(IEnumerable&lt;ScatterViewItem&gt; list)\n{\n var linesToRemove = lines\n .Select(line =&gt; ((Call)line.Tag).getCallee())\n .Where(destination =&gt; list.Any(svi =&gt; Equals(svi.Tag, destination)))\n .ToList();\n\n foreach (Line l in linesToRemove)\n {\n lines.Remove(l);\n Dependencies.Children.Remove(l);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-01T22:06:06.840", "Id": "532", "ParentId": "462", "Score": "1" } } ]
{ "AcceptedAnswerId": "464", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-30T15:59:41.270", "Id": "462", "Score": "10", "Tags": [ "c#", "casting" ], "Title": "Loops for removing unnecessary lines" }
462
<p>I have a very simple PHP MVC library for my auto-didactic pedagogical purposes. I'm having a little trouble figuring out how to add in the observer patterns as show in <a href="http://en.wikipedia.org/wiki/File:ModelViewControllerDiagram2.svg" rel="nofollow noreferrer">this UML diagram from Wikipedia</a>.</p> <p><code>model</code> is simply contains an array and acts as a key-value store. <code>contrlr</code> accepts input, ostensibly from <code>$_POST</code>, to update a model.</p> <p>So then the observation relationships between the three are where my understanding breaks down. I have <code>contrlr</code> implementing <code>SplOberserver</code> and <code>SplSubject</code>, but how exactly should I handle communication between them? Concatenate strings to <code>strHtml</code>?</p> <p>Please note that I want to have these classes conform to the UML diagram linked from Wikipedia above.</p> <pre><code>class model { private $arrValues = array(); public function __get($var) { return $this-&gt;arrValues[$var]; } public function __set($var, $val) { $this-&gt;arrValues[$var] = $val; } } class contrlr implements SplOberver, SplSubject { private $objModel; public function __construct( model $objModel ) { $this-&gt;objModel = $objModel; } public function parsePost( array $arrPost ) { foreach ( $arrPost as $key =&gt; $value ) { $this-&gt;objModel-&gt;$key = $value; } } public function update() { } public function attach() { } public function detach() { } } class view implements SplObserver { private $strHtml; public function getHtml() { return $this-&gt;strHtml; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-15T09:54:42.697", "Id": "347868", "Score": "0", "body": "@Abbas I've rolled back you last edit, see this [meta](https://codereview.meta.stackexchange.com/questions/762/should-you-edit-someone-elses-code-in-a-question)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-15T10:07:43.613", "Id": "347871", "Score": "0", "body": "@Ludisposed ok, I understand, I (mistakenly) thought I was helping :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-15T10:10:00.010", "Id": "347872", "Score": "1", "body": "@Abbas No problem, I understand the good intentions, it's just that that can be aprt of the review :)" } ]
[ { "body": "<p>Unlike other SPL interfaces, I'm not finding that this pair of built-in interfaces has any intrinsic value other than to provide a template. It would be nice if Observer can automatically trigger its <code>update()</code> method any time Subject properties are modified in any way, but this isn't the case. You have to set it up manually.</p>\n\n<p>So to start, you want to separate <code>contrlr</code> into separate SplSubject and SplObserver classes. Otherwise, for all intents and purposes, it's only notifying itself. <code>model</code> can actually be the one that implements SplObserver in your case. But really, which class implements which interface would be up to you. Here's just an example of a basic usage...</p>\n\n<pre><code>class Observer implements SplObserver {\n\n function update(SplSubject $subject) {\n echo \"notified: \" . $subject-&gt;status . \"\\n\";\n }\n\n }\n\nclass Subject implements SplSubject {\n private $status;\n private $observer;\n\n function __construct(SplObserver $observer) {\n $this-&gt;attach($observer);\n }\n\n function __destruct() {\n $this-&gt;detach($this-&gt;observer);\n }\n\n function __get($prop) {\n return $this-&gt;$prop;\n }\n\n function __set($prop, $val) {\n $this-&gt;$prop = $val;\n $this-&gt;notify();\n }\n\n function notify() {\n $this-&gt;observer-&gt;update($this);\n }\n\n function attach(SplObserver $observer) {\n $this-&gt;observer = $observer;\n $this-&gt;__set(\"status\", \"attaching\");\n }\n\n function detach(SplObserver $observer) {\n $this-&gt;__set(\"status\", \"detaching\");\n $this-&gt;observer = null;\n }\n\n }\n\n\n$observer = new Observer();\n$sub1 = new Subject($observer);\n$sub1-&gt;status = \"testing\";\n$sub2 = new Subject($observer);\nunset($sub2);\n$sub1-&gt;status = \"testing again\";\n</code></pre>\n\n<p>Edit: You could have separate \"model\", \"view\", and \"controller\" classes all extending an abstract base class which implements SplSubject, SplObserver. This way they can all communicate with each other and complete your chart. But, the problem with that all centers around the <code>notify()</code> method, where without the option to select which observer to notify, everyone gets the update message. The solution to allow communication between only one observer at a time would be to rip out the reference to the SPL interfaces entirely, and having your <code>notify()</code> method take in a specific observer argument to send to.</p>\n\n<p>Take the following example, which although has basically the same methods as the SPL interfaces blended together require, it doesn't implement those interfaces at all. Instead, each method takes in a variable number of arguments (expected to be other SubjectObserver objects)...</p>\n\n<pre><code>abstract class SubjectObserver {\n protected $observer_list = array(); // assoc array of classname=&gt;object\n public $status;\n\n function update(SubjectObserver $subject) {\n echo get_class($this) . \" notified by \" . get_class($subject) . \": \" . $subject-&gt;status . \"\\n\";\n }\n\n function __destruct() {\n foreach ($this-&gt;observer_list as $observer)\n { $this-&gt;detach($observer); }\n }\n\n function notify() {\n $args = func_get_args();\n foreach ($args as $arg)\n { $this-&gt;observer_list[get_class($arg)]-&gt;update($this); }\n }\n\n function attach() {\n $args = func_get_args();\n foreach ($args as $arg) {\n $this-&gt;observer_list[get_class($arg)] = $arg;\n $this-&gt;status = \"attaching \" . get_class($arg);\n $this-&gt;notify($arg);\n }\n }\n\n function detach() {\n $args = func_get_args();\n foreach ($args as $arg) {\n $this-&gt;status = \"detaching \" . get_class($arg);\n $this-&gt;notify($arg);\n unset($this-&gt;observer_list[get_class($arg)]);\n }\n }\n\n }\n\nclass model extends SubjectObserver {}\n\nclass view extends SubjectObserver {}\n\nclass controller extends SubjectObserver {}\n\n// initialize\n$model = new model();\n$view = new view();\n$controller = new controller();\n\n$model-&gt;attach($controller, $view);\n$view-&gt;attach($controller, $model);\n$controller-&gt;attach($model, $view);\n\n\n// process some input\n$controller-&gt;status = \"input received\";\n$controller-&gt;notify($model);\n$model-&gt;status = \"data filtered\";\n$model-&gt;notify($controller, $view);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T03:50:44.200", "Id": "774", "Score": "1", "body": "Maybe it's just me, but I find the [banner indent style](http://en.wikipedia.org/wiki/Indent_style#Banner_style) very confusing in your last code block." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T06:38:14.957", "Id": "777", "Score": "0", "body": "@scribu: I suppose good thing the question didn't ask for points on style then :). Maybe it was the lack of brackets on the one-liner foreach loops or the fact that these are just extremely short demo functions? Just going for brevity here, so folks can pick out just the concepts." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T14:37:01.390", "Id": "797", "Score": "0", "body": "Yeah. This pair of interfaces is most disappointing." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T20:09:19.773", "Id": "469", "ParentId": "465", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-30T17:12:36.653", "Id": "465", "Score": "4", "Tags": [ "php", "mvc", "spl" ], "Title": "Simple MVC in PHP" }
465
<p>I'm new into Javascript, and I'm not sure that is a good approach. The code works, and does what I need it to do but I'm sure I didn't do the things the right way.</p> <p>Can you give me feedback about the implementation idea and code?</p> <p>So, let's say that in index.html I have the following code into body section.</p> <pre><code>&lt;script type="text/javascript" src="js/main.js" language="javascript"&gt;&lt;/script&gt; </code></pre> <p>The content of the main.js file is the following:</p> <pre><code>document.write('&lt;script language="javascript" type="text/javascript" &gt;'); function loaded() { } loaded(); document.write('&lt;/script&gt;'); </code></pre> <p>I know that using document.write it is not a smart thing at all. I'm sure that other things are faulty, but I'm newbie and I'm looking for your feedback.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-31T13:11:52.120", "Id": "792", "Score": "0", "body": "For what purpose are you using document.write? I doubt that you need to insert an internal script in this way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T19:28:55.243", "Id": "37718", "Score": "0", "body": "With the original question code deleted, most of the answers are incomprehensible or confusing (not the answers fault). Can you restore the original code, and then make an UPDATE: section with changes you have taken on advice?" } ]
[ { "body": "<p>I think you want to take out the document.writes and add</p>\n\n<pre><code>&lt;body onload=\"loaded()\"&gt;\n</code></pre>\n\n<p>(or whatever function you need to run first) to index.html</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T19:16:45.577", "Id": "467", "ParentId": "466", "Score": "1" } }, { "body": "<p>From a quick glance there are a couple of points where your making simple mistakes.</p>\n\n<pre><code>// Document.write is bad\ndocument.write('&lt;script language=\"javascript\" type=\"text/javascript\" &gt;');\n\n// use css definitions instead\ncounter_div.setAttribute('style', 'width: 310px; height: 50px; font-family:lucida,tahoma,helvetica,arial,sans-serif; display: block; overflow:hide;');\n\n// dont set inner html. This is bad. use DOM manipulation instead\ntitle_span.innerHTML = meter_title;\n\n// uses eval here. pass a function rather then a string\nsetInterval(\"increment()\", interval);\n\n// forgetting to declare addCommas with `var`. This is implecetly global.\naddCommas = function(nStr) {\n</code></pre>\n\n<p>I shall have a look at how to redesign this. </p>\n\n<p>Why do you need to append the div after the script tag. It's bad by design to use the script tag in the DOM for positioning.</p>\n\n<p>it would be better to create a <code>&lt;div&gt;</code> to fill with the timer/counter.</p>\n\n<p>Refactored partly <a href=\"http://jsfiddle.net/Raynos/ReqkL/1/\" rel=\"nofollow\">here</a>. This includes fixing the issues above plus making the dom manipulation a bit nicer. </p>\n\n<p>I'm not too certain how to do refactoring on your timer code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-01-30T19:29:17.587", "Id": "468", "ParentId": "466", "Score": "3" } } ]
{ "AcceptedAnswerId": "468", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-01-30T18:45:47.833", "Id": "466", "Score": "5", "Tags": [ "javascript" ], "Title": "Need a feedback on my Javascript code and app implementation idea" }
466