body
stringlengths 111
6.48k
| 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->link = mysql_connect($this->server.':'.$this->port, $this->username);
if(!$this->link)
die('Could not connect: '.mysql_error());
if(!mysql_select_db($this->database, $this->link))
die('Could not select database: '.mysql_error());
}
function __destruct()
{
if(mysql_close($this->link))
$this->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 & 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->connect();\n }\n }\n\n public function connect()\n {\n if($this->connected() === false)\n {\n $result = $this->driver->sendCommand(\"connect\");\n if($result === true)\n {\n $this->setConnectionState(\"active\");\n $this->setConnectionResource($this->driver->sendCommand(\"get_resource\"));\n }else\n {\n throw new DatabaseConnectionError($this->driver->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&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 < 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>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 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->CI =& get_instance();
$this->db = array();
$this->statement = array();
$this->join_type = array();
$this->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->CI->load->database('', true);
$this->db[] = $db;
$this->statement[] = $statement;
if(strtolower($statement) == 'join'){
$this->join_type[] = $join_type;
$this->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->db);
$sql = "({$db->_compile_select()})";
$alias = $alias!='' ? "AS $alias" : $alias;
$statement = array_pop($this->statement);
$database = (count($this->db) == 0)
? $this->CI->db: $this->db[count($this->db)-1];
if(strtolower($statement) == 'join'){
$join_type = array_pop($this->join_type);
$join_on = array_pop($this->join_on);
$database->$statement("$sql $alias", $join_on, $join_type);
}
else{
$database->$statement("$sql $alias");
}
}
/**
* 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[] = "SELECT $r AS $alias";
}
$range[0] = substr($range[0], 7);
$range = implode(' UNION ALL ', $range);
$sub = $this->start_subquery('join', 'inner');
$sub->select($range, false);
$this->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->db->select('word')->from('words')->where('wordID', 3);
$sub = $this->subquery->start_subquery('select');
$sub->select('number')->from('numbers')->where('numberID', 2);
$this->subquery->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"
}
}
] | {
"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->_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` >= $min AND `id` <= $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 &itemlink)
{
stringstream parseitemlink(itemlink);
uint32 hexform[ITEMLINKGROUPCOUNT] = {0};
uint32 hexsum = 0;
//Parse itemLink string into hexform array
for (int i = 0; i < ITEMLINKGROUPCOUNT; ++i)
parseitemlink >> hex >> hexform[i];
//sum all the itemlink group together
for (int i = 0; i < ITEMLINKGROUPCOUNT; ++i)
hexsum += hexform[i];
for (int i = 0; i < 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 & 0x01)
ebx = hexform[i] >> 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 < 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 >>= 16;
eax += ecx;
hexsum = eax ^ hexform[i];
}
//return the lower 2-bytes of hexsum
//as the final checksum
return hexsum & 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 >> hex >> 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><cstdint></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 < 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& operator>>(std::istream &is, hex_word &h) { \n return is >> hex >> h;\n }\n operator uint32() { return val; }\n};\n\nstd::vector<uint32> hexform{std::istream_iterator<hex_word>(parseitemlink),\n std::istream_iterator<hex_word>()};\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>>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 => 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>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><?php
class Mpages extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function fetch_page($page_slug = 'home')
{
$db = $this->db;
$query =
$db
->where('page_status', 1)
->where('page_slug', strtolower($page_slug))
->get('pages')
->result_array();
$page_id = $query[0]['id'];
$query['modules'] =
$db
->select('modules.module_name, modules.module_slug, modules.id moduleid')
->where('page_id', $page_id)
->join('pages_modules lpm', 'moduleid = lpm.module_id')
->order_by('module_order', 'asc')
->get('modules')
->result_array();
/*$query['media'] =
$db
->select('lucifer_media.media_file_name, lucifer_media.media_file_extension, lucifer_media.media_directory')
->join('lucifer_pages_media', 'lucifer_pages_media.page_id = '.$page_id.'')
->get('lucifer_media')
->result_array();*/
if ($query) {
return $query;
} else {
return false;
}
}
public function fetch_navigation()
{
$result = $this->db->order_by("nav_order", "asc")->where('published', 1)->get('navigation')->result_array();
return $result;
}
public function fetch_layout($id)
{
$result = $this->db->where('id', $id)->get('layouts')->result_array();
return $result[0];
}
}
?>
</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->db->order_by(\"nav_order\", \"asc\")->where('published', 1)->get('navigation')->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->db\n ->order_by(\"nav_order\", \"asc\")\n ->where('published', 1)\n ->get('navigation')\n ->result_array();\n }\n</code></pre>\n\n<hr>\n\n<pre><code>$db = $this->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\" => 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 ->where('page_status', 1)\n ->where('page_slug', strtolower($page_slug))\n ->get('pages')\n ->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->where...->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...->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->setAttribute(Doctrine::ATTR_DEFAULT_COLUMN_OPTIONS,
array('type' => 'string', 'length' => 255, 'notnull' => true));
$conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true);
$manager->setAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE, true);
// Don't load a model until it's needed (causes problems when this is on)
//$manager->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->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->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'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 < DeltaMinimum)
_Integrator = DeltaMinimum;
if (_Integrator > 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 < Minimum)
output = Minimum;
if (output > 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>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<T> 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<T></code></a>:</p>\n\n<pre><code>public class Foo : IFoo\n{\n private static readonly Lazy<IFoo> __instance\n = new Lazy<IFoo>(valueFactory: () => 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 = "<div>";
$closing = "</div>";
$names = array("Doc", "Marty", "George", "Lorraine", "Einstein", "Biff");
foreach($names as $name) { /** $condition was not a bool. My fault. */
if($open && !($i % n)) {
print $opening;
$open = FALSE;
$done = !$open;
} elseif(!($i % n)) $done = FALSE;
/** print element. */
print $name;
if(!$open && !($i % n) && !$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></div></code> tag if there are less than <code>$n</code> elements inside the last <code><div></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 \"<div>\"; //always open one\n$lcv = 1; // loop count variable\nforeach ($array as $key => $val) {\n //format $key/$val as needed here...\n if ($lcv++ % $n == 0) { //every Nth item\n echo \"</div><div>\"; //close old one and open new one\n }\n}\necho \"</div>\"; //always close the last one.\n</code></pre>\n\n<p>Worst case here is you might have an empty <code><div></div></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 \"<div>\"; //always open one\n$lcv = 1; // loop count variable\nforeach ($array as $key => $val) {\n //format $key/$val as needed here...\n if ($lcv++ % $n == 0 && $lcv < $num) { // every Nth item, unless we're done\n echo \"</div><div>\"; //close old one and open new one\n }\n}\necho \"</div>\"; //always close the last one.\n</code></pre>\n\n<p>(Of course you can use <code>print</code>, <code>echo</code>, or <code>?>...<?</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 \"<div>No results?</div>\";\n} else {\n $n = 5; //or whatever you want to chunk into\n echo \"<div>\"; //always open one\n $lcv = 1; // loop count variable\n foreach ($array as $key => $val) {\n //format $key/$val as needed here...\n if ($lcv++ % $n == 0 && $lcv < $num) { // every Nth item, unless we're done\n echo \"</div><div>\"; //close old one and open new one\n }\n }\n echo \"</div>\"; //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 < 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 < 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 & 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<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<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&lang=nl&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 & 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 &$subroutine( @_ );\n}\n\nprint_result( \\&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 => \\&print_result_text,\n xml => \\&print_result_xml );\n\n if( exists( $print_hash{ $outformat } ) )\n {\n &{$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' => sub {\n # print_result_text code goes here\n },\n 'xml' => 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}->($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->can($name);\n\n no strict 'refs';\n &$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->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 & 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> &$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->can($name) and &$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 & 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<string>)\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<string>{\"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<string> 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"
}
}
] | {
"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<Page> pages;
// Constructor, getter, ...
}
public final class Page {
private final List<Paragraph> paragraphs;
// Constructor, getter, ...
}
public final class Paragraph {
private final List<Line> 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<Line> filterWrtSomeCondition();
public List<Line> 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, & 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>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 > referencePoint.Radius
&& point.Theta > 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 > referencePoint.Radius && point.Theta > 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>&&</code>. So, either:</p>\n\n<pre><code>var points = from type in ValidTypes()\n from point in GetData(type)\n where point.Theta > referencePoint.Theta\n where point.Radius > 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 => type.GetData())\n .Where(point.Theta > referencePoint.Theta)\n .Where(point.Radius > referencePoint.Radius)\n .Count();\n</code></pre>\n\n<p>I'd look at the code before & 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 => GetData(type))\n .Count(point => point.Radius > referencePoint.Radius \n && point.Theta > 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>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 < 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 < 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 > 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 < line_length)
do while( line(i:i) == ' ' )
i = i+1
end do
j = i
do while( j < 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 < 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"
}
}
] | {
"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>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 && 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><div id="sidebar">
<div id="main"></div>
<div id="tab"></div>
<br class="clear">
</div></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 && 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->setSomething( $imgPath . $name . $ext );\n$params->setSomethingElse( 'openid_highlight' );\n</code></pre>\n\n<p></p>\n\n<pre><code>$params->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->path;\n }\n\n /* etc */\n\n\n}\n\nclass OpenIdProvider {\n\n private $settings;\n\n public function __construct(OpenIdProviderOptions $options) {\n $this->settings = $options;\n }\n\n public function foo {\n $path = $this->settings->getPath();\n }\n}\n\n$settings = new OpenIdProviderOptions(\"myopenid.example.com\", \"i need this\");\n$settings->setFoo(\"bar\");\n$settings->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->setup = array_merge(\n array('height' => 68,\n 'highlighting' => 'openid_highlight',\n 'info' => NULL,\n 'name' => NULL,\n 'path' => NULL, \n 'something' => 6, \n 'width' => 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->setup['info']))\n {\n throw new InvalidArgumentException(\n __METHOD__ . ' requires info as array');\n }\n\n if (!is_string($this->setup['name']))\n {\n throw new InvalidArgumentException(\n __METHOD__ . ' requires name as string');\n }\n\n if (!is_string($this->setup['path']))\n {\n throw new InvalidArgumentException(\n __METHOD__ . ' requires path as string');\n }\n\n if (!is_int($this->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->path =& $this->setup['path'];\n }\n\n public function internalFunction()\n {\n // Use the parameters like so.\n echo $this->setup['width'];\n echo $this->path;\n }\n}\n\n// The call is very easy.\n$op = new OpenIdProvider(\n array('info' => $info,\n 'name' => $name,\n 'path' => $imgPath . $name . $ext,\n 'width' => 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: &defaults
email_regex: /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i
development:
<<: *defaults
# neat_setting: 800
test:
<<: *defaults
production:
<<: *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 - <short explanation to taste>\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: &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# => /abc/ix\nYAML.load('!ruby/regexp /abc/ix').class\n# => 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
{
/// <summary>
/// Returns a populated Game objects that has a list of players and other information.
/// </summary>
/// <param name="pathToLog">Path to the .log file.</param>
/// <returns>A Game object.</returns>
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, "maxNumPlayers", 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, "maxNumPlayers", 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>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<SourceFile> list)
{
//Get the initial set of sourcefiles
var sourceFiles = list
.SelectMany(current => current.getInvocations()
.Select(invocation => new {current = (SourceFile) null, invocation}))
.ToList() //This ensures that getInvocations is only called once for each sourcefile
.GroupBy(x => x.current, x => x.invocation);
for (var currentDepth = 0; currentDepth <= 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 => current.Select(invocation => invocation))
//Get all of the invocations paired with the new current level of source files
.SelectMany(newCurrent => newCurrent.getInvocations()
.Select(invocation => new { newCurrent, invocation }))
//Group them so that we can loop through each set of invocations seperately
.ToList().GroupBy(x => x.newCurrent, x => 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<IGrouping<SourceFile, SourceFile>> GetNextSourceFileLevel(IEnumerable<IGrouping<SourceFile, SourceFile>> sourceFiles)\n {\n var previousLevelOfSourceFiles = sourceFiles.SelectMany(current => current.Select(invocation => invocation));\n\n var previousLevelOfSourceFilesWithInvocations = previousLevelOfSourceFiles\n .SelectMany(newCurrent => newCurrent.getInvocations()\n .Select(invocation =>new {newCurrent, invocation}));\n var listOfSourceFiles = previousLevelOfSourceFilesWithInvocations.ToList();\n\n return listOfSourceFiles.GroupBy(x => x.newCurrent, x => 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<SourceFile> list)\n {\n //Get the initial set of sourcefiles \n var sourceFiles = list.SelectMany(current => current.getInvocations() \n .Select(invocation => new {current = (SourceFile) null, invocation})) \n .ToList() //This ensures that getInvocations is only called once for each sourcefile \n .GroupBy(x => x.current, x => x.invocation); \n for (var currentDepth = 0; currentDepth <= 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<IGrouping<SourceFile, SourceFile>> sourceFiles)\n {\n foreach (var currentGroup in sourceFiles)\n {\n currentGroup.Count(); \n LoopThroughSourceFilesToUpdateGrid(currentGroup);\n }\n }\n\n private void LoopThroughSourceFilesToUpdateGrid(IGrouping<SourceFile, SourceFile> 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 => current.getInvocations()\n .Select(invocation => new {current = (SourceFile) null, invocation}))\n .ToList() //This ensures that getInvocations is only called once for each sourcefile\n .GroupBy(x => x.current, x => 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 => current.getInvocations())\n .Select(invocation => new {current = (SourceFile) null, invocation})\n .ToList() //This ensures that getInvocations is only called once for each sourcefile\n .GroupBy(x => x.current, x => 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 < 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>/// <summary>
/// Convert from polar coordinates to rectangular coordinates.
/// Only works for points to the left of the origin.
/// </summary>
/// <param name="radius">The radius of the point in pixels.</param>
/// <param name="theta">The angle of the point in radians.</param>
/// <returns>The point in rectangular coordinates.</returns>
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() && !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><?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="schoolName" value="Uboldi"/>
</appSettings>
</configuration>
</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><configuration>\n <configSections>\n <section name=\"uboldi\" type=\"Uboldi.UboldiConfigurationSection, Uboldi\" />\n </configSections>\n <uboldi schoolName=\"Fillmore Central\" />\n</configuration>\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<TReturnType>(string name, bool required, TReturnType defaultValue)\n {\n // Check for missing settings\n if (!ArrayExt.Contains<string>(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<bool>(\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<int>(\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'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('<ul class="menuLvl'+currentDepth+'"></ul>');
$(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 > currentDepth){
$(".menuLvl"+ currentDepth).append('<ul class="menuLvl'+ placeAtDepth +'">');
}
currentDepth = placeAtDepth;
//Determine if we have an hyperlink
if(hyper != null){
var link = $(results).find('Relationship[Id='+hyper+']').attr('Target');
liValue = '<a href="'+ link +'">'+ liValue +'</a>';
}
$(".menuLvl"+currentDepth).last().append('<li>'+ liValue +'</li>');
}
});
}
});
</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 > currentDepth){\n $(\".menuLvl\"+ currentDepth).append('<ul class=\"menuLvl'+ placeAtDepth +'\">');\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 = '<a href=\"'+ link +'\">'+ liValue +'</a>';\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><?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\"> \n <assemblyIdentity version=\"1.0.0.0\"\n processorArchitecture=\"X86\"\n name=\"<your exec name minus extension>\"\n type=\"win32\"/> \n <description>Description of your application</description> \n <!-- Identify the application security requirements. -->\n <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v2\">\n <security>\n <requestedPrivileges>\n <requestedExecutionLevel\n level=\"requireAdministrator\"\n uiAccess=\"false\"/>\n </requestedPrivileges>\n </security>\n </trustInfo>\n</assembly>\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->query(array(
'select' => 1,
'from' => 'table',
'where' => array('id' => 1, 'name' => 'charlie'),
'limit' => 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']) > 1)
{
$list = $where_value;
foreach ($list as $a => $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 => $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 \" => \"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 => $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' => 1, 'str2' => 2, 'str3' => 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' => 1, 'param2' => 2, 'param3' => 3),
true
));
# ... this one.
someFunction(array(
'query' => 'PDO SQL STATEMENT',
'param' => array('param1' => 1, 'param2' => 2, 'param3' => 3),
'fetch' => 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=>$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 => $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\" => 'a', \"1\" => 'b', \"2\" => 'c'))); // true\nvar_dump(is_numeric_array(array(\"1\" => 'a', \"0\" => 'b', \"2\" => 'c'))); // false\nvar_dump(is_numeric_array(array(\"a\" => 'a', \"b\" => 'b', \"c\" => '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<=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\" => \"myquery\", \"fetchmode\" => \"myfetchmode, \"params\" => 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 => $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 => $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 < $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 # => nil</code></p></li>\n<li><p><code>object.to_s # => \"\"</code></p></li>\n<li><p><code>object = Object.new # => #<Object:0x10132e220></code></p></li>\n<li><code>object.to_s # => \"#<Object:0x10132e220>\"</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 <= k <= 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 <= k <= 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 > 5:\n setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets\n if n <= 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) < 2 or longest < 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 >= 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 > 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 >= longest
assert highest <= 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><?php
private function calculateMedian($aValues) {
$aToCareAbout = array();
foreach ($aValues as $mValue) {
if ($mValue >= 0) {
$aToCareAbout[] = $mValue;
}
}
$iCount = count($aToCareAbout);
sort($aToCareAbout, SORT_NUMERIC);
if ($iCount > 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 >= 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) && $v >= 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 > 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()
->from('Post p')
->leftJoin('p.PostComment pc')
->leftJoin('pc.User u')
->where('p.post_id = ?', $id);
$p = $q->fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY);
...
foreach ($p['PostComment'] as $comment) {
$this->Controls->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->Controls->Add( new CommentPanel(\n $comment->text\n , $comment->User->nickname\n , $comment->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<T> {
private static class Node<E> {
final E value;
volatile Node<E> next;
Node(E value) {
this.value = value;
}
}
private AtomicReference<Node<T>> head, tail;
public LockFreeQueue() {
// have both head and tail point to a dummy node
Node<T> dummyNode = new Node<T>(null);
head = new AtomicReference<Node<T>>(dummyNode);
tail = new AtomicReference<Node<T>>(dummyNode);
}
/**
* Puts an object at the end of the queue.
*/
public void putObject(T value) {
Node<T> newNode = new Node<T>(value);
Node<T> 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<T> 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 && !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<T> {\nprivate static class Node<E> {\n E value;\n volatile Node<E> next;\n\n Node(E value) {\n this.value = value;\n }\n}\n\nprivate final AtomicReference<Node<T>> refHead, refTail;\npublic LockFreeQueue() {\n // have both head and tail point to a dummy node\n Node<T> dummy = new Node<T>(null);\n refHead = new AtomicReference<Node<T>>(dummy);\n refTail = new AtomicReference<Node<T>>(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<T> node = new Node<T>(value);\n Node<T> 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<T> 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() << "Error Recieved" << 42 << " " << some_code << " '" << some_msg << "'");
</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<<</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&</code>.</p>
<p>Here is the class definition:</p>
<pre><code>class Formatter
{
public:
Formatter() {};
template<class Field> Formatter& operator<<(Field f)
{
ss_ << 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 & run as-is. Do you see any UB?</p>
<pre><code>#include <cstdlib>
#include <string>
#include <sstream>
#include <iostream>
class Formatter
{
public:
Formatter() {};
template<class Field> Formatter& operator<<(Field f)
{
ss_ << f;
return *this;
}
operator std::string() const { return ss_.str(); }
private:
std::stringstream ss_;
};
void Reject(const std::string& msg)
{
std::cout << "Recieved Message: '" << msg << "'" << std::endl;
}
int main()
{
const char& some_code = 'A';
const char* some_msg = "Something";
Reject( Formatter() << "Error Recieved" << 42 << " " << some_code << " '" << some_msg << "'");
}
</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<<</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<class Field> Formatter& operator<<(Field const& 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() << expr_a) << expr_b) << 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() << make_a_temp() << \"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& operator<<(std::ios_base& (*manip)(std::ios_base&)) {\n ss_ << manip;\n return *this;\n }\n Formatter& operator<<(std::ios& (*manip)(std::ios&)) {\n ss_ << manip;\n return *this;\n }\n Formatter& operator<<(std::ostream& (*manip)(std::ostream&)) {\n ss_ << 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>How can I clean this up?</p>
<pre><code>std::wstring LinkResolve::ResolveLink( const std::wstring& source ) const
{
HRESULT errorCheck;
wchar_t linkTarget[MAX_PATH];
wchar_t expandedTarget[MAX_PATH];
wchar_t arguments[INFOTIPSIZE];
ATL::CComPtr<IPersistFile> ipf;
errorCheck = ipf.CoCreateInstance(CLSID_ShellLink, 0, CLSCTX_INPROC_SERVER);
if (!SUCCEEDED(errorCheck))
{
throw _com_error(errorCheck);
}
errorCheck = ipf->Load(source.c_str(), 0);
ATL::CComPtr<IShellLink> shellLink;
errorCheck = ipf->QueryInterface(&shellLink);
if (!SUCCEEDED(errorCheck))
{
throw _com_error(errorCheck);
}
errorCheck = shellLink->Resolve(0, SLR_NO_UI);
if (!SUCCEEDED(errorCheck))
{
throw _com_error(errorCheck);
}
errorCheck = shellLink->GetPath(linkTarget, MAX_PATH, 0, SLGP_RAWPATH);
if (!SUCCEEDED(errorCheck))
{
throw _com_error(errorCheck);
}
ExpandEnvironmentStringsW(linkTarget, expandedTarget, MAX_PATH);
errorCheck = shellLink->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->Load(source.c_str(), 0) );\nATL::CComPtr<IShellLink> shellLink;\nThrowOnFail( ipf->QueryInterface(&shellLink) );\nThrowOnFail( shellLink->Resolve(0, SLR_NO_UI) );\nThrowOnFail( shellLink->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& operator =(const HRESULT& 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& 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<IPersistFile> ipf;\n\n\n errorCheck = ipf.CoCreateInstance(CLSID_ShellLink, 0, CLSCTX_INPROC_SERVER);\n errorCheck = ipf->Load(source.c_str(), 0);\n\n ATL::CComPtr<IShellLink> shellLink;\n\n errorCheck = ipf->QueryInterface(&shellLink);\n errorCheck = shellLink->Resolve(0, SLR_NO_UI);\n errorCheck = shellLink->GetPath(linkTarget, MAX_PATH, 0, SLGP_RAWPATH);\n\n ExpandEnvironmentStringsW(linkTarget, expandedTarget, MAX_PATH);\n\n try {\n errorCheck = shellLink->GetArguments(arguments, INFOTIPSIZE);\n return std::wstring(expandedTarget) + L\" \" + arguments;\n }\n catch (const XHR&)\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<T></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; }
/// <summary>
/// Commits all changes made on the unit of work.
/// </summary>
void Commit();
bool WasRolledBack { get; }
/// <summary>
/// Rolls back all changes made on the unit of work.
/// </summary>
void Rollback();
/// <summary>
/// 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.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
T Load<T>(int id)
where T : class;
void Attach<T>(T entity)
where T : class, IIdentifiable;
void Detach<T>(T entity)
where T : class;
IRepository<T> GetRepository<T>()
where T : class;
}
public interface IRepository<T>
where T : class
{
IUnitOfWork UnitOfWork { get; }
void Add(T entity);
void Remove(T entity);
/// <summary>
/// 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.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
T Get(int id);
IQueryable<T> 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<T>\n where T : class\n{\n\n bool IsActive { get; }\n\n bool WasCommitted { get; }\n\n /// <summary>\n /// Commits all changes made on the unit of work.\n /// </summary>\n void Commit();\n\n bool WasRolledBack { get; }\n\n /// <summary>\n /// Rolls back all changes made on the unit of work.\n /// </summary>\n void Rollback();\n\n /// <summary>\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 /// </summary>\n /// <param name=\"id\"></param>\n /// <returns></returns>\n T Load<T>(int id)\n where T : class;\n\n void Attach<T>(T entity)\n where T : class, IIdentifiable;\n\n void Detach<T>(T entity)\n where T : class;\n\n IRepository<T> GetRepository<T>()\n where T : class;\n\n void Add(T entity);\n\n void Remove(T entity);\n\n /// <summary>\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 /// </summary>\n /// <param name=\"id\"></param>\n /// <returns></returns>\n T Get(int id);\n\n IQueryable<T> 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<TEntity> 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<TEntity> where TEntity : IEntity, class \n : IDisposable\n{\n IUnitOfWork<TEntity> UnitOfWork { get; }\n\n TEntity CreateNew();\n T FindOne(ISpecification criteria);\n IEnumerable<T> FindMandy(ISpecification criteria);\n IEnumerable<T> 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 < 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<Integer> possibleStartIndices = new ArrayList<Integer>();
int keyListSize = toFind.length;
for (int i = 0; i <= 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 < 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 <= 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 <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 <T> int indexOf(final T[] target, final T[] candidate) {\n\n for (int t = 0, i = 0; i < 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 <T> int indexOf(final T[] target, final T[] candidate) {\n int t = 0, i = 0; \n while (i < 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 < haystack.length - needle.length; a++) {\n for (int b = 0; b < 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 |
<pre><code>void removeForbiddenChar(string* s)
{
string::iterator it;
for (it = s->begin() ; it < s->end() ; ++it){
switch(*it){
case '/':case '\\':case ':':case '?':case '"':case '<':case '>':case '|':
*it = ' ';
}
}
}
</code></pre>
<p>I used this function to remove a string that has any of the following character: \, /, :, ?, ", <, >, |. 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>\"\\\\/:?\"<>|\"</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 = \"\\\\/:?\\\"<>|\"\nfor (it = s->begin() ; it < s->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 <algorithm>\n#include <string>\n#include <iostream>\n\nconst std::string forbiddenChars = \"\\\\/:?\\\"<>|\";\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 << str << 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&</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 <algorithm>\n#include <string>\n#include <iostream>\n\nbool isForbidden( char c )\n{\n static std::string forbiddenChars( \"\\\\/:?\\\"<>|\" );\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 << \"Now: \" << myString << 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>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 , \"\\\\/:?\\\"<>|\")) != 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 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 (> 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&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 #(<= % 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 (< 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->left );
tree_make_empty( tree->right );
free( tree );
}
return NULL;
}
tree_position tree_find( CHAR_DATA *target, search_tree tree )
{
if ( tree == NULL )
return NULL;
if ( target < tree->hatedata->target_char )
return tree_find( target, tree->left );
else if ( target > tree->hatedata->target_char )
return tree_find( target, tree->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->hatedata = hatedata;
tree->left = tree->right = NULL;
}
}
else if ( hatedata->target_char < tree->hatedata->target_char )
tree->left = tree_insert( hatedata, tree->left );
else if ( hatedata->target_char > tree->hatedata->target_char )
tree->right = tree_insert( hatedata, tree->right );
return tree;
}
tree_position tree_find_min( search_tree tree )
{
if ( tree == NULL )
return NULL;
else if ( tree->left == NULL )
return tree;
else
return tree_find_min( tree->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->target_char < tree->hatedata->target_char )
tree->left = tree_delete( hatedata, tree->left );
else if ( hatedata->target_char > tree->hatedata->target_char )
tree->right = tree_delete( hatedata, tree->right );
else if ( tree->left && tree->right )
{
pos = tree_find_min( tree->right );
tree->hatedata = pos->hatedata;
tree->right = tree_delete( tree->hatedata, tree->right );
}
else
{
pos = tree;
if ( tree->left == NULL )
tree = tree->right;
else if ( tree->right == NULL )
tree = tree->left;
free( pos );
}
return tree;
}
HATE_DATA *tree_retrieve( tree_position pos )
{
return pos->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->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->hatedata )) == NULL || tree_retrieve( P )->target_char != ch )
{
int test;
hatedata = (HATE_DATA * ) malloc( sizeof( HATE_DATA ) );
hatedata->target_char = ch;
test = number_range( 1, 50 );
hatedata->hate_amount = test;
victim->hatedata = tree_insert( hatedata, victim->hatedata );
ch_printf( ch, "It should now hate you for %d.\n\r", test );
}
else
{
hatedata = tree_retrieve(tree_find( ch, victim->hatedata ));
ch_printf(ch, "You are already hated for %d!\n\r", hatedata->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->left != NULL)\n tree = tree->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 <stdlib.h></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><</code> and <code>></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> create table t (\n 2 col1 number,\n 3 col2 number\n 4 );\n\nTable created.\n\nSQL> insert into t\n 2 select level, mod(level,10)\n 3 from dual\n 4 connect by level <= 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> set autotrace traceonly;\nSQL> 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> 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 < 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 < length; i++) {\n var child = data[key[i]];\n var has_child = (child !== undefined);\n\n if (!has_child && !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>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<<((rand<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] > 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 << ((rand()<rate) ? ((bit=='1') ? "0" : "1") : bit)
end
return child
end
def crossover(parent1, parent2, rate)
return ""+parent1 if rand()>=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 << child
break if children.size >= 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=>random_bitstring(num_bits)}
end
population.each{|c| c[:fitness] = onemax(c[:bitstring])}
best = population.sort{|x,y| y[:fitness] <=> 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] <=> x[:fitness]}
best = children.first if children.first[:fitness] >= best[:fitness]
population = children
puts " > 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>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] <=> x[:fitness]}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>children.sort!{ |x,y| y[:fitness] <=> 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()>=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() >= 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 < notes.size()) {
return notes.get(position);
}
int cursorPosition = notes.size();
while (cursorPosition <= 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><%@ Control Language="C#" AutoEventWireup="true" CodeFile="TabMenu.ascx.cs" Inherits="TabMenu" %>
<asp:Panel runat="server" ID="TabMenuWrapper" CssClass="tabWrapper">
</asp:Panel>
</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 < 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><CrystalControls:TabMenu runat="server" ID="TopMenu" TabGroup="Artwork" SelectedTab="1" />
</code></pre>
<p>And renders like:</p>
<pre><code><div class="tab">
<a href="Controls/artworkHome.aspx">First!</a>
</div><div class="tab tabSelected">
<a href="Controls/artworkHome.aspx">Second!</a>
</div><div class="tab">
<a href="Controls/artworkHome.aspx">3rd!</a>
</div><div class="tab">
<a href="Controls/artworkHome.aspx">Fourth!</a>
</div><div class="clear">
</div>
</div>
</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><%@ Control Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"WebUserControl.ascx.cs\" Inherits=\"WebUserControl\" %>\n<table style=\"width: 330px\">\n <tr>\n <td style=\"height: 148px\" align=\"center\">\n <asp:Label ID=\"Label1\" runat=\"server\" Text=\"Thanks To awadh Sir\" Font-Bold=\"True\" Font-Size=\"XX-Large\" ForeColor=\"Red\" Visible=\"False\"></asp:Label>\n </td>\n </tr>\n <tr>\n <td style=\"height: 55px\" align=\"center\">\n <asp:Button ID=\"Button1\" runat=\"server\" Text=\"Button\" OnClick=\"Button1_Click\" />\n </td>\n </tr>\n</table>\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->ip;
ipAsString = inet_ntoa(addr);
actualLength = strlen("name=") + strlen(dev->name) +
strlen("&ip=") + strlen(ipAsString) +
strlen("&mac=") + strlen(dev->mac) +
strlen("&type=") + strlen(dev->type) + 1;
if (actualLength > maxLength)
{
return SIZE_ERROR;
}
strncat(asString, "name=", strlen("name="));
strncat(asString, dev->name, strlen(dev->name));
strncat(asString, "&ip=", strlen("&ip="));
strncat(asString, ipAsString, strlen(ipAsString));
strncat(asString, "&mac=", strlen("&mac="));
strncat(asString, dev->mac, strlen(dev->mac));
strncat(asString, "&type=", strlen("&type="));
strncat(asString, dev->type, strlen(dev->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->name, strlen(dev->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"
}
}
] | {
"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><table>
<?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<=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<9;$i++){
//begin of a row
if(fmod($i,3)==0){echo '<tr>';}
echo '<td>';
//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 '<a href="tictactoe.php?values='.implode(',',$values_link).'">&nbsp;</a>';
}else{
echo '&nbsp;';
}
}
echo '</td>';
//end of a row
if(fmod($i,3)==2){echo '</tr>';}
}
?>
</table>
<?php
//If someone won, display the message
if($winstate!=0){
echo '<p><b>Player '.(($winstate==1)?'X':'O').' won!</b></p>';
}
?>
</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 "processing" and "displaying" 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>&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 => 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 => s.Split(new[] {':'}, 1))\n .ToDictionary(s => s[0], s => 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 () => Console.WriteLine(\"Usage is switch1=value1,value2 switch2=value3\"),\n new CommandLine.Switch(\"switch1\",\n val => Console.WriteLine(\"switch 1 with value {0}\",\n string.Join(\" \", val))),\n new CommandLine.Switch(\"switch2\",\n val => 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<task_id>\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 %}
<form action="/yata/{{ id }}/edit/" method="post">
{% else %}
<form action="/yata/add_task/" method="post">
{% endif %}
{{ form.as_p }}
<input type="submit" value="Save!" />
</form>
</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><form action=\"{{ action }}\" method=\"post\">\n {{ form.as_p }}\n <input type=\"submit\" value=\"Save!\" />\n</form>\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<form action=\"\" method=\"post\">\n {{ form.as_p }}\n <input type=\"submit\" value=\"Save!\" />\n</form>\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><?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 < 8 ) {
$hour = 8;
$min = 0;
}
else if ( $hour < 10 ) {
$hour = 10;
$min = 0;
}
else if ( $hour < 12 ) {
$hour = 12;
$min = 0;
}
else if ( $hour <= 18 && $min < 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 < 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 < 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->modify("+$addDay day");
}
$date = strtotime($date->format("Y-m-d G:i:s"));
$now = strtotime("now");
$count = $date - $now;
?>
<script type="text/javascript">
var myTime = <?=$count?>;
$('#countdown').countdown({ until: myTime});
</script>
</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><?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 &$val) {\n $val = strtotime($val);\n // fix schedule to next week if time resolved to the past\n if ($val - $current_time < 0) $val += 604800; \n }\nsort($schedule);\n$countdown = $schedule[0] - $current_time;\n\n?>\n\n<script type=\"text/javascript\">\n var myTime = <?php echo $countdown; // just personally prefer full tags ?>;\n $('#countdown').countdown({ until: myTime}); \n</script>\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<Employee> getAllEmployees() {
return service.getAllEmployees();
}
public boolean isEmployeeEligibleForRaise() {
//business logic here
return true;
}
//Getters & 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<Employee> getAllEmployees() {
return proxy.getAllEmployees();
}
}
//On the server-side we have EmployeeWebService
public class EmployeeWebService implements EmployeeService {
EmployeeDao employeeDao;
@Override
public List<Employee> 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"
}
}
] | {
"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'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>/// <summary>
/// Check existence and write permissions of supplied directory.
/// </summary>
/// <param name="directory">The directory to check.</param>
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><untrusted></code><strong>Set <code>directory</code> to \"c:\\Windows\\System32\\\"</strong><code></untrusted></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& 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& 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& 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, &r[0], len);
return r;
}
std::string ws2s(const std::wstring& 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, &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<std::string>(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>&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(&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 <codecvt>\n#include <string>\n\nstd::wstring utf8ToUtf16(const std::string& utf8Str)\n{\n std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> conv;\n return conv.from_bytes(utf8Str);\n}\n\nstd::string utf16ToUtf8(const std::wstring& utf16Str)\n{\n std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> 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 <string></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<wchar_t, char, std::mbstate_t></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]) => 1150 points
# score([2,3,4,6,2]) => 0 points
# score([3,4,5,3,3]) => 350 points
# score([1,5,1,2,4]) => 250 points
#
# More scoring examples are given in the tests below:
class AboutScoringProject < 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] >= 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(&: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 > 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 > 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 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 = \"$#\" ] &&\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\" &&\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\" && 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`\" && ./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<Ribbon>
{
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<RibbonTab>())
{
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<RibbonRegionAdapter>());
}
return mappings;
}
</code></pre>
<p>CarRibbonTab.xaml</p>
<pre><code><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">
<ribbon:RibbonGroup Header="New">
</ribbon:RibbonGroup>
<ribbon:RibbonGroup Header="Manage">
<ribbon:RibbonButton Label="Make"
LargeImageSource="..\Resources\make.png" />
<ribbon:RibbonButton Label="Inventory"
LargeImageSource="..\Resources\Inventory.png" />
<ribbon:RibbonButton Label="Assignments" />
</ribbon:RibbonGroup>
</ribbon:RibbonTab>
</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><ribbon:Ribbon DockPanel.Dock="Top" Title="CarManager" prism:RegionManager.RegionName="RibbonRegion">
<ribbon:Ribbon.ApplicationMenu>
<ribbon:RibbonApplicationMenu SmallImageSource="Images\Icon.png">
<ribbon:RibbonApplicationMenuItem Header="Exit"
ImageSource="Images\ExitIcon.png"/>
</ribbon:RibbonApplicationMenu>
</ribbon:Ribbon.ApplicationMenu>
</ribbon:Ribbon>
</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<Object, CarRibbonTab>("CarRibbonTab");
_regionManager.AddToRegion("RibbonRegion", _container.Resolve<CarRibbonTab>());
}
}
</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>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<Item> items, List<Coupon> coupons, List<Payment> 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 => 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<ItemCoupon>())
{
// new Item to hold the item to be discounted.
Item item;
// Find which item to discount.
if (coupon.DiscountMostExpensive)
{
item = items.OrderByDescending(i => i.Price).FirstOrDefault();
}
else // Otherwise, Discount LEAST Expensive.
{
item = items.OrderByDescending(i => 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 => 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<TransactionCoupon>())
{
if (coupon.PercentageCoupon)
{
// If it is a Percentage Coupon, simply take said percentage of off each item.
items.ForEach(i => 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 => 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 => i.Taxable))
{
tax += ((item.Price ?? 0) * taxRate);
}
// Get the total amount paid.
payments.ForEach(p => 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 => 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 => 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>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 <= max_stars; i++) {
$rating.append('<img id="' + i + '"src="star_default.png" />');
}
}
}
//variables...
var hovered = 0;
var has_clicked = false;
var star_clicked = 0;
function handle_ratings() {
if(has_clicked == true) {
for(i = 1; i <= star_clicked; i++) {
$('#rating img#' + i).attr('src', 'star.png');
}
}
$('#rating img').hover(function() {
hovered = Number($(this).attr('id'));
for(i = 1; i <= max_stars; i++) {
if(i <= 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 <= 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 <= max_stars; i++) {
if(i <= 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><div id="ratings"></div>
</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>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 %}
<a href="/recipe/{{ recipe.recipe_slug }}/">{{ recipe.recipe_name }}</a></li>
{% 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<ScatterViewItem> list)
{
List<Line> remove = new List<Line>();
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<T>.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<></code> for method parameter, not <code>List<></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<ScatterViewItem> list)\n{\n var linesToRemove = lines\n .Select(line => ((Call)line.Tag).getCallee())\n .Where(destination => list.Any(svi => 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'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><script type="text/javascript" src="js/main.js" language="javascript"></script>
</code></pre>
<p>The content of the main.js file is the following:</p>
<pre><code>document.write('<script language="javascript" type="text/javascript" >');
function loaded() {
}
loaded();
document.write('</script>');
</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><body onload=\"loaded()\">\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('<script language=\"javascript\" type=\"text/javascript\" >');\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><div></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 |
<p>What is your opinion in arguments in constructors matching members as in the following example</p>
<pre><code>public Join(final int parent, final TIntHashSet children) {
this.parent = parent;
this.children = children;
}
</code></pre>
<p>I find this annoying since I have to use <code>this.</code> and also some code review applications generate warnings.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-30T23:53:11.900",
"Id": "765",
"Score": "3",
"body": "I'm not sure if this question really fits on code review but I provided a response for it below anyway."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T00:20:02.620",
"Id": "768",
"Score": "1",
"body": "This is something more for Programmers.SE than for here."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T14:21:33.073",
"Id": "860",
"Score": "2",
"body": "I feel like the question is in scope for Code Review: is using the same name for arguments and members confusing? Is it readable?"
}
] | [
{
"body": "<p>If you're worried about typing the extra characters for <code>this</code> you can consider the coding style used in C++. To avoid ambiguity between class data and parameter's passed into a method I usually use one of the following naming conventions for data members: <code>m_parent</code> and <code>m_children</code> (prefix m indicates member), <code>parent_</code> and <code>children_</code>, <code>myParent</code> and <code>myChildren</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-30T23:55:20.430",
"Id": "766",
"Score": "0",
"body": "I will consider your ideas. Since I use `this.` mainly in constructor and setters I find it inconsistent with the rest of my code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-30T23:51:52.230",
"Id": "473",
"ParentId": "471",
"Score": "2"
}
},
{
"body": "<p>I've personally always found the <code>_parent</code> or Hungarian-notation letters at the beginning far uglier than just saying <code>this</code>. <code>this</code> is very straightforward, especially if somebody else is reading your code. If I inherit somebody else's code and they use _ I change it immediately.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T02:11:41.687",
"Id": "773",
"Score": "1",
"body": "I personally dislike identifiers that begin with _ as the rules in C++ for their usage are non trivial (OK its trivial if you know the rules, but most people don't). Though this question is about Java I use the same rule just to make code more consistent across languages."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T18:41:59.473",
"Id": "814",
"Score": "0",
"body": "What compiler diagnostics will be generated if the parameter is misspelled? If one calls the constructor parameter NewWhatevr then \"Whatever = NewWhatever\" will fail; if one calls it Whatevr, then \"this.Whatevr = Whatever\" will be legitimate but erroneous code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T00:32:14.213",
"Id": "475",
"ParentId": "471",
"Score": "12"
}
},
{
"body": "<p>If you have access to a copy of \"Clean Code\" it has a chapter called \"Meaningful Names\" that I agree with. Bottom line, your name should denote exactly what it is referring to. Creating an encoding for the name a la C++ only slows down reading and causes devs to mentally skip it anyways. Also, your ide, be it eclipse, emacs, etc. should provide highlighting that makes the difference between class variables and parameters distinct.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T02:00:51.667",
"Id": "476",
"ParentId": "471",
"Score": "4"
}
},
{
"body": "<p>Personally I use the most natural names for member variables.<br>\nThis is because these are the ones you are going to use the most often (thus I dislike the m_ prefix).</p>\n\n<p>For things that are going to happen less often (like parameters in constructors) I shorten them or add p_ depending on context and which is the most appropriate.</p>\n\n<p>I have found most Java coding standards I have encountered seem to prefer (in the constructor) the use of </p>\n\n<pre><code>this.member = member;\n</code></pre>\n\n<p>Personally I dislike this (but always stick to the coding standards) as it it feels more error prone. I like distinct names for all identifiers (overlapping names lead to easier mistakes). I also think that distinct identifiers make it easier to spot (for humans) trivial mistakes.</p>\n\n<pre><code>this.member = p_member;\n</code></pre>\n\n<p>Can't get that wrong as each identifier is unique.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T02:20:27.713",
"Id": "477",
"ParentId": "471",
"Score": "5"
}
},
{
"body": "<p>My take is that what you have should be the preferred way of doing things. First of all, the names of the input parameters are what will show up in javadocs, and therefore should not have any prefix or silly names that will make the javadocs cryptic. Second, if the input parameter names clearly define what the things are, then why name the global variables something else that will make the rest of the code less meaningful or more difficult to maintain? Third, the scope of the input parameters is so limited, that it seems to me that you would rarely find this to be error-prone, especially when simply initializing class data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T12:20:25.620",
"Id": "922",
"Score": "1",
"body": "You have a valid point with names showing in java docs."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T05:20:01.963",
"Id": "543",
"ParentId": "471",
"Score": "4"
}
},
{
"body": "<p>I would start with your first instinct of giving them different names, but only if the different names make sense. No Hungarian Notation! (Learned what a mess that was recently. Why do so many style guides still recommend it?) I commonly use different names in situations like this</p>\n\n<pre><code>public Leaf(Color initialColor) {\n color = initialColor;\n}\n</code></pre>\n\n<p>If the two variables represent the same thing and have no other meaningful name, then the <code>this</code> keyword is the way to go.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T12:46:23.330",
"Id": "20583",
"ParentId": "471",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "475",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-30T23:30:36.383",
"Id": "471",
"Score": "6",
"Tags": [
"java",
"constructor"
],
"Title": "Arguments in constructors matching fields"
} | 471 |
<p>I've recently been doing some mods to some old code I've been maintaining for a couple of years now. </p>
<p>As part of a wider set of scripts using YAHOO YUI 2.2 (yes, that old) for dialog-style panels, I have a function that listens to click events on 3 buttons in a given panel set:</p>
<pre><code>addFooListeners = function (panelType) {
YAHOO.util.Event.addListener("show" + panelType, "click", showFoo, eval(ns + ".panel_" + panelType), true);
YAHOO.util.Event.addListener("hide" + panelType, "click", hideFoo, eval(ns + ".panel_" + panelType), true);
YAHOO.util.Event.addListener("commit" + panelType, "click", commitFoo, eval(ns + ".panel_" + panelType), true);
}
</code></pre>
<p>This code is the result of a number of panels/dialogs having near identical behaviour.</p>
<p>For this round of development I've needed to add the ability to do things a little differently from time to time, so I added an object, <code>overrides</code> which allows me to point the <code>show</code>, <code>hide</code> and <code>commit</code> actions elsewhere. I came up with the following:</p>
<pre><code>addFooListeners = function (panelType, overrides) {
var handlers = {
show: ( overrides != null ? ( overrides.show != null ? overrides.show : showFoo ) : showFoo ),
hide: ( overrides != null ? ( overrides.hide != null ? overrides.hide : hideFoo ) : hideFoo ),
commit: ( overrides != null ? ( overrides.commit != null ? overrides.commit : commitFoo ) : commitFoo )
}
YAHOO.util.Event.addListener("show" + panelType, "click", handlers.show, eval(ns + ".panel_" + panelType), true);
YAHOO.util.Event.addListener("hide" + panelType, "click", handlers.hide, eval(ns + ".panel_" + panelType), true);
YAHOO.util.Event.addListener("commit" + panelType, "click", handlers.commit, eval(ns + ".panel_" + panelType), true);
}
</code></pre>
<p>As you can see I'm enforcing default behaviour unless an appropriate attribute in the <code>overrides</code> object is set with another function (named or anonymous).</p>
<p>Is there a cleaner / more readable way to concisely setup the <code>handlers</code> object? The nested ternary seems to my eyes to be cluttering things a bit but other approaches like <code>if ( overrides != null ) { ... }</code> seem just as messy.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T21:47:59.170",
"Id": "75726",
"Score": "1",
"body": "My personal opinion is that the `?` ternary operator is worth using only when it's not nested. In your case it just makes the code more unreadable and unmaintainable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T22:14:00.867",
"Id": "75727",
"Score": "0",
"body": "I like formatting nested ternary operators so they read like multiple questions: http://codereview.stackexchange.com/a/6562/8891"
}
] | [
{
"body": "<p>It looks like you can reduce that ternary a bit by using && like this:</p>\n\n<pre><code>var handlers = {\n show: ( overrides != null && overrides.show != null ? overrides.show : showFoo ),\n hide: ( overrides != null && overrides.hide != null ? overrides.hide : hideFoo ),\n commit: ( overrides != null && overrides.commit != null ? overrides.commit : commitFoo )\n}\n</code></pre>\n\n<p>I'm not too familiar with javascript but does the function parameter have to be checked against null? Like for example, can you further shorten the check by doing something like this?</p>\n\n<pre><code>show: ( overrides && overrides.show ? overrides.show : showFoo ),\nhide: ( overrides && overrides.hide ? overrides.hide : hideFoo ),\n// ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T00:03:44.920",
"Id": "767",
"Score": "2",
"body": "Generally speaking, I think you're right about not needing to check against null - however it can be not-null and false then it would evaluate to false (though in this case I think that'd be ok)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T01:36:48.613",
"Id": "770",
"Score": "0",
"body": "Overrides.show looks like it could be a boolean; if so, you'd need to test it against null explicitly."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T01:48:46.940",
"Id": "771",
"Score": "0",
"body": "@Fred the intention is to pass functions for show, hide and commit. If a false is passed there then showFoo() will be used. If a true is passed there then that'll be passed in place of showFoo() and cause trouble further down so I guess I need to tread carefully there. Having said that though, I'll only ever be passing a function in those parameters so I'll probably survive for now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T08:01:41.087",
"Id": "12784",
"Score": "0",
"body": "Might be worth pointing out that this use of `&&` is only valid as long as `&&` is a short-circuiting `and` operation (which is a safe assumption for C-derived languages, but not all languages)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-13T22:51:55.890",
"Id": "23742",
"Score": "1",
"body": "Can be even shorter: `show: overrides && overrides.show || showFoo`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T00:02:02.203",
"Id": "474",
"ParentId": "472",
"Score": "7"
}
},
{
"body": "<p>Let's do some fixing. First, this is how you pass optional (non-boolean) parameters in JS (the Good Way<sup>tm</sup>):</p>\n\n<pre><code>addFooListeners = function (panelType, handlers) {\n handlers = handlers || {};\n handlers.show = handlers.show || showFoo;\n handlers.hide = handlers.hide || hideFoo;\n handlers.commit = handlers.commit || commitFoo;\n</code></pre>\n\n<p>The above can be rewritten in a neater way using jQuery (not sure what the name of YUI equivalent to <code>extend</code> is):</p>\n\n<pre><code>handlers = $.extend({\n show : showFoo, \n hide : hideFoo, \n commit: commitFoo\n}, handlers || {})\n</code></pre>\n\n<p>Now, using eval for this code is criminal. Say the object <code>ns</code> refers to is <code>module</code>, then you can do this instead of <code>eval</code>:</p>\n\n<pre><code>YAHOO.util.Event.addListener(\"show\" + panelType, \"click\", handlers.show, module[\"panel_\" + panelType], true);\nYAHOO.util.Event.addListener(\"hide\" + panelType, \"click\", handlers.hide, module[\"panel_\" + panelType], true);\nYAHOO.util.Event.addListener(\"commit\" + panelType, \"click\", handlers.commit, module[\"panel_\" + panelType], true);\n</code></pre>\n\n<p>Now, as you can see, you are assigning a lot of events in a similar fashion. Did you think of defining an addPanelListener function within your function?</p>\n\n<pre><code>function addPanelListener (event, panelType, handler) {\n YAHOO.util.Event.addListener(event + panelType, \"click\", handler, module[\"panel_\" + panelType], true);\n} \n\naddPanelListener(\"show\" , panelType, handlers.show);\naddPanelListener(\"hide\" , panelType, handlers.hide);\naddPanelListener(\"commit\", panelType, handlers.commit):\n</code></pre>\n\n<p>Hope it helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T13:06:48.697",
"Id": "791",
"Score": "9",
"body": "+1 for flagging use of eval as criminal :) I find \"the Good Way\" more readable than the jQuery way."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T21:25:01.197",
"Id": "822",
"Score": "6",
"body": "Using `eval` in my company pretty much guarantees a 3-hour _basics of javascript_ meeting with me :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T21:32:02.357",
"Id": "823",
"Score": "0",
"body": "aaah good old \"the-first-one-is-free\" `eval`. Much like a drug pusher. I cringe every time I see that in my code (especially the code I post here ;-)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T21:34:58.157",
"Id": "825",
"Score": "0",
"body": "@glebm can you elaborate on what makes \"The Good Way\" the good way?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T21:36:22.243",
"Id": "826",
"Score": "2",
"body": "Of course. It is easily readable, less error-prone, and, as a bonus, it's faster. :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T21:38:37.093",
"Id": "828",
"Score": "0",
"body": "Always welcome!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-31T07:58:48.267",
"Id": "482",
"ParentId": "472",
"Score": "28"
}
},
{
"body": "<p>In JavaScript, you are not required to explicitly check if a variable is null or undefined because:</p>\n\n<ol>\n<li>null or undefined return false in a boolean expression.</li>\n<li>JS expressions are evaluated from left to right. So for <code>a || b</code>, if <code>a</code> is false, then only <code>b</code> will be evaluated. But if <code>a</code> is true, <code>b</code> will not be checked. Similarly for <code>a && b</code> if <code>a</code> is false, <code>b</code> will not be evaluated.</li>\n</ol>\n\n<p>Hence, <code>if (a != null) { \"do something\" }</code> can be written as <code>if (a) { \"do something\" }</code> or simply <code>a && \"do something\"</code>.</p>\n\n<p>In the same way it can be used to set a default value when the value is set to null or undefined:</p>\n\n<pre><code>function someFunction(age){\n :\n var age= age|| 18;\n :\n}\n</code></pre>\n\n<p><code>someFunction(28)</code> results in 28 whereas <code>someFunction()</code> results in 18.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T05:41:32.597",
"Id": "43772",
"ParentId": "472",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "482",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-30T23:43:07.143",
"Id": "472",
"Score": "26",
"Tags": [
"javascript"
],
"Title": "Usage of the ternary \"?:\" operator with functions listening to click events"
} | 472 |
<p>My homework question states:</p>
<blockquote>
<p>Develop a class to measure distance as feet (should be <code>int</code>), inches (should
be <code>float</code>). Include member functions to set and get attributes. Include
constructors. Develop functions to add two distances.</p>
<p>The prototype of the sum function is:</p>
<pre><code>Distance Sum(Distance d);
</code></pre>
</blockquote>
<p>Please check out my coding style and other aspects that can make this program better.</p>
<pre><code>#include <iostream>
using namespace std;
class Distance
{
private:
int feet;
float inch;
public:
Distance();
Distance(int a,float b);
void setDistance();
int getFeet();
float getInch();
void distanceSum(Distance d);
};
int main()
{
Distance D1,D2;
D1.setDistance();
D2.setDistance();
D1.distanceSum(D2);
return 0;
}
/*Function Definitions*/
Distance::Distance()
{
inch=feet=0;
}
Distance::Distance(int a,float b)
{
feet=a;
inch=b;
}
void Distance::setDistance()
{
cout<<"Enter distance in feet";
cin>>feet;
cout<<endl<<"Enter inches:";
cin>>inch;
}
int Distance::getFeet()
{
return feet;
}
float Distance::getInch()
{
return inch;
}
void Distance::distanceSum(Distance d)
{
cout<<"feet="<<d.feet+feet<<endl;
cout<<"inches="<<d.inch+inch<<endl;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T20:28:20.247",
"Id": "3213",
"Score": "1",
"body": "Whitespace is cheap nowadays: don't be afraid to use it."
}
] | [
{
"body": "<p>A bunch of these functions should be operators. You also seem to be confused about the purpose of addition. Also, <code>using namespace std</code> is bad. You also didn't provide any other operators- even though any class user will logically expect that if you can add a distance, you can add a distance to the current object, and that you can subtract distances too. You also didn't provide any kind of input verification or const correctness.</p>\n\n<pre><code>class Distance\n{\n int feet;\n float inch;\npublic:\n // Constructors\n Distance();\n Distance(int a, float b);\n\n // Getters\n int getFeet() const;\n float getInch() const;\n\n // Operator overloads - arithmetic\n Distance operator-(const Distance&) const;\n Distance& operator-=(const Distance&);\n Distance operator+(const Distance&) const;\n Distance& operator+=(const Distance&);\n\n // Create from console\n static Distance getDistanceFromConsole();\n};\n// Operator overloads - I/O\nstd::ostream& operator<<(std::ostream&, const Distance&);\n</code></pre>\n\n<p>And the implementations are...</p>\n\n<pre><code>Distance::Distance() : feet(0), inch(0.0f) {}\nDistance::Distance(int argfeet, float arginch) : feet(argfeet), inch(arginch) {\n // Verify that we are actually in feet and inches.\n // Not gonna write this code- dependent on the class invariants\n // which were not explicitly specified (e.g., can have negative Distance?)\n}\nint Distance::getFeet() const {\n return feet;\n}\nfloat Distance::getInch() const {\n return inch;\n}\nDistance Distance::operator-(const Distance& dist) const {\n Distance retval(*this);\n retval -= dist;\n return retval;\n}\nDistance& Distance::operator-=(const Distance& dist) {\n feet -= dist.feet;\n inches -= dist.inches;\n // Verify values- e.g. that inches is less than 12\n return *this;\n}\nDistance operator+(const Distance& dist) const {\n Distance retval(*this);\n retval += dist;\n return retval;\n}\nDistance& operator+=(const Distance& dist) {\n feet += dist.feet;\n inches += dist.inches;\n // More verification here.\n}\n\nstd::ostream& operator<<(std::ostream& output, const Distance& dist) {\n output << \"Feet: \" << dist.feet << \"\\n\";\n output << \"Inches: \" << dist.inches << std::endl; // flush when done.\n return output;\n}\n\nDistance getDistanceFromConsole() {\n int feet; float inch;\n std::cout<<\"Enter distance in feet\";\n std::cin>>feet;\n std::cout<<endl<<\"Enter inches:\";\n std::cin>>inch;\n return Distance(feet, inch);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T10:06:52.023",
"Id": "484",
"ParentId": "479",
"Score": "7"
}
},
{
"body": "<p>There's no reason to have both inches and feet since the one can be calculated from the other. Superfluous redundancy just adds complexity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T00:18:02.597",
"Id": "1097",
"Score": "2",
"body": "Why this is not the top comment is beyond me. Though there are lots of possible improvements like mentioned in Vicors good and elaborate answer, this hits the nail on the head. Whatever you do, fix this first (and stuff will become much simpler)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T08:56:04.697",
"Id": "1440",
"Score": "2",
"body": "Perhaps because the very first sentence of the assignment stated that the class should model feet and inches separately. I learned long ago to do what the assignment asks unless I know _for sure_ that the grader will accept optimizations."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T19:31:26.757",
"Id": "1451",
"Score": "0",
"body": "@David - the text quoted as the homework assignment doesn't say that."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-15T21:33:51.887",
"Id": "1457",
"Score": "1",
"body": "@Crazy Eddie - The first sentence specifically states the data types of the two attributes: \"Develop a class to measure distance as feet(should be int),inch(should be float).\" The second sentence implies at least two attributes by using the plural form: \"Include member functions to set and get attributes.\" I don't know what other attributes it would be talking about."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T18:11:42.030",
"Id": "487",
"ParentId": "479",
"Score": "8"
}
},
{
"body": "<h3>C++ comments:</h3>\n\n<p>Prefer initializer lists:</p>\n\n<pre><code>Distance::Distance()\n :feet(0), inch(0)\n{\n // NOT THIS -> inch=feet=0;\n}\n</code></pre>\n\n<h3>General coding comments:</h3>\n\n<p>Don't combine functionality:<br>\nYou should define a function to add Distance objects and one to print them. (DeadMG has that covered above).</p>\n\n<pre><code>void Distance::distanceSum(Distance d)\n{\n cout<<\"feet=\"<<d.feet+feet<<endl;\n cout<<\"inches=\"<<d.inch+inch<<endl;\n}\n</code></pre>\n\n<p>Also I see you don't normalize your results. You could have 1 foot 300.05 inches. When ever the state of an object changes where one parameter flows into another you should normalize the data. Have an explicit function to do so and call it each time state changes:</p>\n\n<pre><code>private: void Normalize() { int eFeet = inches / 12; feet += eFeet; inches -= (eFeet * 12);}\n</code></pre>\n\n<h3>Implementation Comments:</h3>\n\n<p>But then again why do you store what is actually a single value in two different variables (feet and inches). Why not just store the total distance in inches (and then do conversion on the way in/out). Look at the unix time. It just counts the seconds since the epoch. All other values are calculated from this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T18:57:10.630",
"Id": "489",
"ParentId": "479",
"Score": "5"
}
},
{
"body": "<p>I also prefer to write public methods first, because when you review big classes you must scroll to see public members. </p>\n\n<p>For example:</p>\n\n<pre><code>class MyClass\n{\npublic:\n// public members\nprotected:\n// protected members\nprivate:\n// private members\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-13T10:39:47.377",
"Id": "1857",
"ParentId": "479",
"Score": "1"
}
},
{
"body": "<p>You could have written implementation of methods in the class itself where the template of methods are defined. Its generally a good practice to write all those methods in the class. In your case even if you have written the methods out side the class, C++ compiler will make then inline at the time of compilation.So it is better to write those methods as inline methods. It will make the execution bit faster and will remove the use of scope resolution operator which is seemingly difficult. Below is the example how to write..It contains just one method but you can do the same for rest of the methods. </p>\n\n<pre><code>#include <iostream>\nusing namespace std;\nclass Distance\n{\n private:\n int feet;\n float inch;\n public:\n Distance()\n {\n inch=feet=0;\n }\n Distance(int a,float b);\n void setDistance();\n int getFeet();\n float getInch();\n void distanceSum(Distance d);\n};\nint main()\n{\n Distance D1,D2;\n D1.setDistance();\n D2.setDistance();\n D1.distanceSum(D2);\n return 0;\n}\n</code></pre>\n\n<p>This is the better way. All the class methods should be defined in the class only.\nSuppose are to develop just a class in java, then you can not develope a good class by writing like this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-19T05:42:49.510",
"Id": "4208",
"ParentId": "479",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "481",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-31T06:33:47.660",
"Id": "479",
"Score": "28",
"Tags": [
"c++",
"homework"
],
"Title": "Class for measuring distance as feet and inches"
} | 479 |
<p>I have written a simple spinner wrapper, but was wondering if any of you could think of any ways to make it more robust. It only handles strings at the moment.</p>
<p><code>MySpinner</code>:</p>
<pre><code>package a.b.c;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MySpinner extends Spinner {
// constructors (each calls initialise)
public MySpinner(Context context) {
super(context);
this.initialise();
}
public MySpinner(Context context, AttributeSet attrs) {
super(context, attrs);
this.initialise();
}
public MySpinner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.initialise();
}
// declare object to hold data values
private ArrayAdapter<String> arrayAdapter;
// add the selected item to the end of the list
public void addItem(String item) {
this.addItem(item, true);
}
public void addItem(String item, boolean select) {
arrayAdapter.add(item);
this.setEnabled(true);
if (select) this.selectItem(item);
arrayAdapter.sort(new Comparator<String>() {
public int compare(String object1, String object2) {
return object1.compareTo(object2);
};
});
}
// remove all items from the list and disable it
public void clearItems() {
arrayAdapter.clear();
this.setEnabled(false);
}
// make the specified item selected (returns false if item not in the list)
public boolean selectItem(String item) {
boolean found = false;
for (int i = 0; i < this.getCount(); i++) {
if (arrayAdapter.getItem(i) == item) {
this.setSelection(i);
found = true;
break;
}
}
return found;
}
// return the current selected item
public String getSelected() {
if (this.getCount() > 0) {
return arrayAdapter.getItem(super.getSelectedItemPosition());
} else {
return "";
}
}
// allow the caller to use a different DropDownView, defaults to android.R.layout.simple_dropdown_item_1line
public void setDropDownViewResource(int resource) {
arrayAdapter.setDropDownViewResource(resource);
}
// internal routine to set up the array adapter, bind it to the spinner and disable it as it is empty
private void initialise() {
arrayAdapter = new ArrayAdapter<String>(super.getContext(), android.R.layout.simple_spinner_item);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
this.setAdapter(arrayAdapter);
this.setEnabled(false);
}
}
</code></pre>
<p>To use:</p>
<ol>
<li>Use <code>a.b.c.MySpinner</code> instead of <code>Spinner</code> in your XML layout file</li>
<li>Set up a variable, <code>mMySpinner = (MySpinner)findViewById(R.id.spinner);</code></li>
<li>You can then use all the functions which should be self-explanatory</li>
<li>If there are no items in the list, the spinner is disabled to prevent untoward events</li>
</ol>
<p></p>
<ul>
<li><code>mMySpinner.clearItems()</code> - to remove all the items</li>
<li><code>mMySpinner.addItem("Blue")</code> - to add Blue as an item in list (items are sorted by abc)</li>
<li><code>mMySpinner.selectItem("Red")</code> - to make the indicate item the current selection</li>
<li><code>mMySpinner.getSelected()</code> - to return the current selected item string</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T06:02:33.630",
"Id": "11475",
"Score": "0",
"body": "Why were so many common things like \"add\" and \"clear\" and \"insert\" and \"delete\" totally left out of Android Spinners, in the first place????"
}
] | [
{
"body": "<p>A few ways you could make it more robust.</p>\n\n<ol>\n<li>In <code>getSelected()</code>, why not call <code>getSelectedItem()</code> instead?</li>\n<li>You tend to use <code>super.foo()</code> instead of <code>foo()</code>; that's usually a bad idea. Just call <code>foo()</code>, unless you really want to avoid any override in your class. If you always use <code>super.foo()</code>, then if you decide you want to override <code>foo()</code>, perhaps for some debug code, you have to go change your code everywhere from <code>super.foo()</code> to just <code>foo()</code> or perhaps <code>this.foo()</code>.</li>\n<li>This code doesn't seem to enforce a consistent policy around duplicates in the spinner. If duplicates are not allowed, perhaps good to check for that at add time.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T21:49:11.817",
"Id": "529",
"ParentId": "491",
"Score": "3"
}
},
{
"body": "<p>I think it would be great to replace:</p>\n\n<pre><code>arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n</code></pre>\n\n<p>My issue was to implement two spinners with the following feature: if some string is selected in the spinner 1, it should disappear in spinner 2 and the same for the second spinner.</p>\n\n<p>So it would be very nice to have some method to \"hide\" some item. I'm just clearing the adapter and adding other items, without hidden.</p>\n\n<p>Update after half a day of workaround:</p>\n\n<p>ULTIMATE BUG:</p>\n\n<pre><code>if(arrayAdapter.getItem(i) == item)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T13:41:22.950",
"Id": "4637",
"ParentId": "491",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-31T20:29:24.857",
"Id": "491",
"Score": "11",
"Tags": [
"java",
"android"
],
"Title": "Simplified Android Spinner"
} | 491 |
<p>I'm looking for the most commonly used style for writing the <code>delete_item()</code> function of a singly linked list, that find a matching item and deletes it. Is what I have the 'typical' or 'normal' solution? Are there more elegant ones?</p>
<p>What seems inelegant to me about my solution below, although I don't know a better way to express it, is that the code needs to check the first record individually (i.e. a special case), then as it goes through the iteration, it's not checking <code>iter</code>, it's checking <code>iter->next</code>, ahead of the iterator's present location, because in a singly linked list you can't go backwards.</p>
<p>So, is there a cleaner way to write the <code>delete_item()</code> function?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
struct node {
int x;
struct node *next;
};
struct node *head;
struct node *create_item(int x);
void print_list();
void delete_item(int x);
int main(int argc, int argv) {
struct node *n;
int i;
// initialise a linked list with a few items
head = create_item(1);
n = head;
for (i = 2; i < 10; i++) {
n->next = create_item(i);
n = n->next;
}
// before
print_list();
// delete 7.
delete_item(7);
// after
print_list();
// lets delete all odd numbers for effect.
delete_item(1);
delete_item(3);
delete_item(5);
delete_item(9);
print_list();
}
struct node *create_item(int x) {
struct node *new;
new = (struct node *) malloc (sizeof(struct node));
new->x = x;
return new;
}
void print_list() {
struct node *iter;
iter = head;
while (iter != NULL) {
printf("num: %i\n", iter->x);
iter = iter->next;
}
}
//We're looking for the best way to right this.
//This is _my_ standard solution to the problem.
// (that is, to test the first element explicitly
// the use current->next != NULL to be one behind
// the search).
//I wondered what other people's is or if there
//is a convention?
void delete_item(int x) {
struct node *iter;
iter = head;
if (iter == NULL) {
printf("not found\n");
return;
}
if (iter->x == x) {
printf("found in first element: %i\n", x);
head = head->next;
return;
}
while (iter->next != NULL) {
if (iter->next->x == x) {
printf("deleting element: %i\n", x);
iter->next = iter->next->next;
return;
}
iter = iter->next;
}
printf("not found\n");
}
</code></pre>
<p>This is a complete example that can be compiled and tested. The output:</p>
<pre><code>23:28: ~$ gcc -o ll linked_list.c
23:28: ~$ ./ll
num: 1
num: 2
num: 3
num: 4
num: 5
num: 6
num: 7
num: 8
num: 9
deleting element: 7
num: 1
num: 2
num: 3
num: 4
num: 5
num: 6
num: 8
num: 9
found in first element: 1
deleting element: 3
deleting element: 5
deleting element: 9
num: 2
num: 4
num: 6
num: 8
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-01-31T23:47:22.593",
"Id": "832",
"Score": "1",
"body": "Forgetting for a moment it should invoke free() somewhere."
}
] | [
{
"body": "<h3>General Comments:</h3>\n<p>Why do your list handling functions not take a list as a parameter?<br />\nAs a result your application can only have one list.</p>\n<h3>Comments on Delete:</h3>\n<p>You are leaking the list item when you delete it.</p>\n<p>Since the <code>create_item()</code> is calling <code>malloc()</code> I would expect the <code>delete_item()</code> to call <code>free()</code>.</p>\n<p>I would split the <code>delete_item()</code> into two parts. The first part that deals with the head as a special case and the second part that deals with removing elements from the list (and <code>free()</code>ing them).</p>\n<pre><code>void delete_item(struct node** list, int x)\n{\n if ((list == NULL) || ((*list) == NULL))\n {\n printf("not found\\n");\n return;\n }\n \n (*list) = delete_item_from_list(*list);\n}\n\nstruct node* delete_item_from_list(struct node* head)\n{\n struct node* iter = head;\n struct node* last = NULL;\n\n while (iter != NULL)\n {\n if (iter->x == x)\n {\n break;\n }\n\n last = iter;\n iter = iter->next;\n }\n\n if (iter == NULL)\n {\n printf("not found\\n");\n }\n else if (last == NULL)\n {\n printf("found in first element: %i\\n", x);\n head = iter->next;\n }\n else\n {\n printf("deleting element: %i\\n", x);\n last->next = iter->next;\n }\n \n free(iter);\n return head;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T13:53:44.410",
"Id": "1073",
"Score": "0",
"body": "The reason I use a single global list was purely because it was a simplistic sample code block. This isn't to do with writing some generic linked list library or anything."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T00:32:57.170",
"Id": "498",
"ParentId": "496",
"Score": "5"
}
},
{
"body": "<p>Deleting an item from a singly-linked list requires finding the previous item. There are two approaches one can use to deal with this:</p>\n\n<ol>\n<li>When deleting an item, search through the list to find the previous item, then do the unlink.\n<li>Have a \"deleted\" flag for each item. When traversing the list for some other reason, check the \"deleted\" flag on each node. If a \"deleted\" node is encountered, unlink it from the previously-visited node.\n</ol>\n\n<p>Note that in a garbage-collected system, it's possible to add items to the start of the list, or perform the #2 style of deletion, in a lock-free thread-safe manner. Nodes which are deleted may get unlinked in one thread and accidentally relinked in another, but the delete flag will cause the node to be unlinked again on the next pass. In a multi-threaded system requiring explicit deallocation, such an unlink and relink sequence could be disastrous, since a node could be unlinked, deallocated, and relinked; locks would thus be necessary to avoid problems.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T01:40:49.503",
"Id": "834",
"Score": "0",
"body": "Not true. You have to scan the whole list in order to find the item you want to delete in any case, so there's no need to have to \"search for the item before you want to delete\" -- you just remember that as you're walking the list. And it's perfectly possible to put items at the front of the list in a non-garbage collected system."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T15:35:56.620",
"Id": "868",
"Score": "0",
"body": "@Billy: Searching for an item immediately prior to deletion is a reasonably common scenario, and you're correct that in that case one will have the previous-item pointer. The scenario is not universal, however. The last time I used a linked list was for an \"thread-safe lock-free arbitrary-order bag\" with O(1) insertion and removal. The creator of each node kept a link to the node itself, but would not know if a node was added immediately before its node. So in that application the only time the list had to be traversed was to enumerate it."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T15:40:45.070",
"Id": "869",
"Score": "0",
"body": "@Billy: As for garbage collection, that's an issue if one is trying to write thread-safe lock-free code which can function correctly even if a thread is asynchronously aborted. In a non-GC lock-free system, it's almost impossible to know for certain whether anyone might hold a reference to a node, and thus whether the node can be safely deleted."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T22:33:38.800",
"Id": "885",
"Score": "0",
"body": "@supercat: But to remove the item from the list, you must first find the item to remove (the OP's interface specifies the value of the entry to remove, not a pointer to the node itself) which will already tell you the previous node."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T22:34:22.997",
"Id": "886",
"Score": "0",
"body": "As for thread-safe/lock-free, first of all that's a completely difference scenario which has nothing to do with the OP's question, second if you're using a GC in that way the code is no longer lock-free (the GC is not lock free), third it's not even possible to handle that scenario with a GC in a thread-safe/lock-free way (i.e. if an element is removed from the list while someone is enumerating it)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T05:27:34.077",
"Id": "905",
"Score": "0",
"body": "@Billy: It's clear the scenario when I was deleting something is different from the original poster's. As for thread safety in a GC system, if an element is deleted during enumeration, it will either be included in the enumeration or not; what's required is that items which are in the bag throughout enumeration be enumerated. It's generally to assume that the GC won't suffer from async abort or priority inversion than to assume that no other threads will. Anyway, I think we're drifting off-topic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T12:47:16.593",
"Id": "74564",
"Score": "0",
"body": "@supercat: I'd suggest calling this \"lazy freeing\", so that people don't confuse it with generic garbage collection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T23:39:40.867",
"Id": "74645",
"Score": "0",
"body": "@Brendan: Whether the node is immediately physically removed from the linked list when a \"delete\" request is issued is an implementation detail, provided that the number of nodes physically in the list can never exceed a bounded multiple of the number of nodes which are supposed to be in the list. The deletion may be \"lazy\", but in many cases the application shouldn't care, since the fact that the \"deleted\" node was still linked would not be externally visible."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T00:41:26.403",
"Id": "499",
"ParentId": "496",
"Score": "-1"
}
},
{
"body": "<p>If you don't mind recursion (although C programmers generally DO mind), then you can do:</p>\n\n<pre><code>node* delete_item(node* curr, int x) {\n node* next;\n if (curr == NULL) { // Found the tail\n printf(\"not found\\n\");\n return NULL;\n } else if (curr->x == x) { // Found one to delete\n next = curr->next;\n free(curr);\n return next;\n } else { // Just keep going\n curr->next = delete_item(curr->next, x);\n return curr;\n }\n}\n</code></pre>\n\n<p>then, in main, you should do</p>\n\n<pre><code>head = delete_item(head, 7);\n</code></pre>\n\n<p>This uses the C stack to hold the \"backwards look\" in the list.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T23:34:52.573",
"Id": "1052",
"Score": "3",
"body": "As a C programmer, I love recursion as a technique (e.g. traversing trees, or printing evil numbers (http://www.bobhobbs.com/files/kr_lovecraft.html :-) )), but not when it's applied inappropriately (e.g. for something like this in the case where the lists can be large, or the machine has tiny stack)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-23T19:39:54.997",
"Id": "193223",
"Score": "0",
"body": "@MattCurtis it's not applied inappropriately. If you have a linked list so big that traversing it recursively overflows the stack, then you are having much bigger problems. This deletion is much more elegant than one where one has to keep track of the previous item explicitly and treat the head of the list specially."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-20T20:55:22.800",
"Id": "241095",
"Score": "1",
"body": "Am I missing something? How could this possibly be more efficient than simply traversing the list in a loop until you find the node just before the target? Also, this looks like it's re-writing the \"next\" pointer of every node in the list whether it needs it or not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-23T21:03:21.230",
"Id": "266711",
"Score": "0",
"body": "They asked for elegant, not efficient."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T04:40:19.223",
"Id": "508",
"ParentId": "496",
"Score": "5"
}
},
{
"body": "<p>The neatest way to deal with this is to use what I was taught as the \"2 pointer trick\" (thank you Charles Lindsay all those years ago):</p>\n\n<p>Instead of holding a pointer to the record you hold a pointer to the pointer that points to it - that is you use a double indirection. This enables you to both modify the pointer to the record and to modify the record without keeping track of the previous node.</p>\n\n<p>One of the nice things about this approach is that you don't need to special case dealing with the first node.</p>\n\n<p>An untested sketch using this idea for delete_item (in C++) looks like:</p>\n\n<pre><code>void delete_item(node** head, int i) {\n for (node** current = head; *current; current = &(*current)->next) {\n if ((*current)->x == i) {\n node* next = (*current)->next;\n delete *current;\n *current = next;\n break;\n }\n }\n}\n</code></pre>\n\n<p>This loop will break after the first entry it finds, but if you remove the \"break\" then it will remove all entries that match.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T01:11:38.240",
"Id": "539",
"ParentId": "496",
"Score": "18"
}
},
{
"body": "<p>My favorite technique would look something like this (copious amounts of comments added for illustrative purposes...):</p>\n\n<pre><code>void remove_item(struct node **head, int x)\n{\n struct node *n = *head,\n *prev = NULL;\n\n /* Loop through all the nodes... */\n while (n)\n {\n /* Store the next pointer, since we might call free() on n. */\n struct node *next = n->next;\n\n /* Is this a node we're interested in? */\n if (n->x == x)\n {\n /* Free the node... */\n free(n);\n\n /* Update the link... */\n if (prev)\n {\n /* Link the previous node to the next one. */\n prev->next = next;\n }\n else\n {\n /* No previous node. Update the head of the list. */\n *head = next;\n }\n }\n else\n {\n /* We didn't free this node; track that we visited it for the next iteration. */\n prev = n;\n }\n\n n = next;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-04T04:34:09.920",
"Id": "2224",
"ParentId": "496",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "508",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-01-31T23:44:49.807",
"Id": "496",
"Score": "13",
"Tags": [
"c",
"linked-list"
],
"Title": "C function to find and delete a node from a singly linked list"
} | 496 |
<p>This function in my <code>Profile</code> model receive a hash from a search form and should filter the table depending on those values. I guess there is something like a pattern for such a standard behavior, right now I ended up with this (unfortunately I had to reproduce the code here, so it might not work for some reasons, but you get the idea).</p>
<p>Just a note: we're storing in the model some strings containing multiple data, each of these fields should be a one-to-many relationship (db normality violation). I give an example: <code>country_preferences</code> is a string filled up by an html <code>select :multiple => true</code>. In the string I then find values like: <code>["Australia", "China", "United Kingdom"]</code>.</p>
<pre><code> def search opts # This default doesn't work the way I would like = {:user_type => :family}
#TODO: default opts value in method sign if possible
opts[:user_type] ||= :family
# initial criteria
fields= "user_type= ?"
values= [opts[:user_type]]
# each field filters the list in one of these three ways
staight_fields = [ :country, :first_name, :last_name, :nationality ]
like_fields = [:country_preferences, :keyword, :languages ]
bool_fields = [:driver, :housework, :children ]
# cicle the options and build the query
opts.each do |k, v|
if straight_fields.include? k
fields += " AND #{k} = ?"
values += v
elsif like_fields.include? k
fields += " AND #{k} like %?%"
values += v
elsif bool_fields.include? k
fields += " AND #{k} = ?"
values += v == 'true'
else
logger.warn "opts #{k} with value #{v} ignored from search"
end
end
# execute the query and return the result
self.registered.actives.where([fields] + values)
end
</code></pre>
<p>I think I can use more <code>scope</code> but how can I combine them together? In general, how can I make this code much better?</p>
<p>The boss, when introducing the project, said one-to-many relationships for that kind of fields would be a pain in the back. What do you think about this pragmatic solution?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T18:40:24.187",
"Id": "879",
"Score": "1",
"body": "Does the code you posted in your edit actually work? It seems like you're missing `profiles =` at the beginning of every line after the first and a final `profiles` at the end of the method."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T23:21:54.470",
"Id": "1383",
"Score": "0",
"body": "Good point! - I've already corrected my code and I'm not going to refactor, but that behavior (getting rid of all the assignment) can be achieved with a **dynamic delegator** explained by Ryan Bates http://railscasts.com/episodes/212-refactoring-dynamic-delegator"
}
] | [
{
"body": "<p>Have you looked into using a pre existing gem for this? I found one called <a href=\"https://github.com/plataformatec/has_scope\" rel=\"noreferrer\">has_scope</a> that seems like it might do exactly what you're trying to refactor. You would need to add a scope for each of your filters and then add some <code>has_scope</code> calls in your controller.</p>\n\n<p>Here's a few examples. I'm not as familiar with Rails 3 scopes as I am with 2, so the code likely won't work as is.</p>\n\n<p>Model:</p>\n\n<pre><code>class Profile < ActiveRecord::Base\n scope :country, lambda {|country| where(:country => country) }\n scope :keyword, lambda {|keyword| where([\"keyword LIKE :term\", {:term => \"%#{keyword}%\"}]) }\n scope :driver, where{:driver => true)\nend\n</code></pre>\n\n<p>Controller:</p>\n\n<pre><code>class ProfileController < ApplicationController\n has_scope :country\n has_scope :keyword\n has_scope :driver, :type => :boolean\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T09:24:58.063",
"Id": "843",
"Score": "0",
"body": "this plugin looks easy tiny and tested, I would avoid to install an external plugin to substitute a single function used once, but when I have some time I'm going to dive in the code, there should be something to learn, thanks"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T09:17:55.000",
"Id": "912",
"Score": "0",
"body": "thanks a lot, that was it, but you don't need to declare scopes like country or driver, as you can see in the question edit you have by default scoped_by_driver(true) that works the same."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T13:12:12.990",
"Id": "925",
"Score": "0",
"body": "I didn't even know about the scoped_by_* methods, great tip!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T01:15:52.663",
"Id": "501",
"ParentId": "500",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "501",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T00:46:02.727",
"Id": "500",
"Score": "8",
"Tags": [
"ruby-on-rails",
"ruby"
],
"Title": "Filtering (search) a model with multiple params in hash"
} | 500 |
<p>A little background first. I've been working on a fairly large Rails application which quickly grew into a breeding ground for "smelly" code. One antipattern we were using a lot was storing objects in an STI lookup table and having lots of scattered logic based on the name of the object.</p>
<p>Here's a dumbed down example of what we had:</p>
<pre><code>class Lookup < ActiveRecord::Base
end
class AlarmStatus < Lookup
has_many :alarm_logs
end
class AlarmLog < ActiveRecord::Base
belongs_to :alarm_status
end
</code></pre>
<p>Then all over our application we would do things like:</p>
<pre><code>case @alarm_log.alarm_status.name
when "active"
# Do something
when "verified"
# Do something
when "inactive"
# Do something
end
</code></pre>
<p>This is obviously bad for a lot of reasons, but let's just say it was everywhere. After a few months of this, a consultant came along and pointed out our "code smell" and made some suggestions on how to refactor, which included a Ruby implementation of <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Enum.html" rel="nofollow noreferrer">Java's Enum class</a>. </p>
<p>We ended up using this frequently in our app, and have extracted into a ruby gem called <a href="https://github.com/beerlington/classy_enum" rel="nofollow noreferrer">classy_enum</a>. The premise of classy_enum is that you get the power of OOP mixed with the strictness of an enumerated type, which is pretty much what we were trying to mimic with our STI Lookup model.</p>
<p>Example of defining an enum:</p>
<pre><code>class Priority < ClassyEnum::Base
enum_classes :low, :medium, :high
def send_email?
false
end
end
class PriorityHigh < Priority
def send_email?
true
end
end
</code></pre>
<p>The gem's <a href="https://github.com/beerlington/classy_enum/blob/master/README.md" rel="nofollow noreferrer">README</a> has some other usage examples, including how to integrate it with a Rails project.</p>
<p>I may be asking for a lot here, but I would love some feedback from anyone willing to give it. It seems like a really cool solution to our problem and I can't imagine we're the only ones who have attempted to solve this before. Here's a list of questions that would be really useful for us:</p>
<ul>
<li>Is this a common problem?</li>
<li>Does our solution make sense? Is there a better way to do it?</li>
<li>Is the documentation clear?</li>
<li>Would you use this in your application? Why or why not?</li>
<li>How could we improve it?</li>
<li>How is the code quality?</li>
</ul>
| [] | [
{
"body": "<p>Yes, it is a common problem. </p>\n\n<p>I think this is a great way to solve this, I wish I'd done it! Back in my java days I did use the typesafe enum pattern. In ruby I tend to create method objects after the third or so repetition in cases like this, but this is a much cleaner solution and I'm going to start using it for sure.</p>\n\n<p>I found the documentation really clear. I do intend to use it in my app, because it is an excellent way to formalize what I am doing when I create method objects and suggest to others that they replace their long nested if statements with method objects.</p>\n\n<p>The only think I think of at the moment that I might want to improve on it would be to have an option to create a back reference to the owning object for cases where double dispatch will further remove conditional logic. (or like for example where I had a a set of alarms that each should ring at some percentage of the owning objects master volume)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T14:47:41.703",
"Id": "1111",
"Score": "0",
"body": "Thanks Michael, I appreciate the feedback. I'm not sure I follow your suggestion about creating a back reference. Would it be possible for you to provide an example of how you'd want to use it?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T11:39:17.400",
"Id": "625",
"ParentId": "503",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "625",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T02:20:22.557",
"Id": "503",
"Score": "8",
"Tags": [
"ruby",
"ruby-on-rails",
"enum",
"lookup"
],
"Title": "RubyGem for Enums"
} | 503 |
<p>I have a class whose purpose is to display a comment. I'd like to be able to instantiate it by passing a <code>Comment</code> object if I happen to have it available, or just the values if that's what I have available at the time. Unfortunately PHP doesn't allow overloaded constructors, so here's the workaround I came up with.</p>
<pre><code>class CommentPanel extends Panel {
//Private Constructor, called only from MakeFrom methods
private function CommentPanel($text, $userName, $timestamp) {
parent::Panel(0, $top, System::Auto, System::Auto);
// Render comment
}
public static function MakeFromObject(Comment $comment) {
return new CommentPanel($comment->text, $comment->User->nickname, $comment->last_updated_ts);
}
public static function MakeFromValues($text, $userName, $timestamp) {
return new CommentPanel($text, $userName, $timestamp);
}
}
</code></pre>
<p>So here's the two methods for instantiating a <code>CommentPanel</code>:</p>
<pre><code>$cp = CommentPanel::MakeFromObject($comment);
// or...
$cp = CommentPanel::MakeFromValues($text, $user, $last_updated_ts);
// but not
$cp = new CommentPanel(); //Runtime error
</code></pre>
<p>I'm moderately satisfied, although it's not near as intuitive as an overloaded constructor. Any thoughts on improving this?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-01T22:31:49.617",
"Id": "3537",
"Score": "0",
"body": "Partly covered by the migrated [Single array or many single argument to call a constructor with params](http://codereview.stackexchange.com/questions/2189/single-array-or-many-single-argument-to-call-a-constructor-with-params)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-01T22:35:35.777",
"Id": "62835",
"Score": "0",
"body": "As discussed in http://codereview.stackexchange.com/questions/2189/single-array-or-many-single-argument-to-call-a-constructor-with-params, you could use a constructor that takes an associative array."
}
] | [
{
"body": "<p>Given that php allows optional parameters and doesn't require type checking of parameters that are passed in, you can sort of \"fake\" an overloaded constructor.</p>\n\n<p>something like this:</p>\n\n<pre><code>class CommentPanel extends Panel {\n public function __construct($text_or_comment, $username=null, $timestamp=null) {\n if (is_string($text_or_comment) {\n $this->textConstructor($text_or_comment, $username, $timestamp);\n }\n else { // assume that it's a comment since it's not a string ... there are better ways to handle this though\n $this->commentConstructor($text_or_comment);\n }\n }\n\n private function textConstructor($text, username, $timestampe) { /* . . . */ }\n private function commentConstructor(Comment $comment) { /* . . . */ }\n}\n</code></pre>\n\n<p>This method will allow for a more consistent API and one that is perhaps more familiar to Java and C++ developers.</p>\n\n<p>Also, I'm not positive which version of PHP you're targeting, but I believe in the current version, uses __construct instead of the class name as the constructor. I'm not sure if this is preferred but the documentation does say that it checks for __construct first and then the class name style constructor, so I would guess that using __construct() instead of CommentPanel() would reduce runtime ever so slightly. I'm not 100% sure on that though, that's just my understanding. Please correct me if I'm wrong :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T07:55:06.763",
"Id": "841",
"Score": "5",
"body": "It is in fact preferred to use `__construct()` instead class name for constructor. The latter is deprecated, and can cause problems in name resolution when working with PHP 5.3 namespaces."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T06:24:10.867",
"Id": "509",
"ParentId": "504",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "509",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T02:57:13.353",
"Id": "504",
"Score": "7",
"Tags": [
"php",
"constructor"
],
"Title": "Workaround for overloaded constructor in PHP"
} | 504 |
<p>I intend this to be a general question on writing an effective set of test cases for a controller action.</p>
<p>I include the following ingredients:</p>
<ul>
<li><strong>Ruby on Rails</strong></li>
<li><strong>RSpec:</strong> A testing framework. I considered doing a vanilla Rails question, but I personally use RSpec, and I feel many other folks do too. The principles that come out of this discussion should be portable to other testing frameworks, though.</li>
<li><strong>Will Paginate:</strong> I include this to provide an example of code whose implementation is blackboxed to the controller. This is an extreme example of just using the model methods like <code>@programs = Program.all</code>. I chose to go this route to incorporate an additional factor for discussion, and to demonstrate that the same principles apply whether using external application code (e.g., model code) or an external plugin.</li>
</ul>
<p>There seems to be a lack, given my humble Google Fu, of style guides for RSpec testing at this level, so it is my hope that, on top of me improving my code, this can become a useful guide for my fellow travelers.</p>
<p>For example purposes, let's say I currently have in my controller the following:</p>
<pre><code>class ProgramssController < ApplicationController
def index
@programs = Program.paginate :page => params[:page], :per_page => params[:per_page] || 30
end
end
</code></pre>
<blockquote>
<p><strong>Sidebar:</strong> For those unfamiliar with <code>will_paginate</code>, it tacks onto a ActiveRecord Relation (<code>all</code>, <code>first</code>, <code>count</code>, <code>to_a</code> are other examples of such methods) and delivers a paginated result set of class <code>WillPaginate::Collection</code>, which <em>basically</em> behaves like an array with a few helpful member methods.</p>
</blockquote>
<p>What are the effective tests I should run in this situation? Using RSpec, this is what I've conceived at the moment:</p>
<pre><code>describe ProgramsController do
def mock_program(stubs={})
@mock_program ||= mock_unique_program(stubs)
end
def mock_unique_program(stubs={})
mock_model(Program).as_null_object.tap do |program|
program.stub(stubs) unless stubs.empty?
end
end
describe "GET index" do
it "assigns @programs" do
Program.stub(:paginate) { [mock_program] }
get :index
response.should be_success
assigns(:programs).should == [mock_program]
end
it "defaults to showing 30 results per page" do
Program.should_receive(:paginate).with(:page => nil, :per_page => 30) do
[mock_program]
end
get :index
response.should be_success
assigns(:programs).should == [mock_program]
end
it "passes on the page number to will_paginate" do
Program.should_receive(:paginate).with(:page => '3', :per_page => 30) do
[mock_program]
end
get :index, 'page' => '3'
response.should be_success
assigns(:programs).should == [mock_program]
end
it "passes on the per_page to will_paginate" do
Program.should_receive(:paginate).with(:page => nil, :per_page => '15') do
[mock_program]
end
get :index, 'per_page' => '15'
response.should be_success
assigns(:programs).should == [mock_program]
end
end
end
</code></pre>
<p>I wrote this with the following principles in mind:</p>
<ul>
<li><strong>Don't test non-controller code:</strong> I don't delve into the actual workings of <code>will_paginate</code> at all and abstract away from its results.</li>
<li><strong>Test all controller code:</strong> The controller does four things: assigns <code>@programs</code>, passes on the <code>page</code> parameter to the model, passes on the <code>per_page</code> parameter to the model, and defaults the <code>per_page</code> parameter to 30, and nothing else. Each of these things are tested.</li>
<li><strong>No false positives:</strong> If you take away the method body of <code>index</code>, all of the test will fail. </li>
<li><strong>Mock when possible:</strong> There are no database accesses (other ApplicationController logic notwithstanding)</li>
</ul>
<p>My concerns, and hence the reason I post it here:</p>
<ul>
<li><strong>Am I being too pedantic?</strong> I understand that TDD is rooted in rigorous testing. Indeed, if this controller acts as a part of a wider application, and say, it stopped passing on <code>page</code>, the resulting behaviour would be undesirable. Nevertheless, is it appropriate to test such elementary code with such rigor?</li>
<li><strong>Am I testing things I shouldn't be? Am I not testing things I should?</strong> It think I've done an okay job at this, if anything veering on the side of testing too much.</li>
<li><strong>Are the <code>will_paginate</code> mocks appropriate?</strong> You see, for instance, with the final three tests, I return an array containing only one program, whereas <code>will_paginate</code> is quite liable to return more. While actually delving this behaviour by adding, say 31 records, may (?) violate modular code and testing, I am a bit uneasy returning an unrealistic or restrictive mock result.</li>
<li><strong>Can the test code be simplified?</strong> This seems quite long to test one line of controller code. While I fully appreciate the awesomeness of TDD, this seems like it would bog me down. While writing these test cases were not too intensive on the brain and basically amounted to a fun vim drill, I feel that, all things considered, writing this set of tests may cost more time than it saves, even in the long run.</li>
<li><strong>Is this a good set of tests?</strong> A general question.</li>
</ul>
| [] | [
{
"body": "<p>just something that i have considered how about hiding the paginate stuff behind a helper method and then stub the helper method this way you can swap out the pagination implementation with anytime you want\nand then just test the helper method is delegating the params to will_paginate</p>\n\n<pre><code>class ProgramssController < ApplicationController\n def index\n @programs = paginate_progams(params)\n end\nend\n</code></pre>\n\n<p>now you stub the paginate_programs method\nand then you can spec up the helper method paginate</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-07T22:18:04.843",
"Id": "682",
"ParentId": "505",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T03:01:24.973",
"Id": "505",
"Score": "28",
"Tags": [
"ruby",
"unit-testing",
"ruby-on-rails",
"controller"
],
"Title": "Unit-testing a controller in Ruby on Rails"
} | 505 |
<p>Please review this:</p>
<pre><code>from os import path, remove
try:
video = Video.objects.get(id=original_video_id)
except ObjectDoesNotExist:
return False
convert_command = ['ffmpeg', '-i', input_file, '-acodec',
'libmp3lame', '-y', '-ac', '2', '-ar',
'44100', '-aq', '5', '-qscale', '10',
'%s.flv' % output_file]
convert_system_call = subprocess.Popen(
convert_command,
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE
)
logger.debug(convert_system_call.stdout.read())
try:
f = open('%s.flv' % output_file, 'r')
filecontent = ContentFile(f.read())
video.converted_video.save('%s.flv' % output_file,
filecontent,
save=True)
f.close()
remove('%s.flv' % output_file)
video.save()
return True
except:
return False
</code></pre>
| [] | [
{
"body": "<p>Clean, easy to understand code. However:</p>\n\n<p>Never hide errors with a bare except. Change </p>\n\n<pre><code>try:\n ...\nexcept:\n return False\n</code></pre>\n\n<p>into </p>\n\n<pre><code>try:\n ...\nexcept (IOError, AnyOther, ExceptionThat, YouExpect):\n logging.exception(\"File conversion failed\")\n</code></pre>\n\n<p>Also, unless you need to support Python 2.4 or earlier, you want to use the files context manager support:</p>\n\n<pre><code>with open('%s.flv' % output_file, 'r') as f:\n filecontent = ContentFile(f.read())\n video.converted_video.save('%s.flv' % output_file, \n filecontent, \n save=True)\nremove('%s.flv' % output_file)\n</code></pre>\n\n<p>That way the file will be closed immediately after exiting the <code>with</code>-block, even if there is an error. For Python 2.5 you would have to <code>from __future__ import with_statement</code> as well.</p>\n\n<p>You might also want to look at using a temporary file from <code>tempfile</code> for the output file. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T15:15:26.917",
"Id": "866",
"Score": "0",
"body": "Thanks a lot for the review! I have updated the snippet to be http://pastebin.com/9fAepHaL But I am confused as to how to use tempfile. The file is already created by the \"convert_system_call\" before I use it's name in the try/catch block. Hmm,, maybe I use tempfile.NamedTemporaryFile()?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T15:43:30.093",
"Id": "870",
"Score": "0",
"body": "@Chantz: Yeah, exactly. If not you may end up with loads of temporary files in a current directory, where users won't find them and they ever get deleted."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:43:47.623",
"Id": "951",
"Score": "1",
"body": "Lennart following your & sepp2k's suggestion I modified my code to be like http://pastebin.com/6NpsbQhz Thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T06:29:50.330",
"Id": "510",
"ParentId": "507",
"Score": "5"
}
},
{
"body": "<p>In addition to the points that Lennart made, there's just one minor thing I'd like to add:</p>\n\n<p>You repeat the expression <code>'%s.flv' % output_file</code> four times in your code. You might want to store this in a variable like <code>filename = '%s.flv' % output_file</code>. This way there's less repetition and if you ever want to change the target file format, all you'll have to change are the <code>filename</code> and <code>convert_command</code> variables.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T18:18:09.150",
"Id": "878",
"Score": "0",
"body": "Makes sense. Will make the change. Thanks!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:43:21.880",
"Id": "950",
"Score": "0",
"body": "sepp2k following your & Lennart's suggestion I modified my code to be like http://pastebin.com/6NpsbQhz Thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T15:38:25.913",
"Id": "525",
"ParentId": "507",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "510",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T04:39:28.163",
"Id": "507",
"Score": "5",
"Tags": [
"python",
"converting",
"django"
],
"Title": "Converting an already-uploaded file and saving it to a model's FileField"
} | 507 |
<pre><code><% @descriptions.each_with_index do |description, i| %>
<% description.tale2.each do |tax_ref| %>
<% if condition %>
<% if condition %>
<% if condition %>
<%= $text_first_describe%> <%= $paren_author_yr %>
<% ref_sp_uniq.each_with_index do |ref, i| %>
<% if ref == tax_ref.ref_wo_brace%>
<% execution %>
<% elsif i == (ref_sp_uniq.size - 1)%>
<%# @ref_desc = "#{@ref_desc_numb}. #{tax_ref.ref_wo_brace}" %>
<% end %>
<% end %>
<% if condition %>
<% execution %>
<% elsif condition %>
<% execution %>
<% elsif taxon_name.emend_author_year %>
<%= print %>
<% else %>
<%= print %>
<% end %>
<% end %>
<% else %>
<% if condition %>
<%= print %>
<% ref_sp_uniq.each_with_index do |ref, i| %>
<% if condition %>
<% execution %>
<% elsif condition %>
<% execution %>
<% end %>
<% end %>
<% if condition %>
<% execution %>
<% elsif condition %>
<% execution %>
<% elsif condition %>
<% execution %>
<% else %>
<% execution %>
<% end %>
<% end %>
<% end %>
<% end %>
<% end %>
<% end %>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T10:03:52.760",
"Id": "845",
"Score": "0",
"body": "try to edit your code with a good completion"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T10:04:34.177",
"Id": "846",
"Score": "1",
"body": "that depend your condition. Its almost impossible to help your without more information"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T10:12:52.433",
"Id": "848",
"Score": "12",
"body": "As it stands this question is _impossible_ to answer. Without knowing what conditions are being checked or what code is being executed there is literally _nothing_ we can suggest. Maybe you are repeating code, or maybe several chunks of code could just be run under a single check, but we simply do not know. We need the actual code with conditions _and_ execution before we can do anything."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T20:04:23.710",
"Id": "881",
"Score": "5",
"body": "-1: please edit your question, use code formatting (four spaces at the start of each line) and provide some context."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T08:59:26.863",
"Id": "1156",
"Score": "0",
"body": "This looks like code to post if you're trolling. It's practically line noise and ruby is one of the most expressive languages I know but this manages to make it look bad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T06:26:04.197",
"Id": "58767",
"Score": "1",
"body": "See [Flattening arrow code](http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-06T08:58:05.367",
"Id": "108890",
"Score": "0",
"body": "Ruby has 'case when' statement that is pretty nifty and when used properly can help a lot with complicated if statements because 'case when' allows range checking which comes up a lot in conditional code."
}
] | [
{
"body": "<p>In general, you can try inverting the condition on your outermost if block, and work your way in. This will often result in less nesting, eg:</p>\n\n<pre><code>if condition1\n if condition2\n #ifblock\n else\n #elseblock2\n end\nelse\n #elseblock\nend\n</code></pre>\n\n<p>Inside a loop, as you have your code, it would become this strcture, which is less nested:</p>\n\n<pre><code>if !condition\n #elseblock\n next\nend\nif !condition2\n #elseblock2\n next\nend\n#ifblock\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T15:14:46.230",
"Id": "524",
"ParentId": "514",
"Score": "6"
}
},
{
"body": "<p>A thing to try: case statement</p>\n\n<pre><code>case tax_ref\nwhen a then execution1\nwhen b then execution2\nend\n</code></pre>\n\n<p><a href=\"http://www.tutorialspoint.com/ruby/ruby_if_else.htm\" rel=\"nofollow\">http://www.tutorialspoint.com/ruby/ruby_if_else.htm</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:03:05.800",
"Id": "554",
"ParentId": "514",
"Score": "1"
}
},
{
"body": "<p>Why can't you use the operators <code>||</code> and <code>&&</code> ?</p>\n\n<p>im not at all literate with the syntax but you should be able to convert:</p>\n\n<pre><code><% if condition %> \n <% if condition %>\n <% if condition %>\n <% end %>\n <% end %>\n<% end %>\n</code></pre>\n\n<p>into:</p>\n\n<pre><code><% if condition && condition && condition %>\n <% expression %>\n<% end %>\n</code></pre>\n\n<p>Looking at the docs this logical expressions are available!</p>\n\n<p>also removing the language identifiers you should be able to do:</p>\n\n<pre><code><%\n if condition && condition && condition\n expression\n end\n%>\n</code></pre>\n\n<p>When it comes down to the <code>else if</code>'s then you can increase readability by doing a switch statement:</p>\n\n<p>The main point is to remove the not so required <code><%</code> and <code>%></code> in places.</p>\n\n<p><a href=\"http://www.ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html#and\" rel=\"nofollow\">http://www.ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html#and</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T20:56:51.783",
"Id": "567",
"ParentId": "514",
"Score": "2"
}
},
{
"body": "<p>There are several things you should do with this template, and templates that look like this in general:</p>\n\n<ol>\n<li><p>Break some elements into partials.</p></li>\n<li><p>Push logic to the model. Instead of </p>\n\n<pre><code> <% if condition with model %>\n stuff\n <% else %>\n other stuff\n <% end %>\n</code></pre>\n\n<p>when stuff or other stuff are strings with little or no markup, do</p>\n\n<pre><code> <%= model.display_for_condition %>\n</code></pre></li>\n<li><p>Use helpers for cases like 2) where the things to be displayed have some markup:</p>\n\n<pre><code> <% condition_helper(model.condition?) %>\n</code></pre></li>\n<li><p>Use presenter objects, especially when dealing with display logic that references more than one model. </p></li>\n<li><p>Most abstractly, but most importantly for learning to write code with fewer if statements, internalize one of the key distinctions between OO style and procedural style code: with OO you ask objects to do things they know how to do. If you find yourself always asking objects for information and deciding what to do with it, you are using objects as nothing more than structs and writing procedural code. </p>\n\n<p>Or as my intern described it the other day: (this has become one of my favourite quotes about programming)</p></li>\n</ol>\n\n<blockquote>\n <p>if you're itchy it's ok to scratch your own itch, but it would be kind of weird to scratch other people's itches.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T11:14:34.537",
"Id": "622",
"ParentId": "514",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "524",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T09:36:07.163",
"Id": "514",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "How to reduce number of hierarchical 'if statements'"
} | 514 |
<p>I need a code review for <em>best practices</em> and <em>code correctness</em> of the following piece of code. <code>run</code> executes a program and validates in output. If the output is valid status can be found in <code>VALID_SOLUTIONS</code>.</p>
<pre><code>elapsed = None
tmpdir = tempfile.mkdtemp(prefix='structure-%s-' % os.path.basename(instance))
try:
for r in range(options.repeat):
run_returncode, run_status, run_elapsed = run(
r, path, program, tmpdir, options.timeout, options.satisfiable)
if run_status not in VALID_SOLUTIONS:
returncode, status, elapsed = run_returncode, run_status, None
break
if r == 0:
# Set the expected results
returncode, status = run_returncode, run_status
elapsed = [run_elapsed]
else:
if returncode != run_returncode or status != run_status:
# Results don't match
returncode, status, elapsed = None, 'inconsistent_results', None
break
else:
# Extra set
elapsed.append(run_elapsed)
except Exception as e:
# Unexpected error in script itself
print(e, file=sys.stderr)
#traceback.print_exc()
status = 'error'
except KeyboardInterrupt as e:
print('interrupted', file=sys.stderr)
returncode, status, elapsed = None, 'interrupted', None
finally:
if status in VALID_SOLUTIONS:
avg = sum(elapsed) / len(elapsed)
std = (sum((e - avg)**2 for e in elapsed) / len(elapsed)) ** 0.5
ci = 1.96 * std / (len(elapsed) ** 0.5)
print(instance, returncode, status, avg, ci)
else:
print(instance, returncode, status, None, None)
sys.stdout.flush()
exit(int(status not in ['interrupted'] + VALID_SOLUTIONS))
</code></pre>
| [] | [
{
"body": "<p>Well, firstly, don't be afraid of empty lines. This code is quite hard to read.</p>\n\n<p>Secondly, functions is good invention. ;) That code as it is now is a bare piece of code, with no indication of where most of the parameters come from, and it seems that the acceptable solutions is a global, as you have capitalized it? That doesn't make much sense to me.</p>\n\n<p>Just as you have a function called run() to run the program, it would make sense to have a function to run it multiple times, with the tests for that you have.</p>\n\n<p>I'm also not sure why you trap KeyboardInterrupt, without seeming to actually do anything with it, except setting the status, and then testing the status. You could just do exit directly from that exception handler, that would be clearer.</p>\n\n<p>Otherwise it seems fine. Feedback on correctness is impossible when your code isn't a running example. But then again, tests generally work better than code reviews there, although they are not exclusive.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T14:04:08.687",
"Id": "856",
"Score": "0",
"body": "Thanks for the feedback. `KeboardInterrupt` because the script is run inside an infinite loop which stops when the output is invalid. Can't exit directly since exit() throws an exception (`SystemExitError` I think)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T14:26:01.333",
"Id": "862",
"Score": "0",
"body": "+1 for adding whitespace to enhance readability. Also moving code to separate functions would help."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T13:44:42.763",
"Id": "521",
"ParentId": "519",
"Score": "12"
}
},
{
"body": "<p>Comments. Well written code tells you how a problem is being solved. Well written comments tell you <em>what</em> problem is being solved. Great comments tell you what assumptions the programmer is making about the data going in and coming out.</p>\n\n<p>In the finally clause: You have a magic constant. Best practice is that you declare constants with descriptive variables names.</p>\n\n<p>The variables 'r' and 'e': no single letter variable names please, save for those that are so basic no one will get them wrong, which is basically x,y,z and t, in the context for cartesian coordinates or parameterized plots. And 'e' was an exception a few lines ago, now it's a list element?</p>\n\n<p>Lastly, x**.5 is accurate, but sqrt(x) is more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T14:24:31.153",
"Id": "523",
"ParentId": "519",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "521",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T13:25:51.633",
"Id": "519",
"Score": "14",
"Tags": [
"python",
"file",
"error-handling",
"timer"
],
"Title": "Executing a program with a temporary directory and measuring the running time"
} | 519 |
<p>I'm building an ASP.NET MVC app and would like some feedback for my way to query/execute statements to the ORM.</p>
<p>I'm using Fluent NHibernate, and have mixed the UoW provided by NHibernate with a Command pattern.</p>
<p><strong>ICommand.cs</strong> (Core layer)</p>
<pre><code>using NHibernate;
namespace MyDemon.Core.Commands
{
public interface ICommand<out TResult>
{
TResult Execute(ISession session);
}
}
</code></pre>
<p><strong>ISessionExtensions.cs</strong> (Core layer)</p>
<pre><code>using NHibernate;
namespace MyDemon.Core.Commands
{
public static class ISessionExtensions
{
public static TResult Execute<TResult>(this ISession session, ICommand<TResult> unitOfWork)
{
return unitOfWork.Execute(session);
}
}
}
</code></pre>
<p><strong>GetUserById.cs</strong> (Core layer)</p>
<pre><code>using NHibernate;
namespace MyDemon.Core.Commands.User
{
using Entities;
public class GetUserById : ICommand<User>
{
public int UserId { get; set; }
public GetUserById(int userId)
{
UserId = userId;
}
#region Implementation of IUnitOfWork<out User>
public User Execute(ISession session)
{
return session.Get<User>(UserId);
}
#endregion
}
}
</code></pre>
<p><strong>AccountController.cs</strong> (Web layer)</p>
<pre><code>[AjaxOnly]
[Authorize]
public ActionResult Details(int id)
{
User userToGet = _session.Execute(new GetUserById(id));
if (userToGet == null)
{
return PartialView("Partials/UserNotFound");
}
DetailsUserViewModel userToViewModel = Mapper.Map<User, DetailsUserViewModel>(userToGet);
return PartialView("Partials/Details", userToViewModel);
}
</code></pre>
<p>What do you think? A clever design, or just another "too-much code" approach?</p>
| [] | [
{
"body": "<p>This seems to be a lot of code to say the same as this:</p>\n\n<pre><code>[AjaxOnly]\n[Authorize]\npublic ActionResult Details(int id)\n{\n User userToGet = _session.Get<User>(id);\n\n if (userToGet == null)\n {\n return PartialView(\"Partials/UserNotFound\");\n }\n\n DetailsUserViewModel userToViewModel = Mapper.Map<User, DetailsUserViewModel>(userToGet);\n\n return PartialView(\"Partials/Details\", userToViewModel);\n}\n</code></pre>\n\n<p>What problem are you trying to solve here?</p>\n\n<p>(or am I missing something?)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T11:10:52.460",
"Id": "1069",
"Score": "1",
"body": "I wouldn't go as raw as having the _session in the Controller (would have a DAO or Repository layer), but definetely this is the way to go. This is the way NH is used in web apps in .NET. Unless you have a (good) reason there is no motive to come up with something so \"complicated\" (not because the inherent complexity but just because it not the standard) to deal with NH + DB."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T17:27:43.583",
"Id": "1084",
"Score": "0",
"body": "@tucaz Agree with you there. But the session was already in the controller, so I left it there rather than complicating the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-29T19:17:24.417",
"Id": "19440",
"Score": "0",
"body": "@tucaz For what reason would you have a DAO or repo layer here? Isn't NHibernate enough of a DAO in this case? (I'm new to NHibernate too so I'm curious about these things)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-30T21:13:45.613",
"Id": "19506",
"Score": "0",
"body": "@JamieDixon, it is, and I'm probably should not add another layer of indirection unless needed for some other reason, but I like to think that adding it allows me to make sure that the usage of NHibernate does not get out of hand and is spreaded where it should not be and also allows me to change strategies easily later as well encapsulating the lifecicle of the ISession."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T22:43:24.520",
"Id": "596",
"ParentId": "522",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-01T14:22:20.707",
"Id": "522",
"Score": "4",
"Tags": [
"c#",
"asp.net"
],
"Title": "NHibernate (UoW) + cCommand pattern"
} | 522 |
<p>Is there a better (more pythonic?) way to filter a list on attributes or methods of objects than relying on lamda functions?</p>
<pre><code>contexts_to_display = ...
tasks = Task.objects.all()
tasks = filter(lambda t: t.matches_contexts(contexts_to_display), tasks)
tasks = filter(lambda t: not t.is_future(), tasks)
tasks = sorted(tasks, Task.compare_by_due_date)
</code></pre>
<p>Here, <code>matches_contexts</code> and <code>is_future</code> are methods of <code>Task</code>. Should I make those free-functions to be able to use <code>filter(is_future, tasks)</code>?</p>
<p>Any other comment?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T22:49:25.317",
"Id": "889",
"Score": "3",
"body": "I think this is too specific a question to qualify as a code review."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T16:47:05.750",
"Id": "1319",
"Score": "0",
"body": "Are you coding Django? Looks like it from the `Task.objects.all()` line."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-10T17:03:39.870",
"Id": "1320",
"Score": "0",
"body": "That's part of the Django app I'm writing to learn both Python and Django, yes..."
}
] | [
{
"body": "<p>I think lambdas are fine in this case. (Yeah, not much of a code review, but what can I say... You basically ask a yes/no question. Answer: \"No\". :) )</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T00:10:29.493",
"Id": "537",
"ParentId": "533",
"Score": "2"
}
},
{
"body": "<p>The first lambda (calling <code>matches_contexts</code>) can't be avoided because it has to capture the <code>contexts_to_display</code>, but the <code>not is_future()</code> can be moved into a new <code>Task</code> method <code>can_start_now</code>: it's clearer (hiding the negative conditions), reusable, and this condition will most probably be more complicated in the future. Yes, <a href=\"http://en.wikipedia.org/wiki/You_ain%27t_gonna_need_it\" rel=\"nofollow\">YAGNI</a>, I know... ;)</p>\n\n<p>And because I did not need the sorting phase to return a copy of <code>tasks</code>, I used in-place sort. By the way, the arguments are reversed between <code>filter(f,iterable)</code> and <code>sorted(iterable,f)</code>, using one just after the other seemed akward...</p>\n\n<p>So the code is now:</p>\n\n<pre><code>class Task:\n ...\n def can_start_now(self):\n return not self.is_future()\n\n\ncontexts_to_display = ...\ntasks = Task.objects.all()\ntasks = filter(lambda t: t.matches_contexts(contexts_to_display), tasks)\ntasks = filter(Task.can_start_now, tasks)\ntasks.sort(Task.compare_by_due_date)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T08:53:18.163",
"Id": "545",
"ParentId": "533",
"Score": "0"
}
},
{
"body": "<p>I would use a list comprehension:</p>\n\n<pre><code>contexts_to_display = ...\ntasks = [t for t in Task.objects.all()\n if t.matches_contexts(contexts_to_display)\n if not t.is_future()]\ntasks.sort(cmp=Task.compare_by_due_date)\n</code></pre>\n\n<p>Since you already have a list, I see no reason not to sort it directly, and that simplifies the code a bit.</p>\n\n<p>The cmp keyword parameter is more of a reminder that this is 2.x code and will need to be changed to use a key in 3.x (but you can start using a key now, too):</p>\n\n<pre><code>import operator\ntasks.sort(key=operator.attrgetter(\"due_date\"))\n# or\ntasks.sort(key=lambda t: t.due_date)\n</code></pre>\n\n<p>You can combine the comprehension and sort, but this is probably less readable:</p>\n\n<pre><code>tasks = sorted((t for t in Task.objects.all()\n if t.matches_contexts(contexts_to_display)\n if not t.is_future()),\n cmp=Task.compare_by_due_date)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:20:22.993",
"Id": "966",
"Score": "0",
"body": "Thanks for the tip about list comprehension! As `compare_by_due_date` specifically handles null values for the due date, I'm not sure I can use a key. But I'll find out!"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:24:03.433",
"Id": "969",
"Score": "0",
"body": "@XavierNodet: Anything which can be compared by a cmp parameter can be converted (even if tediously) to a key by simply wrapping it. With my use of the \"due_date\" attribute, I'm making some assumptions on how compare_by_due_date works, but if you give the code for compare_by_due_date (possibly in a SO question?), I'll try my hand at writing a key replacement for it."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T20:00:57.003",
"Id": "977",
"Score": "0",
"body": "Thanks! SO question is here: http://stackoverflow.com/q/4879228/4177"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T11:44:09.317",
"Id": "547",
"ParentId": "533",
"Score": "7"
}
},
{
"body": "<p>Since you are writing Django code, you don't need lambdas at all (explanation below). In other Python code, you might want to use list comprehensions, as other commenters have mentioned. <code>lambda</code>s are a powerful concept, but they are extremely crippled in Python, so you are better off with loops and comprehensions.</p>\n\n<p>Now to the Django corrections.</p>\n\n<pre><code>tasks = Task.objects.all()\n</code></pre>\n\n<p><code>tasks</code> is a <code>QuerySet</code>. <code>QuerySet</code>s are lazy-evaluated, i.e. the actual SQL to the database is deferred to the latest possible time. Since you are using lambdas, you actually force Django to do an expensive <code>SELECT * FROM ...</code> and filter everything manually and in-memory, instead of letting the database do its work.</p>\n\n<pre><code>contexts_to_display = ...\n</code></pre>\n\n<p>If those contexts are Django model instances, then you can be more efficient with the queries and fields instead of separate methods:</p>\n\n<pre><code># tasks = Task.objects.all()\n# tasks = filter(lambda t: t.matches_contexts(contexts_to_display), tasks) \n# tasks = filter(lambda t: not t.is_future(), tasks)\n# tasks = sorted(tasks, Task.compare_by_due_date)\nqs = Task.objects.filter(contexts__in=contexts_to_display, date__gt=datetime.date.today()).order_by(due_date)\ntasks = list(qs)\n</code></pre>\n\n<p>The last line will cause Django to actually evaluate the <code>QuerySet</code> and thus send the SQL to the database. Therefore you might as well want to return <code>qs</code> instead of <code>tasks</code> and iterate over it in your template.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T14:25:55.053",
"Id": "1360",
"Score": "0",
"body": "`Context` is indeed a model class, but tasks may have no context, and I want to be able to retrieve the set of all tasks that 'have a given context or no context'. But `context__in=[c,None]` does not work... Maybe 'no context' should actually be an instance of Context..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T14:26:45.067",
"Id": "1361",
"Score": "0",
"body": "Similarly, the date may be null, so I can't simply filter or order on the date..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-11T10:40:35.640",
"Id": "743",
"ParentId": "533",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "547",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-01T22:44:01.423",
"Id": "533",
"Score": "1",
"Tags": [
"python"
],
"Title": "Is there a better way than lambda to filter on attributes/methods of objects?"
} | 533 |
<p>I've written an abstract class in C# for the purpose of random number generation from an array of bytes. The .NET class <code>RNGCryptoServiceProvider</code> can be used to generate this array of random bytes, for example.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyLibrary
{
/// <summary>
/// Represents the abstract base class for a random number generator.
/// </summary>
public abstract class Rng
{
/// <summary>
/// Initializes a new instance of the <see cref="Rng"/> class.
/// </summary>
public Rng()
{
//
}
public Int16 GetInt16(Int16 min, Int16 max)
{
return (Int16)(min + (Int16)(GetDouble() * (max - min)));
}
public Int32 GetInt32(Int32 min, Int32 max)
{
return (Int32)(min + (Int32)(GetDouble() * (max - min)));
}
public Int64 GetInt64(Int64 min, Int64 max)
{
return (Int64)(min + (Int64)(GetDouble() * (max - min)));
}
public UInt16 GetUInt16(UInt16 min, UInt16 max)
{
return (UInt16)(min + (UInt16)(GetDouble() * (max - min)));
}
public UInt32 GetUInt32(UInt32 min, UInt32 max)
{
return (UInt32)(min + (UInt32)(GetDouble() * (max - min)));
}
public UInt64 GetUInt64(UInt64 min, UInt64 max)
{
return (UInt64)(min + (UInt64)(GetDouble() * (max - min)));
}
public Single GetSingle()
{
return (Single)GetUInt64() / UInt64.MaxValue;
}
public Double GetDouble()
{
return (Double)GetUInt64() / UInt64.MaxValue;
}
public Int16 GetInt16()
{
return BitConverter.ToInt16(GetBytes(2), 0);
}
public Int32 GetInt32()
{
return BitConverter.ToInt32(GetBytes(4), 0);
}
public Int64 GetInt64()
{
return BitConverter.ToInt64(GetBytes(8), 0);
}
public UInt16 GetUInt16()
{
return BitConverter.ToUInt16(GetBytes(2), 0);
}
public UInt32 GetUInt32()
{
return BitConverter.ToUInt32(GetBytes(4), 0);
}
public UInt64 GetUInt64()
{
return BitConverter.ToUInt64(GetBytes(8), 0);
}
/// <summary>
/// Generates random bytes of the specified length.
/// </summary>
/// <param name="count">The number of bytes to generate.</param>
/// <returns>The randomly generated bytes.</returns>
public abstract byte[] GetBytes(int count);
}
}
</code></pre>
<p>Any suggestions for improvements would be welcome.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T00:50:00.677",
"Id": "899",
"Score": "0",
"body": "What is the purpose of the interdependent get() methods?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T00:59:42.587",
"Id": "900",
"Score": "0",
"body": "@Michael: The overloads with `min`/`max` params require floating-point random numbers. They in turn require integral random numbers to generate. (I see no other way, since `BitConverter.GetDouble` would skew the distribution.)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T08:03:56.680",
"Id": "908",
"Score": "0",
"body": "Are you doing this as an exercise? The built-in random number generator already has this kind of functionality. So if this is just an exercise in interface design it can be reviewed. If this is a real attempt at providing a random number interface I think you have some more explaining to do before anybody can really provide any decent feedback. Note: Random number generation done correctly is a lot harder than you would think (i.e. it is very easy to screw up and get a bad distribution)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T10:10:45.383",
"Id": "913",
"Score": "0",
"body": "I would add a comment to `Get...` methods regarding min/max parameters, whether these values are inclusive or exclusive. It was never obvious for me in `System.Random` class."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T12:40:27.490",
"Id": "923",
"Score": "0",
"body": "@Snowbear: Yeah, I've added comments to my local version of the code. Will update soon. :)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T12:42:35.287",
"Id": "924",
"Score": "1",
"body": "@Martin York: The whole point of this is to provide an abstract contract for RNGs. `System.Random` does indeed provide this sort of functionality, but it is specific to an internal PNG (that has poor entropy). The idea is that implementations can derive from this class to implement specific RNG algorithms like the CSP one (RNGCryptoServiceProvider), Mersenne Twister, etc., simply by providing a generator for random bytes. The code above says nothing as to the random bytes are generates."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:20:25.803",
"Id": "929",
"Score": "0",
"body": "@Snowbear: the terms \"minimum\" and \"maximum\" are implicitly inclusive by the definition of the words. That said, it's never bad to add documentation and, to be fair, the word \"between\" can imply inclusive or exclusive behavior which can confuse the situation. Not that everyone does so, but from the English language perspective in general min/max should only be used for inclusive behavior. The previously more common terms \"upper bound\" and \"lower bound\" are more appropriate for varying exclusivity."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:39:14.877",
"Id": "932",
"Score": "0",
"body": "@TheXenocide: Thanks for your opinion, for me also min and max should be inclusive numbers. But MS has own opinion: http://msdn.microsoft.com/en-us/library/2dx6wyd4.aspx - that is why I've added my comment."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:40:50.787",
"Id": "933",
"Score": "1",
"body": "@TheXenocide: Also looking on this code I suppose `maximum` is exclusive here ;)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:25:06.677",
"Id": "970",
"Score": "0",
"body": "Interestingly, I've come across the *Math.NET Numerics* library after having posted this question, which seems to have a pretty nice abstract implementation of an RNG class. (Though not quite as complete, it looks sufficient.) It also includes a range of probability distribution sampling methods, which is very nice."
}
] | [
{
"body": "<p>If you're planning on placing this in a reusable library you should validate inputs (min > max throws an IndexOutOfRangeException, etc.) Also, you do not need to cast to double in the GetDouble method as the division implicitly returns a double and casting the first operand of the division in GetSingle still causes the division to return a double though you may be sacrificing some precision in the randomness as a result of sacrificing 32bits before you divide. </p>\n\n<p>Otherwise the code does seems as though it would be sufficient. Depending on the scope of your solution perhaps you want to consider min/max overloads for GetSingle and GetDouble and if you're really looking to be special maybe support for System.Numerics.BigInteger and System.Decimal?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:37:46.000",
"Id": "931",
"Score": "1",
"body": "Just thought of this one, and it's no biggie really, but perhaps you want to provide a virtual void GetBytes(byte[] buffer, int offset, int length) with a default implementation. It's a very common pattern in code that uses byte arrays and implementations may leverage their underlying APIs to make this more efficient (no unnecessary allocation/GC, no need for them to copy data from one array to another, etc)"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:22:59.517",
"Id": "968",
"Score": "0",
"body": "@TheXenoicde: Your points are all good ones I think. I should indeed be throwing `ArgumentExceptions`s, and that overload for `GetBytes` would probably be handy too. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:11:14.490",
"Id": "548",
"ParentId": "538",
"Score": "3"
}
},
{
"body": "<p>I think the design is pretty good. A few comments:</p>\n\n<ul>\n<li><p>I'd rename the class to something a bit more descriptive, say <code>RandomGenerator</code>. Then when you implement the class you can declare it with <code>CspGenerator: RandomGenerator</code> or <code>MersenneGenerator: RandomGenerator</code> and it's obvious what the class does.</p></li>\n<li><p>Comment the <code>get()</code> methods. IMO all public elements should be documented. Get/set could be left out, but that is a matter of preference. In particular I'd like to know what kind of range <code>min</code> anf <code>max</code> is and is used for.</p></li>\n<li><p>Is <code>getBytes()</code> needed externally? If not, I would consider making it class-level rather than public.</p></li>\n</ul>\n\n<p>The formatting is good - even in Visual Studio I've seen it get messed up as code is refactored and changed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:32:45.337",
"Id": "930",
"Score": "1",
"body": "I concur with the class rename. Comments are always good and especially in reusable libraries, though I personally tend to forget to mention them when reviewing code, lol. Generally GetBytes is publicly available on random number generators."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:49:57.367",
"Id": "952",
"Score": "0",
"body": "I think “Rng” is one of the very few cases where an abbreviation can actually be safely used (this may not be such a commending reference but the .NET framework *does* use it, after all)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:21:51.423",
"Id": "967",
"Score": "0",
"body": "Thanks for the answer. I agree with commenting the `Get` methods; in fact I did that some time after I posted this. :) You may have a point about the name, but like Konrad Rudolph I believe that RNG is a very common/understandable acronym. I wasn't sure about the modifier for `GetBytes` either, but I can foresee potential usage cases, so it doesn't hurt to expose it."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:40:02.780",
"Id": "971",
"Score": "2",
"body": "I think `GetBytes` is useful as a public method, for tasks too numerous to list (e.g. generating a key of some length, fuzz testing etc.)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:16:44.113",
"Id": "550",
"ParentId": "538",
"Score": "8"
}
},
{
"body": "<p>I think using <code>GetDouble</code> to generate the other random numbers can create performance problems when the user needs efficient random numbers.</p>\n\n<p>Since <code>GetBytes</code> should return a uniform distribution anyway, can’t you bypass using floating-point numbers? See e.g. Java’s <a href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/util/Random.html#nextInt%28int%29\"><code>Random.nextInt</code> implementation</a>.</p>\n\n<p>Something else, but this may be unnecessary and YAGNI for you: have you considered decoupling the RNG from the probability density function? At the moment your RNG directly supports generating uniformly distributed numbers from within a given range – but it supports no other distributions. This could be off-loaded into a separate <code>Distribution</code> class. For reference, <a href=\"http://www.boost.org/doc/libs/1_45_0/doc/html/boost_random/reference.html#boost_random.reference.distributions\">Boost.Random</a> does just that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:19:57.507",
"Id": "965",
"Score": "0",
"body": "Ah yes, good point about the implementation for ranges. For some reason using the modulo operator did not occur to me! Regarding distributions, random numbers have to be generated according to *some* distribution to start - uniform is as good (and simpler) than any other."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T19:42:19.340",
"Id": "976",
"Score": "0",
"body": "@Noldorin: re distribution: of course. I was merely stating that this assumption existed anyway, so it could as well be used to generate the ranges. But in fact such a distribution shouldn’t be taken as granted. For example, LCGs exhibit different weaknesses (such as repeating lower bits, or unevenly distributed upper bits) so using either modulo or division must take that into account. The Java implementation does, but then it knows what kind of weakness the generated bytes have. [Wikipedia](http://bit.ly/59nzh) has details (“Parameters in common use” table)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T17:14:04.367",
"Id": "1019",
"Score": "0",
"body": "@Noldorin, it's not just performance: it's uniformity of distribution, which becomes a lot harder to guarantee once doubles get involved. I agree with using something à la Java's nextInt(int n). Note in particular that nextInt calculates, effectively (1<<32)%n and uses it to avoid slight bias in favour of numbers smaller than that."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-04T00:21:19.240",
"Id": "1053",
"Score": "0",
"body": "@Peter: Well yes, indeed. Funnily, I think the above code is how `System.Random` does it (haven't checked Reflector with it though). I agree though, it's not ideal, and could potentially introduce skew."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:46:57.683",
"Id": "557",
"ParentId": "538",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "550",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T00:39:38.673",
"Id": "538",
"Score": "12",
"Tags": [
"c#",
"random"
],
"Title": "Random Number Generator Class"
} | 538 |
<p>I have a small 10-liner function that writes some data to a file using an <code>std::ofstream</code>. I did not explicitly call <code>.close()</code> at the end of my function, but it failed code review with the reason that it is better to explicitly call it for style and verbosity reasons. I understand there is no harm in calling <code>.close()</code> explicitly, but does calling it explicitly just before a <code>return</code> statement indicate a lack of understanding or faith in RAII?</p>
<p>The C++ standard says:</p>
<blockquote>
<p>§27.8.1.2</p>
<p><code>virtual ~ basic_filebuf ();</code></p>
<p>[3] Effects: Destroys an object of <code>class basic_filebuf<charT,traits></code>. Calls <code>close()</code>.</p>
</blockquote>
<p>Am I justified in my argument that calling <code>.close()</code> at the end of a function is redundant and/or unnecessary?</p>
<pre><code>bool SomeClass::saveData()
{
std::ofstream saveFile(m_filename);
if (!saveFile.is_open())
return false;
saveFile << m_member1 << std::endl;
saveFile << m_member2 << std::endl;
saveFile.close(); // passed review only with this line
return true;
}
</code></pre>
<p>The function is only supposed to return <code>false</code> if the file could not be opened for writing.</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T11:33:17.797",
"Id": "920",
"Score": "7",
"body": "If the reviewers need reassurance that close is called automatically, then C++ is probably not the best language choice. The \"verbosity\" reason is particularly alarming."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:16:24.613",
"Id": "927",
"Score": "2",
"body": "“it failed code review with the reason that it is better to explicitly call it for … *verbosity reasons* ” – Please explain that last bit, it doesn’t make any sense."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:11:20.037",
"Id": "944",
"Score": "0",
"body": "Obviously your reviewers' style conflict with the _standard_ design of the _standard_ library."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T02:34:48.173",
"Id": "990",
"Score": "3",
"body": "@Konrad: By verbosity, I mean that we are closing the file even knowing it will be closed anyway in the destructor, because it shows that we know we are done with it. In some instances, we have files open for a long time; so we have a rule that we close every stream explicitly."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T07:16:48.790",
"Id": "999",
"Score": "0",
"body": "Was this requirement added because *the other instance* had caused a bug which wasn't caught by the code review?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T08:21:31.080",
"Id": "1004",
"Score": "1",
"body": "@dreamlax: but how is verbosity ever an *advantage*? I agree that *explicitness* may be, and that this sometimes entails verbosity – but this is always a trade-off between the two. I have never seen a situation where verbosity would be an advantage in itself. That’s what I meant by “it doesn’t make any sense”."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T08:45:14.063",
"Id": "1006",
"Score": "0",
"body": "@rwong: I would imagine so. The question is, why is the variable lingering around when the stream is no longer needed? The scope of the variable should be limited, in my opinion, to represent more-or-less the timeframe of an open file. If the stream variable is lingering, it is probably more an indication that the function is far too long."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T08:51:58.613",
"Id": "1007",
"Score": "0",
"body": "@Konrad: I guess in some situations it is better to \"spell things out in full\" than to use more concise versions. For example, a few lines of nicely written code is often better than a clever-yet-esoteric one-liner. The rule is not so applicable in this particular case, however, and instead I think the actual reason is for explicitness."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T12:56:40.587",
"Id": "1011",
"Score": "0",
"body": "@dreamlax: \"because it shows that we know we are done with it\" .. I think it can be a good enough reason then. It also force you to think about when you are done with it. Maybe majority of the time it is not a concern but sometimes maybe it matter. What is your industry? I agree with the commenter that said this question would be better on SO though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-22T16:40:29.420",
"Id": "364928",
"Score": "0",
"body": "I [changed the title](/q/540/revisions) so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Feel free to give it a different title if there is something more appropriate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-22T16:48:15.470",
"Id": "364929",
"Score": "0",
"body": "I believe your reviewers are wrong, but not for the reason you think. If the return value is supposed to be true for success, then it should return false if *any* of the file operations fail, not just the constructor. I've answered accordingly."
}
] | [
{
"body": "<p>I'm torn on this one. You are absolutely correct. However if a coding standard requires calling close() explicitly or it's a group people's consensus of doing that, there's not much you can do. If I were you, I would just go with the flow. Arguing such things is unproductive.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T07:57:25.050",
"Id": "907",
"Score": "9",
"body": "The problem with small group consensus (i.e. development teams). It can often be wrong because the group is swayed by the loudest voice. For group consensus to work the group has to be large enough so that loud individuals can be counteracted by the correct decision of a lot of people (this is why SO works (loud people may get an initial vote up but eventually the correct answer usually get the votes (eventually)))."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T00:32:11.217",
"Id": "985",
"Score": "1",
"body": "@Martin: Nice nested parenthesis."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T13:51:15.383",
"Id": "6837",
"Score": "0",
"body": "@grokus I agree with Tux-D's sentiment. But, I don't believe in design/review by committee. If someone has the power to dictate these types of standards, they need to be shown another way or proven incorrect. The strategy for this will completely depend on the individual. The only thing that is going to happen in large meetings is arguing, and eventual increase in volume unti a mediator steps in and makes the decision for you. The best response to this is to construct an app in which .close() is called and throws. Show it kills the app. Then give them a choice, handle all errors or use RAII."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T04:22:11.317",
"Id": "541",
"ParentId": "540",
"Score": "10"
}
},
{
"body": "<p>Assuming that the fstream object is local to the function, I <em>would</em> tend to argue against this. People need to become accustomed to letting RAII do its job, and closing an fstream object falls under that heading. Extra code that doesn't accomplish something useful is <em>almost</em> always a poor idea.</p>\n\n<p><strong>Edit:</strong> Lest I be misunderstood, I would argue against this, not only for this specific case, but in general. It's not merely useless, but tends to obscure what's needed, and (worst of all) is essentially impossible to enforce in any case -- people who think only in terms of the \"normal\" exit from the function really need to stop and realize that the minute they added exception handling to C++, the rules changed in a fundamental way. You <em>need</em> to think in terms of RAII (or something similar) that <em>ensures</em> cleanup on exit from scope -- and explicitly closing files, releasing memory, etc., does <em>not</em> qualify.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T05:24:11.147",
"Id": "904",
"Score": "0",
"body": "Sorry, your assumption is correct, I forgot to mention that the fstream is local to the function."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T06:41:34.280",
"Id": "906",
"Score": "0",
"body": "I feel a little bit like asking \"what's the point in having destructors if we're doing the work manually...\" but I know it won't go far. I put the explicit call in just to satisfy the code review but I felt extremely reluctant."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T08:09:29.950",
"Id": "909",
"Score": "0",
"body": "@dreamlax: Its to give you flexibility. In most cases you don't care if the close() works or not (there is nothing you can do about it (except log the information)) so the destructor works perfectly. But in the situations were you do care you have the option of calling close() manually and checking to see if the close worked (and if not sending that 2AM SMS to support telling them the file system is down and needs immediate replacement)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T10:54:57.773",
"Id": "917",
"Score": "0",
"body": "re. Exceptions: The next (il)logical step is to put a try/catch construct in so that the unnecessary 'close()' function still gets called if an exception is throw...."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T02:54:26.020",
"Id": "991",
"Score": "0",
"body": "One reason that the project manager gave was that under stressed conditions where file handles are scarce, we need to close files as soon as we're done with them. By creating a rule that you close every stream, regardless of how trivial the function, you force the developer to think about the lifetime of the object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T13:46:34.890",
"Id": "6835",
"Score": "0",
"body": "@dreamlax This is why development organisations should prove a legitimate need to use C++ before starting. It is not a language an average team can utilize correctly. Hopefully you were able to stick your ground and convince them that RAII is a real concept in c++, which is where I think the bad code review is stemming from."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-02T04:52:45.043",
"Id": "542",
"ParentId": "540",
"Score": "41"
}
},
{
"body": "<h2>I would argue the exact opposite.</h2>\n\n<p>Explicitly closing a stream is probably not what you want to do. This is because when you <code>close()</code> the stream there is the potential for exceptions to be thrown. Thus when you explicitly close a file stream it is an indication you both want to close the stream and explicitly handle any errors that can result (exceptions or bad-bits) from the closing of the stream (or potentially you are saying if this fails I want to fail fast (exception being allowed to kill the application)).</p>\n\n<p>If you don't care about the errors (ie you are not going to handle them anyway). You should just let the destructor do the closing. This is because the destructor will catch and discard any exceptions thus allowing code to flow normally. When dealing with the closing of a file this is what you normally want to do (if the closing fails does it matter?).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T10:40:12.933",
"Id": "916",
"Score": "2",
"body": "\"if the closing fails does it matter?\" For output streams, I think it probably does, as the output may be buffered until the call to close()."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:17:36.250",
"Id": "928",
"Score": "2",
"body": "@Roddy: but you can’t do anything to stop this from failing. It may matter to report this failure, but no other meaningful action can be taken."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T15:11:55.360",
"Id": "938",
"Score": "4",
"body": "@Konrad. Agree you can't stop it failing (but that's true with many exceptions). If the user selects \"Save...\" in a GUI app, and close() throws, then notifying the user and allowing him to re-try the save (maybe to a different volume) is probably very meaningful..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T15:16:20.333",
"Id": "940",
"Score": "0",
"body": "@Roddy: granted. But something different: does this error actually occur? I can’t remember ever seeing something like that (except when you prematurely plug off a USB drive etc. …)."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T15:57:26.103",
"Id": "942",
"Score": "0",
"body": "@Konrad. Well, I guess hardware problems, filesystem corruptions or, network problems, for that matter are the only obvious ones it. But, isn't that also the case with writing to a fstream? I'd still *consider* what would happen with exceptions while writing, even if I decide not to catch them."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:07:18.370",
"Id": "943",
"Score": "0",
"body": "@Konrad I guess that's why they're called _exceptions_"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:11:44.390",
"Id": "945",
"Score": "0",
"body": "@kizzx: No it’s not. What has this got to do with anything?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:17:40.233",
"Id": "946",
"Score": "0",
"body": "@Konrad: I thought you were responding to \"If the user selects \"Save...\" in a GUI app, and close() throws,\" I just assumed \"throws\" means \"throws exception\", no?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:33:27.880",
"Id": "948",
"Score": "0",
"body": "@kizz: yes. So what?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T17:19:57.327",
"Id": "954",
"Score": "2",
"body": "@Roddy: Of course there are times when it does matter and you want ot report it (GUI applications). then you would use close() explicitly and check the error. Weather you care or not is totally situational and only the dev can decide that at the point of usage. In the above example it does not sound like any checking was done and thus they did not care."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-02T07:51:25.353",
"Id": "544",
"ParentId": "540",
"Score": "74"
}
},
{
"body": "<p>There is a middle ground here. The reason the reviewers want that explicit <code>close()</code> \"as a matter of style and verbosity\" is that without it they can't tell just from reading the code if you meant to do it that way, or if you completely forgot about it and just got lucky. It's also possible their egos were bruised from failing to notice or remember, at least at first, that <code>close()</code> would be called by the destructor. Adding a comment that the destructor calls <code>close()</code> isn't a bad idea. It's a little gratuitous, but if your coworkers need clarification and/or reassurance now, there's a good chance a random maintainer a few years down the road will too, especially if your team doesn't do a lot of file I/O.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T16:28:04.193",
"Id": "73537",
"Score": "0",
"body": "There shouldn't be any \"just got lucky\" w.r.t. resources in C++. There should be \"just works\". That's how RAII is designed, and how it works when used properly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-25T22:30:00.287",
"Id": "79072",
"Score": "5",
"body": "I disagree. This is C++, if you need a comment reminding you that an fstream will close on its own, then you're not a C++ programmer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T11:29:32.820",
"Id": "546",
"ParentId": "540",
"Score": "19"
}
},
{
"body": "<p>I believe you are asking two questions in one. Should you use exceptions or return values? Should you use RAII or not?</p>\n\n<p><strong>If exceptions are not permitted in your company</strong>, then <code>fstream::exceptions()</code> must be set globally for your project. And you have to interrogate the error flag too.</p>\n\n<p><strong>If RAII is not permitted in your company</strong>, then do not use C++. If you use RAII, then any exception thrown in the destructor will be swallowed. This sounds terrible and it is. However I agree with others that RAII is the way to go also because any error handling here is futile and creates unreadable code. This is because \"flush\" does not do what you may think it does. It instructs the operating system to do it on your behalf. The OS will do it when it believes it is convenient. Then, when the operating flushes (which may be a minute after your function returns) similar things may happen at the hardware level. The disk may have an SSD cache which it flushes to the rotating disks later (which may happen at night when it is less busy). At last the data ends on the disk. But the story does not end here. The data may have been saved correctly but the disk gets destroyed by whichever of the many possible causes. Hence if RAII is not transactionally safe enough for you, then you need to go to a lower API level anyway and even that will not be perfect. Sorry for being a party pooper here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T15:41:04.963",
"Id": "33181",
"ParentId": "540",
"Score": "7"
}
},
{
"body": "<p>I agree with Loki's answer: the difference between calling close explicitly, and letting the destructor call close, is that the destructor will implicitly catch (i.e. conceal) any exception thrown by close.</p>\n\n<p>The destructor must do this (not propagate exceptions) because it may be called if/while there is an exception already being thrown; and throwing a 2nd exception during a 1st exception is fatal (therefore, all destructors should avoid throwing exceptions).</p>\n\n<p>Unlike Loki I would argue that you do want to call close explicitly, precisely because you do want any exception from close to be visible. For example, perhaps the data is important and you want it written to disk; perhaps the disk is full, the <code><<</code> output operator is written to in-memory cache, and no-one notices that the disk is full until close implicitly calls flush. You're not allowed to return false because false is defined as meaning that the file couldn't be opened. IMO the only sane/safe thing you can do, then, is throw an exception.</p>\n\n<p>It's up to the caller to catch any exception; having no exception thrown should be a guarantee that close was successful and the data safely written to the O/S.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:28:59.447",
"Id": "43458",
"ParentId": "540",
"Score": "11"
}
},
{
"body": "<p>You also need to check that the write operations (<code><<</code>) succeeded. So instead of checking <code>is_open()</code>, just go through the whole series of operations, and check <code>failbit</code> at the end:</p>\n\n<pre><code>bool save_data() const\n{\n std::ofstream saveFile(m_filename);\n\n saveFile << m_member1 << '\\n'\n << m_member2 << '\\n';\n\n saveFile.close(); // may set failbit\n\n return saveFile;\n}\n</code></pre>\n\n<p>Also, unless there's a pressing need to flush each line as it's written, prefer to use <code>'\\n'</code> rather than <code>std::endl</code> (as I've shown), and let <code>close()</code> write it all in one go - that can make a significant difference to the speed, particularly when there's a large number of lines to be written.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-14T10:51:37.323",
"Id": "187548",
"ParentId": "540",
"Score": "3"
}
},
{
"body": "<p>After reading through the question and the answers I came to the conclusion that this is were comments can come into play. I had recently read this Q/A <a href=\"https://codereview.stackexchange.com/questions/90111/guessing-a-number-but-comments-concerning\">Guessing a number, but comments concerning</a> and the accepted answer gave me insight to the situation here. Use comments to explain the why, let the code explain the how. I can use your function similarly for each case as an example:</p>\n\n<pre><code>bool SomeClass::saveData() {\n std::ofstream saveFile(m_filename);\n\n if (!saveFile.is_open())\n return false;\n\n saveFile << m_member1 << std::endl; // I would replace `endl` with `'\\n'`\n saveFile << m_member2 << std::endl; // for performance reasons. \n\n // I intentionally want to close the file before the closing scope to\n // free up limited resources and to log potential exceptions and errors. \n saveFile.close(); \n return true;\n} \n\nbool SomeClass::saveData() {\n std::ofstream saveFile(m_filename);\n\n if (!saveFile.is_open())\n return false;\n\n saveFile << m_member1 << std::endl; // I would replace `endl` with `'\\n'`\n saveFile << m_member2 << std::endl; // for performance reasons. \n\n // Resources and errors are not a concern: relying on RAII no need\n // to call file.close();\n return true;\n}\n</code></pre>\n\n<p>Then with the appropriate type of commenting for valid reasons might serve you well. Then at least this way; one would know that you intended to call or omit it and why! Well written code is the how and shouldn't need comments. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-22T12:06:17.277",
"Id": "190196",
"ParentId": "540",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "544",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-02T04:00:41.190",
"Id": "540",
"Score": "70",
"Tags": [
"c++",
"stream",
"raii"
],
"Title": "Open, write and close a file"
} | 540 |
<p>How does this class to resize an image look?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Web;
using System.Drawing;
using System.IO;
/*
* Resizes an image
**/
public static class ImageResizer
{
// Saves the image to specific location, save location includes filename
private static void saveImageToLocation(Image theImage, string saveLocation)
{
// Strip the file from the end of the dir
string saveFolder = Path.GetDirectoryName(saveLocation);
if (!Directory.Exists(saveFolder))
{
Directory.CreateDirectory(saveFolder);
}
// Save to disk
theImage.Save(saveLocation);
}
// Resizes the image and saves it to disk. Save as property is full path including file extension
public static void resizeImageAndSave(Image ImageToResize, int newWidth, int maxHeight, bool onlyResizeIfWider, string thumbnailSaveAs)
{
Image thumbnail = resizeImage(ImageToResize, newWidth, maxHeight, onlyResizeIfWider);
thumbnail.Save(thumbnailSaveAs);
}
// Overload if filepath is passed in
public static void resizeImageAndSave(string imageLocation, int newWidth, int maxHeight, bool onlyResizeIfWider, string thumbnailSaveAs)
{
Image loadedImage = Image.FromFile(imageLocation);
Image thumbnail = resizeImage(loadedImage, newWidth, maxHeight, onlyResizeIfWider);
saveImageToLocation(thumbnail, thumbnailSaveAs);
}
// Returns the thumbnail image when an image object is passed in
public static Image resizeImage(Image ImageToResize, int newWidth, int maxHeight, bool onlyResizeIfWider)
{
// Prevent using images internal thumbnail
ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
// Set new width if in bounds
if (onlyResizeIfWider)
{
if (ImageToResize.Width <= newWidth)
{
newWidth = ImageToResize.Width;
}
}
// Calculate new height
int newHeight = ImageToResize.Height * newWidth / ImageToResize.Width;
if (newHeight > maxHeight)
{
// Resize with height instead
newWidth = ImageToResize.Width * maxHeight / ImageToResize.Height;
newHeight = maxHeight;
}
// Create the new image
Image resizedImage = ImageToResize.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
// Clear handle to original file so that we can overwrite it if necessary
ImageToResize.Dispose();
return resizedImage;
}
// Overload if file path is passed in instead
public static Image resizeImage(string imageLocation, int newWidth, int maxHeight, bool onlyResizeIfWider)
{
Image loadedImage = Image.FromFile(imageLocation);
return resizeImage(loadedImage, newWidth, maxHeight, onlyResizeIfWider);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:46:29.657",
"Id": "935",
"Score": "3",
"body": "PascalCase on the methods...since you stated no matter how nitty..."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:47:07.283",
"Id": "936",
"Score": "0",
"body": "Thanks, yeah I need to work on my naming convention for sure, I'm just so used to leading lower"
}
] | [
{
"body": "<p><a href=\"http://c2.com/cgi/wiki?PascalCase\">PascalCase</a> the method names and method params if you are feeling overly ambitious.</p>\n\n<pre><code> // Set new width if in bounds\n if (onlyResizeIfWider)\n {\n if (ImageToResize.Width <= newWidth)\n {\n newWidth = ImageToResize.Width;\n }\n }\n</code></pre>\n\n<p>FindBugs barks in Java for the above behavior... refactor into a single if since you are not doing anything within the first if anyways...</p>\n\n<pre><code> // Set new width if in bounds\n if (onlyResizeIfWider && ImageToResize.Width <= newWidth)\n {\n newWidth = ImageToResize.Width;\n }\n</code></pre>\n\n<p>Comments here could be a bit more descriptive; while you state what the end result is I am still lost as to why that would resolve the issue.</p>\n\n<pre><code> // Prevent using images internal thumbnail\n ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);\n ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); \n</code></pre>\n\n<p>Maybe something similar to what is stated on <a href=\"http://smartdev.wordpress.com/2009/04/09/generate-image-thumbnails-using-aspnetc/\">this blog</a>...</p>\n\n<pre><code> // Prevent using images internal thumbnail since we scale above 200px; flipping\n // the image twice we get a new image identical to the original one but without the \n // embedded thumbnail\n ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);\n ImageToResize.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T15:14:41.697",
"Id": "939",
"Score": "1",
"body": "I wouldn't recommend pascal casing parameters even in an ambitious scenario as I've never once seen it in any common commercial or BCL code and the purpose of class and variable/param casing being different is to identify definitions from declarations. Due to compiler optimizations and condition short-circuiting both variations of the \"if (onlyResize...\" will evaluate to the same native code so, while I hold the same opinion on combining them, there are circumstances where readability or comparison to requirements may benefit and there's no harm either way."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T15:09:08.827",
"Id": "552",
"ParentId": "549",
"Score": "12"
}
},
{
"body": "<p>In C# it's generally common practice to use Pascal Case in method names (so SaveImageToLocation instead of saveImageToLocation) and Camel Case in parameter names (so \"public static Image ResizeImage(Image imageToResize, ...\")</p>\n\n<p>RotateFlip can be a rather expensive operation just to clear an internal thumbnail. As far as the images are concerned, do you need to support vector images or will this generally be used for Bitmap (rasterized) images (this includes compressed variations like png, jpg, gif, etc.)? If you only plan to output Bitmaps then I suggest using the <a href=\"http://msdn.microsoft.com/en-us/library/334ey5b7\" rel=\"nofollow noreferrer\">Bitmap(Image original, int width, int height)</a> constructor which will take a source image and scale it, removing the need to do costly rotations. There are a number of methods to draw scaled images, some of which are much more efficient than others and each have varying pros and cons to using them, but the biggest advantage to GetThumbnailImage is use of embedded thumbnails.</p>\n\n<p>It is generally not good practice to dispose of a parameter so it may warrant a different pattern (returning an image and letting the calling code call image.Save(filename) at its own discretion isn't that terrible), but if you intend to leave it this way you should definitely comment it. Refer to <a href=\"https://stackoverflow.com/questions/788335/why-does-image-fromfile-keep-a-file-handle-open-sometimes\">this post</a> for information about loading images without locking files. The overloads that receive a file path instead of an Image object should wrap their loaded Image files in a using block (or try/finally+dispose) like so:</p>\n\n<pre><code>public static void ResizeImageAndSave(string imageLocation, int newWidth, int maxHeight, bool onlyResizeIfWider, string thumbnailSaveAs)\n{\n Image thumbnail = null;\n\n try\n {\n using (Image loadedImage = Image.FromFile(imageLocation)) \n {\n thumbnail = resizeImage(loadedImage, newWidth, maxHeight, onlyResizeIfWider);\n }\n saveImageToLocation(thumbnail, thumbnailSaveAs);\n }\n finally\n {\n if (thumbnail != null) thumbnail.Dispose();\n }\n}\n</code></pre>\n\n<p>Hope this helps :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T15:11:32.120",
"Id": "553",
"ParentId": "549",
"Score": "5"
}
},
{
"body": "<p>If you're using C# 3.0, you can use extension methods</p>\n\n<pre><code>// declare as\npublic static Image ResizeImage(this Image source, ...\n\n// use as \nImage myThumb = myImage.Resize(...);\n</code></pre>\n\n<p>Treating width differently than height seems inconsistent. </p>\n\n<p>Never dispose passed-in arguments in a public function (<code>ImageToResize</code>). The caller almost never expects this to happen. </p>\n\n<p>Do dispose the temporary local variables (<code>loadedImage</code>). No other code can do it, and it could cause a memory leak.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T19:05:26.697",
"Id": "561",
"ParentId": "549",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "552",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-02T14:13:43.487",
"Id": "549",
"Score": "12",
"Tags": [
"c#",
"asp.net",
"image"
],
"Title": "Image resizing class"
} | 549 |
<p>Here you go:</p>
<pre><code>#define abort(msg) (fprintf(stderr, msg) && *((char*)0))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:44:24.167",
"Id": "934",
"Score": "3",
"body": "I'm pretty sure others are going to agree with me on this, but this is way way too short to be considered for a code review."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T14:49:45.720",
"Id": "937",
"Score": "1",
"body": "Also, interesting that you want to cause a SIGSEGV instead of a SIGABRT."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T15:48:17.100",
"Id": "941",
"Score": "2",
"body": "@mark: I'm not so sure, I think a meaty one liner could count as a minimum size. Of course the answers are going to be more limited, but they could cover style and efficiency."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T07:21:50.970",
"Id": "1000",
"Score": "0",
"body": "Do you intend your code to be platform-independent? The correct implementation may be platform specific. At the end of that function, it may need to raise a certain signal, or some other system call."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-05T17:15:45.733",
"Id": "1116",
"Score": "0",
"body": "I think accessing the null pointer results in undefined behavior. On some operating systems it might silently return some value instead of crashing."
}
] | [
{
"body": "<h3>Non-standard interface to standard function</h3>\n\n<p>The obvious criticism of that implementation is that it has a different interface from what the C standard requires:</p>\n\n<blockquote>\n <p>§7.20.4.1 The abort function</p>\n \n <p>Synopsis</p>\n\n<pre><code>#include <stdlib.h>\nvoid abort(void);\n</code></pre>\n \n <p>Description</p>\n \n <p>The <code>abort</code> function causes abnormal program termination to occur, unless the signal\n <code>SIGABRT</code> is being caught and the signal handler does not return. Whether open streams\n with unwritten buffered data are flushed, open streams are closed, or temporary files are\n removed is implementation-defined. An implementation-defined form of the status\n unsuccessful termination is returned to the host environment by means of the function\n call <code>raise(SIGABRT)</code>.</p>\n \n <p>Returns</p>\n \n <p>The abort function does not return to its caller.</p>\n</blockquote>\n\n<h3>Unreliable implementation of 'crash'</h3>\n\n<p>There were systems, notoriously the DEC VAX, where accessing the memory at address 0 did not cause problems (until the programs that were written on the VAX were ported to other platforms that did abort).</p>\n\n<p>Dereferencing a null pointer is undefined behaviour - that means anything could happen, including 'no crash'.</p>\n\n<h3>Nitpicks in implementation</h3>\n\n<p>If, for some reason, <code>fprintf()</code> returns 0, your program will not abort. For example:</p>\n\n<pre><code>abort(\"\");\n</code></pre>\n\n<p>does not abort. It is also dangerous to use the string as the format string; you should use:</p>\n\n<pre><code>#define abort(msg) (fprintf(stderr, \"%s\\n\", msg) && *((char*)0))\n</code></pre>\n\n<p>It would be better to use a comma operator in place of the <code>&&</code>:</p>\n\n<pre><code>#define abort(msg) (fprintf(stderr, \"%s\\n\", msg), raise(SIGABRT))\n</code></pre>\n\n<p>Since the standard library could have defined a macro <code>abort()</code>, you should <code>#undef</code> it before defining it yourself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-16T01:29:39.850",
"Id": "8125",
"Score": "0",
"body": "maybe prefer `fputs`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-16T03:34:33.470",
"Id": "8126",
"Score": "0",
"body": "One reason not to use `fputs()` is that it does not add a newline to the string (unlike `puts()` - but that writes to stdout instead of stderr), so you'd have to call it twice, once with the user string and once with the newline. It seems simpler to call `fprintf()` once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-16T03:55:58.960",
"Id": "8127",
"Score": "0",
"body": "@Johnathan: I'm pretty sure that `fputs` followed by `fputc(stderr, '\\n')` (and then flush) would be far faster than `fprintf`. When you're reporting an error, you usually want to use the most trivial functions possible (lest data corruption prevent them from running) and `fputs` and `fputc` are much much simpler than `fprintf`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T16:06:02.677",
"Id": "555",
"ParentId": "551",
"Score": "16"
}
},
{
"body": "<p>My criticism is you are trying to abort via a crash:</p>\n\n<pre><code>*((char*)0))\n</code></pre>\n\n<p>This invokes undefined behavior. It does not necessarily invoke a crash (or termination).</p>\n\n<p>If you want to raise the abort signal do so explicitly:</p>\n\n<pre><code>raise(SIGABRT)\n</code></pre>\n\n<p>Also you are re-defing a system method using #define (I am relatively sure this is not allowed and causes undefined behavior though I can not quote chapter and verse).</p>\n\n<pre><code>#define abort(msg) \n</code></pre>\n\n<p>Also by doing this you need to search through all the source to find any current usage of abort. As this may clash with the new usage (or will the pre-processor be intelligent about it. The fact that I ask the question should make you worry let alone the answer).</p>\n\n<p>Why not define your own function with a slightly different name (this will also allow you to call the system abort).</p>\n\n<pre><code>#define abortWithMsg(msg) do { fprintf(stderr, msg); abort(); } while (false)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T17:35:28.120",
"Id": "559",
"ParentId": "551",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-02-02T14:39:53.470",
"Id": "551",
"Score": "3",
"Tags": [
"c",
"error-handling"
],
"Title": "abort() implementation"
} | 551 |
<p>Please have a look at these iterators which I use for my Sudoku solver. They behave slightly different from STL iterators and don't implement all functionality that would be needed to use them in a stl context. But the basic idea behind them was to clean up the code in the Sudoku program that makes heavy use of the three access patterns (row, col, block) that I implemented.</p>
<p>The most "important" iterator is the BlockIterator, since without that iterating over all nine fields in a block looked quite ugly. Iterating rows and columns wasn't that bad, but since I started writing the stuff I decided to create a complete set.</p>
<p>Some technical details:</p>
<p>The grid class holds an (evil) array of pointers to Field objects, that's one dimensional (I could have used a two dimensional array as well, but I often do it this way and feel quite comfortable with modulo operations). Maybe I will replace this with a vector later.</p>
<p>The grid class adds a few static functions to calculate offsets in the array based on row, col or block positions.</p>
<pre><code>class Grid {
public:
Grid();
Grid(std::string s);
class Iterator {
public:
Iterator(Grid* g) : grid(g), it(0){}
Field* operator*(){return field;}
void operator++(){
++it;
if(it < 9) field = calc_field();
else field = NULL;
}
protected:
virtual Field* calc_field() = 0;
Field* field;
Grid* grid;
int it;
};
class RowIterator : public Iterator {
public:
RowIterator(Grid* g, int row) : Iterator(g){
row_offset = row * size; //Grid::block_offset(block);
field = calc_field();
}
Field* calc_field(){
int field_index = row_offset + it;
return grid->field[field_index];
}
protected:
int row_offset;
};
class ColIterator : public Iterator {
public:
ColIterator(Grid* g, int col) : Iterator(g){
col_offset = col;
field = calc_field();
}
Field* calc_field(){
int field_index = it * size + col_offset;
return grid->field[field_index];
}
protected:
int col_offset;
};
class BlockIterator : public Iterator {
public:
BlockIterator(Grid* g, int block) : Iterator(g){
block_offset = Grid::block_offset(block);
field = calc_field();
}
Field* calc_field(){
int field_index = block_offset + ((it / 3) * size) + (it % 3);
return grid->field[field_index];
}
protected:
int block_offset;
};
RowIterator& row_iter(int row){return *(new RowIterator(this, row));}
ColIterator& col_iter(int col){return *(new ColIterator(this, col));}
BlockIterator& block_iter(int block){return *(new BlockIterator(this, block));}
(...)
static int block_offset(int block){return ((block / 3) * size * 3) + ((block % 3) * 3);}
protected:
Field* field[grid_size];
</code></pre>
<p>Sample usage:</p>
<p>This function is called, when I set a value in a field. It goes through all fields, that would possibly be influenced by this field (same row, col or block)</p>
<pre><code>void Field::do_exclusions(){
// row
for(Grid::RowIterator it = grid->row_iter(row); *it; ++it)
(*it)->set_excluded(value);
// col
for(Grid::ColIterator it = grid->col_iter(col); *it; ++it)
(*it)->set_excluded(value);
// block
for(Grid::BlockIterator it = grid->block_iter(block); *it; ++it)
(*it)->set_excluded(value);
}
</code></pre>
<p>So please tell me, if something like this would be "acceptable" (not to mention "best practices"), even if it somehow takes a very free view on the iterator concept.</p>
<p>And of course every idea how this could be improved is welcome.</p>
<p>PS: I tried to add a tag "iterator" but I'm not allowed for too few reputation.</p>
| [] | [
{
"body": "<p>In my first quick scan through, here are some things I want to bring up:</p>\n\n<ul>\n<li>If you are going to overload operators, do it the way the users of the language expect, or don't do it at all. I expect <code>operator++</code> to return something, not be a <code>void</code>.</li>\n<li>Does <code>block_offset</code> really need to be public?</li>\n<li>On that same note, do your actual concrete implementations of the iterators need to be public, since you have methods to create them that are public? Would it make sense for anyone to ever want to create them a different way?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T17:59:18.540",
"Id": "955",
"Score": "0",
"body": "The third point is excellent. It is pretty much never necessary to explicitly create an iterator, as they are always tied to the collection being iterated over. So, the implementation should be hidden."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T17:59:49.730",
"Id": "956",
"Score": "0",
"body": "Thanks Mark. I changed block_offset and the classes to protected. I thought the classes would need to be public, to allow them to be used outside of the Grid class. But code still compiles. block_offset was public, because before I implemented the iterators, I used it everywhere for the purpose to \"manually\" iterate the fields."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:02:49.147",
"Id": "957",
"Score": "0",
"body": "The iterator types themselves need to be public if you want to [create variables of those types](http://codepad.org/L9zlqIpF). @Michael: The for loop code in the question needs them to be public, since it doesn't appear Field is a friend of Grid."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:04:53.153",
"Id": "958",
"Score": "0",
"body": "I took the operator from some online sample. I will have a look at Stroustrup or some other source to see how to implement them properly. I didn't think much about returning anything, since at least here I only need the incremental functionality."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:06:23.947",
"Id": "959",
"Score": "0",
"body": "@Fred: At the moment they're used only by the grid class and by the Field class (which is declared friend). I will adjust that if I need to use them elsewhere."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:08:01.353",
"Id": "960",
"Score": "2",
"body": "@Thorsten: They only need to be public if you want to explicitly reference them as a type, otherwise you can use the abstract base. With regards to operator++, here is a good resource: http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.14"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:12:02.850",
"Id": "961",
"Score": "0",
"body": "@Fred: Do they need to be public if it returned an `Iterator` rather than a `RowIterator` etc.?"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:18:40.753",
"Id": "963",
"Score": "0",
"body": "@Michael: You can't return the abstract type Iterator by value. So Iterator doesn't need to be public unless you wanted a pointer or reference to it (instead of a non-pointer, non-reference variable), but for the concrete derived classes, creating variables applies (as in my previous link). I would simply make them public, as hiding them serves no purpose."
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T18:19:18.463",
"Id": "964",
"Score": "0",
"body": "btw: Should I adjust the code in my question to the changes I made thanks to your hints? Or should I leave it as in my first edit for reference?"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T17:46:54.173",
"Id": "560",
"ParentId": "558",
"Score": "9"
}
},
{
"body": "<p>There is a memory leak in <code>Grid::row_iter()</code>, et al. Why use <code>new</code> in this case? I'd prefer</p>\n\n<pre><code>RowIterator row_iter(int row){return RowIterator(this, row);}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-02T20:26:58.230",
"Id": "1944",
"Score": "0",
"body": "Thanks for pointing that out. I use those iterators only at a few places in the program. So I didn't notice this yet."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-03-02T20:16:47.237",
"Id": "1098",
"ParentId": "558",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "560",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T17:26:42.450",
"Id": "558",
"Score": "15",
"Tags": [
"c++",
"iterator",
"sudoku"
],
"Title": "Sudoku Grid special purpose Iterators"
} | 558 |
<p>I have a class that spawns threads to process data. I am working on instrumentation code. When the process is started, <code>time = System.currentTimeMillis();</code> When it completes, <code>time = System.currentTimeMillis() - time;</code> I have a method to retrieve this time:</p>
<pre><code>/**
* Get the time taken for process to complete
*
* @return Time this process has run if running; time it took to complete if not
*/
public long getRunTime() {
return processRunning? System.currentTimeMillis() - time : time;
}
</code></pre>
<p>Is this a clear use of the ternary operator? Is my <a href="https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html" rel="nofollow noreferrer">javadoc</a> comment clear?</p>
| [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T03:03:11.907",
"Id": "992",
"Score": "3",
"body": "should document your units"
}
] | [
{
"body": "<p>It appears that the method sometimes returns a timestamp (<code>time</code>) and sometimes it returns a duration (difference between timestamps) (assuming that <code>time</code> is always a timestamp - if not, then this issue simply moves to <code>time</code> having a dual definition).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T19:26:45.140",
"Id": "974",
"Score": "3",
"body": "What about `processRunning? System.currentTimeMillis() - startTime : completedTime - startTime;`"
},
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T19:30:48.960",
"Id": "975",
"Score": "1",
"body": "Works for me, as does `processRunning ? System.currentTimeMillis() - startTime : runTime;`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T19:23:55.380",
"Id": "563",
"ParentId": "562",
"Score": "4"
}
},
{
"body": "<p>Since the method has a return value even if the code is not finished processing the first line of your javadoc ought not read \"Get the time taken for process to complete\" but perhaps rather \"Get the current or total processing time\" or something of that nature? I also agree with Bert F's comment, but if there were clear comments explaining the behavior and you don't intend on exposing start and end times individually then there's no reason to waste an extra variable; you can either keep the code as it is and add comments or optionally get rid of the boolean \"processRunning\" and instead use your completedTime/runTime variable to establish the fact that it's still running. All minor gripes, all in all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T19:55:09.177",
"Id": "565",
"ParentId": "562",
"Score": "5"
}
},
{
"body": "<p>I have no problem the ternary operator.</p>\n\n<p>But it is hard to tell that the result is what the comments is saying. Without having a context on what time is (which is a bad variable name) it is hard to understand the result of the function.</p>\n\n<p>time: Bad variable name. Time of what?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T20:33:53.490",
"Id": "566",
"ParentId": "562",
"Score": "6"
}
},
{
"body": "<p>It is a matter of style and taste but I'd rather go with</p>\n\n<pre><code>public long getRunTime() {\n if(processRunning)\n return System.currentTimeMillis() - time; \n\n return time;\n}\n</code></pre>\n\n<p>I just think this reads easier, and its easier to comment this. Now set me on fire for multiple return statements :D</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-21T21:14:28.593",
"Id": "1649",
"Score": "0",
"body": "Actually, I don't have a problem with this style. I do have a problem with multiple exit points spread throughout the function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-22T08:03:57.183",
"Id": "12785",
"Score": "0",
"body": "Looks a little odd without the `else`, IMHO."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-21T13:22:24.657",
"Id": "898",
"ParentId": "562",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "565",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-02-02T19:14:50.720",
"Id": "562",
"Score": "8",
"Tags": [
"java",
"multithreading",
"datetime"
],
"Title": "Spawning threads to process data"
} | 562 |
<p>I am learning clojure and decided to start out by trying to write a solution to a fairly simple algorithm, reservoir sampling. As I stated, I am learning clojure specifically and problem solving in a functional language in general. Can someone please take a look at my code and critique it on it's "clojureness". Am I using the right idiomatic conventions, is there a way that performs better (and why), formatting, anything really.</p>
<pre><code>(defn sample-seq [size data]
(loop [sample (transient (vec (take size data)))
idx size
data (drop size data)]
(if (empty? data)
(persistent! sample)
(let [rand-num (rand-int idx)
new-sample (if (< rand-num size)
(assoc! sample rand-num (first data))
sample)]
(recur new-sample (inc idx) (rest data))))))
(println (sample-seq 4 [2.0, 4.0, 7.0, 6.0, 3.0, 8.0, 12.0, 9.0, 4.0, 1.0]))
</code></pre>
| [] | [
{
"body": "<p>I think your code is pretty readable and looks like idiomatic enough Clojure code¹. So from a readability standpoint your code seems fine. However performing <code>assoc</code> on a vector of length <code>n</code> takes <code>O(log n)</code> time, so your runtime will be in <code>O(n log n)</code> as opposed to <code>O(n)</code>, which an imperative implementation would be in.</p>\n\n<p>However there's not much you can do about this other than perhaps using java arrays imperatively, but that would be very unidiomatic Clojure code. And <code>O(n log n)</code> isn't that bad (definitely not as bad as the <code>O(n^2)</code> I incorrectly claimed before).</p>\n\n<p>(Note that my previous note about transients was wrong as <code>assoc!</code> on a transient vector has the same runtime complexity as on a persistent vector).</p>\n\n<hr>\n\n<p>¹ Usually you'd avoid index-based loops wherever possible, but the nature of the algorithm makes that pretty much impossible here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T10:09:25.797",
"Id": "1009",
"Score": "2",
"body": "@MGoDave: if this answer was useful, then you should probably up-vote it to thank @sepp2k..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-19T23:32:16.820",
"Id": "3936",
"Score": "2",
"body": "Note that the log factor in clojure's vectors is large: assoc is `O(log32 n)`. For any size of integer that fits in your computer, this is effectively constant."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-03T00:10:56.150",
"Id": "577",
"ParentId": "568",
"Score": "11"
}
},
{
"body": "<p>sepp2k's critique is incorrect - <code>assoc</code> on a vector takes <code>O(log n)</code> time not <code>O(n)</code> time because Clojure uses persistent vectors. You should avoid using <code>assoc!</code> because it is Clojure style to avoid needless destructive behavior.</p>\n\n<p>For more on persistent vectors see:\n<a href=\"http://blog.higher-order.net/2009/02/01/understanding-clojures-persistentvector-implementation/\" rel=\"nofollow\">http://blog.higher-order.net/2009/02/01/understanding-clojures-persistentvector-implementation/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-19T11:09:26.303",
"Id": "1581",
"Score": "1",
"body": "Damn, sorry about that. I corrected my answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-18T22:13:25.407",
"Id": "845",
"ParentId": "568",
"Score": "1"
}
},
{
"body": "<p>It's a bit unfortunate that the reservoir sampling algorithm is funadmentally imperative. If squeezing the last bit of performance out of it is important to you, I'd <em>try</em> using a Java Array internally. (I say try, you'd want to actually time it to see if you'd actually gained any performance.)</p>\n\n<p>The only other performance tip I'd try is to replace <code>idx size</code> with <code>idx (int size)</code> which should guarantee the type internally.</p>\n\n<p>I wouldn't worry about using transients. The Clojure source code uses them all of the time for the exact purpose you have here. Pods are likely to make the code simpler when they drop. Finally, although Kevin L is definitely correct about assoc being an O(log n) operation, I wouldn't guarantee that was also true of transient vectors.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-07-12T18:02:06.403",
"Id": "3411",
"ParentId": "568",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "577",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-02-02T21:25:51.983",
"Id": "568",
"Score": "13",
"Tags": [
"functional-programming",
"clojure"
],
"Title": "Reservoir Sampling in Clojure"
} | 568 |