body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I've created these 3 functions to count the value of letters in a word.</p>
<p>All these functions are functionally the same.</p>
<p>Apparently List comprehensions (<code>count_word3</code>) are usually seen as the most pythonic in these situations. But to me it is the least clear of the 3 examples.</p>
<p>Have I stumbled across something that is so simple that lambdas are acceptable here or is "the right thing to do" to use the list comprehension?</p>
<p>Or is there something better?</p>
<pre><code>def count_word1(w):
def count(i, a):
return i + ord(a) - 64
return reduce(count, w, 0)
def count_word2(w):
return reduce(lambda a,b : a + ord(b) - 64, w, 0)
def count_word3(w):
vals = [ord(c) - 64 for c in w]
return sum(vals)
</code></pre>
|
[] |
[
{
"body": "<p>how's example 3 the least readable? I would write it a little better but you've got it right already:</p>\n\n<pre><code>def count_word3(word): \n return sum(ord(c) - 64 for c in word) \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T13:10:01.740",
"Id": "22384",
"Score": "0",
"body": "I've probably just done too much scala :-). \nI'm just asking for opinions from the python community to refine my python style."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T12:08:14.523",
"Id": "13865",
"ParentId": "13863",
"Score": "2"
}
},
{
"body": "<p>These are the most readable for me:</p>\n\n<pre><code>sum((ord(letter) - ord('A') + 1) for letter in word)\n</code></pre>\n\n<p>Or </p>\n\n<pre><code>def letter_value(letter):\n return ord(letter) - ord('A') + 1\n\nsum(map(letter_value, word))\n</code></pre>\n\n<p>btw, the code might break for non-ASCII strings.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T12:18:22.397",
"Id": "13866",
"ParentId": "13863",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "13865",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T10:54:47.693",
"Id": "13863",
"Score": "1",
"Tags": [
"python",
"comparative-review"
],
"Title": "Three ways to sum the values of letters in words"
}
|
13863
|
<p>I want to perform some operations on the gridview (asp.net 4.0). So, to achieve this i have written a jquery function which i am calling on pageload but, because this function takes some time for execution my grid performance degrades (IE 8). Can i optimize it someway? </p>
<pre><code> $.each($("#divTab2GridInquiries").find("tr").not(":first"), function () {
var tr = $(this);
var val = tr.find("input[id*='hdnLineStatus']").val();
var btnDelete = tr.find("div[id='divBtnDelete']");
var btnTobeDeleted = tr.find("div[id='divBtnTobeDeleted']");
if (val == "N") {
btnDelete.hide();
btnTobeDeleted.hide();
}
if (val == "S") {
tr.css("background-color", "#99FF99");
tr.find("input").css("background-color", "#99FF99");
btnDelete.show();
btnTobeDeleted.hide();
}
if (val == "D") {
tr.css("background-color", "#FFFF99");
tr.find("input").css("background-color", "#FFFF99");
btnDelete.show();
btnTobeDeleted.hide();
}
//From user rights
if ($("input[id*='hdnTab2ShowDelete']").val() != "Y") {
btnTobeDeleted.hide();
//btnDelete.show();
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T03:34:10.897",
"Id": "22371",
"Score": "4",
"body": "Not an optimisation, but two comments: (1) You seem to have multiple elements with the same id, which is invalid html and should be avoided - use classes; (2) The first line will work but is using the \"wrong\" sort of `.each()`, so I'd say: `$(\"#divTab2GridInquiries\").find(\"tr\").not(\":first\").each(function () {`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T02:26:20.993",
"Id": "22410",
"Score": "0",
"body": "Do you mean to always hide `btnTobeDeleted.hide();`?"
}
] |
[
{
"body": "<p>The best that I can see if changing the IFs to switches, but overall, the speed of execution will not change.</p>\n\n<pre><code>switch (val){\n\ncase \"N\":\n// Code for N\nbreak;\n\ncase \"S\":\n// Code for S\nbreak;\n\ncase \"D\":\n// Code for D\nbreak;\n\ndefault:\n// For the rest, use \"not\" to subtract Y from the equasion.\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T03:37:46.463",
"Id": "22372",
"Score": "0",
"body": "Op's issues are likely DOM traversal related (especially as IE8 is very slow at that), so, I kinda doubt this helps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T03:42:02.687",
"Id": "22373",
"Score": "0",
"body": "I said that before I suggested any sort of code..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T03:32:18.280",
"Id": "13869",
"ParentId": "13868",
"Score": "1"
}
},
{
"body": "<p><strike>Use a single selector instead of \"find\" and \"not.\"</strike> Leave the <code>find</code>, this is <a href=\"http://jsperf.com/faster-query-by-splitting-it-up\" rel=\"nofollow\">faster</a> in every browser except opera (see comments).</p>\n\n<p>For the 2nd part of the selector, you can use the \"sibling\" combinator <code>~</code> to grab everthing except its first operand, and the <code>:first-child</code> pseudoclass selector to get the first child, giving you the same set of elements without using several jQuery methods. This is faster than using <code>not(':first')</code> in all browsers, and faster than a single selector (e.g. not using <code>find</code> either) in all browsers except Opera (which maintains its native-selector edge). See <a href=\"http://jsperf.com/faster-query-by-splitting-it-up/2\" rel=\"nofollow\">this test</a>.</p>\n\n<p><em>Note: <code>#someTable tr</code> will also return tr elements from a nested table. You really want to target the direct row descendants of the table. But don't forget about tbody, which is a required element. So this probably should be \"#divTab2GridInquiries > tbody > tr:first-child ~ tr\". But that is a mouthful... and it's <a href=\"http://jsperf.com/faster-query-by-splitting-it-up/3\" rel=\"nofollow\">really slow.</a> If you have no nested tables it will work fine as coded below.</em></p>\n\n<pre><code>$.each($(\"#divTab2GridInquiries\").find(\"tr:first-child ~ tr\"), function () { \n var tr = $(this);\n</code></pre>\n\n<p>Not sure what you're doing here - the selector is using a wildcard match, but <code>val</code> only operates against the first element in a selection set. Can you target this element more specifically? In any event, instead of wildcard matching the id, add a class and select on that. Classes are <em>much</em> faster than substring matching attributes.</p>\n\n<pre><code> //var val = tr.find(\"input[id*='hdnLineStatus']\").val();\n var val = tr.find(\".hdnLineStatus\").val();\n</code></pre>\n\n<p>IDs are supposed to be unique. I'm not sure why you would have to target it this way. But using an attribute selector like this will definitely be slower than a regular ID or class selector. If these ids are really unique then just use <code>#divBtnDelete</code>. I suspect that they aren't and you're creating invalid html. Get rid of the ID an add a class.</p>\n\n<pre><code> // var btnDelete = tr.find(\"div[id='divBtnDelete']\");\n var btnDelete = tr.find(\".divBtnDelete\");\n\n //var btnTobeDeleted = tr.find(\"div[id='divBtnTobeDeleted']\");\n var btnTobeDeleted = tr.find(\".divBtnTobeDeleted\");\n</code></pre>\n\n<p>This set of ifs should be a switch, but that's probably not slowing you down nearly as much as the selectors.</p>\n\n<pre><code> if (val == \"N\") {\n btnDelete.hide();\n btnTobeDeleted.hide();\n }\n if (val == \"S\") {\n tr.css(\"background-color\", \"#99FF99\");h\n tr.find(\"input\").css(\"background-color\", \"#99FF99\");\n btnDelete.show();\n btnTobeDeleted.hide();\n }\n\n if (val == \"D\") {\n tr.css(\"background-color\", \"#FFFF99\");\n tr.find(\"input\").css(\"background-color\", \"#FFFF99\");\n btnDelete.show();\n btnTobeDeleted.hide();\n }\n</code></pre>\n\n<p>Use a class again.</p>\n\n<pre><code> //From user rights \n //if ($(\"input[id*='hdnTab2ShowDelete']\").val() != \"Y\") {\n if ($(\".hdnTab2ShowDelete\").val() != \"Y\") {\n\n btnTobeDeleted.hide();\n //btnDelete.show();\n }\n });\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T03:50:33.423",
"Id": "22374",
"Score": "0",
"body": "thanx for detailed explanation. I found what was slowing down foreach loop. my last condition : $(\"input[id*='hdnTab2ShowDelete']\").val()!='Y' because while scanning each row of the table it was accessing outside hidden field. I fixed it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T03:53:25.463",
"Id": "22375",
"Score": "0",
"body": "Ha, I noticed that at first and then totally forgot by the time I got done :) yeah that would be a killer, since the wildcard match would have to be run against every input element on the DOM for each iteration of the loop. The other stuff can't hurt either."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T16:18:33.623",
"Id": "22390",
"Score": "0",
"body": "Since selectors are always matched right to left, [using `find` is actually *much* faster](http://jsperf.com/faster-query-by-splitting-it-up)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T16:36:21.887",
"Id": "22391",
"Score": "0",
"body": "Learn something new every day. I have to say I am astounded that Chrome doesn't optimize even for ID selectors. Apparently they are not *always* matched this way, though, in your test results Opera's native operation is faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T17:15:17.660",
"Id": "22394",
"Score": "0",
"body": "Was wondering about Opera myself. I'd really like to know what sort of witchcraft they're employing to get those results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T17:22:34.270",
"Id": "22396",
"Score": "0",
"body": "Out of curiosity I read some history, anecdotally it sounds like they operate this way because it uses less *memory* not because it's generally faster. By a complete coincidence I have actually written my own CSS selector engine & jQuery port: https://github.com/jamietre/csquery and I never thought twice about it working any way other than left to right :) in CsQuery the \"find\" would perform nearly identically to the single-selector, except for a few stack frames they would take exactly the same path through the index."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T02:13:04.560",
"Id": "22409",
"Score": "0",
"body": "Technically there is no reason to specify `:first-child` on that selector, `tr ~ tr` will select any sibling `tr` that follows the initial `tr`; you could also use [`tr + tr`](http://jsperf.com/faster-query-by-splitting-it-up/5) which I think might be the best way to do this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T04:49:57.920",
"Id": "22413",
"Score": "0",
"body": "I figured that the specificity would be more efficient; and I would again be wrong! Your instinct was right, tr+tr is fastest (at least in chrome): http://jsperf.com/faster-query-by-splitting-it-up/6"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T03:43:54.387",
"Id": "13870",
"ParentId": "13868",
"Score": "3"
}
},
{
"body": "<p>I think you should use behind C# code in aspx.cs to do this. If the visibility and style of the elements(buttons, table cells) is NOT interactive.<br/>\nThis solution doesn't need javascript at all, and will get better performence in browsers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T03:52:55.497",
"Id": "22376",
"Score": "0",
"body": "ASP.NET rowdatabound is too slow. I dont think that will help because i am trying to improve my application performance"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T03:54:31.767",
"Id": "22377",
"Score": "0",
"body": "ASP.NET rowdatabound run on the server, JS run in the browser. Your question is to optimize JS code, this can only affect the performance in browser, not the server side. If you use ASP.NET rowdatabound, you use the server to do the job, and leave Browser free. So your program's performance in browser is got optimized."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T03:58:49.533",
"Id": "22378",
"Score": "0",
"body": "But, If we talk about overall performance which process will be faster?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T04:00:09.223",
"Id": "22379",
"Score": "0",
"body": "Server's are generally much faster than a personal computer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T04:00:54.963",
"Id": "22380",
"Score": "1",
"body": "I haven't used webforms in a while but I remember gridview/listview being a huge pain to manipulate the individual row data in any way other than simple templating actions from the server. His demands here aren't excessive, this seems reasonable to do on the client. Templated grid controls that run entirely on the client are common these days and they actually perform a lot better than server models because of low latency & minimized data transfer, the only reason he had a performance problem was due to an egregious error with a selector."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T04:01:10.223",
"Id": "22381",
"Score": "0",
"body": "This depends on your server's hardward and the number of clients. If your server is good enough, and only limited users (for example less than 100) will use the server, it will work well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T04:04:06.993",
"Id": "22382",
"Score": "0",
"body": "@jamietre: `because of low latency & minimized data transfer,' in my first answer, i suggest this solution if it does NOT need interactivity. If no interactivity, then no latency and no data transfer at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T04:06:59.097",
"Id": "22383",
"Score": "0",
"body": "Given that the point of this is to show and hide controls like a delete button, I think it is safe to assume it's interactive."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T03:49:17.067",
"Id": "13871",
"ParentId": "13868",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "13870",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T03:25:52.763",
"Id": "13868",
"Score": "0",
"Tags": [
"javascript",
"jquery"
],
"Title": "Showing/hiding deletion buttons in a grid view"
}
|
13868
|
<p>At the moment I am trying to create a Japanese rehearsal system, and it's working perfectly. However, I am not pleased with the code. Basically I had a .txt file called lesson1.txt. I saved it as UTF-8 so it can contain Japanese characters. </p>
<p>I had the problem that I couldn't directly use the Japanese characters in JavaScript. I tried bypassing that issue by finding the Unicode code point of each character in PHP, echo that out in as a JavaScript array and use a JavaScript function to convert it back to the Japanese characters. </p>
<p>Now I figured this is not the way to go, because someone on this site told me this is an awful way of coding. My question is, how do I go by improving this? How can I get the Japanese characters into my JavaScript code the most efficient way? Also, have a look at how badly it is coded right now to get a better way of understanding my problem.</p>
<p>In case necessary: I used this PHP loop to get each Unicode point transferred into characters and saved into a JavaScript array:</p>
<pre><code>$x = 0;
//$LineArray is an array in which each element contains a line of lesson1.txt
// so for example: $LineArray[0] = "γγ€γ";
foreach($LineArray as $s)
{
echo "TextCharacters[" . $x . "] = new Array();\n";
for($i = 0; $i < mb_strlen($s,"utf-8"); $i++)
{
$char = mb_substr($s, $i, 1, "utf-8");
// REMOVE BOM
if(strtoupper(bin2hex(iconv('UTF-8', 'UCS-2', $char))) != "FEFF")
{
echo "TextCharacters[" . $x . "].push(go(\"" . strtoupper(bin2hex(iconv('UTF-8', 'UCS-2', $char))) . "\"));\n";
}
}
$x++;
}
</code></pre>
|
[] |
[
{
"body": "<p><code>X</code> is a very bad variable name.\nIt comes like a lightning from a clear sky there in the beginning.</p>\n\n<p>The following comment is good:</p>\n\n<pre><code>//$LineArray is an array in which each element contains a line of lesson1.txt\n// so for example: $LineArray[0] = \"γγ€γ\";\n</code></pre>\n\n<p>But how about naming the array \"<code>current_lesson__lines</code>\"?</p>\n\n<p>An array should never state in its name that it's an array. That's kinda like naming your buddy '<code>human john</code>', just to make sure people realize that he's a human.</p>\n\n<p>I think <code>$cline_content</code> would be better than <code>$s</code>.</p>\n\n<p>In the following:</p>\n\n<pre><code>if(strtoupper(bin2hex(iconv('UTF-8', 'UCS-2', $char))) != \"FEFF\")\n</code></pre>\n\n<p>You're doing many things in a single session here.<br>\nThat's always bad, try to do just one thing at a time.<br>\nAlways doing only one thing at a time boosts readability, reuse-ability and modularity.<br>\nIt is a formula for high quality.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T13:56:01.853",
"Id": "22388",
"Score": "0",
"body": "Hello, Thanks for your help. I agree on your comment that the naming is a bit weak, but my real concern here is that the current structure of getting the japanese words into javascript is bad. The real question is: How can I get the japanese characters into my javascript code the most efficient way? If you look at my current site you'll see me having to push each character in a multidimensional array. Example:\n\nTextCharacters[0].push(go(\"304A\"));\nTextCharacters[0].push(go(\"304A\"));\nTextCharacters[0].push(go(\"304D\"));\nTextCharacters[0].push(go(\"3044\"));\nTextCharacters[0].push(go(\"000D\"));"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T13:27:44.050",
"Id": "13873",
"ParentId": "13872",
"Score": "0"
}
},
{
"body": "<p>Try this and see if you like it - made a few improvements (see comments) and created a couple of functions to reduce duplicate code and increase readability.</p>\n\n<pre><code>$counter = 0;\n\n# Set Test Data\n$currentLessonLine[0] = \"γγ€γ\";\n$currentLessonLine[1] = \"γγ€γ\";\n$currentLessonLine[2] = \"γγ€γ\";\n$currentLessonLine[3] = \"γγ€γ\";\n$currentLessonLine[4] = \"γγ€γ\";\n\n/**\n * $currentLessonLine is an array in which each element contains a line of lesson1.txt\n * so for example: $currentLessonLine[0] = \"γγ€γ\";\n */\nforeach($currentLessonLine as $lessonLine){\n printOut($counter);\n\n /** \n * Let's only find the string length once, shall we? Storing length in a \n * variable instead of finding length every time is better practice.\n */\n $lessonLineLength = mb_strlen($lessonLine,\"utf-8\");\n\n for($i = 0; $i < $lessonLineLength; $i++){\n $char = mb_substr($lessonLine, $i, 1, \"utf-8\");\n\n # REMOVE BOM\n if(charConvert($char) != \"FEFF\") printOut($counter, TRUE, $char);\n }\n\n $counter++;\n}\n\n\n/**\n * if $selector == TRUE, $char must be set\n * function gets rid of print statements above and makes it cleaner\n */\nfunction printOut($counter, $selector = FALSE, $char = \"\"){\n if($selector == TRUE && !empty($char)){\n echo \"TextCharacters[\" . $counter . \"].push(go(\\\"\" . charConvert($char) . \"\\\"));\\n\"; \n } else {\n echo \"TextCharacters[\" . $counter . \"] = new Array();\\n\";\n }\n}\n\n/**\n * You were duplicating this code twice above - once in the if-statement\n * and once in the if-body, this just takes reference to char and mods it \n */ \nfunction charConvert(&$char){\n return strtoupper( bin2hex( iconv('UTF-8', 'UCS-2', $char) ) );\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T17:47:56.670",
"Id": "13880",
"ParentId": "13872",
"Score": "0"
}
},
{
"body": "<p>First off, post any and all code that you want reviewed. Just posting a little and saying the rest is \"here\" is not going to get you many good answers. Some of us dislike venturing to sites unknown to view someone else's code. If you post the rest of it and drop me a comment I will return to take a look at it if you wish. That being said, here is my take on your current code. Note: I reference the other two answers heavily, so this is merely an addition and not a true answer.</p>\n\n<p><strong>Incremental Variables</strong></p>\n\n<p>I don't really agree with Hermann's first comment. \"x\" is only a bad variable name if it is being used for something concrete and easily expressible in some other way. Here it is an incremental, a throw-away variable, so nothing is wrong with it. It's odd, \"i\" is usually used as the default incremental with \"j\" usually being secondary, but there's nothing wrong with \"x\". I do agree that it came out of no where and might be a little jarring, but if you move that line down to just above the loop it will be less so. Also, following jsanc623's example would also be acceptable.</p>\n\n<p><strong>For vs Foreach</strong></p>\n\n<p>The advantage to using a foreach loop over a for loop is that the first uses internal pointers that are dynamically updated, while the second uses external pointers that are statically updated. Another advantage is speed. A foreach loop is usually faster than a for loop. There are more advantages, but I'm going to stick with the ones that are important here. There is one instance where a for loop is better than a foreach loop. That is when you are looping over an associative array and using an external pointer inside of it that coincides with the internal pointer. So, instead of using a foreach loop in these circumstance, it may be best to use a for loop with <code>array_keys()</code> to access the array index manually. If, on the other hand, you are looping a numerically indexed array you can just use the key of the current element.</p>\n\n<pre><code>foreach( $LineArray AS $x => $s ) {\n</code></pre>\n\n<p><strong>Variable Names</strong></p>\n\n<p>Again, I have to disagree with Hermann, there is nothing wrong with calling your variables an array, or a map, or anything else that indicates what they hold. Unnecessary? Sure, but at the same time it doesn't hurt anything and can actually help in some cases. Now, I won't say that calling a variable a \"String\" or an \"Int\" is good. PHP is very loosely typed, and that can easily change those contents, but adding an \"array\" or \"obj\" suffix to your variable lets those reading it know what it is supposed to be and is common enough.</p>\n\n<p>I do agree with Hermann about <code>$s</code> however. It is a horrible name. I would expect to see <code>$line</code> or something similarly related to the array. The only single letter variables you should have are incremental (i, j) or something else that is commonly expressed with a single letter, such as coordinates (x, y, z).</p>\n\n<p><strong>Strings</strong></p>\n\n<p>I'm going to get argued with about this next suggestion, so let me just say up front that it is a stylistic choice that has some basis in fact. PHP allows for two methods of adding variables to a string. The first is escaping. Using double quotes to surround a variable or escape sequence you can escape the variable or sequence without any special syntax, just include them between the double quotes (\"$var\\n\"). The second is concatenation and is the method you are currently using ('abc' . $var1 . \"\\n\"). When concatenating it is best, in my opinion, to use single quotes instead of double. There's one major reason for this, double quotes tells PHP your string has entities that need escaping, whether they are PHP variables or manually escaped returns, tabs, etc... doesn't matter. So when you use double quotes PHP expects these escape routines and uses a small amount of extra processing power to parse the string for them. Now the processing power required and the time it takes are both negligible, but there is a difference and I like to point it out.</p>\n\n<p><strong>For Loops</strong></p>\n\n<p>Another thing about for loops. The arguments passed to a for or while loop are reparsed on each iteration. So passing a function in as an argument is usually a bad idea, at least if that function's return value is not meant to change i.e.(<code>count()</code> or in this case <code>mb_strlen()</code>). Both get the number of iterations the loop is going to go through. These numbers typically don't change between iterations so there is no need to recalculate it. It is just taking up extra processing power. If you move this function out of the argument list and set it as a variable it will run a bit faster, though it may be negligible in this case. jsanc623 touched on this, but I wanted to give the full reason.</p>\n\n<p><strong>Nested Functions</strong></p>\n\n<p>Again, I agree with Hermann, don't have long nested function calls in a statement. Declare it a variable before checking it, especially if you are going to be using it again elsewhere. This follows the DRY (Don't Repeat Yourself) Principle. Personally, I would break it up further, as I don't like nested function calls at all, but that might just be a stylistic choice. Here's how I'd write your if statement.</p>\n\n<pre><code>$bin = iconv('UTF-8', 'UCS-2', $char);\n$hex = strtoupper( bin2hex( $bin ) );//Only one nested, and still not as desirable.\nif( $hex != \"FEFF\" ) {\n</code></pre>\n\n<p><strong>Functions</strong></p>\n\n<p>Again jsanc623 brings up a good point. This single function should be broken up into multiple functions. He doesn't come right out and say it, but it is implied. So I figured I'd go ahead and say it for him. Functions should do one thing and do it well. They should not be concerned with anything else. This is the Single Responsibility Principle.</p>\n\n<p><strong>Pushing to an Array</strong></p>\n\n<p>The following is equivalent to pushing onto the end of an array, and is usually the preferred method for appending array data.</p>\n\n<pre><code>TextCharacters[ 0 ] [] = go( '304A' );\n</code></pre>\n\n<p>Now, in your comment you said that you were pushing each element. Am I to assume you are doing so manually? If so, a better way would be to create an array of these hex values and loop over them to add them. Even better would be to create a JSON document, that way they could be accessed from both PHP and JS if needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-14T18:56:44.250",
"Id": "27882",
"Score": "0",
"body": "Wow, you really took your time writing this. Its an old project of mine so sorry for posting late but you really did make sense about some stuff. Thanks for your time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-14T19:06:12.303",
"Id": "27883",
"Score": "0",
"body": "By the way, whats the difference between internal and external pointers? (in your for vs foreach paragraph)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T15:22:27.763",
"Id": "13976",
"ParentId": "13872",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13976",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T13:02:45.173",
"Id": "13872",
"Score": "2",
"Tags": [
"javascript",
"php",
"array"
],
"Title": "Japanese rehearsal system"
}
|
13872
|
<p>Here is a simple Python script that I wrote with lots of help from the Python mailing list. I moves all the files of subdirectories to the top level directory. It works well for my use, but if there are things that can be improved then I would like to know. I ask in the interest of being a better Python programmer and learning the language better. Thanks.</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import shutil
currentDir = os.getcwd()
forReal = False
if ( currentDir in ['/home/dotancohen', '/home/dotancohen/.bin'] ):
print "Error: Will not run in "+currentDir
exit()
if ( len(sys.argv)>1 and sys.argv[1] in ['m', 'M', 'c', 'C'] ):
forReal = True
else:
print "\nThis is a test run. To actually perform changes, add 'm' (move) or 'c' (copy) after the program name.\n"
filesList = os.walk(currentDir)
for rootDir, folders, files in filesList:
for f in files:
if (rootDir!=currentDir):
toMove = os.path.join(rootDir, f)
print toMove
newFilename = os.path.join(currentDir,f)
renameNumber = 1
while(os.path.exists(newFilename)):
newFilename = os.path.join(currentDir,f)+"_"+str(renameNumber)
renameNumber = renameNumber+1
if ( forReal and sys.argv[1] in ['m', 'M'] ):
os.rename(toMove, newFilename)
elif ( forReal and sys.argv[1] in ['c', 'C'] ):
shutil.copy(toMove, newFilename)
if ( not forReal ):
print "\nThis was a test run. To actually perform changes, add 'm' (move) or 'c' (copy) after the program name."
</code></pre>
|
[] |
[
{
"body": "<p>I'll typically wrap the main body of my code in a python script in a function and break the code apart into more functions, allowing me to reuse that code later.</p>\n\n<pre><code>import os\nimport shutil\nimport sys\n\ndef flattenDirectory(location, action, actuallyMoveOrCopy=True):\n \"\"\" This function will move or copy all files from subdirectories in the directory location specified by location into the main directory location folder\n location - directory to flatten\n action - string containing m(ove) or M(ove) or c(opy) or C(opy)\"\"\"\n #Your code here\n\nif __name__ == \"__Main__\":\n #same code to find currentDirectory here\n actuallyMoveOrCopy = len(sys.argv)>1 and sys.argv[1] in ['m', 'M', 'c', 'C']\n flattenDirectory(currentDirectory, sys.argv[1], actuallyMoveOrCopy)\n</code></pre>\n\n<p>Now you can still run this code as you normally would, but should you need it in another script you can use it in an import without having to worry about the code automatically running at the time of import.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T10:37:26.293",
"Id": "22452",
"Score": "0",
"body": "Thank you. This is a good example of a script that likely _will_ be called from another program someday, so it is a good fit to this approach."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T16:14:00.307",
"Id": "13877",
"ParentId": "13876",
"Score": "2"
}
},
{
"body": "<p>Peter has already mentioned putting the code into methods. This isnβt just a personal preference, itβs a general recommendation that <em>all</em> Python code should follow.</p>\n\n<p>In fact, consider the following an idiomatic Python code outline:</p>\n\n<pre><code>import sys\n\ndef main():\n # β¦\n\nif __name__ == '__main__':\n sys.exit(main())\n</code></pre>\n\n<p>Implement <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8 βΒ Style Guide for Python Code</a>. In particular, use <code>underscore_separated</code> variables instead of <code>camelCase</code>.</p>\n\n<p>Programs should follow the general flow (1) input, (2) processing, (3) output. Argument reading is part of (1); consequently, do it only once, at the start.</p>\n\n<p>Set variables depending on that input.</p>\n\n<pre><code>perform_move = sys.argv[1] in ['M', 'm']\nperform_copy = sys.argv[1] in ['C', 'c']\ndry_run = not perform_copy and not perform_move\nβ¦\n</code></pre>\n\n<p>Note that Iβve inverted the conditional for <code>forReal</code>. First of all, because itβs more common (βdry runβ is what this is usually called). Secondly, the name <code>forReal</code> is rather cryptic.</p>\n\n<p>Put the <code>['/home/dotancohen', '/home/dotancohen/.bin']</code> into a configurable constant at the beginning of the code, or even into an external configuration file. Then make it a parameter to the method which performs the actual logic.</p>\n\n<p>By contrast, the <code>filesList</code> variable is unnecessary. Just iterate directly over the result of <code>os.walk</code>.</p>\n\n<p>Operations of the form <code>renameNumber = renameNumber+1</code> should generally be written as <code>rename_number += 1</code>. Also, pay attention to consistent whitespace usage.</p>\n\n<p>Iβd put the logic to find a unique target path name into its own method <code>unique_pathname</code>. Then Iβd replace the concatenation by string formatting.</p>\n\n<pre><code>def unique_pathname(basename):\n unique = basename\n rename_no = 1\n while os.path.exists(unique):\n unique = '{0}_{1}'.format(basename, rename_no)\n rename_no += 1\n\n return unique\n</code></pre>\n\n<p>Notice that Iβve also removed the redundant parenthese around the loop condition here. The same should be done for all your <code>if</code> statements.</p>\n\n<pre><code>if ( forReal and sys.argv[1] in ['m', 'M'] ):\n</code></pre>\n\n<p>The test for <code>forReal</code> here is redundant anyway, itβs implied in the second condition. But weβve got variables now anyway:</p>\n\n<pre><code>if perform_move:\n # β¦\nelif perform_copy:\n # β¦\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T10:38:20.507",
"Id": "22453",
"Score": "0",
"body": "Thank you. Your explanation is quite what I was looking for, to write code that is \"more Pythonic\"."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T17:04:52.777",
"Id": "13878",
"ParentId": "13876",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "13878",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T14:16:19.887",
"Id": "13876",
"Score": "2",
"Tags": [
"python"
],
"Title": "Python: flatten directories"
}
|
13876
|
<p>I created simple app that read <code>~</code> delimited txt file, convert it to <code>[String]</code> and display quotes on screen.</p>
<ul>
<li>How would you improve this code? To be more Haskell like... </li>
<li>in <code>splitStr</code> <code>(c/=)</code> is faster than <code>(/=c)</code> by 20-50 ns. Why?</li>
<li>Any other ways to clear screen in windows console app?</li>
<li>If we compile this code as win console app, I assume <code>threadDelay</code> pauses whole app not just <code>outQ</code> function. Right?</li>
<li>Can someone point me in right direction how to refactor this code to use someting like <a href="http://www.w3schools.com/js/js_timing.asp" rel="nofollow">JavaScripts setInterval or setTimeout</a>.</li>
<li>is there some easy way to catch <code>ctrl+c</code> so I can <code>showCursor</code> on exit?</li>
</ul>
<p>.</p>
<pre><code>import System.IO
import System.Random
import Control.Concurrent (threadDelay) -- microseconds
import System.Console.ANSI -- clearScreen
fileName = "quotes.txt"
oneSecond = 1000000
delay = 1 -- sec
splitStr _ [] = []
splitStr c xs = takeWhile (c/=) xs : splitStr c (drop 1 $ dropWhile (c/=) xs)
--clear = putStr "\ESC[2J" -- not working on windows
outQ list l sec g = do
clearScreen
setCursorPosition 0 0 -- row col
let (index, gen') = randomR (0, l) g
putStrLn $ list !! index
threadDelay $ sec * oneSecond
outQ list l delay gen' -- works
main :: IO ()
main = do
setTitle "Quotes"
hideCursor -- catch ctrl+c for showCursor
gen <- newStdGen
str <- readFile fileName
let qlist = splitStr '~' str
let len = length qlist -1
outQ qlist len delay gen
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T08:47:53.220",
"Id": "22636",
"Score": "0",
"body": "Re `(c/=)` -v- `(/=c)`: did you compile using optimisation (`-O` switch to ghc)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T11:56:37.280",
"Id": "22653",
"Score": "0",
"body": "You are right! I test it in ghci!!! Didn't use any -O"
}
] |
[
{
"body": "<p>I'm going to talk about your <code>splitStr</code> function.</p>\n\n<p>First, it's almost the same as <a href=\"http://hackage.haskell.org/packages/archive/split/latest/doc/html/Data-List-Split.html#v%3asplitOn\" rel=\"nofollow\"><code>splitOn</code></a> from Data.List.Split in the <a href=\"http://hackage.haskell.org/package/split\" rel=\"nofollow\">split</a> package.</p>\n\n<ul>\n<li>Run <code>cabal install split</code></li>\n<li>Add <code>import Data.List.Split</code> at the start of your code</li>\n<li><p>Replace</p>\n\n<pre><code>let qlist = splitStr '~' str\n</code></pre>\n\n<p>with</p>\n\n<pre><code>let qlist = splitOn \"~\" str\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>But let's suppose you can't use the split package for some reason, and try to improve your <code>splitStr</code>.</p>\n\n<pre><code>splitStr :: Eq a => a -> [a] -> [[a]]\nsplitStr _ [] = []\nsplitStr c xs = takeWhile (c/=) xs : splitStr c (drop 1 $ dropWhile (c/=) xs)\n</code></pre>\n\n<p>We can use <a href=\"http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-List.html#v%3aspan\" rel=\"nofollow\"><code>span</code></a> instead of <code>takeWhile</code> and <code>dropWhile</code>. This is clearer and also more efficient as we only have to traverse the list once instead of twice.</p>\n\n<pre><code>splitStr :: Eq a => a -> [a] -> [[a]]\nsplitStr _ [] = []\nsplitStr c xs = ys : splitStr c (drop 1 zs)\n where (ys, zs) = split (c/=) xs\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T08:46:26.640",
"Id": "13998",
"ParentId": "13888",
"Score": "4"
}
},
{
"body": "<p>Let me deal with <code>outQ</code>. I see 3 problems there:</p>\n\n<ol>\n<li>stateful computation without a monad (passing the generator state around)</li>\n<li>recursion instead of library function (<code>forever</code> from <code>Control.Monad</code> is appropriate)</li>\n<li>using <code>!!</code> to repeatedly access lists which is O(N) and thus not a good idea in most cases.</li>\n</ol>\n\n<p>Let's clean up recursive calls so only the changing parts are passed around and constant parts are kept in a closure:</p>\n\n<pre><code>outQ list l sec = foo where\n foo g = do\n clearScreen\n setCursorPosition 0 0 -- row col\n let (index, gen') = randomR (0, l) g\n putStrLn $ list !! index\n\n threadDelay $ sec * oneSecond\n foo gen' -- works\n</code></pre>\n\n<p>It's a good practice to split recursive parts from non-recursive, so you more easier can see which library function to use for recursion:</p>\n\n<pre><code>forever1 f = f >=> forever1 f\n\noutQ list l sec = forever1 foo where\n foo g = do\n clearScreen\n setCursorPosition 0 0 -- row col\n let (index, gen') = randomR (0, l) g\n putStrLn $ list !! index\n\n threadDelay $ sec * oneSecond\n return gen'\n</code></pre>\n\n<p>Now we can load <code>ghci Quotes.hs</code> and check <code>:t forever1</code>. It tells us that</p>\n\n<p>forever1 :: Monad m => (b -> m b) -> b -> m c</p>\n\n<p>Using Hoogle we check that there's no standard function with such type, so we have to stick \nwith our own. Now we can get rid of <code>foo</code>:</p>\n\n<pre><code>outQ list l sec = forever1 $ \\g -> do\n clearScreen\n setCursorPosition 0 0 -- row col\n let (index, gen') = randomR (0, l) g\n putStrLn $ list !! index\n\n threadDelay $ sec * oneSecond\n return gen'\n</code></pre>\n\n<p>As for getting rid of generator passing, there are two options:</p>\n\n<ol>\n<li>To use <code>RandT</code> monad transformer from <code>Control.Monad.Random</code></li>\n<li>To use <code>randomRs</code> function to generate all random numbers outside of <code>outQ</code></li>\n</ol>\n\n<p>For such simple case it's better to stick with option 2. Note as we don't need to pass anything from previous iteration call to next one, we can now use library function <code>mapM_</code>:</p>\n\n<pre><code>outQ list l sec = mapM_ $ \\index -> do\n clearScreen\n setCursorPosition 0 0 -- row col\n putStrLn $ list !! index\n\n threadDelay $ sec * oneSecond\n\nmain :: IO ()\nmain = do\n setTitle \"Quotes\"\n hideCursor -- catch ctrl+c for showCursor\n gen <- newStdGen \n str <- readFile fileName\n let qlist = splitStr '~' str\n let len = length qlist -1\n let rand = randomRs (0, len) gen\n outQ qlist len delay rand\n</code></pre>\n\n<p>At this point we can convert our <code>list</code> to an immutable array:</p>\n\n<pre><code>outQ array sec = mapM_ $ \\index -> do\n clearScreen\n setCursorPosition 0 0 -- row col\n putStrLn $ array ! index\n\n threadDelay $ sec * oneSecond\n\nlistArray' l = listArray (1, length l) l\n\nmain :: IO ()\nmain = do\n setTitle \"Quotes\"\n hideCursor -- catch ctrl+c for showCursor\n gen <- newStdGen \n str <- readFile fileName\n let qlist = splitStr '~' str\n\n let qarray = listArray' qlist\n let rand = randomRs (bounds qarray) gen\n outQ qarray delay rand\n</code></pre>\n\n<p>At this point I see there's no need in passing both <code>array</code> and <code>rand</code> to <code>outQ</code>:</p>\n\n<pre><code>outQ sec = mapM_ $ \\s -> do\n clearScreen\n setCursorPosition 0 0 -- row col\n putStrLn s\n threadDelay $ sec * oneSecond\n\nlistArray' l = listArray (1, length l) l\n\nmain :: IO ()\nmain = do\n setTitle \"Quotes\"\n hideCursor -- catch ctrl+c for showCursor\n gen <- newStdGen \n str <- readFile fileName\n let qlist = splitStr '~' str\n\n let qarray = listArray' qlist\n let rand = randomRs (bounds qarray) gen\n let stringsToDisplay = map (qarray !) rand\n outQ delay stringsToDisplay\n</code></pre>\n\n<p>Now <code>outQ</code> is crystal clear, so we can condense <code>main</code>:</p>\n\n<pre><code>main :: IO ()\nmain = do\n setTitle \"Quotes\"\n hideCursor -- catch ctrl+c for showCursor\n qarray <- listArray' <$> splitStr '~' <$> readFile fileName\n map (qarray !) <$> randomRs (bounds qarray) <$> newStdGen >>= outQ delay \n</code></pre>\n\n<p>Finally, to make code more readable, we can extract two general functions which may become useful elsewhere:</p>\n\n<pre><code>mapM_interval sec f = mapM_ $ \\s -> do\n f s\n threadDelay $ sec * oneSecond\n\nrandomElemsFrom qarray = map (qarray !) . randomRs (bounds qarray)\n\nmain :: IO ()\nmain = do\n setTitle \"Quotes\"\n hideCursor -- catch ctrl+c for showCursor\n qarray <- listArray' <$> splitStr '~' <$> readFile fileName\n randomElemsFrom qarray <$> newStdGen >>= mapM_interval delay outQ\n</code></pre>\n\n<p>As the delay may be applied to other functions such as <code>forever</code>, <code>mapM</code> without underscore and, <code>forM_</code> etc, you may want to generalize mapM_interval further:</p>\n\n<pre><code>withInterval sec mapFn innerFn = mapFn $ \\s -> innerFn s >> threadDelay (sec * oneSecond)\n\nmain :: IO ()\nmain = do\n setTitle \"Quotes\"\n hideCursor -- catch ctrl+c for showCursor\n qarray <- listArray' <$> splitStr '~' <$> readFile fileName\n randomElemsFrom qarray <$> newStdGen >>= withInterval delay mapM_ outQ\n</code></pre>\n\n<p>So the final version is:</p>\n\n<pre><code>import System.Random (randomRs, newStdGen)\nimport Control.Concurrent (threadDelay) -- microseconds\nimport System.Console.ANSI (clearScreen, setCursorPosition, setTitle, hideCursor)\nimport Control.Applicative ((<$>))\nimport Data.Array (listArray, bounds, (!))\nimport Data.List.Split (splitOn)\n\nfileName = \"quotes.txt\"\noneSecond = 1000000\ndelay = 1 -- sec\n\n--clear = putStr \"\\ESC[2J\" -- not working on windows\n\noutQ s = do\n clearScreen\n setCursorPosition 0 0 -- row col\n putStrLn s\n\nlistArray' l = listArray (1, length l) l\n\nrandomElemsFrom qarray = map (qarray !) . randomRs (bounds qarray)\n\nwithInterval sec mapFn innerFn = mapFn $ \\s -> innerFn s >> threadDelay (sec * oneSecond)\n\nmain :: IO ()\nmain = do\n setTitle \"Quotes\"\n hideCursor -- catch ctrl+c for showCursor\n qarray <- listArray' <$> splitOn \"~\" <$> readFile fileName\n randomElemsFrom qarray <$> newStdGen >>= withInterval delay mapM_ outQ\n</code></pre>\n\n<p>Found yet another improvement:</p>\n\n<pre><code>randomElemsFrom x = map (qarray !) . randomRs (bounds qarray) where\n qarray = listArray' $ splitOn \"~\" x\n\nmain :: IO ()\nmain = do\n setTitle \"Quotes\"\n hideCursor -- catch ctrl+c for showCursor\n liftM2 randomElemsFrom (readFile fileName) newStdGen >>= withInterval delay mapM_ outQ\n</code></pre>\n\n<p>This version has more separation between monadic and non-monadic code (which is good) but <code>randomElemsFrom</code> was a generally useful function before but now it is tied to the task at hand (which is bad).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T16:34:05.183",
"Id": "28480",
"Score": "0",
"body": "WoW! Thanks for answer. I just came back from 58 days long vacation :) I didn't quit Haskell!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T13:03:55.613",
"Id": "15317",
"ParentId": "13888",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15317",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T02:16:46.010",
"Id": "13888",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Simple quotes app"
}
|
13888
|
<p>I don't see anyway for a SQL attack to happen with its all hard coded.</p>
<pre><code><?php
$db = mysql_connect('host', 'user', 'pass') or die('Could not connect: ' . mysql_error());
mysql_select_db('DBNAME') or die('Could not select database');
// Strings must be escaped to prevent SQL injection attack.
$name = mysql_real_escape_string($_GET['name'], $db);
$score = mysql_real_escape_string($_GET['score'], $db);
$QuestionN = mysql_real_escape_string($_GET['QuestionN'], $db);
$hash = $_GET['hash'];
$num = (int)$QuestionN;
$secretKey = "mykey"; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if ($real_hash == $hash) {
// Send variables for the MySQL database class.
if ($QuestionN == "1") {
if ($score == "A") {
$query = " UPDATE Quiz1 SET A = ( A + 1) WHERE Question = 1 ";
}
if ($score == "B") {
$query = " UPDATE Quiz1 SET B = ( B + 1) WHERE Question = 1 ";
}
if ($score == "C") {
$query = " UPDATE Quiz1 SET C = ( C + 1) WHERE Question = 1 ";
}
if ($score == "D") {
$query = " UPDATE Quiz1 SET D = ( D + 1) WHERE Question = 1 ";
}
}
if ($QuestionN == "2") {
if ($score == "A") {
$query = " UPDATE Quiz1 SET A = ( A + 1) WHERE Question = 2 ";
}
if ($score == "B") {
$query = " UPDATE Quiz1 SET B = ( B + 1) WHERE Question = 2 ";
}
if ($score == "C") {
$query = " UPDATE Quiz1 SET C = ( C + 1) WHERE Question = 2 ";
}
if ($score == "D") {
$query = " UPDATE Quiz1 SET D = ( D + 1) WHERE Question = 2 ";
}
}
if ($QuestionN == "3") {
if ($score == "A") {
$query = " UPDATE Quiz1 SET A = ( A + 1) WHERE Question = 3 ";
}
if ($score == "B") {
$query = " UPDATE Quiz1 SET B = ( B + 1) WHERE Question = 3 ";
}
if ($score == "C") {
$query = " UPDATE Quiz1 SET C = ( C + 1) WHERE Question = 3 ";
}
if ($score == "D") {
$query = " UPDATE Quiz1 SET D = ( D + 1) WHERE Question = 3 ";
}
}
if ($QuestionN == "4") {
if ($score == "A") {
$query = " UPDATE Quiz1 SET A = ( A + 1) WHERE Question = 4 ";
}
if ($score == "B") {
$query = " UPDATE Quiz1 SET B = ( B + 1) WHERE Question = 4 ";
}
if ($score == "C") {
$query = " UPDATE Quiz1 SET C = ( C + 1) WHERE Question = 4 ";
}
if ($score == "D") {
$query = " UPDATE Quiz1 SET D = ( D + 1) WHERE Question = 4 ";
}
}
if ($QuestionN == "5") {
if ($score == "A") {
$query = " UPDATE Quiz1 SET A = ( A + 1) WHERE Question = 5 ";
}
if ($score == "B") {
$query = " UPDATE Quiz1 SET B = ( B + 1) WHERE Question = 5 ";
}
if ($score == "C") {
$query = " UPDATE Quiz1 SET C = ( C + 1) WHERE Question = 5 ";
}
if ($score == "D") {
$query = " UPDATE Quiz1 SET D = ( D + 1) WHERE Question = 5 ";
}
}
if ($QuestionN == "6") {
if ($score == "A") {
$query = " UPDATE Quiz1 SET A = ( A + 1) WHERE Question = 6 ";
}
if ($score == "B") {
$query = " UPDATE Quiz1 SET B = ( B + 1) WHERE Question = 6 ";
}
if ($score == "C") {
$query = " UPDATE Quiz1 SET C = ( C + 1) WHERE Question = 6 ";
}
if ($score == "D") {
$query = " UPDATE Quiz1 SET D = ( D + 1) WHERE Question = 6 ";
}
}
if ($QuestionN == "7") {
if ($score == "A") {
$query = " UPDATE Quiz1 SET A = ( A + 1) WHERE Question = 7 ";
}
if ($score == "B") {
$query = " UPDATE Quiz1 SET B = ( B + 1) WHERE Question = 7 ";
}
if ($score == "C") {
$query = " UPDATE Quiz1 SET C = ( C + 1) WHERE Question = 7 ";
}
if ($score == "D") {
$query = " UPDATE Quiz1 SET D = ( D + 1) WHERE Question = 7 ";
}
}
if ($QuestionN == "8") {
if ($score == "A") {
$query = " UPDATE Quiz1 SET A = ( A + 1) WHERE Question = 8 ";
}
if ($score == "B") {
$query = " UPDATE Quiz1 SET B = ( B + 1) WHERE Question = 8 ";
}
if ($score == "C") {
$query = " UPDATE Quiz1 SET C = ( C + 1) WHERE Question = 8 ";
}
if ($score == "D") {
$query = " UPDATE Quiz1 SET D = ( D + 1) WHERE Question = 8 ";
}
}
if ($QuestionN == "9") {
if ($score == "A") {
$query = " UPDATE Quiz1 SET A = ( A + 1) WHERE Question = 9 ";
}
if ($score == "B") {
$query = " UPDATE Quiz1 SET B = ( B + 1) WHERE Question = 9 ";
}
if ($score == "C") {
$query = " UPDATE Quiz1 SET C = ( C + 1) WHERE Question = 9 ";
}
if ($score == "D") {
$query = " UPDATE Quiz1 SET D = ( D + 1) WHERE Question = 9 ";
}
}
if ($QuestionN == "10") {
if ($score == "A") {
$query = " UPDATE Quiz1 SET A = ( A + 1) WHERE Question = 10 ";
}
if ($score == "B") {
$query = " UPDATE Quiz1 SET B = ( B + 1) WHERE Question = 10 ";
}
if ($score == "C") {
$query = " UPDATE Quiz1 SET C = ( C + 1) WHERE Question = 10 ";
}
if ($score == "D") {
$query = " UPDATE Quiz1 SET D = ( D + 1) WHERE Question = 10 ";
}
}
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>Yes, it's secure because you aren't allowing any variable to be inserted as part of a query. However it is horribly inefficient as it violates the <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY principle</a>: you are writing the same code out in a dozen different places.</p>\n\n<p>A better (and perfectly secure by design) approach would be to use a <a href=\"http://php.net/manual/en/mysqli.quickstart.prepared-statements.php\" rel=\"nofollow noreferrer\">prepared statement</a> via a <a href=\"http://php.net/manual/en/book.pdo.php\" rel=\"nofollow noreferrer\">parameterised data object (PDO)</a>, which would allow all the sanitising of the data to happen automatically. See examples here: <a href=\"https://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php\">https://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php</a></p>\n\n<pre><code>$query = \"UPDATE Quiz1 SET :score1 = ( :score2 + 1) WHERE Question = :question \";\n$statement = $pdo->prepare($query);\n$params = array(\n 'score1' => 'A',\n 'score2' => 'A',\n 'question' => 2\n);\n$statement->execute($params);\nforeach ($statement as $row) {\n // Do stuff.\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T00:00:31.493",
"Id": "22439",
"Score": "0",
"body": "You cannot parameterize entity names. (`:score1` is not valid, since you'd essentially be doing `SET 'A' = 'A' + 1`, not `SET A = A + 1`.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T12:10:41.840",
"Id": "22454",
"Score": "0",
"body": "@Corbin Good catch - I missed that one. I'd edit to improve, but you've already posted some code that fixes the problem using an array of ascceptable values, so I'll leave it :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T23:10:41.007",
"Id": "13895",
"ParentId": "13891",
"Score": "3"
}
},
{
"body": "<p>Depends on if you actually use the variables containing the information you escaped. </p>\n\n<pre><code>// Strings must be escaped to prevent SQL injection attack. \n$name = mysql_real_escape_string($_GET['name'], $db);\n$score = mysql_real_escape_string($_GET['score'], $db);\n$QuestionN = mysql_real_escape_string($_GET['QuestionN'], $db);\n$hash = $_GET['hash'];\n</code></pre>\n\n<p>The problem with mysql_real_escape_string is that if you are using numeric values, they do not need to be quoted. If they are not quoted, you do not need a quote to break out from quotes. Thus, you can simply do: <code>0; drop table...</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T23:59:49.933",
"Id": "22438",
"Score": "0",
"body": "The problem isn't with mysql_real_escape_string; it's with people's misunderstanding of it. When working with numeric data, it should be interpolated into the query as numeric data, not as a string. mysql_real_escape_string is only meant to be used on strings. The easiest way to escape integers is to cast them to an integer in PHP. (`$i = (int) $i; $q = \"UPDATE ... SET c = {$i} WHERE ... \";`)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T13:02:52.293",
"Id": "22602",
"Score": "0",
"body": "As stated before, the `mysql_*` functions are outdated and should not be used."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T23:35:15.213",
"Id": "13899",
"ParentId": "13891",
"Score": "0"
}
},
{
"body": "<p>This code is secure, however, there are a lot of other issues with it.</p>\n\n<p>In particular:</p>\n\n<p><strong>Don't assume array key exists</strong></p>\n\n<p>I've elaborated on this in various other posts, so <a href=\"https://codereview.stackexchange.com/questions/12757/basic-user-registration-code-in-php/12769#12769\">here's a link</a>.</p>\n\n<p>In short, either use <a href=\"http://php.net/isset\" rel=\"nofollow noreferrer\">isset</a>, <a href=\"http://php.net/empty\" rel=\"nofollow noreferrer\">empty</a> or <a href=\"http://php.net/filter_input\" rel=\"nofollow noreferrer\">filter_input</a> to ensure that you do not access an array key that does not exist.</p>\n\n<p><strong>Always be aware of context</strong></p>\n\n<pre><code>if ($QuestionN == \"1\") {\n</code></pre>\n\n<p>Only use escaped data when you're actually putting it into the context where it needs to be escaped. Comparing or any kind of processing on escaped data doesn't make sense. For example, what if you had a <code>$name</code> that you needed to check the length of? <code>O'Reilly</code> would be 8 characters, but the MySQL escaped version, <code>O\\'Reilly</code> would be incorrectly considered 9.</p>\n\n<p><strong>A ton of code repetition</strong></p>\n\n<p>Matt Gibson nailed it on this one, but his implementation is wrong (you cannot bind object names in prepared statements).</p>\n\n<p>When working with entity and not data, instead of escaping, you'll want to always use whitelists (to prevent a user from using an incorrect or non-existent column, table, etc).</p>\n\n<pre><code> $scoreColumn = (isset($_GET['score']) && is_string($_GET['score'])) ? $_GET['score'] : null;\n\n$errors = array();\n\nif (!in_array($scoreColumn, array('A', 'B', 'C', 'D'))) {\n //Uh oh! This should be handled some how\n $errors[] = \"Invalid score provided\";\n}\n\n$question = (isset($_GET['question']) && is_string($_GET['question'])) ? (int) $_GET['question'] : null;\n\nif ($question === null) {\n //Error: question not provided\n $errors[] = \"No question provided\";\n} else if ($question < 1 || $question > 10) {\n //Error: invalid question provided\n $errors[] = \"Invalid question provided\";\n}\n\nif (!count($errors)) {\n $query = \"UPDATE Quiz1 SET {$scoreColumn} = ({$scoreColumn} + 1) WHERE Question = {$question}\";\n}\n</code></pre>\n\n<p><strong>mysql vs PDO</strong></p>\n\n<p>MySQL is an outdated, thin wrapped around MySQL's C API. You should be using either PDO or MySQLi (I strongly recommend PDO, but to each his own).</p>\n\n<p><strong>Schema</strong></p>\n\n<p>I suspect your schema could be changed to be more normalized. Hard to say with the information given, but I have a feeling that there's a few anti-patterns tucked away in your DB.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T03:35:00.300",
"Id": "22442",
"Score": "0",
"body": "Thanks for all the help thus far, basically I need to send data from a small survey type app . Now this is my first exposure to PHP and MySql , I'm talking to my database from a C# script, but I don't allow ANY direct text input from the user- basically they hit a button, that button tells the app to send a few specific strings up and exicute the code above . \n\nAny help with PDO would be great ... Variables inside of Mysql queries has been an absolute nightmare ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T04:02:47.050",
"Id": "22443",
"Score": "0",
"body": "This isn't working ether , do i have to change $question back into an int for the if < or > compare, then back into a string . So far I've been banging my head against the wall trying to submit variables inside of SQL queries"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T21:43:47.130",
"Id": "22465",
"Score": "0",
"body": "@user1539152 If C# application is connecting directly, that's a problem. I'm hoping you mean that the C# program makes calls to the script you posted in your original question? Anyway, $question needs to be an int for the inequalities, and it should also be an int when interpolating it into the string. Can you explain what problems you're having? Have you tried `echo`ing out the query to make sure it contains what you expect it to?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T23:58:20.187",
"Id": "13900",
"ParentId": "13891",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T20:19:22.760",
"Id": "13891",
"Score": "4",
"Tags": [
"php",
"sql",
"mysql",
"quiz"
],
"Title": "Updating quiz statistics in a database"
}
|
13891
|
<p>This is a fraction of the binary writer I'm writing, and I'm trying find some way to improve it.</p>
<pre><code>using System;
using System.Collections.Generic;
public class ByteBuffer
{
// List used to hold all bytes that will be read
private List<byte> buffer = new List<byte>(32);
private int bitIndex = 0;
/// <summary>
/// Writes an n bits byte onto the buffer.
/// </summary>
public void Write(byte source, int n)
{
if ((n + bitIndex) / 8 > buffer.Count)
{
buffer.AddRange(new byte[(n + bitIndex) / 8 - buffer.Count]);
}
for (int i = 0; i < n; i++)
{
buffer[(bitIndex + i) / 8] |= (byte)(((source >> (n - 1 - i)) & 1) << (int)(7 - (bitIndex + i) % 8));
}
bitIndex += n;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T22:45:35.787",
"Id": "22426",
"Score": "0",
"body": "For what you're doing here, working with data at the bit level is overkill IMHO. The intrinsic type is the `byte` so you should work at _that_ level at a minimum. You won't gain much in terms of efficiency and maintainability, in fact, it's quite the opposite. You're making it harder on yourself unnecessarily. Besides, that's why there's the [`BitArray`](http://msdn.microsoft.com/en-us/library/System.Collections.BitArray.aspx) type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T00:54:00.843",
"Id": "22440",
"Score": "2",
"body": "@JeffMercado In some cases, this is exactly what you need to do. For example, when implementing Huffman coding or some other compression algorithm."
}
] |
[
{
"body": "<p>If you're after efficiency, you shouldn't write bit by bit. For example, if <code>bitIndex</code> is currently 3 and you're writing the full 8 bits, just two steps are necessary: writing 5 bits to one byte and then the remaining 3 bits to another byte.</p>\n\n<p>And depending on what you do, writing directly to some <code>Stream</code> might make more sense than using a <code>List<byte></code>.</p>\n\n<p>Also, you should probably check the input and throw and exception if <code>n</code> is not between 1 and 8.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T21:42:28.023",
"Id": "22423",
"Score": "0",
"body": "Well, about using a stream, I'm only using the `List<byte>` because of the automatic expansion and Add/AddRange, to exclude the need of a `WriteIndex` field. Would the stream overhead, in fact, worth it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T21:48:37.797",
"Id": "22424",
"Score": "0",
"body": "I mean, you're most likely going to write the result to a file or network anyway in the end, no? If that's the case, it would be more efficient to write it there as soon as possible."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T21:19:56.820",
"Id": "13894",
"ParentId": "13892",
"Score": "1"
}
},
{
"body": "<p>I'm going to go out on a limb, not knowing the full extent of the use cases of the class, but there's a pretty decent class, <code>BitArray</code> that might handle your needs as such:</p>\n\n<pre><code>using System;\nusing System.Collections;\n\npublic class ByteBuffer\n{\n // List used to hold all bytes that will be read\n private BitArray buffer;\n\n /// <summary>\n /// Writes an n bits byte onto the buffer.\n /// </summary>\n public void Write(byte source, int n)\n {\n buffer = Append(buffer, source, n);\n }\n\n private static BitArray Append(BitArray current, byte source, int n)\n {\n var count = current == null ? 0 : current.Count;\n var bools = new bool[count + n];\n\n if (count > 0)\n {\n current.CopyTo(bools, 0);\n }\n\n if (n > 0)\n {\n var after = new BitArray(new[] { source });\n\n for (int i = 0; i < n; i++)\n {\n bools[count + i] = after[i];\n }\n }\n\n return new BitArray(bools);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T05:24:09.013",
"Id": "13903",
"ParentId": "13892",
"Score": "1"
}
},
{
"body": "<p>I ended up with an implementation that looks like this:</p>\n\n<pre><code>using System.Diagnostics;\n\npublic class ByteBuffer\n{\n public byte[] tempBuffer = new byte[16];\n\n public int tempIndex = 0;\n\n /// <summary>\n /// Writes the given number of bits.\n /// </summary>\n public void Write(byte value, int bits)\n {\n Debug.Assert(bits > 0 && bits < 9, \"Number of bits must be between 1 and 8.\");\n\n int localBitLen = (tempIndex % 8);\n if (localBitLen == 0)\n {\n tempBuffer[tempIndex >> 3] = value;\n tempIndex += bits;\n return;\n }\n\n tempBuffer[tempIndex >> 3] &= (byte)(255 >> (8 - localBitLen)); // clear before writing\n tempBuffer[tempIndex >> 3] |= (byte)(value << localBitLen); // write first half\n\n\n // need write into next byte?\n if (localBitLen + bits > 8)\n {\n tempBuffer[(tempIndex >> 3) + 1] &= (byte)(255 << localBitLen); // clear before writing\n tempBuffer[(tempIndex >> 3) + 1] |= (byte)(value >> (8 - localBitLen)); // write second half\n }\n\n tempIndex += bits;\n }\n}\n</code></pre>\n\n<p>I was able to do it with the help of some calculators (I just hate being bad with bitwise operations).</p>\n\n<p>I had to use a <code>byte[]</code> rather than a stream since I can't write directly on the stream back-buffer. I might implement the Read, and exponential expansion for the buffer tomorrow.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T00:46:59.413",
"Id": "13916",
"ParentId": "13892",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "13903",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T20:35:37.490",
"Id": "13892",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Byte buffer writer"
}
|
13892
|
<p>I have started my hand at writing some scheme code. I am trying to get the first n primes. I plan to do so but first getting a list from <code>2</code> to <code>m</code>, and doing the following algorithm. Remove the first number and place in the primes list, remove all #'s from the initial list that are multiples of the number just pulled off, repeat until the size of the primes list equals <code>n</code>.</p>
<p>There are no loops in scheme so I have to use recursion and also modulo will probably help me, how might I go about writing the method "<code>listminusnonprimes</code>"? Also does my code so far look good?</p>
<p>Code: </p>
<pre><code>;Builds a list from [arg] to 2
(define buildlist
(lambda (m)
(if (<= m 2)
'(2)
(cons m (buildlist(- m 1))))))
;Returns a list from 2 to [arg]
(define listupto
(lambda (m)
(reverse (buildlist m))))
;Returns a list with nonprimes based off num removed
(define listminusnonprimes
(lambda (num list)
(
;Returns the first n primes
(define firstnprimes
(lambda (n nlist slist)
(append (car nlist) slist)
(if (= n (length slist))
slist
(firstnprimes (- n 1) (listMinusNonprimes (car nList) nlist) slit))))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T23:03:46.057",
"Id": "22427",
"Score": "0",
"body": "Just out of curiosity, wouldn't it be simpler to just build a list of primes by keeping track of the primes found, and for each number see if it is divisible by one of the already found primes (until you've found enough)? Is there a reason (beyond curiosity) for building the initial list?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T23:06:13.717",
"Id": "22428",
"Score": "0",
"body": "We are talking about a software sieve and ways we can apply it to find out answer to problems. We were allowed to choose from finding hamming primes, to printing out the fib#'s. But we must implement a sort of sieve. Mine is outlined in the algorithm of removing #'s that a multiples of the first # in the list. I am not sure how to iterate through the list and check each # for its divisibility."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T23:09:47.163",
"Id": "22429",
"Score": "0",
"body": "You can include the accumulated list of primes as an argument to your function (starting with either an empty or a small list such as the one just containing 2) generating the list, each time you find a new prime, you simply tuck it on to this list of primes before recursing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T23:20:37.120",
"Id": "22430",
"Score": "1",
"body": "@BumSkeeter FWIW you can write loops with `do`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T23:41:13.683",
"Id": "22431",
"Score": "0",
"body": "If this is homework, you should tag it accordingly"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T23:47:07.927",
"Id": "22432",
"Score": "0",
"body": "indeed, I shall"
}
] |
[
{
"body": "<p>In your function <code>firstnprimes</code> there is a typo near the end; more importantly it uses <code>append</code> but it is the wrong function to use there. What does <code>append</code> append? If called with two arguments the 2nd of which is a list, what must the first argument be - a list, or a value?</p>\n\n<p>Another problem is your call <code>(append (car nlist) slist)</code> returns new value, a bigger list, but you do nothing with it. <code>slist</code>'s value remains unchanged.</p>\n\n<p>What are the two arguments of <code>firstnprimes</code> function, <code>nlist</code> and <code>slist</code>? What are their initial values? Will any two lists do? Obviously not. So, it seems better to define the real top-level function that is safe and easy to use:</p>\n\n<pre><code>(define myfirstnprimes\n (lambda (n)\n (firstnprimes n (listupto ...) (...))))\n</code></pre>\n\n<p>Something is missing there, isn't it? Some new, hidden parameter? </p>\n\n<p>Now, you ask how to implement</p>\n\n<pre><code>(define listminusnonprimes\n (lambda (num list)\n ....\n</code></pre>\n\n<p>you call it as <code>(listMinusNonprimes (car nList) nlist)</code> so we know that initially, <code>num</code> is the first element of <code>list</code>; we also know that <code>list</code> is an ordered list of numbers increasing in value. So we just need to compare <code>num</code> with the <code>list</code>'s first element:</p>\n\n<pre><code> (let ((a (car list)))\n (cond\n ( (< num a) ... (listminusnonprimes ...) )\n ( ... )\n ( ... ))) ))\n</code></pre>\n\n<p>what are the cases? less-then, equal, greater-then, right? All that's left is to fill in the blanks. In particular, if the two are equal, both need to be removed and <code>num</code> changed to the next multiple of the prime; if <code>num</code> is greater, the top element should be kept; otherwise <code>num</code> should be changed to the next multiple of the prime. New missing parameters come into light here (<em>prime</em>... what prime? <em>next multiple</em>... how to find it?); also it isn't clear what does it mean \"to keep\" and \"to remove\", right?</p>\n\n<p>About multiples, just write them down in a sequence first: <code>p, 2p, 3p, 4p, ...</code>. Now devise a method of finding the next from the previous one. What information will you have to maintain?</p>\n\n<p>About keeping/removing. There are two ways. One will lead to using <code>set-cdr!</code>, another to using <code>cons</code>, and an additional accumulator parameter. Choose any to your liking.</p>\n\n<p>Lastly, your <code>buildlist</code> builds a descending list <em>towards</em> 2, and <code>listupto</code> just reverses it; instead move the former into the latter and have it build the correct list right away <em>from</em> 2 up to the upper limit, held by <code>listupto</code>'s argument:</p>\n\n<pre><code>(define (listupto m)\n (let buildlist ((n 2))\n (if (> n m) ...\n (cons n (buildlist ...)))))\n</code></pre>\n\n<p>Named let is described e.g. <a href=\"http://docs.racket-lang.org/guide/let.html#%28part._.Named_let%29\" rel=\"nofollow\">here</a>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-21T08:53:10.977",
"Id": "13898",
"ParentId": "13896",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T22:36:09.953",
"Id": "13896",
"Score": "3",
"Tags": [
"homework",
"scheme",
"primes"
],
"Title": "Scheme, first timer first program, simple list removal technique"
}
|
13896
|
<p>So far, I've used this in a few places and it seems solid.</p>
<p>This is what I usually do to make a singleton:</p>
<pre><code>// Assume x86 for now
#ifdef _MSC_VER
#include <intrin.h> // for _mm_pause
#else
#include <xmmintrin.h> // for _mm_pause
#endif
#include <cstdint>
#include <exception>
#include <atomic>
#include <memory>
// When thrown by get(), this indicates the singleton failed to initialize.
//
// It is better to devise a more elaborate set of exceptions for diagnostic purposes
// (e.g. If it must be initialized in the main thread only, etc...).
class bad_singleton : public std::exception{};
template<typename singleton_t>
class singleton
{
// Should start life as false, no initialization logic needed
// (unless working with a brain-dead compiler, in which case
// we're screwed anyway).
static bool _bad_singleton;
// This should also be 0 on start, but some platforms might require
// a constructor that could fudge things if it runs while the lock is
// being used (meaning that the platform requires kernel objects for all atomic
// operations). To make this robust, use a plain uintptr_t here and
// OS-provided atomic functions (e.g. _InterlockedExchange[64]), If atoms aren't
// supported, you shouldn't be using threads anyway.
static std::atomic<uintptr_t> _spinlock;
// Once again, shared_ptr might require initialization logic
// that could run after the allocation in get() [assuming we have things
// running before main]. To make this robust, use a pointer here
// and OS-provided atomic functions.
static std::shared_ptr<singleton_t> _handle;
public:
static std::shared_ptr<singleton_t> get()
{
// Assumes acquire semantics on read.
if(_handle){
// _handle is nonzero? Instant return!
return _handle;
}else{
// Every thread that found _ptr to be null will end up here
// and spin until the lock is released.
while(_spinlock.exchange(1))
{
// One can use system calls here (like Sleep(0) on Windows) if desired
//
// Otherwise, this has a similar effect without dragging in too much
// platform-specific gunk.
_mm_pause();
}
// Only one thread at a time here, so check once more and return
// (another thread could have finished constructing the instance).
if(_handle){
_spinlock.exchange(0);
return _handle;
}
if(_bad_singleton){
// The singleton failed to initialize in another thread.
// EDIT: Forgot to release the lock
_spinlock.exchange(0);
throw bad_singleton();
}
// Since it is assumed that the constructor does something
// simple or nothing at all, the only overhead here is
// having to allocate space on the heap. This is also
// why singletons like this should be made initially
// as small as possible in order to reduce the probability
// of an allocation failure.
singleton_t *_frob = nullptr;
try{
_frob = new singleton_t();
// EDIT: Prevent possible premature _handle initialization
// forces new singleton_t() to finish execution before
// initializing _handle.
//
// It is also assumed that the singleton's constructor
// returns only when the instance is fully initialized.
_WriteBarrier(); //<- or equivalent
std::shared_ptr<singleton_t> _derp(_frob);
// EDIT: Shared_ptr allocates a control block, so
// we could still have a garbage pointer if directly
// constructed into _handle.
_WriteBarrier();
// This should not do anything that throws an exception.
//
// In fact, this should be atomic (It can be made so in a custom
// handle implementation).
_handle = move(_derp);
}catch(...){
// Diaper has been soiled...
// EDIT: Forgot that shared_ptr allocates a control block.
//
// Is possible to have _frob without _handle...
if(_frob)delete _frob;
// There is probably a way to reproduce this exception
// for all other threads, but for now, just throw a
// bad_singleton exception everywhere else.
_bad_singleton = true;
_spinlock.exchange(0);
// Throw whatever was caught for logging.
throw;
}
// Now release the spinlock to let any contending threads in.
_spinlock.exchange(0);
return _handle;
}
}
};
template<typename singleton_t>
bool singleton<singleton_t>::_bad_singleton;
template<typename singleton_t>
std::atomic<uintptr_t> singleton<singleton_t>::_spinlock;
template<typename singleton_t>
std::shared_ptr<singleton_t> singleton<singleton_t>::_handle;
class my_singleton
{
protected:
// allows the singleton wrapper to use the constructor
friend class singleton<my_singleton>;
my_singleton()
{
// Very simple things in here
//
// Split singletons into related subsystems
// that can be initialized when required,
// but in a controlled way through the instance
// itself (e.g. allocate a kernel object and
// use that for serializing initializations of other
// systems that take longer or are more complex).
}
private:
// No duplicating or moving this singleton whatsoever
my_singleton &operator=(const my_singleton &);
my_singleton &operator=(my_singleton &&);
my_singleton(const my_singleton &);
my_singleton(my_singleton &&);
public:
// Destructor is out here in the public because shared_ptr needs it.
//
// A custom smart handle implementation could allow for private destructors.
~my_singleton()
{
// Note that this will only get called
// when the last shared_ptr has been destroyed.
//
// Note also that _handle will keep the singleton
// alive when there are no handles elsewhere
// during execution.
}
};
int main(int argc, char **argv)
{
std::shared_ptr<my_singleton> hsingleton;
try{
hsingleton = singleton<my_singleton>::get();
}catch(bad_singleton &){
// blah initialization error
}catch(...){
// blah all other errors
}
return 0;
}
</code></pre>
<p>Using a template wrapper avoids the complexities associated with inheriting from "singletons" that implement their own initialization logic.</p>
<p>To me, it seems this can't break if used within one process.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T02:12:50.213",
"Id": "22441",
"Score": "1",
"body": "Unfortunately it is broken in a couple of ways. 1) Double checked locking does not work correctly. 2) Order of initialization problems. Full review to come. But it is much easier to write a singleton than you have made it. Take a look here: http://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289 All you need is some locks and the link will work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T04:13:59.610",
"Id": "22444",
"Score": "0",
"body": "Thank you for taking the time. However, I am curious as to how it could be broken. \"_handle\" is presumably atomic (represented here as an std::shared_ptr), such that even if threads spuriously find it null, they'd still have to wait in the spinlock (not only that, it could never be a partial write). Unless something odd happens when reading from an address that has a pending write..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T04:25:26.617",
"Id": "22445",
"Score": "0",
"body": "I'd also like to add that, unless the compiler was written by moldy radishes, it should allocate 4 (or 8) bytes in the executable's image for _spinlock and _ptr, and 1 byte for _bad_singleton, and fill them with 0s. That is, when the image is read into memory, the values for those variables were already 0: No initialization should be needed. If only atomic functions are used on an integer and a pointer (_InterlockedXXX intrinsics with MSC), there is no chance of an initialization interfering with the lock (unless the compiler generates initialization code for individual integers)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T04:31:48.433",
"Id": "22446",
"Score": "0",
"body": "About edit: If forgot to release the spinlock in `if(_handle)...` and `if(_bad_singleton)...`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T04:48:34.467",
"Id": "22447",
"Score": "0",
"body": "Also, I don't allow singletons to request the initialization of another singleton internally, unless the relationship is one-directional. Singletons effectively represent subsystems whose dependencies should form a DAG. If there are cycles in their dependency graph, it is always possible to break them by either coalescing two or more subsystems or introducing a \"mediator\" that does nothing but initialize the two at some point (handled through a specialization of the singleton template)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T05:08:52.103",
"Id": "22448",
"Score": "0",
"body": "About this being difficult: With this template, I don't have to write a \"get_instance\" function for every singleton; a genuine time-saver IMO. Although I only allow a handful of them to exist in a project, it helps to keep the code in one place as to reduce the time spent hunting for errors should any crop up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T10:54:45.263",
"Id": "22650",
"Score": "0",
"body": "There is no point in `get` returning an `std::shared_ptr` since `_handle` has static storage duration and will maintain the object alive for the duration of the program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T13:39:44.017",
"Id": "22657",
"Score": "0",
"body": "That is the idea: The destructor for the shared_ptr is actually called during static cleanup. If there aren't any other handles, the data it points to gets deleted."
}
] |
[
{
"body": "<p>Your use of underscore is correct for variables. <strong>BUT</strong> the actual rules are complex enough, that using them at the start of an identifier is not a good idea. Do you know what all the rules for underscore as the first character of an identifier are? See <a href=\"https://stackoverflow.com/a/228797/1198654\">this SO thread</a> for an in-depth discussion.</p>\n\n<p>You use <code>_WriteBarrier()</code>. This identifier is reserved by the implementation. If you have written this you need to change its name. If this is provided by your implementation its non portable and you are probably using it incorrectly. Any function begin with an underscore provided by the implementation is usually private and there is a function without the underscore that provides public access to this function. Use that.</p>\n\n<p>Note: The compiler is no help and will not warn you when you do it incorrectly.</p>\n\n<p>Order of construction problem:</p>\n\n<pre><code>// Once again, shared_ptr might require initialization logic\n// that could run after the allocation in get() [assuming we have things\n// running before main]. To make this robust, use a pointer here\n// and OS-provided atomic functions.\nstatic std::shared_ptr<singleton_t> _handle;\n</code></pre>\n\n<p>Don't use a pointer to solve it. It just makes the problem worse.</p>\n\n<p>The best way to solve it is using a static member of a static method:</p>\n\n<pre><code>static std::shared_ptr<singleton_t>& getHandle()\n{\n static std::shared_ptr<singleton_t> theHandle;\n return theHandle;\n}\n</code></pre>\n\n<p>If you are worried about construction in a multi-threaded environment. Then add a lock. Note: In gcc it is already guaranteed thread safe but you will need code for other compilers.</p>\n\n<p>Your write barriers:</p>\n\n<pre><code> _frob = new singleton_t();\n _WriteBarrier();\n std::shared_ptr<singleton_t> _derp(_frob);\n _WriteBarrier();\n _handle = move(_derp);\n</code></pre>\n\n<p>Lets assume your <code>_WriteBarrier()</code> actually works. But there is no way to determine this as there is no code for it.</p>\n\n<p>Your first write barrier is a waste of time (and just superfluous code) as <code>derp</code> is not accessed by any other code and can only be accessed by one thread (you have caught other threads in a trap).</p>\n\n<p>The second <code>_WriteBarrier()</code> is where you need a barrier. But it still does not do anything useful as a shared pointer is not atomic or thread safe. Thus half way through the update of this variable (<code>_handle</code>) one of the other threads could escape your trap above result in code being executed using a variable in a non consistent state.</p>\n\n<p>Template's instantiation of members is definitely a bad idea (when done in a header file). </p>\n\n<pre><code>template<typename singleton_t>\nbool singleton<singleton_t>::_bad_singleton;\ntemplate<typename singleton_t>\nstd::atomic<uintptr_t> singleton<singleton_t>::_spinlock;\ntemplate<typename singleton_t>\nstd::shared_ptr<singleton_t> singleton<singleton_t>::_handle;\n</code></pre>\n\n<p>This basically creates an instance of each variable of each type that is used in every compilation unit. Though the linker will then consolidate multiple instances across compilation units for you when building a application (from simple object files) into a single variables. It will <strong>not</strong> do so correctly when building shared libraries. Because the standard has nothing to say about shared libraries. Shared libraries and the runtime linker do not have enough information to consolidate the variables across multiple shared libraries.</p>\n\n<p>Thus each shared library that uses your code will have its own copy of these variables for each type that is used by the library. Thus which variable is used will depend on the library in which the code is called. Thus you can not build shared libraries using your code which makes it practically worthless.</p>\n\n<p>Anyway your code is way over-complicated:\nThe classic singleton design is much simpler (and safer): <a href=\"https://stackoverflow.com/a/1008289/14065\">See this</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T10:47:29.407",
"Id": "22648",
"Score": "1",
"body": "There is nothing wrong with the definitions (which are not instantiations) of the static data members of `singleton`, by virtue of it being a template. In any case `inline` can only be used with functions or function templates, not objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T10:48:26.943",
"Id": "22649",
"Score": "0",
"body": "That [_WriteBarrier](http://msdn.microsoft.com/en-us/library/65tt87y8(v=vs.80).aspx) is certainly not his own function nor is it meant to be an implementation detail."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T13:40:48.443",
"Id": "22658",
"Score": "0",
"body": "_WriteBarrier is an MS-specific compiler intrinsic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T13:48:28.927",
"Id": "22659",
"Score": "0",
"body": "Your suggestion is basically what is known as the Meyer's Singleton (not thread-safe). Furthermore, the C++ compilers I have access to DO NOT generate initialization guards. I have both MSC v10 and Intel C++ v12: Neither of which generate thread-safe static variable initialization guards (just a test and a jump). The code you suggest I use is completely unsafe for concurrent initializations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T13:52:37.240",
"Id": "22660",
"Score": "0",
"body": "When it comes to static data in any class, template or otherwise, it has to be initialized outside of the class (unless it is of constant integral type). Those lines are there merely to satisfy that requirement. If replaced with \"atoms\" (register-sized integers), they don't require the compiler to generate anything more than space in the resulting image."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T17:23:29.347",
"Id": "22665",
"Score": "0",
"body": "@i_photon: If you had actually read the comments on the link you would see that the thread safe initialization is handled in one of the provided links."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T17:24:53.323",
"Id": "22666",
"Score": "0",
"body": "@i_photon: Yes static members must be initialized. **BUT** you should never initialise static members of a template in a header file (which is what it seems like you are doing). If I am wrong then fine. Otherwise it is just broken."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T17:30:02.800",
"Id": "22668",
"Score": "0",
"body": "@LucDanton: Whoops. You are correct. Fixing. Though I stand by the rest of the statement that it will cause problems with shared libraries."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T17:33:58.443",
"Id": "22669",
"Score": "0",
"body": "@Fanael: As your link points out it is a detail of the implementation. When I use the term `implementation` in this context I am talking about the compiler and its support libraries (this is standard way to refer to the compiler environment when you read the standards documents). You will see this terminology a lot on SO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T17:38:48.000",
"Id": "22670",
"Score": "0",
"body": "@i_photon: The \"Meyer Singelton\" (though he was not the first to actually use it) is much safer than this implementation. With only a single lock it becomes thread safe (in all contexts). Since it is a singelton the lock will not be a bottleneck as you can pass the reference around quite easily after creation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T18:09:03.453",
"Id": "22672",
"Score": "0",
"body": "You have to be kidding me. Mine is basically the same thing, but with a spinlock. The only difference here is the use of a shared_ptr to act as a handle instead of exposing a reference. Your repeated insistence that what I have written is broken without any proof is not productive, nor is it helpful to anyone looking for answers here. Either produce a solution that uses a \"lock\" as you suggest, or formal proof that what I have written is broken."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T18:20:45.703",
"Id": "22673",
"Score": "1",
"body": "I am sorry if you think this review is unhelpful. If you don't like me review feel free to ignore it. But it is broken: as I have pointed out in several places (Initialization Order/Shared_ptr is not atomic/Invalid for use in shared libraries). This is not a site for answers if you want a better solution ask on SO. But given the choice between a normal singelton (about 10 lines) verses 200 lines of code that is very hard to read (and thus maintain) I would use the normal version (as it is thread safe in C++11 and can easily be made thread safe in C++03 with a single lock) and is **portable**."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T14:16:56.550",
"Id": "22723",
"Score": "0",
"body": "@LokiAstari: see, the link doesn't say \"private, don't use\", so it's *not* an implementation *detail*. Yes, it's very implementation *specific*, but it's *public* and *meant to be used in user code*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T16:35:58.263",
"Id": "22727",
"Score": "0",
"body": "@Fanael: I stand by my use of the term *`implementation`* and it is used correctly in this context (Note it is only you who use the term 'implementation detail' and this is not correct in the context). Yes it is 'public' in the sense that you can see it, but it is not part of the public interface (as it is not in the standard). It is not mean for `general` public use in user code (ie you should not be using it willy nilly) but it can be used to help build some low-level features that are implementation specific."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T16:49:42.430",
"Id": "22729",
"Score": "0",
"body": "@Fanael: As notes [here](http://msdn.microsoft.com/en-us/library/ms254271%28v=vs.90%29.aspx) mainly for device drivers. Functions of this type (with leading underscore) usually provide a more public interface without the leading underscore (write() and _write() are usually good examples)but in this case there does not seem to be one (which is not all the surprising given that we are dealing with threads and they are not standardized until C++11 and the fact that we are looking at writing device driver code for windows)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T17:53:09.010",
"Id": "22732",
"Score": "0",
"body": "@LokiAstari: ah, okay, so we agree and you're just nitpicking over terminology."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T19:50:26.860",
"Id": "22738",
"Score": "0",
"body": "@Fanael: Probably :-)"
}
],
"meta_data": {
"CommentCount": "17",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T17:33:20.417",
"Id": "13978",
"ParentId": "13901",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T01:09:20.403",
"Id": "13901",
"Score": "3",
"Tags": [
"c++",
"singleton",
"template-meta-programming"
],
"Title": "Singleton with template wrapper"
}
|
13901
|
<p>I have a little experience with Python and am trying to become more familiar with it. As an exercise, I've tried coding a program where the ordering of a list of players is determined by the roll of a die. A higher number would place the player ahead of others with lower numbers. Ties would be broken by the tied players rolling again.</p>
<p>Here is an example:</p>
<blockquote>
<pre><code> player 1, player 2, player 3
rolls 6, rolls 6, rolls 1
/ \
/ \
player 1, player 2 player 3
rolls 5, rolls 4
/ \
/ \
player 1 player 2
</code></pre>
</blockquote>
<p>Final order: player 1, player 2, player 3</p>
<p>I'm interested in how I could have done this better. In particular, I'm not familiar with much of the Python style guide so making it more pythonic would be nice. Also, I'm not that familiar with unit testing. I've used unittest instead of nose since I was using an online IDE that supports it.</p>
<pre><code>from random import randint
from itertools import groupby
import unittest
def rank_players(playerList, die):
tree = [playerList]
nextGeneration = []
keepPlaying = True
while keepPlaying:
keepPlaying = False
for node in tree:
if len(node) == 1:
nextGeneration.append(node)
else:
keepPlaying = True
rolls = [die.roll() for i in range(len(node))]
turn = sorted(zip(rolls,node), reverse=True)
print 'players roll:', turn
for key, group in groupby(turn, lambda x: x[0]):
nextGeneration.append(list(i[1] for i in group))
tree = nextGeneration
nextGeneration = []
return [item for sublist in tree for item in sublist]
class Die:
def __init__(self,rolls=[]):
self.i = -1
self.rolls = rolls
def roll(self):
self.i = self.i + 1
return self.rolls[self.i]
class RankingTest(unittest.TestCase):
def testEmpty(self):
die = Die()
players = []
self.assertEquals(rank_players(players,die),[])
def testOnePlayer(self):
die = Die()
player = ['player 1']
self.assertEquals(rank_players(player,die),['player 1'])
def testTwoPlayer(self):
die = Die([6, 1])
players = ['player 1', 'player 2']
self.assertEquals(rank_players(players,die),['player 1', 'player 2'])
def testThreePlayer(self):
die = Die([6, 6, 1, 4, 5])
players = ['player x', 'player y', 'player z']
self.assertEquals(rank_players(players,die),['player x', 'player y','player z'])
def testRunAll(self):
self.testEmpty()
self.testOnePlayer()
self.testTwoPlayer()
self.testThreePlayer()
if __name__ == '__main__':
unittest.main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T10:01:02.427",
"Id": "22499",
"Score": "0",
"body": "Is there a reason for calling a dice \"die\"? BTW you can find some Python style guides [here](http://meta.codereview.stackexchange.com/a/495/10415)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T10:07:35.310",
"Id": "22500",
"Score": "0",
"body": "Take also a look [here](http://stackoverflow.com/q/1132941/1132524) to know why you shouldn't do `def __init__(self,rolls=[]):`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T15:46:14.210",
"Id": "22508",
"Score": "0",
"body": "Thanks for the links. I used the singular for dice, die, in an attempt to convey that each player would only do one roll for each turn. I would've liked a less ambiguous term."
}
] |
[
{
"body": "<p>Here's one way it could be done with a lot less code:</p>\n\n<pre><code>from itertools import groupby\nfrom operator import itemgetter\nfrom random import randint\n\ndef rank_players(playerList):\n playerRolls = [(player, randint(1, 6)) for player in playerList]\n playerGroups = groupby(\n sorted(playerRolls, key=itemgetter(1), reverse=True),\n itemgetter(1))\n for key, group in playerGroups:\n grouped_players = list(group)\n if len(grouped_players) > 1:\n for player in rank_players(zip(*grouped_players)[0]):\n yield player\n else:\n yield grouped_players[0]\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>>>> print list(rank_players([\"bob\", \"fred\", \"george\"]))\n[('fred', 5), ('george', 6), ('bob', 4)]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T15:52:26.340",
"Id": "22509",
"Score": "0",
"body": "I really appreciate your answer. I will look more carefully into it at the end of today. My impression is though, that this answer does not handle the case of two ties the way I was hoping to. For example, player 1 and player 2 tie with 5, player 3 is in the middle with 4, and player 4 and player 5 tie with 3. Thank you for your effort. I'm not sure of the procedure, but I will probably mark it as the answer by the end of today if it is the best available answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T17:14:21.390",
"Id": "22520",
"Score": "0",
"body": "@jlim: Ah, I see (hence your use of `groupby`.) Well this solution is easily extensible to that end, since the recursion works on any set of sublists of players. I am a little preoccupied at the moment, but I can probably post a modified solution in a couple of hours."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T19:36:35.410",
"Id": "22544",
"Score": "0",
"body": "@jlim: Updated my answer. This version will handle the possiblity of `n` ties, provided that `n` does not exceed the recursion limit ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T01:33:07.100",
"Id": "22569",
"Score": "0",
"body": "Thank you for the update. Sorry I don't have enough rep to up vote yet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T02:02:42.593",
"Id": "22571",
"Score": "0",
"body": "@jlim: No problem man. Glad to help"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T05:28:04.250",
"Id": "13921",
"ParentId": "13902",
"Score": "2"
}
},
{
"body": "<pre><code>from random import randint\nfrom itertools import groupby\nimport unittest\n\ndef rank_players(playerList, die): \n</code></pre>\n\n<p>Python convention is to use names like <code>player_list</code> for arguments/local variables</p>\n\n<pre><code> tree = [playerList] \n</code></pre>\n\n<p>This isn't really used to hold a tree. Its only ever two levels deep, so its a list of lists. You also shouldn't name variables after datastructures, you should name after the meaning in the code.</p>\n\n<pre><code> nextGeneration = []\n</code></pre>\n\n<p>You should move this into the loop. That way you won't have to repeat it later</p>\n\n<pre><code> keepPlaying = True\n while keepPlaying:\n keepPlaying = False\n</code></pre>\n\n<p>Its best to try and avoid boolean logic flags. They tend to make code harder to follow. If you can, try to structure code to avoid their use.</p>\n\n<pre><code> for node in tree: \n if len(node) == 1:\n nextGeneration.append(node)\n else:\n keepPlaying = True\n rolls = [die.roll() for i in range(len(node))]\n</code></pre>\n\n<p>I'd have done:</p>\n\n<pre><code> rolls = [ (die.role, item) for item in node]\n</code></pre>\n\n<p>This avoids the pointless call to len/range, and also handles the zipping in the next line</p>\n\n<pre><code> turn = sorted(zip(rolls,node), reverse=True)\n print 'players roll:', turn\n for key, group in groupby(turn, lambda x: x[0]):\n nextGeneration.append(list(i[1] for i in group))\n</code></pre>\n\n<p>Joel's recursive solution is much nicer, I think. </p>\n\n<pre><code> tree = nextGeneration\n nextGeneration = []\n return [item for sublist in tree for item in sublist]\n\nclass Die:\n def __init__(self,rolls=[]):\n</code></pre>\n\n<p>In general, don't assign mutable objects as defaults. Here I don't even see why you would have a default since the object is useless with the default constructor.</p>\n\n<pre><code> self.i = -1\n</code></pre>\n\n<p>I'd use index, just to be more explicit</p>\n\n<pre><code> self.rolls = rolls\n\n def roll(self):\n self.i = self.i + 1\n return self.rolls[self.i]\n</code></pre>\n\n<p>But here's how I'd write your function</p>\n\n<pre><code>def rank_players(player_list)\n random.shuffle(player_list)\n</code></pre>\n\n<p>All you are doing in the end is shuffling the list of players, and python has a function for that. Unless you really want to simulate dice, there isn't a lot of point in doing it.</p>\n\n<p>Another approach, I'm not sure a good one, would be:</p>\n\n<pre><code>class Die(object):\n def __init__(self, player):\n self.player = player\n self.rolls = []\n\n def __getitem__(self, index):\n # if you don't provide an __iter__\n # python will use __getitem__\n\n # whenever an attempt is made to access\n # past the end, we just roll a new number\n if index == len(self.rolls):\n roll = random.randrange(6)\n print \"Player: %s Rolls a: %d\" % (self.player, roll)\n self.rolls.append(roll)\n return roll\n else:\n return self.rolls[index]\n\n def __cmp__(self, other):\n # the only Die I am equal to is myself\n if self is other:\n return 0\n\n # look at the rolls in both die to \n # find first one that's different\n for a, b in itertools.izip(self, other):\n if a != b:\n return cmp(a,b)\n\n assert False\n\ndef rank_players(player_list):\n decorated = [(Die(player), player) for player in player_list]\n decorated.sort(reverse = True)\n print [die.rolls for die, player in decorated]\n return [player for die, player in decorated]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T01:42:16.143",
"Id": "22570",
"Score": "0",
"body": "Thank you for your input. I agree shuffle would be better, but I wanted to try out the dice rolling and node expansion idea. Sorry, I don't have enough rep to upvote yet. I will look over the rest of your answer later."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T22:55:45.920",
"Id": "13954",
"ParentId": "13902",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13921",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T01:13:54.113",
"Id": "13902",
"Score": "1",
"Tags": [
"python",
"random",
"tree",
"simulation"
],
"Title": "Die-rolling for ordering"
}
|
13902
|
<p>Answer in <a href="https://stackoverflow.com/questions/3140826/windows-system-time-with-millisecond-precision">this question</a> contains <code>DateTimePrecise</code> class that should return current date with millisecond precision. But class is pretty bug and complicated. So I wrote my own version which seems work fine. If you see any problems with my code?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class DateTimePrecise
{
private long startTick;
private Stopwatch sw;
public DateTimePrecise()
{
startTick = DateTime.Now.Ticks;
sw = Stopwatch.StartNew();
}
public DateTime CurDateTime()
{
return new DateTime(startTick + sw.ElapsedTicks);
}
}
}
</code></pre>
<p>I understand that my version is not <em>accurate</em>, meaning that actual system time may be less or more up to several milliseconds (Β±16 ms likely). But my version is still <em>precise</em> meaning that <em>couple of measurements</em> will defer at exactly spent <em>milliseconds</em>. And that's exactly what I need. I need precise but not necessary accurate clock because I only need to compare values between each other and I don't need exact current time up to milliseconds.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T17:58:31.867",
"Id": "22462",
"Score": "0",
"body": "You now need to be able to compare this instance to another or to any object, etc. so there are things like IComparable, IEquitable, ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T09:27:32.753",
"Id": "22495",
"Score": "0",
"body": "Reading your comment below, one thing doesn't make sense: what does *current* time have to do with plotting a graph?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T16:29:01.220",
"Id": "22519",
"Score": "1",
"body": "Microsoft has an example of using the high-resolution timer. This timer provides accuracy to the millisecond. A sample implementation is available here: http://msdn.microsoft.com/en-us/library/aa964692(v=vs.85).aspx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T08:49:07.977",
"Id": "22580",
"Score": "0",
"body": "@Groo because I need to see current time so I can go to trading terminal and to compare what I see on graph with what I see in terminal."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T10:13:10.347",
"Id": "22586",
"Score": "0",
"body": "@javapowered: I still don't see the need for millisecond precision for the current (inaccurate) time. Data which you receive from any data source should already be timestamped. If your PC is serving for some real-time capture from a hardware acquisition card with very low latency, I would see a (potential) need for this (although, again, you would calculate timestamps using sampling frequency, and it would still have nothing to do with current time). Adding ms to current inaccurate time provides no useful information IMHO, instead perhaps as some kind of a hack."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T10:13:49.393",
"Id": "22587",
"Score": "1",
"body": "You should describe your actual use case to get better suggestions, because I am pretty sure that this approach won't solve your problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T13:56:45.553",
"Id": "22605",
"Score": "0",
"body": "@Groo I want current time with +- 100 ms precision, but difference between any two measurements should be with +-1 ms precision. Use case - i need to draw graph in matlab (+- 1 ms precision) and compare it with trading terminal (need current time, +-100 ms precision is fine)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T08:09:01.777",
"Id": "30025",
"Score": "0",
"body": "@ReacherGilt your article with Microsoft HighRes timer is pretty old (for .net 3.0). I assume nowadays Stopwatch can be used instead of it."
}
] |
[
{
"body": "<p>If you don't need a precise <code>DateTime</code>, only differences, then don't use <code>DateTime</code> at all. I think you should work only with <code>TimeSpan</code>s.</p>\n\n<p>This will avoid confusion, because with your class, it looks like <code>DateTimePrecise\n.CurDateTime()</code> is better than <code>DateTime.Now</code>, even when used once. If you only used <code>TimeSpan</code>s, this wouldn't be a problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T14:09:52.453",
"Id": "22458",
"Score": "0",
"body": "i'm using this datetimes to plot graphics in matlab. so I need \"about\" true value (16ms precision is ok) so I can understand where I am on the graphic. but I also need to distinguish dots close to each other because i do analyze trades that close to each other (sometimes i do trade every 1 ms)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T11:00:05.160",
"Id": "13909",
"ParentId": "13908",
"Score": "1"
}
},
{
"body": "<p>You <em>can't</em> have a reliable 1 ms resolution timer like that. </p>\n\n<p>Anyone who knows otherwise should paste a minimal code that runs for full 5 minutes, and outputs an array of ~ 5*60*1000 ms ticks with a max diff of 2.</p>\n\n<hr>\n\n<p>Well, that being said, please consult my timer class and let me know if it's helpful for you:</p>\n\n<pre><code>public class TimerWrapper : ITimer\n{\n #region DLL IMPORT\n [DllImport(\"WinMM.dll\", SetLastError = true)]\n private static extern uint timeSetEvent(int msDelay, int msResolution,\n TimerEventHandler handler, ref int userCtx, int eventType);\n\n [DllImport(\"WinMM.dll\", SetLastError = true)]\n static extern uint timeKillEvent(uint timerEventId);\n\n [DllImport(\"Winmm.dll\")]\n private static extern int timeGetTime();\n #endregion\n\n public event Action<int> __Tick;\n public event Action __Stopped;\n\n public delegate void TimerEventHandler(uint id, uint msg, ref int userCtx,\n int rsv1, int rsv2);\n\n public void Stop()\n {\n timeKillEvent(m_fastTimer);\n InvokeStopped();\n }\n\n public void Start(int interval, int timeout)\n {\n m_res = 0;\n m_count = 0;\n _startCount = timeGetTime();\n m_maxCount = timeout * 1000 / interval;\n m_interval = interval;\n int myData = 0; // dummy data\n _thandler = new TimerEventHandler(tickHandler);\n m_fastTimer = timeSetEvent(interval, interval, _thandler,\n ref myData, 1); // type=periodic\n }\n\n private void InvokeTick(int t)\n {\n if (__Tick != null)\n {\n __Tick(t);\n }\n }\n\n private void InvokeStopped()\n {\n if (__Stopped != null)\n {\n __Stopped();\n }\n }\n\n private long m_maxCount;\n private int m_interval;\n private uint m_fastTimer;\n private long m_count;\n private int _startCount;\n private int _maxTimerTTL = 1000; // ms\n private int m_res;\n private TimerEventHandler _thandler;\n\n private bool IsInfinite { get { return m_maxCount < 0; } }\n private bool IsRestarted { get { return m_interval <= 100 && m_interval >= 5; } }\n\n private void tickHandler(uint id, uint msg, ref int userCtx, int rsv1, int rsv2)\n {\n int span = timeGetTime() - _startCount;\n InvokeTick(span + m_res);\n\n if (m_count++ >= m_maxCount && !IsInfinite)\n {\n Stop();\n }\n else if (IsRestarted && span > _maxTimerTTL)\n {\n m_res += span;\n RestartTimer();\n _startCount = timeGetTime();\n }\n }\n\n private void RestartTimer()\n {\n int myData = 0; // dummy data\n timeKillEvent(m_fastTimer);\n m_fastTimer = timeSetEvent(m_interval, m_interval, new TimerEventHandler(tickHandler), ref myData, 1); // type=periodic\n }\n}\n</code></pre>\n\n<p>Interface:</p>\n\n<pre><code>public interface ITimer\n{\n event Action<int> __Tick;\n event Action __Stopped;\n void Start(int interval, int timeout);\n void Stop();\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>public static void Main()\n{\n var barrier = new ManualResetEvent(false);\n var list = new List<int>();\n ITimer timer = new TimerWrapper();\n timer.__Tick += new Action<int> ( (i) => list.Add(i) );\n timer.__Stopped += new Action ( () => barrier.Set() );\n timer.Start(1, 5 * 60);\n barrier.WaitOne();\n foreach(var v in list)\n Console.WriteLine(v);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T20:22:02.267",
"Id": "18813",
"ParentId": "13908",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18813",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T10:18:43.380",
"Id": "13908",
"Score": "4",
"Tags": [
"c#",
"datetime"
],
"Title": "DateTimePrecise - current DateTime with millisecond precision"
}
|
13908
|
<pre><code>a=raw_input()
prefix_dict = {}
for j in xrange(1,len(a)+1):
prefix = a[:j]
prefix_dict[prefix] = len(prefix)
print prefix_dict
</code></pre>
<p>Is there any possibility of memory error in the above code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T04:57:24.287",
"Id": "22478",
"Score": "0",
"body": "A memory error? Please explain."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T16:02:52.827",
"Id": "22510",
"Score": "0",
"body": "@JoelCornett The above code is a part of another code from a contest. when tried on the website it gave a memoryerroer at `prefix = a[:j]\n`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T17:15:11.250",
"Id": "22521",
"Score": "0",
"body": "Oh, I see. What implementation of python are you using?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T17:31:03.087",
"Id": "22523",
"Score": "0",
"body": "@JoelCornett Sorry, but I lost you \"What implementation of python are you using?\" do u mean version or anything else??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T18:31:58.430",
"Id": "22527",
"Score": "0",
"body": "I mean, what are you running this code on? cPython? Jython? Stackless Python? The code as given shouldn't give you an error, so any errors would be platform specific. Are you sending this code to a server?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T18:55:59.573",
"Id": "22531",
"Score": "0",
"body": "@JoelCornett On my system its not giving any error but on the server of the website its giving an error, the server is a quad core Xeon machines running 32-bit Ubuntu (Ubuntu 12.04 LTS).For few cases its working and for few its showing memory error. FYI: I do not know the cases that they are testing but inputs are lower case alphabets."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T18:58:47.403",
"Id": "22533",
"Score": "0",
"body": "I suggest that you put this question on stackoverflow.com. You'll get an answer to your question more quickly that way."
}
] |
[
{
"body": "<p>The slice operator in <code>a[:j]</code> creates a copy of the sublist so is perfectly possible that you get a MemoryError.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-21T23:50:19.463",
"Id": "18900",
"ParentId": "13910",
"Score": "0"
}
},
{
"body": "<p>It's hard to tell what is making the error occur without giving us the input, but it's certainly possible the input is too large for the system to store.</p>\n\n<p><code>prefix_dict</code> will contain <code>len(a)</code> entries so if your input is larger than 32-bit python allows for dictionary size on your machine, then that could be the issue. </p>\n\n<p>I will note that instead of having <code>prefix_dict[prefix] = len(prefix)</code> you could just have <code>prefix_dict[prefix] = j</code> which would stop you from needing to do an extra length calculation each time (not that this would be the cause of the memory issue).</p>\n\n<p>Take a look at the sample output (I modified the print statement and used an example string):</p>\n\n<pre><code>>>> prefix_dict = {}\n>>> a = 'hello'\n>>> for j in xrange(1,len(a)+1):\n prefix = a[:j]\n prefix_dict[prefix] = len(prefix)\n print j, len(prefix), prefix_dict\n\n1 1 {'h': 1}\n2 2 {'h': 1, 'he': 2}\n3 3 {'hel': 3, 'h': 1, 'he': 2}\n4 4 {'hel': 3, 'h': 1, 'hell': 4, 'he': 2}\n5 5 {'hel': 3, 'h': 1, 'hell': 4, 'hello': 5, 'he': 2}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T01:33:53.587",
"Id": "18901",
"ParentId": "13910",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T12:07:51.700",
"Id": "13910",
"Score": "2",
"Tags": [
"python",
"strings",
"hash-map"
],
"Title": "Creating a dictionary of all prefixes of a string in Python"
}
|
13910
|
<p>Can someone please help to rewrite / tidy up this?</p>
<pre><code>// News Article Slideshow
var periodToChangeSlide = 5000;
var pp_slideshow = undefined;
var currentPage = 0;
$('#news-feature-img-wrap li').css('display', 'list-item').slice(1).css('display', 'none');
$('#news-items li:first').addClass('active');
$("#news-feature-wrap #news-items li").click(function () {
$(this).parent().addClass('active');
$(this).parent().siblings().removeClass('active');
var index = $(this).parent().index();
var toShow = $("#news-feature-wrap #news-feature-img-wrap li").eq(index);
toShow.show();
toShow.siblings().hide();
currentPage = index;
$.stopSlideshow();
});
$.startSlideshow = function () {
if (typeof pp_slideshow == 'undefined') {
pp_slideshow = setInterval($.startSlideshow, periodToChangeSlide);
} else {
$.changePage();
}
}
$.stopSlideshow = function () {
clearInterval(pp_slideshow);
pp_slideshow = undefined;
}
$.changePage = function () {
var numSlides = $('#news-feature-wrap #news-feature-img-wrap li').length;
currentPage = (currentPage + 1) % numSlides;
var menu = $('#news-feature-wrap #news-items li').eq(currentPage);
menu.addClass('active');
menu.siblings().removeClass('active');
var toShow = $("#news-feature-wrap #news-feature-img-wrap li").eq(currentPage);
toShow.show();
toShow.siblings().hide();
}
$.startSlideshow();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T05:37:02.763",
"Id": "22482",
"Score": "0",
"body": "It would be nice to have example html."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-20T17:09:06.883",
"Id": "30061",
"Score": "0",
"body": "@JordyVialoux You should use `===` by default, and not `==`."
}
] |
[
{
"body": "<p>Without HTML we could not do too much, but here is what I noticed right away.</p>\n\n<p>I would definately use more of the chaining that is provided with jQuery.</p>\n\n<pre><code>$(\"#news-feature-wrap #news-items li\").click(function () {\n $(this).parent().addClass('active').siblings().removeClass('active');\n\n var index = $(this).parent().index();\n $(\"#news-feature-wrap #news-feature-img-wrap li\").eq(index).show().siblings().hide();\n currentPage = index;\n $.stopSlideshow();\n});\n</code></pre>\n\n<p>This is more so taking advantage of the chaining in jQuery. It will not change performance and is strictly aesthetic. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T13:34:44.237",
"Id": "13936",
"ParentId": "13912",
"Score": "0"
}
},
{
"body": "<p>I've got a few suggestions for you:</p>\n\n<p>Wrap your entire thing in an IIFE, you don't need any external access to any of your vars.</p>\n\n<pre><code>;(function(){\n ...your code goes here\n}());\n</code></pre>\n\n<p>Now your period to change slide isn't in the global name space. </p>\n\n<p>You don't need to attach your <code>startSlideSnow</code> and <code>stopSlideShow</code> to the jQuery namespace (e.g. $.startSlideShow) you are just polluting jQuery's namespace which isn't goot. </p>\n\n<p>Use <code>setTimeout()</code> instead of <code>setInterval</code>. The <code>setTimeout</code> function will only run after its callback is done, <code>setInterval</code> runs at the interval no matter what, so you can run into some strange behavior. </p>\n\n<p>Try to not repeat selectors, and use chaining:</p>\n\n<pre><code>$(this).parent().addClass('active');\n$(this).parent().siblings().removeClass('active');\n</code></pre>\n\n<p>could become:</p>\n\n<pre><code>$(this).parent().addClass('active').siblings().removeClass('active');\n</code></pre>\n\n<p>You could optimize your selectors as well, remember jQuery goes right to left, so in a lot of cases you're getting all <code>li</code> items on the page and filtering those. It might be a marginal speed boost doing $( 'selector' ).find( 'li' );.</p>\n\n<p>There are a few more things you could do, like pluginize it, but these are the biggest things I see right away. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-19T22:18:40.320",
"Id": "25279",
"ParentId": "13912",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T23:23:47.503",
"Id": "13912",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html",
"css"
],
"Title": "Custom jQuery Slider"
}
|
13912
|
<h1>Code</h1>
<h2>Sudoku.java</h2>
<pre><code>public class Sudoku implements ISudoku {
/**
* Generates wildcard values in case of conflict with the keys of the
* Sudoku. Ensures all characters are alphanumeric, does not generate the
* same wildcard twice, and tries to keep the wildcard as short as
* possible.
*/
protected static class WildcardGenerator {
/**
* Used to build the next wildcard.
*/
protected static final List<String> SINGLE_CHARACTER_WILDCARDS =
createSingleCharacterWildcards();
/**
* Returns a wildcard whose generation is based on wildcard so that
* the same wildcard will not be generated twice by the same
* WildcardGenerator.
* @param wildcard The current wildcard.
* @return The next wildcard generated.
*/
public String nextWildcard(String wildcard) {
String last = wildcard.substring(wildcard.length() - 1);
int index = SINGLE_CHARACTER_WILDCARDS.indexOf(last);
if (index == SINGLE_CHARACTER_WILDCARDS.size() - 1) {
return wildcard + SINGLE_CHARACTER_WILDCARDS.get(0);
}
String replacement = SINGLE_CHARACTER_WILDCARDS.get(index + 1);
return wildcard.replace(last, replacement);
}
/**
* Creates and returns the single character wildcards used in the
* WildcardGenerators.
* @return The single character wildcards created.
*/
protected static List<String> createSingleCharacterWildcards() {
List<String> result = new ArrayList<String>();
for (char ch = '0'; ch <= '9'; ++ch) {
result.add("" + ch);
}
for (char ch = 'A'; ch <= 'Z'; ++ch) {
result.add("" + ch);
}
return result;
}
}
/**
* Used to build Sudokus. All methods within this class barring
* {@link Builder#finish()} (which must be called last) can be called in
* any order for any number of times, but side effects may vary. Default
* values are subject to change. It is recommended that inexperienced
* clients simply call all the methods in this order:
* <ol>
* <li>strict</li>
* <li>withWildcard</li>
* <li>withBoxWidth</li>
* <li>withAddedRow</li>
* <li>finish</li>
* </ol>
*/
public static class Builder {
/**
* A regex that matches a sequence of non-alphanumeric characters in a
* String.
*/
protected static final String DELIMITERS = "[\\W_]+";
/**
* The Sudoku built.
*/
protected Sudoku mSudoku;
/**
* True if strict mode is on.
*/
protected boolean mIsStrict;
/**
* Creates a new Builder for a Sudoku with key key.
* @param key The key.
* @throws IllegalArgumentException If any String in key contains
* non-alphanumeric characters.
* @see ISudoku#getKey()
*/
protected Builder(List<String> key) {
for (String symbol : key) {
if (hasDelimiter(symbol)) {
throw new IllegalArgumentException("Symbol " + symbol +
" in key contains a delimiter.");
}
}
init(key);
}
/**
* Creates a new Builder for a Sudoku with key parsed from key.
* @param key Used to differentiate between constant and variable
* cells. Constant cells have symbols parsed from the key. Also
* determines the number of cells per row.
*/
protected Builder(String key) {
Collection<String> parsedKey = new LinkedHashSet<String>();
Collections.addAll(parsedKey, key.split(DELIMITERS));
// A split String can contain the empty String, but that doesn't
// make much sense for a key value
parsedKey.remove("");
init(new ArrayList<String>(parsedKey));
}
/**
* Sets creation mode to strict, so that the subsequent method calls
* must conform to a standard otherwise they will throw an exception.
* Subsequent calls have no affect.
* @return A reference to this Builder.
*/
public Builder strict() {
mIsStrict = true;
return this;
}
/**
* Sets the wildcard to wildcard. Only the final call to this method
* has any affect. If not in strict mode, a null wildcard or a
* wildcard that is contained in the key will have no affect.
* @return A reference to this Builder
* @throws NullPointerException If in strict mode and wildcard is null.
* @throws IllegalArgumentException If in strict mode and the key
* contains wildcard. In addition, the wildcard must contain only
* alphanumeric characters in strict mode.
*/
public Builder withWildcard(String wildcard) {
if (wildcard == null) {
if (mIsStrict) {
throw new NullPointerException("Strict Mode: Null " +
"parameter.");
} else {
return this;
}
}
if (mSudoku.mKey.contains(wildcard)) {
if (mIsStrict) {
throw new IllegalArgumentException("Strict Mode: Key " +
"contains wildcard.");
} else {
return this;
}
}
if (mIsStrict && hasDelimiter(wildcard)) {
throw new IllegalArgumentException("Strict Mode: Wilcard " +
"contains non-alphanumeric characters.");
}
mSudoku.mWildcard = wildcard;
return this;
}
/**
* Sets the width of a box in the Sudoku to boxWidth. When not in
* strict mode, widths that are not positive integers that go evenly
* into the width of the Sudoku (determined by the number of keys)
* will be discarded. For example, if the width of the Sudoku is 9,
* valid box widths are 3 and 9. Entering any other number will be
* discarded, or, in strict mode, throw an exception. Subsequent calls
* will override previous calls to this method.
* @param boxWidth The width of a box in the Sudoku.
* @return A reference to this Builder.
* @throws IllegalArgumentException If boxWidth is not positive or
* does not evenly go into the width of the Sudoku during strict mode.
*/
public Builder withBoxWidth(int boxWidth) {
if (boxWidth > 0 && mSudoku.getWidth() % boxWidth == 0) {
mSudoku.mBoxWidth = boxWidth;
mSudoku.mBoxHeight = mSudoku.getWidth() / mSudoku.mBoxWidth;
} else if (mIsStrict) {
throw new IllegalArgumentException("Strict Mode: Invalid " +
"box width.");
}
return this;
}
/**
* Parses and appends row to the rows in the Sudoku. Parsing uses
* non-alphabetic characters as delimiters. Has no affect if row is
* null and not in strict mode. If the parsed length is not equal to
* the width and it is not strict mode, the row will be filled out
* with wildcards or truncated to the right length. If never called
* with the proper arguments, the Sudoku will be empty. (Note: Strict
* mode does not allow empty Sudokus.)
* @param row The row added.
* @return A reference to this Builder.
* @throws NullPointerException If row is null in strict mode.
* @throws IllegalArgumentException If in strict mode and the parsed
* length is not equal to the width of the Sudoku (determined by the
* number of elements in the key) or an element parsed is neither in
* the key nor equal to the wildcard.
*/
public Builder withAddedRow(String row) {
if (row == null) {
if (mIsStrict) {
throw new NullPointerException("Strict Mode: Null " +
"parameter.");
} else {
return this;
}
}
fillColumns();
String[] cells = row.split(DELIMITERS);
int nAddedCells = 0;
for (int index = 0; index < cells.length; ++index) {
if (nAddedCells == mSudoku.getWidth()) {
if (mIsStrict) {
throw new IllegalArgumentException("Strict Mode: " +
"Too many symbols in " + row);
} else {
break;
}
}
String cell = cells[index];
if ("".equals(cell)) continue;
++nAddedCells;
withAddedCell(cell);
}
if (mIsStrict && nAddedCells < mSudoku.getWidth()) {
throw new IllegalArgumentException("Strict Mode: Too few " +
"symbols in " + row);
}
while (nAddedCells++ < mSudoku.getWidth()) {
mSudoku.mCells.add("");
}
return this;
}
/**
* Appends cell to the cells in the Sudoku. Has no affect if cell is
* null and not in strict mode.
* @param cell The cell added.
* @return A reference to this Builder.
* @throws NullPointerException If cell is null in strict mode.
* @throws IllegalArgumentException If in strict mode and cell is
* neither in the key nor equal to the wildcard.
*/
public Builder withAddedCell(String cell) {
// Test for null first, otherwise strict mode will throw an
// IllegalArgumentException on null
if (cell == null) {
if (mIsStrict) {
throw new NullPointerException("Strict Mode: Null " +
"parameter.");
} else {
return this;
}
}
if (mSudoku.mKey.contains(cell)) {
mSudoku.mCells.add(cell);
} else if (mIsStrict && !mSudoku.getWildcard().equals(cell)) {
throw new IllegalArgumentException("Strict mode: " +
"Invalid symbol " + cell);
} else {
mSudoku.mCells.add("");
}
return this;
}
/**
* Returns a Sudoku ready for use. If not in strict mode and the cells
* do not fill the last row, extra blank cells will be added. If not
* in strict mode and the box height does not go into the height
* evenly, extra blank rows will be added.
* @return A Sudoku ready for use.
* @throws IllegalStateException If in strict mode and the Sudoku is
* empty, the cells do not fills the last row, or the box height does
* not go into the height evenly.
*/
public Sudoku finish() {
if (mSudoku.getSize() == 0) {
if (mIsStrict) {
throw new IllegalStateException("Strict Mode: Sudoku " +
"is empty.");
} else {
mSudoku.mKey = new ArrayList<String>();
}
}
fillColumns();
adjustRows();
if (mSudoku.mBoxWidth == 0) withBoxWidth(1);
buildDimensionLists();
return mSudoku;
}
/**
* A common function called by the Builder constructors to avoid code
* duplication.
* @param key The key.
* @see ISudoku#getKey()
*/
protected void init(List<String> key) {
mSudoku = new Sudoku(key);
WildcardGenerator wildcardGenerator = new WildcardGenerator();
do {
mSudoku.mWildcard =
wildcardGenerator.nextWildcard(mSudoku.getWildcard());
} while (key.contains(mSudoku.getWildcard()));
}
/**
* Returns true if symbol contains a delimiter.
* @param symbol Checked for whether it contains a delimiter.
* @return True if symbol contains a delimiter.
*/
protected boolean hasDelimiter(String symbol) {
return Pattern.compile(DELIMITERS).matcher(symbol).find();
}
/**
* If not is strict mode, fills the columns of the last row. If in
* strict mode, validates that the columns do not need to be filled.
* @throws IllegalStateException If in strict mode and the rows need
* to be filled.
*/
protected void fillColumns() {
int nAddedCells = (mSudoku.getWidth() == 0) ? 0:
(mSudoku.getWidth() - mSudoku.getSize() % mSudoku.getWidth())
% mSudoku.getWidth();
if (mIsStrict && nAddedCells != 0) {
throw new IllegalStateException("Strict Mode: Cells do not " +
"fill all rows.");
}
for (int count = 0; count < nAddedCells; ++count) {
withAddedCell(mSudoku.getWildcard());
}
}
/**
* If not in strict mode, adjusts the number of rows so that the width
* of the Sudoku equals the height. If in strict mode, validates that
* the rows do not need to be adjusted.
* @throws IllegalStateException If in strict mode and the width does
* not match the height.
*/
protected void adjustRows() {
int rowDiff = mSudoku.getWidth() - mSudoku.getHeight();
if (mIsStrict && rowDiff != 0) {
throw new IllegalStateException("Strict Mode: Width does " +
"not equal height.");
}
if (rowDiff > 0) {
String wildcardRow = createWildcardRow();
for (int count = 0; count < rowDiff; ++count) {
withAddedRow(wildcardRow);
}
} else if (rowDiff < 0) {
int nCells = mSudoku.getWidth() * mSudoku.getWidth();
mSudoku.mCells = mSudoku.mCells.subList(0, nCells);
}
}
/**
* Builds the lists of rows, columns, and boxes.
*/
protected void buildDimensionLists() {
mSudoku.mRows = new ArrayList<List<String>>();
mSudoku.mCols = new ArrayList<List<String>>();
mSudoku.mBoxes = new ArrayList<List<String>>();
for (int cellNo = 0; cellNo < mSudoku.mCells.size(); ++cellNo) {
int rowNo = cellNo / mSudoku.getWidth();
int colNo = cellNo % mSudoku.getWidth();
int boxNo = mSudoku.getBoxNo(rowNo, colNo);
List<String> row = mSudoku.getOrCreateAt(rowNo, mSudoku.mRows,
ArrayList.class);
List<String> col = mSudoku.getOrCreateAt(colNo, mSudoku.mCols,
ArrayList.class);
List<String> box = mSudoku.getOrCreateAt(boxNo,
mSudoku.mBoxes, ArrayList.class);
String cell = mSudoku.cellAt(cellNo);
if (cell.isEmpty()) cell = mSudoku.getWildcard();
row.add(cell);
col.add(cell);
box.add(cell);
}
}
/**
* Creates and returns a row full of wildcard symbols.
* @return A row full of wildcard symbols.
*/
protected String createWildcardRow() {
StringBuilder wildcardRow = new StringBuilder();
for (int count = 0; count < mSudoku.getWidth(); ++count) {
wildcardRow.append(mSudoku.getWildcard());
}
return wildcardRow.toString();
}
}
/**
* The cells organized by order of insertion into the Sudoku.
*/
protected List<String> mCells = new ArrayList<String>();
/**
* The cells organized by dimensions.
*/
protected List<List<String>> mRows, mCols, mBoxes;
/**
* Contains the possible symbols of the ConstantCells.
*/
protected List<String> mKey;
/**
* The representation of the VariableCells.
*/
protected String mWildcard = " "; // Setting the initial wildcard to
// contain a single non-alphanumeric
// character will ensure that the
// WildcardGenerator will generate an
// appropriate default value for it
/**
* The dimensions of a box.
*/
protected int mBoxWidth, mBoxHeight;
/**
* Creates a new, empty Sudoku. The Builder should set its fields.
*/
protected Sudoku(List<String> key) {
mKey = key;
}
/**
* Initiates building a Sudoku with key key.
* @param key The key.
* @return The Builder that will create this Sudoku.
* @throws IllegalArgumentException If any String in key contains
* non-alphanumeric characters.
* @see ISudoku#getKey()
*/
public static Builder make(List<String> key) {
return new Builder(key);
}
/**
* Initiates building a Sudoku with key parsed from key using
* non-alphanumeric characters as delimiters.
* @param key The key.
* @return The Builder that will create this Sudoku.
* @see ISudoku#getKey()
*/
public static Builder make(String key) {
return new Builder(key);
}
/**
* Returns the box number given the row number and the column number.
* @param rowNo The row number.
* @param colNo The column number.
* @return The box number.
*/
protected int getBoxNo(int rowNo, int colNo) {
int nBoxesAtRowStart = rowNo / mBoxHeight;
int nBoxesPerRow = getWidth() / mBoxWidth;
int nBoxesInRow = colNo / mBoxWidth;
return nBoxesAtRowStart * nBoxesPerRow + nBoxesInRow;
}
/**
* Adds elements of class elementClass to list until index is a valid
* index and returns the element at index.
* @param index The index of the element returned.
* @param list Contains the element returned.
* @param elementClass The class of the elements in list.
* @return The element of list at index index.
* @throws IndexOutOfBoundsException If index is negative.
*/
@SuppressWarnings("unchecked")
protected <T> T getOrCreateAt(int index, List<T> list, Class<?> elementClass) {
while (list.size() < index + 1) {
try {
list.add((T) elementClass.newInstance());
} catch (InstantiationException e) {
e.printStackTrace();
System.exit(1);
} catch (IllegalAccessException e) {
e.printStackTrace();
System.exit(1);
}
}
return list.get(index);
}
}
</code></pre>
<h2>Example Usage</h2>
<pre><code>ISudoku sudoku = Sudoku.make("A B C D").strict()
.withWildcard("Q").withBoxWidth(2)
.withAddedRow("Q B C D")
.withAddedRow("D C Q A")
.withAddedRow("B A D Q")
.withAddedRow("C Q A B").finish();
</code></pre>
<h1>Questions</h1>
<ol>
<li>Is it appropriate to use the Fluent Builder pattern for a Sudoku program? I know that it's easy to overuse the pattern, so I'm wondering if I should go a different route here.</li>
<li>Do my javadoc comments make sense?</li>
<li>Are my method names ok? I searched, but I couldn't find tips on Fluent Builder naming conventions. I understand that its supposed to be "readable", but that's really vague.</li>
<li>Is my logic sound? Do I allow any nonsensical Sudoku grids to be built?</li>
<li>Any other critiques would be much appreciated. Thanks!</li>
</ol>
|
[] |
[
{
"body": "<p><code>List<String></code> is not good way, use <code>Set<Character></code> to store (<code>return false</code> if wildcard exists) your wildcard.</p>\n\n<p>So you will avoid the <code>\"\" +</code> (very bad way) and use <code>Character.ValueOf(char));</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T21:33:08.067",
"Id": "22943",
"Score": "0",
"body": "Thank you. A good suggestion. I thought that part smelled a bit."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T07:09:44.340",
"Id": "13924",
"ParentId": "13914",
"Score": "3"
}
},
{
"body": "<p>Answers to a few questions and a few other notes:</p>\n<ol>\n<li><p>Method names and the builder interface/pattern looks fine. I would rename the <code>finish</code> to <code>build</code> as the <a href=\"http://code.google.com/p/fluent-builders-generator-eclipse-plugin/\" rel=\"nofollow noreferrer\">Fluent builders generator for Eclipse</a> calls it but the others are OK.</p>\n</li>\n<li><p>Here I'd not allow any nonsensical Sudoku grids to be built. If it was a GUI application it would make sense to create (temporarily) nonsensical tables for easier editing but I don't see any reasons why should it be allowed here. Some method just ignore input errors on non-strict mode which could be really hard to debug.</p>\n</li>\n<li><p><code>System.exit</code> isn't a nicest way to stop an entire application, especially hidden in a <code>catch</code> block. I'd throw and exception and let callers to handle the errors.</p>\n</li>\n<li><p>The <code>getOrCreateAt</code> method are always called with <code>ArrayList.class</code>. I would not use <code>newInstance</code> here.</p>\n</li>\n<li><p>As a client I would not expect that the order of the methods are defined for a builder, so calling <code>strict()</code> at the end of the chain would be completely fine for me.</p>\n</li>\n<li><p>I'd redesign the class hierarchy a little bit, I'd except a <code>Sudoku</code> (or <code>Table</code>) class which stores <code>Cell</code> objects and not simple <code>String</code>s. I'd create a <code>Cell</code> wrapper class (which would contain a <code>String</code> only) for the cell values. It would improve type-safety and make the code easier to read.</p>\n</li>\n<li><p>The <code>Sudoku.cellAt()</code> method does not implies good encapsulation and it results tight coupling. Clients should not know the internals of the <code>Sudoku</code> class.</p>\n</li>\n<li><p>It's rather hard to understand the role of <code>mRows, mCols, mBoxes</code> fields. If I'm right the code stores every cell value in all of the three <code>List</code>s. It does not smell good.</p>\n<p>I think <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Table.html\" rel=\"nofollow noreferrer\">Guava's Table class</a> (or a similar custom implementation) could be a better choice here.</p>\n</li>\n<li><p>The <code>m</code> field name prefix is unnecessary and rather uncommon in the Java world. Modern IDEs use different colors for local variables and fields. See <em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em></p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T21:32:21.187",
"Id": "22942",
"Score": "1",
"body": "This isn't the complete class, so #4 doesn't apply and #8 has a good reason. The cellAt method was designed as such to allow for extensions to nonstandard Sudokus (e.g. Sudoku Samurai, 3D Sudoku). It just returns the Sudoku cell in order of addition. I never thought of Sudoku as a table; this gives me so many ideas. All in all good suggestions. Thank you very much!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T14:31:21.140",
"Id": "14168",
"ParentId": "13914",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14168",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T00:20:13.953",
"Id": "13914",
"Score": "3",
"Tags": [
"java",
"design-patterns",
"sudoku"
],
"Title": "Is this Sudoku a good use of the Fluent Builder Pattern?"
}
|
13914
|
<h1>Solution to 99 lisp problems: P08, with functional javascript</h1>
<blockquote>
<p>If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.</p>
</blockquote>
<pre><code>* (compress '(a a a a b c c a a d e e e e))
(A B C A D E)
</code></pre>
<p><br>
Anyone want to review?<br>
<br></p>
<pre><code>function cond( check, _then, _continuation ) {
if(check) return _then( _continuation )
else return _continuation()
}
function compress( list ) {
return (function check( index, item, nextItem, compressed ) {
return cond( item !== nextItem, function _then( continuation ) {
compressed = compressed.concat([ item ])
return continuation()
},
function _continueation() {
return cond(!nextItem, function _then() {
return compressed
},
function _continuation() {
return check( index + 1, list[index + 1], list[index + 2], compressed )
})
})
})( 0, list[0], list[1], [] )
}
</code></pre>
<p>ref: <br>
<a href="http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html" rel="nofollow">http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T05:19:21.410",
"Id": "22479",
"Score": "0",
"body": "Wouldn't a loop or recursive calling be a better idea?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T05:20:39.443",
"Id": "22480",
"Score": "0",
"body": "The `cond` function can probably be replaced with a ternary operator and switching the order a little."
}
] |
[
{
"body": "<p>I don't think you need so much complexity in javascript. It's not a fully functional language, don't try to make it so.</p>\n\n<pre><code>var arr = [\n 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'd', 'a', 'e', 'e', 'e'\n];\n\narr = arr.filter( function( el, i ) {\n // return if the current isn't the same as the next\n return el !== arr[ i + 1 ];\n});\n\nconsole.log( arr ); // [\"a\", \"b\", \"c\", \"d\", \"a\", \"e\"]\n</code></pre>\n\n<p>This is 2 lines.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T01:10:59.753",
"Id": "22709",
"Score": "0",
"body": "The function passed to `filter` can be generalized by adding a third parameter `arr`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T08:01:05.743",
"Id": "13928",
"ParentId": "13917",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T01:51:29.713",
"Id": "13917",
"Score": "1",
"Tags": [
"javascript",
"lisp",
"functional-programming"
],
"Title": "Solution to 99 lisp problems: P08 with functional javascript"
}
|
13917
|
<p>I am teaching myself C, and feel like I am just starting to get the hang of pointers and arrays (I come from Python, where everything is magic). I'm looking for reviews, especially if I'm doing anything wrong. In this code I wrote my own <code>strcat()</code> function, though it needs 3 args instead of the standard 2 (I couldn't figure out how to do it with just 2 without overrunning allotted memory).</p>
<pre><code>#include <stdio.h>
#include <string.h>
char* cat(char *dest, char *a, char*b)
{
int len_a = strlen(a);
int len_b = strlen(b);
int i;
for(i = 0; i < len_a; i++)
{
dest[i] = a[i];
}
puts("");
int j;
for(j = 0;j < len_b; i++, j++)
{
dest[i] = b[j];
}
dest[i] = '\0';
puts("FUNCTION FINISHED");
}
int main()
{
char strA[] = "I am a small ";
char strB[] = "cat with whiskers.";
char strC[strlen(strA) + strlen(strB) + 1];
printf("length A: %lu, B: %lu, C: %lu\n", strlen(strA), strlen(strB), strlen(strC));
printf("sizeof A: %lu, B: %lu, C: %lu\n", sizeof(strA), sizeof(strB), sizeof(strC));
printf("A: '%s'\nB: '%s'\n", strA, strB);
cat(strC, strA, strB);
printf("c: '%s'\n", strC);
printf("length A: %lu, B: %lu, C: %lu\n", strlen(strA), strlen(strB), strlen(strC));
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>What's not magic in C is that pointers can be null, and assigning to <code>NULL</code> will cause segfault. The same applies to <code>[]</code> access on <code>char*</code> that are <code>NULL</code>.</p></li>\n<li><p>You've created a function with a return type, but you never return anything. It doesn't matter in your test case, but anyone else calling this could expect a value there. Most compilers will complain.</p></li>\n<li><p>If you are trying to replicate <code>strcat()</code> just to learn, understand its assumptions. It is assuming that the arg to which something is having <code>strcat()</code> performed on it will be big enough not to be overrun, and it's up to the caller to prepare against this. If you are trying to write something safer, then you need to figure out how to handle the error conditions (e.g. since you're using a third arg here, do you want to return some kind of BOOL indicating a good <code>strcat()</code> took place (i.e. that all the args were good and non-<code>NULL</code>?)).</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T02:00:21.220",
"Id": "22807",
"Score": "0",
"body": "Personally I think it's completely valid if your function segfaults given a null input, provided that expectation is understood by the function's callers. (Callee expects a valid pointer - so don't pass null.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T07:24:34.483",
"Id": "13925",
"ParentId": "13920",
"Score": "1"
}
},
{
"body": "<p>Just a few things to add to john.k.doe's answer:</p>\n\n<p><strong>cat's strlen calls</strong></p>\n\n<p>The implementation of strlen is usually something vaguely like:</p>\n\n<pre><code>size_t strlen(const char* str)\n{\n size_t len = 0;\n while (str[len] != 0) {\n ++len;\n }\n return len;\n}\n</code></pre>\n\n<p>This has two significant effects:</p>\n\n<ul>\n<li>Use size_t instead of an int when working with functions that return a <code>size_t</code>. It often doesn't matter, but it's a bad habit. (For example, file sizes often are larger than an int -- though I'm not actually sure if there's a file size function that returns a size_t... :).)</li>\n<li>No need to loop twice</li>\n</ul>\n\n<p>On the second point, what I mean is that you're basically looping twice. You could just use this construct instead:</p>\n\n<pre><code>char* cat(char* dest, const char* a, const char* b)\n{\n size_t off = 0;\n size_t idx = 0;\n while (a[off]) {\n dest[off] = a[off];\n ++off;\n }\n idx = 0;\n while (b[idx]) {\n dest[off] = b[idx];\n ++off;\n ++idx;\n }\n return dest;\n}\n</code></pre>\n\n<p><strong>Mark arguments as <code>const</code> when possible</strong></p>\n\n<p><code>a</code> and <code>b</code> should be marked as const since the values pointed to by the pointer are not changed in the function. Using <code>const</code> is a way to allow the compiler to do certain optimization, but more importantly, it's a signal to other sections of code that \"I can pass something to this function, and I know that this function won't modify it.\"</p>\n\n<p>My rule of thumb is to have all pointers <code>const</code> (at least in my head) and then un-const them only when necessary.</p>\n\n<p>I should probably also mention that there's different placements for const and they mean different things. Statements are usually most logically apparently from right to left when thinking about <code>const</code>.</p>\n\n<pre><code>const char* a;\n</code></pre>\n\n<p>From right to left this would read, \"a is a pointer to a char that is const.\"</p>\n\n<p>This means that <code>a</code> can be changed, but derefencing <code>a</code> results in a <code>const char</code> (and thus <code>*a</code>, <code>a[5]</code>, <code>*(a + 3)</code> etc cannot be modified).</p>\n\n<pre><code>char const* a;\n</code></pre>\n\n<p>\"a is a pointer to a const char.\"</p>\n\n<p>Exact same thing as the first example.</p>\n\n<pre><code>char * const a;\n</code></pre>\n\n<p>\"a is a constant pointer to a char.\"</p>\n\n<p>This means that <code>a</code> cannot be changed (<code>a = b;</code> and <code>a = &c;</code> are invalid), but the contents of a can be (<code>a[3] = 'b';</code> is valid).</p>\n\n<pre><code>const char* const a;\n</code></pre>\n\n<p>\"a is a constant pointer to a constant char.\"</p>\n\n<p>Neither a nor what it points to can be altered.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T09:39:36.423",
"Id": "13931",
"ParentId": "13920",
"Score": "1"
}
},
{
"body": "<pre><code>char* cat(char *dest, char *a, char*b)\n</code></pre>\n\n<p>Interface critique: You should have the caller specify a maximum size for the destination buffer, and error out when there is not enough space. The mark of a good C programmer is to create interfaces which make this sort of condition unambiguous, rather than blasting away on the buffer, potentially past the allocation size.</p>\n\n<pre><code>for(i = 0; i < len_a; i++)\n{\n dest[i] = a[i];\n}\n</code></pre>\n\n<p>Strictly speaking this is fine, but it is rather un-C-like. I would prefer:</p>\n\n<pre><code>while (*a)\n *dest++ = *a++;\n</code></pre>\n\n<p>With this you do not need to call <code>strlen</code>, either.</p>\n\n<p>Assuming you added the parameter you should add in my interface critique (let's call the new parameter <code>destsz</code>), you could make sure you don't write more than this size with something like:</p>\n\n<pre><code>int cat(char *dest, size_t destsz, const char *a, const char *b)\n{\n while (*a && destsz)\n {\n *dest++ = *a++;\n --destsz;\n }\n\n while (*b && destsz)\n {\n *dest++ = *b++;\n --destsz;\n }\n\n if (!destsz)\n return -1; // ran out of buffer; error condition\n\n *dest = 0; // we have space, so write NUL\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T11:00:02.903",
"Id": "13934",
"ParentId": "13920",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "13934",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T05:12:15.843",
"Id": "13920",
"Score": "3",
"Tags": [
"c",
"strings"
],
"Title": "Custom strcat() with different arguments"
}
|
13920
|
<p>Sass (<strong>S</strong> yntactically <strong>A</strong> wesome <strong>S</strong> tyle <strong>s</strong> heets) extends traditional CSS by providing several features available in other programming languages, particularly object-oriented languages, but that are not available to CSS3 itself. Sass provides features such as variables, mixins, nesting, and selector inheritance.</p>
<ul>
<li><a href="http://sass-lang.com/" rel="nofollow">Official site</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T06:38:01.517",
"Id": "13922",
"Score": "0",
"Tags": null,
"Title": null
}
|
13922
|
Sass is a CSS preprocessor which enables advanced features not available in normal CSS.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T06:38:01.517",
"Id": "13923",
"Score": "0",
"Tags": null,
"Title": null
}
|
13923
|
<p>Here is part of my build system. </p>
<pre><code>guessCompilers :: Options -> IO Options
guessCompilers options = foldl (>>=) (return options) modifiers where
modifiers =
[guessMetapost
-- guessAsymptote,
-- guessTex,
-- guessLatex,
-- guessXelatex
]
guessMetapost :: Options -> IO Options
guessMetapost opts = if isJust $ optMetaPost opts
then
putStrLn $ printf "using enforced Metapost compiler: %s" (fromJust $optMetaPost opts)
>> return opts
else do
cc <- compiler Metapost.interface
if isJust cc then putStrLn $ printf "found Metapost compiler: %s" (fromJust cc)
else putStrLn "found Metapost compiler: none"
</code></pre>
<p>Compiler can be spectified by cmd args or can be guessed. But double checking for <code>Nothing</code> is not cool in my opinion. Also, I heard <code>fromJust</code> is evil. Any suggestions to improve my code? </p>
|
[] |
[
{
"body": "<p>Pattern match instead of using <code>isJust</code> and <code>fromJust</code>. (You could use <code>maybe</code> instead of pattern matching, but I think pattern matching is clearer in this case.)</p>\n\n<p>This eliminates the possibility of forgetting to ensure a value is a Just before calling <code>fromJust</code> on it.</p>\n\n<pre><code>guessMetapost :: Options -> IO ()\nguessMetapost opts\n = case optMetaPost opts of\n Just mcc -> putStrLn $ printf \"using enforced Metapost compiler: %s\" mcc\n Nothing -> do\n cc' <- compiler Metapost.interface\n case cc' of\n Just cc -> putStrLn $ printf \"found Metapost compiler: %s\" cc\n Nothing -> putStrLn \"found Metapost compiler: none\"\n</code></pre>\n\n<p>(Your code wasn't consistently returning any options, so I've stripped that bit out.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T15:01:35.040",
"Id": "22874",
"Score": "2",
"body": "You can also get rid of `putStrLn $ printf ...`, and simply write `printf`. There is an `IO a` instance of [`PrintfType`](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Text-Printf.html#t:PrintfType)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T08:40:00.457",
"Id": "13930",
"ParentId": "13927",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13930",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T07:34:54.270",
"Id": "13927",
"Score": "2",
"Tags": [
"haskell",
"null",
"compiler",
"tex"
],
"Title": "Using a compiler specified on the command line or automatically detected"
}
|
13927
|
<p>I'm trying to validate some results that I see when using <a href="http://www.scl.ameslab.gov/netpipe/" rel="noreferrer">NetPipe</a> to test some connectivity between a couple of Linux boxes (over various hardware). So, I concocted this simple client and server to do the same and I cannot seem to get the same numbers as NetPipe - I'm about 30-40% off the rtt times that it sees.</p>
<p>Is there something stupid that I'm doing wrong with my simple example?</p>
<p><strong>Server:</strong></p>
<pre><code>#include <stdio.h> /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), bind(), and connect() */
#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */
#include <netinet/tcp.h>
#include <stdlib.h> /* for atoi() and exit() */
#include <string.h> /* for memset() */
#include <unistd.h> /* for close() */
#include <stdio.h> /* for perror() */
#include <stdlib.h> /* for exit() */
#define MAXPENDING 1
void die(char *errorMessage)
{
perror(errorMessage);
exit(1);
}
void handle(unsigned short quickAck, int clntSock)
{
long long c_ts; /* current read timestamp */
int value = 1;
// Enable quickAck
if (quickAck && setsockopt(clntSock, IPPROTO_TCP, TCP_QUICKACK, (char *)&value, sizeof(int)) < 0)
die("TCP_QUICKACK failed");
/* Send received string and receive again until end of transmission */
while (recv(clntSock, (char*)&c_ts, sizeof(c_ts), 0) == sizeof(c_ts)) /* zero indicates end of transmission */
{
// Enable quickAck
if (quickAck && setsockopt(clntSock, IPPROTO_TCP, TCP_QUICKACK, (char *)&value, sizeof(int)) < 0)
die("TCP_QUICKACK failed");
/* Echo message back to client */
if (send(clntSock, (char*)&c_ts, sizeof(c_ts), 0) != sizeof(c_ts))
die("send() failed to send timestamp");
// Enable quickAck
if (quickAck && setsockopt(clntSock, IPPROTO_TCP, TCP_QUICKACK, (char *)&value, sizeof(int)) < 0)
die("TCP_QUICKACK failed");
}
close(clntSock); /* Close client socket */
}
int main(int argc, char *argv[])
{
int servSock; /* Socket descriptor for server */
int clntSock; /* Socket descriptor for client */
struct sockaddr_in echoServAddr; /* Local address */
struct sockaddr_in echoClntAddr; /* Client address */
unsigned short echoServPort; /* Server port */
unsigned short quickAck;
unsigned int clntLen; /* Length of client address data structure */
int value = 1;
if (argc != 3) /* Test for correct number of arguments */
{
fprintf(stderr, "Usage: %s <Server Port> <Quick Ack>\n", argv[0]);
exit(1);
}
echoServPort = atoi(argv[1]); /* First arg: local port */
quickAck = atoi(argv[2]); /* Whether quick ack is enabled or not */
/* Create socket for incoming connections */
if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
die("socket() failed");
/* Construct local address structure */
memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */
echoServAddr.sin_family = AF_INET; /* Internet address family */
echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
echoServAddr.sin_port = htons(echoServPort); /* Local port */
/* Bind to the local address */
if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
die("bind() failed");
/* Mark the socket so it will listen for incoming connections */
if (listen(servSock, MAXPENDING) < 0)
die("listen() failed");
for (;;) /* Run forever */
{
/* Set the size of the in-out parameter */
clntLen = sizeof(echoClntAddr);
printf("Waiting for client...\n");
/* Wait for a client to connect */
if ((clntSock = accept(servSock, (struct sockaddr *) &echoClntAddr, &clntLen)) < 0)
die("accept() failed");
/* clntSock is connected to a client! */
printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr));
if (setsockopt(clntSock, IPPROTO_TCP, TCP_NODELAY, (char *)&value, sizeof(int)) < 0)
die("TCP_NODELAY failed");
handle(quickAck, clntSock);
}
/* NOT REACHED */
}
</code></pre>
<p><strong>Client:</strong></p>
<pre><code>#include <stdio.h> /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), connect(), send(), and recv() */
#include <arpa/inet.h> /* for sockaddr_in and inet_addr() */
#include <netinet/tcp.h>
#include <stdlib.h> /* for atoi() and exit() */
#include <string.h> /* for memset() */
#include <unistd.h> /* for close() */
#include <sys/time.h>
void die(char *errorMessage)
{
perror(errorMessage);
exit(1);
}
int main(int argc, char *argv[])
{
int sock; /* Socket descriptor */
struct sockaddr_in echoServAddr; /* Echo server address */
unsigned short echoServPort; /* Echo server port */
char *servIP; /* Server IP address (dotted quad) */
int iterations, gap, i; /* Number of timestamps to send, and gap between each send */
struct timeval ts;
long long c_ts, o_ts, delta, total = 0, max = 0, min = 1000000000;
int value = 1;
if (argc != 5) /* Test for correct number of arguments */
{
fprintf(stderr, "Usage: %s <Server IP> <Server Port> <Iterations> <Gap>\n", argv[0]);
exit(1);
}
servIP = argv[1]; /* server IP address (dotted quad) */
echoServPort = atoi(argv[2]); /* server port */
iterations = atoi(argv[3]); /* number of timestamps to send */
gap = atoi(argv[4]); /* gap between each send */
/* Create a reliable, stream socket using TCP */
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
die("socket() failed");
/* Construct the server address structure */
memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */
echoServAddr.sin_family = AF_INET; /* Internet address family */
echoServAddr.sin_addr.s_addr = inet_addr(servIP); /* Server IP address */
echoServAddr.sin_port = htons(echoServPort); /* Server port */
/* Establish the connection to the echo server */
if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
die("connect() failed");
if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&value, sizeof(int)) < 0)
die("TCP_NODELAY failed");
/* Give the server a chance */
usleep(1000);
/* Now for the given number of iterations */
for(i = 0; i < iterations; ++i)
{
/* Generate the current timestamp */
gettimeofday(&ts, NULL);
c_ts = ts.tv_sec * 1000000LL + ts.tv_usec;
//printf("sending %ld ", c_ts);
/* Send this */
if (send(sock, (char*)&c_ts, sizeof(c_ts), 0) != sizeof(c_ts))
die("send() failed to send timestamp");
/* Now read the echo */
if (recv(sock, (char*)&o_ts, sizeof(o_ts), 0) != sizeof(o_ts))
die("recv() failed to read timestamp");
gettimeofday(&ts, NULL);
c_ts = ts.tv_sec * 1000000LL + ts.tv_usec;
/* Calculate the delta */
delta = c_ts - o_ts;
//printf(" -> received %ld %ld\n", o_ts, delta);
if (i > 0)
{
/* Track max, min, sum */
total += delta;
max = (max < delta)? delta : max;
min = (min > delta)? delta : min;
}
/* Now sleep */
usleep(1000*gap);
}
--iterations;
printf("iterations %d, avg %f, max %ld, min %ld\n", iterations, (total/(double)iterations), max, min);
close(sock);
exit(0);
}
</code></pre>
<p>So, to run, start the server with the port and whether quick_ack is enabled or not (1/0) - this is for a different test. Something like:</p>
<pre><code>./simple_sever 10000 1
</code></pre>
<p>Then run the client:</p>
<pre><code>./simple_client <host IP address> 10000 1000 1
</code></pre>
<p>So send 1000 timestamps with a 1 millisecond gap between each. This, I guess, is where the above differs from NetPipe (which floods, as far as I know).</p>
<p>The interaction is pretty straight forward, so is there something I'm missing?</p>
<p><strong>EDIT:</strong> Okay, I got to the bottom of the difference: caching. NetPIPE has an option to force invalidation of cache, and enabling this results in similar numbers to my test program. Phew, I don't have to re-evaluate my sockets programming! I'll leave this question up for reference I guess.</p>
|
[] |
[
{
"body": "<p>Not much to comment on, this program is pretty straightforward. A few notes:</p>\n<ul>\n<li><p>The user of the client has a lot of information to input.</p>\n<blockquote>\n<pre><code> fprintf(stderr, "Usage: %s <Server IP> <Server Port> <Iterations> <Gap>\\n", argv[0]);\n</code></pre>\n</blockquote>\n<p>The more the user has to enter, the steeper the initial learning curve to use the program is. Also, I'm not sure I want the user to control the <code><Iterations></code> and the <code><Gap></code> anyways. A malicious user might abuse this for a DOS of the server. Eliminating those as required input and setting them in your code would be a more secure and a more user-friendly option.</p>\n</li>\n<li><p>You have too many comments.</p>\n<blockquote>\n<pre><code> close(clntSock); /* Close client socket */\n</code></pre>\n</blockquote>\n<p>For that particular example, it is quite obvious what that statement does. There are a lot of other comparable examples in this code.</p>\n</li>\n<li><p>It is more common to <code>return 0;</code> when <code>main()</code> is finished, rather than to <code>exit(0)</code>. Both will call the registered <code>atexit</code> handlers and will cause program termination though.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T18:46:15.703",
"Id": "71162",
"Score": "0",
"body": "Hi, thanks for the feedback! :) The comments are really just explicit documentation I added for posting here... The options are required to allow different types of tests to be done. I was more interested in the simple examples being correct... Thanks anyway..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T21:33:56.490",
"Id": "71186",
"Score": "1",
"body": "@Nim Besides the input for the client (and perhaps the `return`s), I would say that this example would be considered \"correct\"."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T04:47:50.293",
"Id": "41034",
"ParentId": "13933",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "41034",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T10:15:10.290",
"Id": "13933",
"Score": "9",
"Tags": [
"c",
"performance",
"socket",
"tcp"
],
"Title": "Stupidly simple TCP client/server"
}
|
13933
|
<p>I have this code that places a marker and on mouse-over this marker is scaled out and then back to the 'original' scale:</p>
<pre><code>this.drawPerson = function () {
self.svg.append("path")
.attr("d", personPath)
.attr("transform", "translate(100,100)scale(0.1)")
.attr("class", "member")
.style("fill", "steelblue")
.on("mouseover", function(){
d3.select(this).transition()
.style("fill", "red")
.attr("transform", "translate(100,100)scale(0.2)")
})
.on("mouseout", function() {
d3.select(this).transition()
.style("fill", "steelblue")
.attr("transform", "translate(100,100)scale(0.1)")
});
}
</code></pre>
<p>The x and y are the coordinates for the position on the canvas.</p>
<p>Here is the example: <a href="http://jsfiddle.net/SuTZR/8/" rel="nofollow">http://jsfiddle.net/SuTZR/8/</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T08:40:56.977",
"Id": "22579",
"Score": "1",
"body": "What's wrong with it as it stands? Performance?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T09:28:46.387",
"Id": "22581",
"Score": "0",
"body": "i was thinking that the mouse out could just be reset as the original, rather then having to set it again. similar to the way is done with css"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T10:05:40.493",
"Id": "22584",
"Score": "0",
"body": "Like when you mouseout of an element with css hover set to something different? I think I see what you mean, but you are doing an animated transform, which is a lot more complex than simply switching from state to state. You could use CSS hover for this if the browser supported a transform like that natively, but until CSS3 is widely adopted, it's not going to be possible. Examples here: http://tympanus.net/codrops/2011/11/07/animated-buttons-with-css3/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T10:07:34.657",
"Id": "22585",
"Score": "0",
"body": "As usual, IE spoils it for the rest of us: http://www.w3schools.com/cssref/css3_browsersupport.asp"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T09:17:57.800",
"Id": "22642",
"Score": "0",
"body": "@MattGibson Since IE<9 doesn't support SVG at all, I don't think that is a problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T09:21:36.453",
"Id": "22644",
"Score": "0",
"body": "I'd probably use styles on a class and the `:hover` psuedo-class (I think that works in svg - right?)"
}
] |
[
{
"body": "<p>There does not seem to be a great way of solving this.</p>\n\n<p>The best I can propose is to capture the style that you will re-set to into a function and use that function both during initialization and mouseout, this makes the code DRY'er, but not necessarily nicer:</p>\n\n<pre><code>this.drawPerson = function () {\n\n function style( svg ){\n return svg.style(\"fill\", \"steelblue\") \n .attr(\"transform\", \"translate(100,100)scale(0.1)\");\n }\n\n style( self.svg.append(\"path\")\n .attr(\"d\", personPath)\n .attr(\"class\", \"member\") )\n .on(\"mouseover\", function(){\n d3.select(this).transition()\n .style(\"fill\", \"red\")\n .attr(\"transform\", \"translate(100,100)scale(0.2)\")\n })\n .on(\"mouseout\", function() {\n style( d3.select(this).transition() )\n });\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T15:20:03.270",
"Id": "38326",
"ParentId": "13935",
"Score": "2"
}
},
{
"body": "<p>Okay so this answer does not try to change your code by functionalizing anything or what have you ... but it does optimize it:</p>\n\n<pre><code>function MyClient() {\n var self = this,\n personPath = \"m 1.4194515,-160.64247 c 33.5874165,0 60.8159465,-25.97005 60.8159465,-58.00952 0,-32.0404 -27.22755,-58.0114 -60.8159465,-58.0114 -33.5883965,0 -60.8159415,25.971 -60.8159415,58.0114 0,32.0404 27.228527,58.00952 60.8159415,58.00952 z m 81.9575765,26.25762 C 70.531608,-146.64352 55.269688,-153.983 0.08110256,-153.983 c -55.19742156,0 -70.08915856,7.96609 -82.28062656,19.59815 -12.197359,11.62926 -8.081167,135.7024419 -8.081167,135.7024419 L -63.292733,-59.848397 -46.325227,122.37766 2.6291765,29.116913 48.308878,122.37766 64.467298,-59.848397 91.457218,1.3175919 c 0,-8e-4 4.76917,-123.4484419 -8.08019,-135.7024419 z\",\n fullCanvas = \"100%\",\n w = $('#canvas').width(),\n mapCanvasHeight = (w * 0.75),\n transformVal = \"translate(100,100)scale(0.\";\n\n this.init = function() {\n self.drawCanvas();\n self.drawRect();\n self.drawPerson();\n }\n\n this.drawCanvas = function () {\n self.svg = d3.select('#canvas')\n .append('svg:svg')\n .attr({\n width:fullCanvas,\n height:fullCanvas,\n viewBox:(\"0 0 \" + w + \" \" + mapCanvasHeight)\n });\n }\n\n this.drawRect = function () {\n self.svg\n .append(\"rect\")\n .attr({\n x:0,\n y:0,\n width:w,\n height:mapCanvasHeight,\n fill:\"black\"\n });\n }\n\n this.drawPerson = function () {\n self.svg\n .append(\"path\")\n .attr({\n d:personPath,\n transform:transformVal+\"1)\",\n class:\"member\",\n fill:\"steelblue\"\n })\n .on({\n mouseenter:function(){\n d3.select(this).transition()\n .style({\n fill:\"red\"\n })\n .attr({\n transform:transformVal+\"2)\"\n });\n },\n mouseleave:function() {\n d3.select(this).transition()\n .style({\n fill:\"steelblue\",\n })\n .attr({\n transform:transformVal+\"1)\"\n });\n }\n }); \n }\n\n this.init();\n};\n\nvar MyClient;\njQuery(function() {\n MyClient = new MyClient();\n});\n</code></pre>\n\n<p>The key here is the <strong>DOM object</strong> use of your methods:</p>\n\n<ul>\n<li>style</li>\n<li>attr</li>\n<li>on</li>\n</ul>\n\n<p>This will be faster for three reasons, one major and two minor:</p>\n\n<ul>\n<li>Major = by consolidating your assignments of attributes and <code>mouseenter</code> / <code>mouseleave</code> into a single bind you are applying to the object once instead of many times consecutively, and as we all know the most expensive action in jQuery is DOM querying</li>\n<li>Minor = changing <code>mouseover</code> and <code>mouseout</code> to <code>mouseenter</code> and <code>mouseleave</code> respectively prevents excessive firing (<code>mouseover</code> will fire everytime you move the mouse and it is over the object)</li>\n<li>Minor = use of the DOM object rather than string means less parsing and conversion efforts for the JS compiler to perform</li>\n</ul>\n\n<p><a href=\"http://jsfiddle.net/SuTZR/14/\" rel=\"nofollow\">Here is a working jsFiddle.</a></p>\n\n<p>I also did a couple of minor tweaks like consolidate the variables at the top, assign the <code>\"100%\"</code> value to a variable, rename your <code>width</code> variable (<code>width</code> is a native DOM property for all elements, bad idea to use it as a variable name), and set your <code>transform</code> value to a variable except for the <code>1</code> or <code>2</code> at the end, but these are more coding style than optimizations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T16:19:48.967",
"Id": "38391",
"ParentId": "13935",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T11:42:51.093",
"Id": "13935",
"Score": "5",
"Tags": [
"javascript",
"optimization",
"svg",
"d3.js"
],
"Title": "Optimizing mouse in/out"
}
|
13935
|
<p>I'm creating a class to describe a "zigzag line" fit to a set of data. It implements my interface Fittable, which just contains <code>evaluate()</code> (I have mulitple kinds of curves that all implement this interface). I created the private inner class <code>Node</code> to describe a vertex. It will give the slope going to the left and the slope to the right.</p>
<p>I'm doing a double-check in <code>evaluate()</code>. I am determining the value based off both the <code>floor()</code> and <code>ceiling()</code> values. However, sometimes I get values that don't match up and the <code>IllegalStateException</code> is being thrown. This is because the values for the slopes aren't the same, which lends me to believe that there's a problem with my while loop in the constructor, but I need a fresh set of eyes.</p>
<p>Of course, optimizations are always welcome.</p>
<pre><code>import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.TreeSet;
/**
*
* @author gobernador
*/
public class LinearizedFit implements Fittable {
private TreeSet<Node> data;
public LinearizedFit(double[][] input) throws IllegalArgumentException {
for (int r = 0; r < input.length; r++) {
if (input[r].length != 2) {
throw new IllegalArgumentException("Data must be in a smooth, two-column format.");
}
}
data = new TreeSet(new NodeComparator());
for (double[] coords : input) {
data.add(new Node(coords[0], coords[1]));
}
Iterator<Node> iter = data.iterator();
Node last, node = null, next = iter.next();
while (true) {
last = node;
node = next;
try {
next = iter.next();
node.slopeRight = slope(node, next);
} catch (NoSuchElementException ex) {
next.slopeLeft = slope(last, node);
next.slopeRight = slope(last, node);
break;
}
if (last != null) {
node.slopeLeft = slope(last, node);
} else {
node.slopeLeft = slope(node, next);
}
}
}
public double evaluate(final double x) {
Node thisNode = new Node(x);
Node floor = data.floor(thisNode);
Node ceiling = data.ceiling(thisNode);
double d1, d2;
try {
d1 = floor.y + (floor.slopeRight * (x - floor.x));
} catch (NullPointerException e) {
return ceiling.y + (ceiling.slopeLeft * (x - ceiling.x));
}
try {
d2 = ceiling.y + (ceiling.slopeLeft * (x - ceiling.x));
} catch (NullPointerException e) {
return d1;
}
if (d1 != d2) {
throw new IllegalStateException("Bad information");
}
return d1;
}
private double slope(final Node n1, final Node n2) {
return (n2.y - n1.y) / (n2.x - n1.x);
}
private class Node {
final double x;
final double y;
double slopeLeft;
double slopeRight;
Node(double x, double y) {
this.x = x;
this.y = y;
}
Node(double x) {
this(x, 0);
}
}
private class NodeComparator implements Comparator<Node> {
public int compare(final Node o1, final Node o2) {
if (o1.x < o2.x) {
return -1;
}
if (o1.x > o2.x) {
return 1;
}
return 0;
}
}
public static void main(String... args) {
LinearizedFit lf = new LinearizedFit(new double[][]{{1, 1}, {0, 0}, {2, 0}});
System.out.println(lf.evaluate(-1));
System.out.println(lf.evaluate(0.5));
System.out.println(lf.evaluate(1.5));
System.out.println(lf.evaluate(3));
}
}
</code></pre>
<p>EDIT: added a main method</p>
<p>I expect with this main method to get an output</p>
<blockquote>
<p>-1.0<br>
0.5<br>
0.5<br>
-1.0 </p>
</blockquote>
<p>but instead I get</p>
<blockquote>
<p>-1.0<br>
0.5<br>
Exception in thread "main" java.lang.IllegalStateException: Bad information<br>
at mypackage.LinearizedFit.evaluate(LinearizedFit.java:70)<br>
at mypackage.LinearizedFit.main(LinearizedFit.java:113)<br>
Java Result: 1</p>
</blockquote>
<hr>
<p>Edit: SOLVED: the class below represents the working version</p>
<pre><code>import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.TreeSet;
/**
*
* @author gobernador
*/
public class LinearizedFit implements Fittable {
private TreeSet<Node> data;
public LinearizedFit(double[][] input) throws IllegalArgumentException {
for (int r = 0; r < input.length; r++) {
if (input[r].length != 2) {
throw new IllegalArgumentException("Data must be in a smooth, two-column format.");
}
data.add(new Node(input[r][0], input[r][1]));
}
Iterator<Node> iter = data.iterator();
Node last, node = null, next = iter.next();
do {
last = node;
node = next;
next = iter.next();
node.slopeRight = slope(node, next);
if (last != null) {
node.slopeLeft = slope(last, node);
} else {
node.slopeLeft = slope(node, next);
}
} while (iter.hasNext());
next.slopeLeft = slope(node, next);
next.slopeRight = slope(node, next);
}
public double evaluate(final double x) {
Node thisNode = new Node(x);
Node floor = data.floor(thisNode);
Node ceiling = data.ceiling(thisNode);
double d1, d2;
if (floor != null) {
d1 = floor.y + (floor.slopeRight * (x - floor.x));
} else {
return ceiling.y + (ceiling.slopeLeft * (x - ceiling.x));
}
if (ceiling != null) {
d2 = ceiling.y + (ceiling.slopeLeft * (x - ceiling.x));
} else {
return d1;
}
if (d1 != d2) {
throw new IllegalStateException("Bad information");
}
return d1;
}
private double slope(final Node n1, final Node n2) {
return (n2.y - n1.y) / (n2.x - n1.x);
}
private static class Node {
final double x;
final double y;
double slopeLeft;
double slopeRight;
Node(double x, double y) {
this.x = x;
this.y = y;
}
Node(double x) {
this(x, 0);
}
}
private static class NodeComparator implements Comparator<Node> {
public int compare(final Node o1, final Node o2) {
if (o1.x < o2.x) {
return -1;
}
if (o1.x > o2.x) {
return 1;
}
return 0;
}
}
public static void main(String... args) {
LinearizedFit lf = new LinearizedFit(new double[][]{{1, 1}, {0, 0}, {2, 0}});
System.out.println(lf.evaluate(-1));
System.out.println(lf.evaluate(0.5));
System.out.println(lf.evaluate(1.5));
System.out.println(lf.evaluate(3));
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First, <a href=\"https://stackoverflow.com/questions/2586290/is-catching-a-null-pointer-exception-a-code-smell\">don't catch <code>NullPointerExceptions</code></a>. Not only is it slightly more inefficient, it's a terrible code smell. Instead, do this:</p>\n\n<pre><code>if(floor != null){\n d1 = floor.y + (floor.slopeRight * (x - floor.x));\n} else {\n return ceiling.y + (ceiling.slopeLeft * (x - ceiling.x));\n}\n</code></pre>\n\n<p>Second, if your nested classes don't need access to the outer class, go ahead and make it a static nested class. Just add the <code>static</code> modifier.</p>\n\n<pre><code>private static class NodeComparator implements Comparator<Node> {\n</code></pre>\n\n<p>Third, You loop over the data twice at the beginning. Once to verify integrity and another to add it to your tree. Why not combine the two?</p>\n\n<pre><code>data = new TreeSet(new NodeComparator());\nfor (double[] coords : input) {\n if (coords.length != 2) {\n throw new IllegalArgumentException(\"Data must be in a smooth, two-column format.\");\n }\n data.add(new Node(coords[0], coords[1]));\n}\n</code></pre>\n\n<p>Finally, using an exception to detect the end of the set makes me nervous. I would rewrite that using <code>iter.hasNext()</code>.</p>\n\n<pre><code>if(iter.hasNext()){\n next = iter.next();\n node.slopeRight = slope(node, next);\n} else {\n next.slopeLeft = slope(last, node);\n next.slopeRight = slope(last, node);\n break;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T18:41:10.817",
"Id": "22529",
"Score": "0",
"body": "Thanks for your input, but I'm still getting unexpected results. See my edited question for more error information."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T17:56:57.540",
"Id": "13939",
"ParentId": "13938",
"Score": "4"
}
},
{
"body": "<p>Floating point values are not precise and you compare two doubles with <code>!=</code>.</p>\n\n<p>See:</p>\n\n<ul>\n<li><em>Effective Java, 2nd Edition, Item 48: Avoid float and double if exact answers are required</em></li>\n<li><a href=\"https://stackoverflow.com/questions/8081827/how-to-compare-two-double-values-in-java\">How to compare two double values in Java</a></li>\n</ul>\n\n<p>Some other notes:</p>\n\n<ol>\n<li>\n\n<pre><code>data = new TreeSet(new NodeComparator());\n</code></pre>\n\n<p>should be </p>\n\n<pre><code>data = new TreeSet<Node>(new NodeComparator());\n</code></pre></li>\n<li><p><em>@Danny Kirchmeier</em> has already mentioned the bad practice with <code>NoSuchElementException</code> and <code>NullPointerException</code>. I would like to add another reference to it: <em>Effective Java, 2nd Edition, Item 57: Use exceptions only for exceptional conditions</em>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T19:07:13.397",
"Id": "13944",
"ParentId": "13938",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13939",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T15:42:10.773",
"Id": "13938",
"Score": "1",
"Tags": [
"java"
],
"Title": "Linearized Fit to Data"
}
|
13938
|
<p>When checking for existence of a substring I have been doing this:</p>
<pre><code>var that = "ok hello cool";
if( that.indexOf('hello') + 1 ) {
}
</code></pre>
<p>Instead of: </p>
<pre><code>if( that.indexOf('hello') != -1 ) {
}
</code></pre>
<p>Am I overlooking something or is there a reason not to do this.</p>
<p><strong>Update:</strong></p>
<p>Yes, I was indeed unaware of the even simpler method of:</p>
<pre><code>if ( ~that.indexOf( 'hello' ) ) {
}
</code></pre>
<p>You can read about the <code>~</code> bitwise operator and the other queer bitwise operators here:
<a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators">https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators</a> </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T19:02:35.120",
"Id": "22536",
"Score": "1",
"body": "`if( ~that.indexOf('hello') )` is usually used"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T20:48:41.593",
"Id": "22549",
"Score": "3",
"body": "What's wrong with `indexOf(...) >= 0`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T21:07:27.717",
"Id": "22550",
"Score": "0",
"body": "@RussellBorogove Nothing. It's totally valid. `~` is a lot cleaner than `>= 0`."
}
] |
[
{
"body": "<p>Well, I believe the second one is more obvious what's going on...</p>\n\n<pre><code>if( that.indexOf('hello') != -1 ) {\n}\n</code></pre>\n\n<p>That's all to it however, both expressions are valid and perfectly ok.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T18:59:45.763",
"Id": "13942",
"ParentId": "13941",
"Score": "13"
}
},
{
"body": "<p>Here is the most seen way:</p>\n\n<pre><code>if ( ~that.indexOf( 'hello' ) ) {\n}\n</code></pre>\n\n<p>The <code>~</code> operator does some magic and transforms only -1 in 0, thus it's the only falsy value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T19:03:41.500",
"Id": "22537",
"Score": "1",
"body": "That is neat, never seen that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T19:05:57.947",
"Id": "22539",
"Score": "2",
"body": "@Florian [MDN says:](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators) Inverts the bits of its operand. WTH does that mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T19:06:54.053",
"Id": "22540",
"Score": "1",
"body": "Ok, that's not really important to understand here. All you need to understand is that `~-1 === 0` (false for not found) and `~anythingelse !== 0` (true for found)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T19:07:02.033",
"Id": "22541",
"Score": "0",
"body": "@iambriansreed It's working on the bits of the number. For example, 2 in base 10 is 0010 in base 2. Well, ~ inverts all the bits. But yeah, as Esailija says, it's not really important to know, you probably won't ever use it except for this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T19:08:05.507",
"Id": "22542",
"Score": "0",
"body": "@iambriansreed it seems to be 1-s complement -(1+x)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T20:43:10.760",
"Id": "22548",
"Score": "0",
"body": "I doubt this could be called the \"most seen way\", like GeorgeMauer and iambriansreed, I haven't seen this before either."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T22:45:17.650",
"Id": "22558",
"Score": "0",
"body": "@GeorgeMauer, I believe you mean 2's complement. http://en.wikipedia.org/wiki/Two's_complement"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T08:40:29.173",
"Id": "22578",
"Score": "0",
"body": "@Izkata Should I say \"most used by experienced js dev\"? :-) It's even mentioned in [one of the best js tutorials](http://javascript.info/tutorial/string#finding-a-substring) out there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T09:48:03.800",
"Id": "22582",
"Score": "9",
"body": "I think that this not the best way to make code readable. Why using bitwise operator to create a condition? `!= -1` is used in many languages and it is the simplest and most readable method."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T19:03:12.927",
"Id": "13943",
"ParentId": "13941",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "13943",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T18:54:19.177",
"Id": "13941",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "indexOf() + 1 vs indexOf() != -1"
}
|
13941
|
<p>This is a Python script to save imgur pictures posted to reddit.com forums. I'm looking for an assessment on the design of this script and any web security issues that might exist.</p>
<p>Obvious shortcomings: it only downloads image links <a href="https://i.imgur.com/xx.png" rel="nofollow noreferrer">http://i.imgur.com/xx.png</a> not images from imgur pages <a href="https://imgur.com/page/" rel="nofollow noreferrer">http://imgur.com/page/</a> and lacks the ability to get image albums. </p>
<pre><code># purpose: downloads images from imgur.com links posted to specified reddits
# platform: python 3.2
# references:
# - reddit JSON -- https://github.com/reddit/reddit/wiki/API:-info.json
import json
import urllib.request
import os, sys
def downloadPostsFrom(subreddit):
"Returns reddit posts as JSON"
try:
f = urllib.request.urlopen("http://www.reddit.com/r/"+subreddit+"/.json");
return json.loads(f.read().decode("utf-8"))["data"]["children"]
except Exception:
print("ERROR: malformed JSON response from reddit.com")
raise ValueError
def parseImageURL_From(posts):
"Returns tuple iterator (url, title)"
for node in posts:
post = node['data']
# only accept links from imgur.com
if post['domain'].endswith('imgur.com'):
yield post["url"], post["title"]
def makeFileExt(content_type):
"Return extension for specified content type"
return {
'image/bmp':'bmp',
'image/gif':'gif',
'image/jpeg':'jpg',
'image/png':'png',
'image/tiff':'tif',
'image/x-icon':'ico'
}.get(content_type, 'txt')
def makeFileName(title):
"Compute valid file name from image title. Return file name or default.ext"
title = title.strip(' .?:')
file_name = title.translate(''.maketrans('\/:*?"<>|$@ .','__.-_____S0___'))
file_name = file_name.strip('_').replace('__','_').lower()
return file_name + '.' if file_name else 'default.'
def makeSaveDir(save_dir):
"Creates directory. Returns a valid directory name."
if not os.path.exists(save_dir):
os.makedirs(save_dir)
return save_dir + '/'
def downloadImagesIntoDir(save_dir, image_refs):
"Download image files into specified directory."
save_dir = makeSaveDir(save_dir)
print('saving to:', save_dir)
for url, title in image_refs:
try:
# open connection to image
request = urllib.request.urlopen(url)
if request.code == 200:
content_type = request.headers.get_content_type()
# filter in images
if 'image' == content_type.split('/')[0]:
file_name = save_dir \
+ makeFileName(title) + makeFileExt(content_type)
# download image to local file
print(' downloading:', title)
with open(file_name, "wb") as image_file:
image_file.write(request.read())
except Exception:
print("ERROR: bad request --", title)
def downloadRedditImages(subreddits):
"Download imgur images from reddit. Returns None."
for subreddit in subreddits:
try:
# reddit_posts: JSON
reddit_posts = downloadPostsFrom(subreddit)
image_urls = parseImageURL_From(reddit_posts)
downloadImagesIntoDir(subreddit, image_urls)
except Exception:
pass
def main():
"Use app as console program."
if len(sys.argv) > 1:
downloadRedditImages(sys.argv[1:]);
else:
# specify your default reddits here
downloadRedditImages(['funny']);
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Never do <code>except Exception:</code>, <em>especially</em> not to <code>pass</code>. You probably want to be catching <code>KeyError</code>s specifically, or using <code>dict.get</code> in the first case, and in the other cases adjust accordingly.</p></li>\n<li><p>There's no need to do <code>json.loads(file_like_object.read())</code>, just use <code>json.load(file_like_object)</code>.</p></li>\n<li><p>You can eliminate a race condition in <code>makeSavedir</code> by not calling <code>os.path.exists</code>, just call <code>os.makedirs</code> (and catch the <code>IOError</code> if you'd like to not raise the exception [and make sure to check its <code>errno</code>]).</p></li>\n<li><p>You can use <a href=\"http://docs.python.org/library/stdtypes.html#string-formatting\" rel=\"nofollow\">string formatting</a> in place of adding strings.</p></li>\n<li><p>Your <code>try</code> blocks are too big. They will catch various exceptions that you aren't handling. This is another instance of my first point.</p></li>\n</ul>\n\n<p>There are other things, these were just the quick things from reading top to bottom :).</p>\n\n<p>P.S. There's an unofficial Python wrapper for the reddit API at <a href=\"https://github.com/praw-dev/praw\" rel=\"nofollow\">https://github.com/praw-dev/praw</a> that you could consider using.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T04:23:50.583",
"Id": "14112",
"ParentId": "13945",
"Score": "4"
}
},
{
"body": "<p>I think, the following line should have a else condtion to print error if it failed.</p>\n\n<pre><code>if request.code == 200:\n</code></pre>\n\n<p>From the except block, it looks like you want to print errors.</p>\n\n<ul>\n<li>You can use <a href=\"https://docs.python.org/3/library/logging.html\" rel=\"nofollow noreferrer\"><code>logging</code> module</a> for logging error and debug statements. </li>\n<li>If the script is intended to be used by others, you can use argparse module for command line arguments.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T10:12:34.707",
"Id": "14142",
"ParentId": "13945",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T19:11:45.803",
"Id": "13945",
"Score": "3",
"Tags": [
"python",
"json",
"image",
"reddit"
],
"Title": "Download image links posted to reddit.com"
}
|
13945
|
<p>I have an array of strings which are file names <code>files</code>, and an array of allowed file types or suffixes <code>allowed_types</code>. I want to filter out files which don't end with an allowed suffix.</p>
<p>This does the trick, but I'm wondering if anyone can suggest a neater solution? Such as a way keep with ruby's usual streamlined style without using flag variables. </p>
<pre><code>valid_files = Dir.entries(path).select do |f|
valid = false
allowed_types.each { |suffix| next valid = true if f.end_with? suffix }
next valid
end
</code></pre>
|
[] |
[
{
"body": "<p>How about this?</p>\n\n<pre><code>valid_files = Dir.entries(path).select do |f| \n allowed_types.any? {|suffix| f.end_with? suffix}\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T12:55:39.637",
"Id": "13948",
"ParentId": "13947",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "13948",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T12:52:01.320",
"Id": "13947",
"Score": "1",
"Tags": [
"ruby"
],
"Title": "Neatest way to filter an array of strings by another array in ruby"
}
|
13947
|
<p>I have written code exclusively in both C and C++. I see clear advantages in both and therefore have recently began using them together. I have also read, what I would consider, outrageous comments claiming that to code in C is outright dumb, and it is the language of past generations. So, in terms of maintenance, acceptance, common practice and efficiency; is it something professionals on large scale projects see/do?</p>
<p>Here's an example snippet:
I obviously need to <code>#include</code> both <code><stdio.h></code> and <code><iostream></code>.</p>
<pre><code>#define STRADD ", "
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include "Struct.h"
#include "Rates.h"
#include "Taxes.h"
using namespace std;
</code></pre>
<p>And later I utilize functions like...</p>
<pre><code>void printHeading(FILE * fp)
{
fprintf(fp, "Employee Pay Reg Hrs Gross Fed SSI Net\n");
fprintf(fp, "Name Rate Ovt Hrs Pay State Defr Pay\n");
fprintf(fp, "==================================================================================\n");
return;
}
</code></pre>
<p>and..</p>
<pre><code>void getEmpData(EmpRecord &e)
{
cout << "\n Enter the employee's first name: ";
getline(cin, e.firstname);
cout << " Enter the employee's last name: ";
getline(cin, e.lastname);
e.fullname = e.lastname + STRADD + e.firstname; //Fullname string creation
cout << " Enter the employee's hours worked: ";
cin >> e.hours;
while(e.hours < 0)
{
cout << " You did enter a valid amount of hours!\n";
cout << " Please try again: ";
cin >> e.hours;
}
cout << " Enter the employee's payrate: ";
cin >> e.rate;
while(e.rate < MINWAGE)
{
cout << " You did enter a valid hourly rate!\n";
cout << " Please try again: ";
cin >> e.rate;
}
cout << " Enter any amount to be tax deferred: ";
cin >> e.deferred;
while(e.deferred < 0)
{
cout << " You did enter a valid deferred amount!\n";
cout << " Please try again: ";
cin >> e.deferred;
}
cin.ignore(100, '\n');
return;
}
</code></pre>
<p>Thanks in advance!</p>
|
[] |
[
{
"body": "<p>You can't write <code>exclusively in both C and C++</code>.</p>\n<p>You can write</p>\n<ul>\n<li>exclusively in C</li>\n<li>exclusively in C++</li>\n<li>or using a combination of the two <strong>different</strong> languages.</li>\n</ul>\n<blockquote>\n<p>to code in C is outright dumb, and it is the language of past generations.</p>\n</blockquote>\n<p>C may be an old language but it is still heavily used and has its place.<br />\nIt is practically the only glue language that is universal so great for writing effecient modules for other languages or gluing languages together.</p>\n<p>It is also great for low level coding where you want/need to get close to the hardware.</p>\n<p>But there are downsides to writing in C (but saying it is dumb to do so is stretching it a bit). But you should be able to justify your choice of choosing C over an alternative.</p>\n<blockquote>\n<p>So, in terms of maintenance, acceptance, common practice and efficiency; is it something professionals on large scale projects see/do?</p>\n</blockquote>\n<p>Are there large code bases writing in C that need maintenance: <strong>Yes</strong>.</p>\n<p>Is it common practice to use C: <strong>That is entirely dependent on what you are doing it is imposable to generalize</strong>.</p>\n<p>Personally I write exclusively in C++.<br />\nThere is nothing I can do in C I can't do in C++ so I don't write C anymore (In fact I have dropped it from my resume (especially since I don't want to write C)). The advantage of C++ is I can get code written to as low a level as C but I also have higher level constructs (though not as high as modern scripting languages).</p>\n<h3>Code Review:</h3>\n<p>I see no advantage of using <code>frpintf()</code>. In situations like this C++ std::ofstream is much more flexible,</p>\n<pre><code>printHeading(FILE * fp)\n{\n fprintf(fp, "Employee Pay Reg Hrs Gross Fed SSI Net\\n");\n\n// I would always use C++ stream.\n// It can be more than just a file.\nprintHeading(std::ostream& stream)\n{\n stream << "Employee Pay Reg Hrs Gross Fed SSI Net\\n";\n</code></pre>\n<p>Also if you are doing anything complex it is <strong>TYPE SAFE</strong>. *<em>Unlike C</em> code using <code>fprintf()</code>. This is one major area that C falls down in and is the cause of some of the major bugs in C code.</p>\n<p>You check for an invalid number. But you are not checking for completely invalid input. What happens if somebody typed "Fred"</p>\n<pre><code>cin >> e.hours;\nwhile(e.hours < 0)\n{\n cout << " You did enter a valid amount of hours!\\n";\n cout << " Please try again: ";\n cin >> e.hours;\n}\n</code></pre>\n<p>You expect that there is never more than 100 bad characters in the input?</p>\n<pre><code>cin.ignore(100, '\\n');\n</code></pre>\n<p>What happens if I accidentally paste in a paragraph of text.</p>\n<p>And last but worst of all:</p>\n<pre><code>using namespace std; \n</code></pre>\n<p>Never do this. It is OK if you are writting a ten line toy project. But once you get past anything more than a toy it causes more problems (in name clashes) than it is worth. The reason <code>standard library</code> is shortened to <code>std::</code> is to make it easy and quick to type.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T23:22:35.833",
"Id": "22560",
"Score": "1",
"body": "sorry about the confusion, I meant I have done both exclusively meaning separately. I was asking more if they are indeed used simultaneously. Being a newb I don't really know the full potential of either language and would prefer not to develop bad habits. For maintenance I was speaking to issues with other programmers maintaining dual-language code. I'd justify using C functions because they seem more direct/easy/dependable. I've heard of people changing c(in/out) to the C counterparts and making the difference in passing a benchmark test. Are these wives tales?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T23:53:40.597",
"Id": "22562",
"Score": "0",
"body": "-After edit: I understand on input validation, at this point I do what I'm told! With `cin.ignore(100, '\\n')`, we're using Win32 Console Apps so it's actually only used to hold the console win open for screen shots. You're not the first person to recommend std::, so I read a book which refers to std:: as an older style and made it seem it was normal/usual to declare classes inside of a namespace, define an instance, `using namespace ns;` and refer to it as `class.mem` as opposed to `ns::class.mem`. I also asked a professor of mine who agreed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T23:58:13.560",
"Id": "22563",
"Score": "1",
"body": "Well your professor is absolutely wrong. In real production code you will hardly ever see `using namespace X;`. Just read a couple of other reviews here. Sure in toy code you will see it. But anything more than a few hundred lines using multiple namespaces you will end up with nameclashes. The whole point of namespaces is to avoid nameclashes and by having `using namesapce X` you totally break something the language is trying to fix from C."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T00:06:59.977",
"Id": "22564",
"Score": "1",
"body": "You should probably read some modern C++ books: [\"Herb Sutters\" Exceptional C++](http://www.amazon.com/Exceptional-Engineering-Programming-Problems-Solutions/dp/0201615622/ref=sr_1_sc_1?ie=UTF8&qid=1343088242&sr=8-1-spell&keywords=hurb+sutter+exceptional), [\"Scott Myers\" Effective C++](http://www.amazon.com/gp/product/0321334876?ie=UTF8&tag=aristeia.com-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0321334876), [\"Alexandrescu\" Modern C++ design](http://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315/ref=sr_1_1?ie=UTF8&qid=1343088366&sr=8-1&keywords=Alexandrescu)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T00:09:22.750",
"Id": "22565",
"Score": "0",
"body": "Check [here](http://stackoverflow.com/tags/c%2b%2b/info) for generic information. [Reading List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) for a copy of the [C++ standard](http://stackoverflow.com/a/4653479/14065)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T00:12:50.810",
"Id": "22566",
"Score": "0",
"body": "As for using C/C++ together. Yes it happens. Yes it can work. **BUT** Going forward it is probably best not to. There are problems that crop up mixing and matching that you need to pay attention to. In software you want to minimize the number of variables that can go wrong (why have two languages when one will do). But if you have a good reason then it will happen but most new projects will try and pick 1 language when possible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T00:17:02.143",
"Id": "22567",
"Score": "0",
"body": "I appreciate the references, I will read more on the subject. I'm referencing \"Tony Gaddis\" STARTING OUT WITH C++ - From Controls Through Objects 7e, 2012. It may be too elementary to deal with such issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T00:23:00.720",
"Id": "22568",
"Score": "0",
"body": "Note: Having `usign namespace X;` in a source file is very rare. **BUT** you should **NEVER** have it in a public header file. This will cause namespace pollution for anybody that uses your header file and people will throw your code away because of that."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T22:48:33.493",
"Id": "13953",
"ParentId": "13949",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "13953",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-23T21:43:04.607",
"Id": "13949",
"Score": "1",
"Tags": [
"c++",
"c"
],
"Title": "What are the draw backs, if any, in using C and C++ together? Is doing so considered correct by the large?"
}
|
13949
|
<p><strong>About Data:</strong> 3D data (100x100x20). </p>
<p><strong>Computation/Formula and Method:</strong> I am trying to compute the sum of squared differences along rows, columns and angles for various time differences.</p>
<pre><code>%% Grid and time paramters
%# Grid parameters
nRows=100;
nCol=100;
InitLag_Row=0;
InitLag_Col=0;
InitLag_Ang=0;
LessLags=20;
nLags_Row=nRows-LessLags;
nLags_Col=nCol-LessLags;
nLags_Ang=min(nRows,nCol)-LessLags;
%# Time parameters
T=1:1:20;
nT=numel(T);
%# Load concentrations data file with 100x100x20 dimensions
load('c.mat')
%% Shift values along rows for all columns and all time steps
for hRow=InitLag_Row:nLags_Row
c_ShiftedRow(:,:,:,hRow+1)=circshift(c(:,:,:),[-hRow 0]);
end
%% Shift values along columns for all rows and all time steps
for hCol=InitLag_Col:nLags_Col
c_ShiftedCol(:,:,:,hCol+1)=circshift(c(:,:,:),[0 -hCol]);
end
%% Shift values along NW-SE and NE-SW directions for all time steps
for hAng=InitLag_Ang:nLags_Ang
c_ShiftedNWSE(:,:,:,hAng+1)=circshift(c(:,:,:),[-hAng -hAng]);
c_ShiftedNESW(:,:,:,hAng+1)=circshift(c(:,:,:),[-hAng hAng]);
end
idel_t=1; % initialize index for zero time lag
for del_t=0:nT-1 % time lag
for nLags_t=1:nT-del_t; % number of time lags formed with del_t lag value
for hRow=InitLag_Row:nLags_Row
variogramTemp_hRow3D=(cumsum(((c(1:end-hRow,:,nLags_t)-...
c_ShiftedRow(1:end-hRow,:,nLags_t+del_t,hRow+1)).^2),1))./...
(2*size(c(1:end-hRow,:,nLags_t),1));
variogram_hRow3D(hRow+1,:,nLags_t,idel_t)=variogramTemp_hRow3D(end,:)./...
mean(var(c(1:end-hRow,:,[nLags_t,nLags_t+del_t]),0,1),3);
end
%% Variogram along columns for all images
for hCol=InitLag_Col:nLags_Col
variogramTemp_hCol3D=(cumsum(((c(:,1:end-hCol,nLags_t)-...
c_ShiftedCol(:,1:end-hCol,nLags_t+del_t,hCol+1)).^2),2))./...
(2*size(c(:,1:end-hCol,nLags_t),2));
%# normalized variogram values at all times for different lags at all 'nRows'
variogram_hCol3D(:,hCol+1,nLags_t,idel_t)=variogramTemp_hCol3D(:,end)./...
mean(var(c(:,1:end-hCol,[nLags_t,nLags_t+del_t]),0,2),3);
end
%% Variogram along NW-SE and NE-SW directions for all images
for hAng=InitLag_Ang:nLags_Ang
variogramTemp_h3DNWSE=(cumsum(((c(1:end-hAng,1:end-hAng,nLags_t)-...
c_ShiftedNWSE(1:end-hAng,1:end-hAng,nLags_t+del_t,hAng+1)).^2),1))./...
(2*size(c(1:end-hAng,1:end-hAng,nLags_t),1));
variogramTemp_h3DNESW=(cumsum(((c(1:end-hAng,end:-1:1+hAng,nLags_t)-...
c_ShiftedNESW(1:end-hAng,end:-1:1+hAng,nLags_t+del_t,hAng+1)).^2),1))./...
(2*size(c(1:end-hAng,end:-1:1+hAng,nLags_t),1));
%# normalized variogram values/cumulative sum at all times for different lags along NW-SE and NE-SW directions
variogram_h3DNWSE(hAng+1,1:nCol-hAng,nLags_t,idel_t)=variogramTemp_h3DNWSE(end,:)./...
mean(var(c(1:end-hAng,1:end-hAng,[nLags_t,nLags_t+del_t]),0,1),3);
variogram_h3DNESW(hAng+1,1:nCol-hAng,nLags_t,idel_t)=variogramTemp_h3DNESW(end,:)./...
mean(var(c(1:end-hAng,end:-1:1+hAng,[nLags_t,nLags_t+del_t]),0,1),3);
end
end
%# Change the zero matrices after nT-del_t to NaN
variogram_hRow3D(:,:,nT-del_t+1:end,idel_t)=nan;
variogram_hCol3D(:,:,nT-del_t+1:end,idel_t)=nan;
variogram_h3DNWSE(:,:,nT-del_t+1:end,idel_t)=nan;
variogram_h3DNESW(:,:,nT-del_t+1:end,idel_t)=nan;
%# change to next time lag index
idel_t=idel_t+1;
end
</code></pre>
<p>I would appreciate any help on ways to make this code faster and more efficient.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T01:40:02.383",
"Id": "22551",
"Score": "0",
"body": "As a start, check out `pdist` - you can probably use that to do the bulk of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T01:59:05.153",
"Id": "22552",
"Score": "0",
"body": "tmpearce: Thanks for the function. I was also thinking to use `circshift()`, even though it's just a small step for the problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T04:17:11.963",
"Id": "22553",
"Score": "0",
"body": "Also, if you could come up with a small example (3 by 3 by 2 perhaps) and the expected results, people may be more interested in playing around with the problem and coming up with a good solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T05:56:44.567",
"Id": "22554",
"Score": "0",
"body": "I've added some explanation and the rest I'd try to do tomorrow. Please let me know if there's something in the question which is not clear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-18T21:10:26.613",
"Id": "22555",
"Score": "0",
"body": "@tmpearce: I've added some illustration to explain my specific problem and how it is done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-22T21:34:08.547",
"Id": "96026",
"Score": "0",
"body": "It's not a complete answer, but because of the generic form of the question I would suggest that you use matlab [profiler](http://www.mathworks.com/help/techdoc/matlab_env/f9-17018.html), and after you get the results you can ask a more specific question."
}
] |
[
{
"body": "<p>Here's a way to do it using <code>pdist</code> to generate both the differences in value, plus logical indices that you can use to select which distances you wish to look at/use further.</p>\n\n<pre><code>D1 = [1 2 3;4 5 6;7 8 9];\nD2 = [9 8 7;6 5 4;3 2 1];\nD = cat(3,D1,D2);\n\nD(:,:,1) =\n\n 1 2 3\n 4 5 6\n 7 8 9\n\nD(:,:,2) =\n\n 9 8 7\n 6 5 4\n 3 2 1\n\nY = repmat([1 2 3]', [1 3 2]); %# (' in comment to fix SO highlighting)\nX = repmat([1 2 3],[3 1 2]);\nT = repmat(cat(3,1,2),[3 3 1]);\nD_diffsqrd = pdist(D(:),'euclidean').^2;\nX_dist = pdist(X(:),'euclidean');\nY_dist = pdist(Y(:),'euclidean');\nT_dist = pdist(T(:),'euclidean');\nAngle_dist = pdist([X(:) Y(:)],'euclidean');\n\nD_diffsqrd(X_dist==2 & T_dist==0 & Y_dist==0)\n 4 4 4 4 4 4\n\nD_diffsqrd(X_dist==0 & T_dist==0 & Y_dist==2)\n 36 36 36 36 36 36\n\nD_diffsqrd(X_dist==0 & T_dist==1 & Y_dist==0)\n 64 4 16 36 0 36 16 4 64\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T18:00:31.713",
"Id": "22556",
"Score": "0",
"body": "tmpearce: I did the ones for `Row_Lag` and `Col_Lag` and I am getting some results, though have to make sure they are correct. I did for `Angle_Lab` on a single image (2D) but have not tried yet for the 3D. I used `circshift()` to shift the numbers to take differences. Will post the updated question later. Thanks for your efforts!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-19T15:45:30.040",
"Id": "13951",
"ParentId": "13950",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-07-17T22:34:44.313",
"Id": "13950",
"Score": "1",
"Tags": [
"matrix",
"matlab"
],
"Title": "Computing the sum of squared differences"
}
|
13950
|
<p>This is the stripped down version of my update action for a Posts (blog post) controller:</p>
<pre><code>Posts.update = function(req, res){
_.extend(req.post, {
title: req.body.title
, author: req.body.author
, body: req.body.body
});
post.save();
};
</code></pre>
<p>This way feels a bit clumsy and repetitive, because I have similar code in another method, but I don't want to just straight up <code>_.extend(req.post, req.body)</code> because it may allow someone to change fields that shouldn't be changed in my models.</p>
<p>Is there a better middle ground?</p>
|
[] |
[
{
"body": "<p>How about <a href=\"http://documentcloud.github.com/underscore/#pick\" rel=\"nofollow\"><code>_.pick()</code></a>?</p>\n\n<pre><code>Posts.update = function(req, res){\n _.extend(req.post, _.pick(req.body, 'title', 'author', 'body'));\n post.save();\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T01:50:25.117",
"Id": "13990",
"ParentId": "13957",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T00:10:27.580",
"Id": "13957",
"Score": "2",
"Tags": [
"javascript",
"mvc",
"node.js"
],
"Title": "Is there a better way to update fields in an web app?"
}
|
13957
|
<p>My view submits data to the controller using Json objects which contains child objects.It allows users to add/remove/modify the relationship with child entities(authors,categories,LIbraryBookCopy). Users can only select authors and categories from list but can update/add LibraryBookCopy object.</p>
<p>This is my first MVC project and I have done this so far . Am I doing too much manipulation on the data? Is this the right way of doing this?</p>
<pre><code>[HttpPost]
public ActionResult Edit(BookViewModel bookv)
{
bool found=false;
Mapper.CreateMap<AuthorViewModel, Author>();
Mapper.CreateMap<CategoryViewModel, Category>();
Mapper.CreateMap<LibraryBookCopyViewModel, LibraryBookCopy>();
List<Author> authors = Mapper.Map<List<AuthorViewModel>, List<Author>>(bookv.Authors.ToList());
List<Category> categories = Mapper.Map<List<CategoryViewModel>, List<Category>>(bookv.Categories.ToList());
bookv.Authors.Clear();
bookv.Categories.Clear();
Mapper.CreateMap< BookViewModel,Book>();
Book book = Mapper.Map<BookViewModel,Book>(bookv);
List<LibraryBookCopy> toBeDeletedLibraryBookCopies = new List<LibraryBookCopy>();
List<LibraryBookCopy> toBeAddedLibraryBookCopies = new List<LibraryBookCopy>();
List<LibraryBookCopy> toBeUpdatedLibraryBookCopies = new List<LibraryBookCopy>();
List<LibraryBookCopy> libraryBookCopiesFromDatabase = new List<LibraryBookCopy>();
db.Books.Attach(book);
//Assign categories to book
foreach (Category c in categories) { db.Categories.Attach(c); }
book.Categories.Clear();
foreach (Category c in categories) { book.Categories.Add(c); }
//Assign authors to book
foreach (Author a in authors) { db.Authors.Attach(a); }
book.Authors.Clear();
foreach (Author a in authors) {book.Authors.Add(a); }
if (bookv.LibraryBookCopies != null)
{
List<LibraryBookCopy> bookCopiesFromView = Mapper.Map<List<LibraryBookCopyViewModel>, List<LibraryBookCopy>>(bookv.LibraryBookCopies);
libraryBookCopiesFromDatabase = db.LibraryBookCopies.Where(lbc=>lbc.BookId==book.BookId).ToList();
foreach (LibraryBookCopy bc in libraryBookCopiesFromDatabase)
{
foreach (LibraryBookCopy bcv in bookCopiesFromView)
{
if ((bc.LibraryId == bcv.LibraryId) )
{
found = true;
toBeUpdatedLibraryBookCopies.Add(bcv);
break;
}
}
if (!found)
{
toBeDeletedLibraryBookCopies.Add(bc);
}
found = false;
}
//remove objects moved to toBeDelted
foreach (LibraryBookCopy lbc in toBeDeletedLibraryBookCopies )
{
libraryBookCopiesFromDatabase.Remove(lbc);
}
//NOW FIND NEW BOOK COPIES TO BE ADDED
foreach (LibraryBookCopy bcv in bookCopiesFromView)
{
if (libraryBookCopiesFromDatabase.Count == 0)
{
toBeAddedLibraryBookCopies.Add(bcv);
}
else
{
foreach (LibraryBookCopy bc in libraryBookCopiesFromDatabase)
{
if ((bc.LibraryId != bcv.LibraryId))
{
toBeAddedLibraryBookCopies.Add(bcv);
}
}
}
}
}
else
{
book.LibraryBookCopies.Clear();
}
//mark copies as deleted
foreach (LibraryBookCopy lbcv in toBeDeletedLibraryBookCopies)
{
// db.LibraryBookCopies.Attach(lbcv);
db.LibraryBookCopies.DeleteObject(lbcv);
}
//Add library ref to each libraryBookCopies object in Book
foreach (LibraryBookCopy lBC in toBeAddedLibraryBookCopies)
{
db.LibraryBookCopies.AddObject(lBC);
}
db.ObjectStateManager.ChangeObjectState(book, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
</code></pre>
|
[] |
[
{
"body": "<p>I don't code in C#, so just two generic notes:</p>\n\n<ol>\n<li><p>The following comments are good candidates for method names:</p>\n\n<ul>\n<li><code>//Assign categories to book</code>: <code>assignCategories</code>, <code>assignCategoriesToBook</code></li>\n<li><code>//Assign authors to book</code>: <code>assignAuthors</code>, <code>assignAuthorsToBook</code></li>\n<li><code>//remove objects moved to toBeDelted</code>: <code>removeObjects</code></li>\n<li><code>//NOW FIND NEW BOOK COPIES TO BE ADDED</code>: <code>findNewBooks</code></li>\n<li><code>//mark copies as deleted</code>: <code>markDeleted</code></li>\n<li><code>//Add library ref to each libraryBookCopies object in Book</code>: <code>addLibraryReference</code></li>\n</ul></li>\n<li><p>Short variable names (like <code>lBC</code>, <code>lbcv</code>, <code>bcv</code>, <code>bookv</code>) are not too readable. I suppose you have autocomplete, so using longer names does not mean more typing but I'd help readers and maintainers a lot since they don't have to remember the purpose of each variable - the name would express the programmers intent.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T09:00:15.157",
"Id": "13964",
"ParentId": "13961",
"Score": "0"
}
},
{
"body": "<p>Doing too much on the <code>Controller</code> is subjective. If you do not have a Data Access Layer, I guess this is where you have to write this manipulation logic. However, you can consider followings;</p>\n\n<ul>\n<li>Pick meaningful names which are intention-revealing and pronounceable instead of encoding (such as <code>bookv</code>, <code>c</code>, <code>a</code>, <code>bc</code>, <code>bcv</code>, <code>lBC</code>).</li>\n<li>Split methods so they are small enough to one thing and give descriptive names. In this way you obey to do '<em>method should do one and one only thing</em>' and <em>not to do anything that is not useful for the program</em>.</li>\n</ul>\n\n<p>You can start doing these by;</p>\n\n<ol>\n<li>Rename variables for meaningful names.</li>\n<li>Move mapping logic to a seperate method.</li>\n<li>Move each <code>FOREACH</code>/<code>IF</code> statements to separate methods.</li>\n<li>Encapsulate <code>IF</code> conditions from methods.</li>\n<li>Encapsulate body content of <code>FOREACH</code>/<code>IF</code> statements to separate methods.</li>\n<li>Encapsulate LINQ queries using filters.</li>\n<li>Encapsulate object's state change from a method.</li>\n</ol>\n\n<p>However, doing all these could be over engineering so you might need to find the balance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-22T13:29:17.293",
"Id": "15831",
"ParentId": "13961",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T05:51:52.317",
"Id": "13961",
"Score": "1",
"Tags": [
"c#",
"asp.net-mvc-3",
"entity-framework"
],
"Title": "Many to many crud using entity framework 4.1"
}
|
13961
|
<p>This craps game simulator is based on someone else's posted Python code that I've redone for practice. I'm interested in improving readability and making it more pythonic. I used <code>unittest</code> instead of <code>nose</code> because I'm using an online IDE.</p>
<pre><code>from random import randrange
import unittest
class CrapsGame:
def __init__(self):
self.outcomes = {'2':False,'3':False,'12':False,'7':True,'11':True,
'4&4':True,'5&5':True,'6&6':True,
'8&8':True,'9&9':True,'10&10':True,
'4&7':False,'5&7':False,'6&7':False,
'8&7':False,'9&7':False,'10&7':False}
def play(self, roll_dice):
comeOut = str(roll_dice())
print 'began game with ' + comeOut
if comeOut in self.outcomes:
return self.outcomes[comeOut]
while True:
point = str(roll_dice())
print 'next roll is ' + point
state = comeOut+'&'+point
if state in self.outcomes:
return self.outcomes[state]
class CrapsTest(unittest.TestCase):
def testWinComeOut(self):
game = CrapsGame()
self.assertEquals(game.play(lambda: 7), True)
def testLoseComeOut(self):
game = CrapsGame()
self.assertEquals(game.play(lambda: 2), False)
def testWinPoint(self):
game = CrapsGame()
rollData = [5,6,5]
self.assertEquals(game.play(lambda: rollData.pop()), True)
def testLosePoint(self):
game = CrapsGame()
rollData = [7,5]
self.assertEquals(game.play(lambda: rollData.pop()), False)
if __name__ == '__main__':
unittest.main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T17:37:24.210",
"Id": "466862",
"Score": "0",
"body": "I can give my 2 cents in regard to the naming conventions. Using snake case for the variables' names would be definitely more pythonic, for example `come_out` instead of `comeOut`."
}
] |
[
{
"body": "<p>Some general comments first.</p>\n\n<ol>\n<li><p>There's no need to make your throws in strings for the outcomes - you can use tuples instead. e.g.</p>\n\n<pre><code>self.outcomes = { (2,):False, (5,5):True }\n</code></pre></li>\n<li><p>If you pass a \"wrong\" set of dice throws (say \\$[4,5]\\$), you'll have an exception raised which isn't dealt with (and should probably be a test?).</p></li>\n<li><p><code>pop</code> removes the last element, which means you process them in reverse order - which differs from what the casual reader might expect (\\$[7,5]\\$ = 7 first, then 5).</p></li>\n</ol>\n\n<p>You may want to look at generators which would provide a nice interface to a throw. In this case, what about:</p>\n\n<pre><code>class DiceThrow:\n def __init__( self, rolls = None ):\n self.rolls = rolls\n def First( self ):\n return self.__next__()\n def __iter__( self ):\n return self\n def __next__( self ):\n if self.rolls is not None:\n if len( self.rolls ) == 0:\n raise StopIteration\n r = self.rolls[0]\n self.rolls = self.rolls[1:]\n return r\n return randrange( 1, 13 ) # may be better as randint( 1, 12 )\n</code></pre>\n\n<p>This can then be called as follows:</p>\n\n<pre><code>game.play( DiceThrow( [5,7] ) )\ngame.play( DiceThrow() ) # for a random set of throws\n</code></pre>\n\n<p>and used:</p>\n\n<pre><code>def play(self, dice_throw):\n comeOut = dice_throw.First()\n print( \"began game with %d\"%comeOut )\n if (comeOut,) in self.outcomes:\n return self.outcomes[(comeOut,)]\n for point in dice_throw:\n print( \"next roll is %d\"%point )\n state = (comeOut,point)\n if state in self.outcomes:\n return self.outcomes[state]\n print( \"Bad rolls!\" )\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T06:28:56.250",
"Id": "22626",
"Score": "0",
"body": "Thank you. I appreciate the effort. I like the tuples instead of strings, and the idea of using a generator sounds interesting."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T10:00:44.127",
"Id": "13966",
"ParentId": "13962",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13966",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T06:37:08.500",
"Id": "13962",
"Score": "2",
"Tags": [
"python",
"game",
"random",
"dice"
],
"Title": "Craps dice game simulator"
}
|
13962
|
<p>I am working on a personal iPhone ObjC project, and was recently getting frustrated with how tedious importing the same set of headers over and over was getting⦠So I created a header file that literally only imports other header files, and looks something along the lines of this:</p>
<pre><code>//BackboneTools.h
#import "ASIHTTPRequest.h"
#import "CPTXYGraph.h"
#import "CPTGraphHostingView.h"
#import "CPTColor.h"
#import "CPTPlatformSpecificCategories.h"
#import "CPTFill.h"
#import "CPTPieChart.h"
#import "DateFormatter.h"
#import "JSONAssistant.h"
#import "Query.h"
#import "SegmentsManager.h"
#import "SharedState.h"
#import "NSString+Trimmable.h"
#import "UIImage+Resizable.h"
</code></pre>
<p>So now I usually just import this file in the .m files of my (many) View Controllers. As you can imagine, this makes imports a lot easier for me, especially for classes that mix and match these dependencies.</p>
<p>I was wondering if this is good style in ObjC. I know that monoliths like Foundation.h and UIKit.h do the same thing, though I wasn't sure if that approach is frowned upon for smaller projects.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-18T09:33:32.230",
"Id": "31575",
"Score": "0",
"body": "Be sure to read and understand this: http://qualitycoding.org/precompiled-headers/\nIt tells you about some ways PCHs cripple your code."
}
] |
[
{
"body": "<p>You can import all you need in <code>AppName_Prefix.pch</code> header. And all this imported headers will be available app-wide. </p>\n\n<p>But I think this isn't good idea. In most cases it's helpful to see which other classes and parts of application current class depends of.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T09:27:08.367",
"Id": "14001",
"ParentId": "13963",
"Score": "4"
}
},
{
"body": "<p>You should always create classes as components, components you can rearrange.</p>\n\n<p>Now you are lazy and import all needed classes in <code>Prefix.pch</code>, and it works fine for you. But imaging in few month you are working in another project and you realize, that that class you wrote would fit perfectly into your new app.<br>\nYou have been busy in the meantime and forgot about few implementation details. you open the implementation file to see, what other files you need to copy over to the new project. But: as everything is imported in one place, you cannot tell easily. you must go through code and trial&error to identify the pre-requiereties. What a nightmare.</p>\n\n<p>That said here is my policy of imports:</p>\n\n<ul>\n<li>in .h files only the bare necessary:<br>\nforward declaration for any class<br>\nimports for any file containing an unknown protocol that will be extended or implemented publicly, or that a property like an delegate need to conform to. </li>\n<li>in .m files next to the own .h file import of the classes, that were forward declared and all classes needed. </li>\n</ul>\n\n<p>So actually it is a Β«latest moment possibleΒ» strategy. </p>\n\n<hr>\n\n<p>oh, and of course it means: If you change some parts of the class, check, if you can remove imports.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-18T17:16:26.027",
"Id": "19749",
"ParentId": "13963",
"Score": "5"
}
},
{
"body": "<p>Another reason to not do this is compile time. If you change a header every implementation file that either directly or indirectly imports it needs to be recompiled. If you include every header in every .m file you basically have to recompile your whole app every time you change a single header.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T14:45:42.810",
"Id": "46644",
"ParentId": "13963",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "14001",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T07:18:53.893",
"Id": "13963",
"Score": "4",
"Tags": [
"objective-c",
"import"
],
"Title": "Import management"
}
|
13963
|
<p>I need your opinion on writing a constructor that's clean code and unit test friendly.</p>
<p>Option 1 :</p>
<pre><code>var res1 = bigObject.GetResource1();
var res2 = bigObject.GetResource2();
var res3 = bigObject.GetResource3();
var myObject = new Foo(bigObject, res1, res2, res3);
//and the foo ctor just initializes its internal fields with given data
</code></pre>
<p>Option 2 :</p>
<pre><code>var myObject = new Foo(bigObject);
[...]
public Foo(Bar bigObject)
{
_bigObject = bigObject;
_res1 = _bigObject.GetResource1();
_res2 = _bigObject.GetResource2();
_res3 = _bigObject.GetResource3();
}
</code></pre>
<p>Option 2 is cleaner (?) in the code (in option 1 I have the feeling I have to spoon-feed the Foo object because it is not smart enough to get what it needs by itself)), but requires helper methods in the tests to mock calls to <code>Get*</code> and pass what we want.</p>
<p>Of course, I can also write both ctors, and use one in the tests and the other in the "real" code, but it'd looks a bit weird and bloated to someone discovering the class, and the simple constructor wouldn't be tested.</p>
<p>What would you advise ?</p>
<hr>
<p>EDIT :</p>
<p>Resources are not especially linked to the big object (i.e. there is no "wrong" combination). Imagine for example that the big object is a College, and resources are a list of teachers, a list of courses and a list of rooms, and we want to build, say, a timetable.</p>
|
[] |
[
{
"body": "<p>I'm not sure if this argument applies to your use case, but option 1 invites inconsistencies. Someone (even you) might pass resource values that are incompatible with each other. If you rely on any kind of relationship between <code>bigObject</code> and the resources, definitely use option 2.</p>\n\n<p>In any case, I'd say that a clean and compact interface is more important than the complexity of the unit tests.</p>\n\n<p>To make your unit testing easier, couldn't you derive from <code>Bar</code> and give the derived class a constructor that takes the three resources? Then you could do something like this:</p>\n\n<pre><code>var myObject = new Foo(TestBar(res1, res2, res3));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T14:02:23.407",
"Id": "22607",
"Score": "0",
"body": "using a derived object for testing is actually equivalent to mock calls to functions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T10:20:14.917",
"Id": "13967",
"ParentId": "13965",
"Score": "1"
}
},
{
"body": "<p>Are these resources always linked to the <code>bigObject</code> instance? Do they have something in common with certain data or functionality in <code>bigObject</code>? Are they somehow related mutually? It's hard to say exactly what is the better approach without knowing all this, but there are several sanity checks you can do:</p>\n\n<ol>\n<li><p>Do <code>GetResource1</code> to <code>GetResource3</code> really all depend on the <code>bigObject</code> instance? Can you extract this functionality into a different class? <a href=\"http://sourcemaking.com/refactoring/extract-class\" rel=\"nofollow\">Extract class</a> refactoring might be an option.</p></li>\n<li><p>Does <code>bigObject</code> know too much? Big kinda sounds like God, as in <a href=\"http://sourcemaking.com/antipatterns/the-blob\" rel=\"nofollow\">\"god object\"</a>.</p></li>\n<li><p>If these three resources always come together (i.e. they all belong to the <strong>same interface</strong>), you might want to extract only them into a <a href=\"http://sourcemaking.com/refactoring/introduce-parameter-object\" rel=\"nofollow\">\"parameter object\"</a>. This means that you might end up with something in the middle, like:</p>\n\n<pre><code>public Foo(Bar bigObject, IResources resources)\n{\n ...\n}\n</code></pre>\n\n<p>Which means your <code>bigObject</code> will implement <code>IResources</code>, but you will also be able to implement them in a different way, and it will reduce the number of params.</p></li>\n<li><p>If these resources are all of the same type, and there is a large number of them, then even a simple delegate might be enough. You might even want to make the call weakly typed for greater extensibility:</p>\n\n<pre><code>public Foo(Bar bigObject, Func<string, IRes> getResourceByName)\n{\n var res1 = getResourceByName(\"1\");\n var res2 = getResourceByName(\"2\");\n ...\n}\n</code></pre></li>\n</ol>\n\n<p>These suggestions popped out as I was writing, but ultimately, it's hard to give any exact guidance unless you state the actual problem you are trying to solve. Design should then follow from there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T12:23:30.173",
"Id": "22599",
"Score": "1",
"body": "I don't like the weak typing suggestion. Especially since each resource is most likely used in a different way, which would mean adding casts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T14:00:14.423",
"Id": "22606",
"Score": "0",
"body": "my big object is indeed close to a god object, but it's not my line to refactor this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T14:07:04.757",
"Id": "22608",
"Score": "0",
"body": "I updated my question to provide an example of what my objects are."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T08:50:59.477",
"Id": "22637",
"Score": "0",
"body": "@Zonko: a good refactoring option might also be to avoid passing the actual `bigObject` to the `Foo` class entirely, and to abstract all functionality needed by `Foo` through one or more interfaces. This should make `Foo` follow [Single responsibility principle](http://en.wikipedia.org/wiki/Single_responsibility_principle), and should make it easier for testing since you don't need to mock the entire `bigObject`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T11:35:31.823",
"Id": "13970",
"ParentId": "13965",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "13970",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T09:54:56.743",
"Id": "13965",
"Score": "1",
"Tags": [
"c#",
"unit-testing",
"constructor"
],
"Title": "Get resources inside or outside constructor?"
}
|
13965
|
<p>This is my current method for populating the sub-items of <code>ListView</code> controls. I like this method for two reasons... </p>
<p>1) I don't have to keep up with the display order of the columns.</p>
<p>2) If I enable column re-ordering, I don't have to change anything with the code. </p>
<p>So, the question is... Is this a good approach? Can it be improved?</p>
<p><em>Note: I'm not too happy about declaring <code>Result As Object</code>. It seems like there should be a better way to handle that, but it's the only way I could get it to working.</em></p>
<pre><code>Private Function RetrieveItem(Of T)(ByVal displayIndex As Integer) As T
Dim Result As Object = If(GetType(T) Is GetType(ListViewItem), New ListViewItem, New ListViewItem.ListViewSubItem)
Select Case displayIndex
Case ColumnHeader1.DisplayIndex
Result.Text = "First Item"
Result.Tag = "First"
Case (ColumnHeader2.DisplayIndex)
Result.Text = "Second Column"
Result.Tag = "Second"
Case ColumnHeader3.DisplayIndex
Result.Text = "Third Column"
Result.Tag = "Third"
Case ColumnHeader4.DisplayIndex
Result.Text = "Fourth Column"
Result.Tag = "Fourth"
End Select
Return Result
End Function
</code></pre>
<p>Example Usage... </p>
<pre><code>Dim item As ListViewItem = RetrieveItem(Of ListViewItem)(0)
For i As Integer = 1 To ListView1.Columns.Count - 1
item.SubItems.Add(RetrieveItem(Of ListViewItem.ListViewSubItem)(i))
Next
ListView1.Items.Add(item)
</code></pre>
<hr>
<p>Here is the example I came up with using @MarkHurd's suggestion of using a <a href="http://msdn.microsoft.com/en-ca/library/yf7b9sy7%28VS.80%29.aspx" rel="nofollow"><code>Widening CType Operator</code></a>... </p>
<pre><code>Private Class LVI
Public Name As String
Public Text As String
Public Tag As Object
Public Sub New(ByVal name As String, ByVal text As String, ByVal tag As Object)
Me.Name = name
Me.Text = text
Me.Tag = tag
End Sub
Public Shared Widening Operator CType(ByVal item As LVI) As ListViewItem
Dim Result As New ListViewItem(item.Text)
Result.Name = item.Name
Result.Tag = item.Tag
Return Result
End Operator
Public Shared Widening Operator CType(ByVal item As LVI) As ListViewItem.ListViewSubItem
Dim Result As New ListViewItem.ListViewSubItem
Result.Text = item.Text
Result.Name = item.Name
Result.Tag = item.Tag
Return Result
End Operator
End Class
Private Function RetrieveItem(ByVal index As Integer) As LVI
Select Case index
Case ColumnHeader1.DisplayIndex : Return New LVI("1", "First Column", "one")
Case ColumnHeader2.DisplayIndex : Return New LVI("2", "Second Column", "two")
Case ColumnHeader3.DisplayIndex : Return New LVI("3", "Third Column", "three")
Case ColumnHeader4.DisplayIndex : Return New LVI("4", "Fourth Column", "four")
Case Else : Return Nothing
End Select
End Function
</code></pre>
<p>Example usage...</p>
<pre><code>Dim item As ListViewItem = RetrieveItem(0)
For i As Integer = 1 To ListView1.Columns.Count - 1
item.SubItems.Add(RetrieveItem(i))
Next
ListView1.Items.Add(item)
</code></pre>
<p>I like both of these approaches, but I feel like the first is shorter and easier to implement, so I lean towards the first option. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T13:49:09.367",
"Id": "22604",
"Score": "0",
"body": "What's wrong with your expected problem of editing the font color? How is this not possible with your code (with obvious changes to actually *try* something, since your code does not seem to do anything with font color ATM)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T15:09:03.553",
"Id": "22612",
"Score": "0",
"body": "@Gaffi, In the original code you would have had to return a custom structure, or class, which I think would be tedious, or make a new function for each property. I have changed the code to use Generic Types instead which should overcome that problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T16:18:39.583",
"Id": "22662",
"Score": "0",
"body": "\"I'm not too happy about declaring `Result As Object`.\" That's not your fault: Microsoft should have at least defined an interface that both `ListViewItem` and `ListViewSubItem` implemented."
}
] |
[
{
"body": "<p>If you want to avoid the late bound <code>.Text</code> and <code>.Tag</code> you could just create your own private type, say <code>LVI</code>, containing these two properties and implicit <code>Widening</code> <code>CType</code> operators for <code>ListViewItem</code> and <code>ListViewItem.ListViewSubItem</code>. Then the <code>Result As New LVI</code> can be converted on return using <code>Return CType(CTypeDynamic(Result, GetType(T)), T)</code> in the latest VB.NET.</p>\n\n<p>Without <code>CTypeDynamic</code> I don't have a working solution yet.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T22:09:16.827",
"Id": "22707",
"Score": "1",
"body": "I was previously unaware of [`Widening CType`](http://msdn.microsoft.com/en-ca/library/yf7b9sy7%28VS.80%29.aspx). Your suggestion looks promising... I think when I get a chance, I will experiment with that approach and see how it turns out. If I like it, I'll post it as an addendum to my question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T17:08:13.623",
"Id": "14009",
"ParentId": "13969",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14009",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T11:14:00.683",
"Id": "13969",
"Score": "2",
"Tags": [
"vb.net"
],
"Title": "Method for populating ListViewSubItems"
}
|
13969
|
<p>I would like to find a more efficienct way to use jQuery for my question and answer page.</p>
<p>Here is the code which I want to change. If a <code>.q_container</code> is clicked, I want its corresponding answer <code>div</code> will slide down.</p>
<pre><code>$(document).ready(function() {
$('#qc1').hover(
function () {
$('#a1').slideDown('fast');
},
function () {
$('#a1').slideUp('fast');
}
);
$("#qc2").hover(
function () {
$('#a2').slideDown('fast');
},
function () {
$('#a2').slideUp('fast');
}
);
$("#qc3").hover(
function () {
$('#a3').slideDown('fast');
},
function () {
$('#a3').slideUp('fast');
}
);
});
</code></pre>
<p>All of my Code:</p>
<pre><code><html>
<head>
<style type="text/css">
* {
padding: 0px;
margin: 0px;
}
body {
background-color: black;
}
#container {
width:1000px;
min-height: 500px;
background-color: #3b3b3b;
padding: 10px;
margin-left: auto;
margin-right: auto;
}
.q_container {
width:300px;
}
.question {
border-radius: 5px 5px 0px 0px;
width:300px;
height:30px;
background-color: red;
padding: 4px;
}
.answer {
border-radius: 0px 0px 5px 5px;
width:300px;
height:100px;
display:none;
background-color: blue;
overflow: hidden;
padding: 4px;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#qc1').hover(
function () {
$('#a1').slideDown('fast');
},
function () {
$('#a1').slideUp('fast');
}
);
$("#qc2").hover(
function () {
$('#a2').slideDown('fast');
},
function () {
$('#a2').slideUp('fast');
}
);
$("#qc3").hover(
function () {
$('#a3').slideDown('fast');
},
function () {
$('#a3').slideUp('fast');
}
);
});
</script>
</head>
<body>
<div id="container">
<div class="q_container" id="qc1">
<div class="question">
What is a question?
</div>
<div class="answer" id="a1">
It is a way to discover something.
</div>
</div>
<div style="width:300px;height:10px;"></div>
<div class="q_container" id="qc2">
<div class="question">
What is a question2?
</div>
<div class="answer" id="a2">
It is a way to discover something2.
</div>
</div>
<div style="width:300px;height:10px;"></div>
<div class="q_container" id="qc3">
<div class="question">
What is a question3?
</div>
<div class="answer" id="a3">
It is a way to discover something3.
</div>
</div>
</div>
</body>
</head>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T12:55:09.883",
"Id": "22600",
"Score": "0",
"body": "Do you want the answer to open when clicked or hovered?"
}
] |
[
{
"body": "<p><strong>Working Demo</strong> <a href=\"http://jsfiddle.net/jEjYp/2/\">http://jsfiddle.net/jEjYp/2/</a></p>\n\n<p>Rest feel free to play around with the code or demo.</p>\n\n<p>Hope it fits your cause. <code>:)</code></p>\n\n<p><strong>code</strong></p>\n\n<pre><code>$(document).ready(function() {\n $('#qc1,#qc2,#qc3').hover(\n function () {\n $(this).find('.answer').slideDown('fast');\n }, \n function () {\n $(this).find('.answer').slideUp('fast');\n }\n );\n\n});β\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T03:37:21.477",
"Id": "22590",
"Score": "0",
"body": "@Cameron No worries! Glad it helped `:)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T03:40:05.463",
"Id": "22591",
"Score": "0",
"body": "I never knew about the `,` separator on multiple id's. Hate to upvote a competing answer but its just so damn helpful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T03:42:43.767",
"Id": "22592",
"Score": "0",
"body": "@ExceptionLimeCat `:)` read this - http://api.jquery.com/multiple-selector/ it might help you to understand more,"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T03:31:17.457",
"Id": "13972",
"ParentId": "13971",
"Score": "6"
}
},
{
"body": "<p>Use classes instead of id's</p>\n\n<pre><code> $('.question').hover(\n function () {\n $(this).find('.answer').slideDown('fast');\n }, \n function () {\n $(this).find('.answer').slideUp('fast');\n }\n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T03:33:13.977",
"Id": "22593",
"Score": "0",
"body": "Just so that you know `:)` this will have a buggy effect (i.e. it will slide all the answers see here: http://jsfiddle.net/bBAXp/) you can try this cod ein my demo. Just letting you know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T03:34:25.373",
"Id": "22594",
"Score": "0",
"body": "Missing the `$(this).find('.answer')` context"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T03:34:58.567",
"Id": "22595",
"Score": "0",
"body": "Awww.... I see. will edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T03:36:31.300",
"Id": "22596",
"Score": "0",
"body": "I tried that, but it slides them all down and up, but thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T03:37:48.923",
"Id": "22597",
"Score": "0",
"body": "Just edited. this should work."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T03:31:25.867",
"Id": "13973",
"ParentId": "13971",
"Score": "2"
}
},
{
"body": "<p>I have done complete bins demo for above issue. you can check demo link.</p>\n\n<p><strong>DEMO:</strong> <a href=\"http://codebins.com/bin/4ldqp9t\" rel=\"nofollow\">http://codebins.com/bin/4ldqp9t</a></p>\n\n<p><strong>HTML:</strong></p>\n\n<pre><code><div id=\"container\">\n <div class=\"q_container\" id=\"qc1\">\n <div class=\"question\">\n What is a question?\n </div>\n <div class=\"answer\" id=\"a1\">\n It is a way to discover something.\n </div>\n </div>\n <div style=\"width:300px;height:10px;\">\n </div>\n\n <div class=\"q_container\" id=\"qc2\">\n <div class=\"question\">\n What is a question2?\n </div>\n <div class=\"answer\" id=\"a2\">\n It is a way to discover something2.\n </div>\n </div>\n <div style=\"width:300px;height:10px;\">\n </div>\n\n <div class=\"q_container\" id=\"qc3\">\n <div class=\"question\">\n What is a question3?\n </div>\n <div class=\"answer\" id=\"a3\">\n It is a way to discover something3.\n </div>\n </div>\n</div>\n</code></pre>\n\n<p><strong>CSS Styles:</strong></p>\n\n<pre><code>body {\n background-color: black;\n}\n#container {\n width:1000px;\n min-height: 500px;\n background-color: #3b3b3b;\n padding: 10px;\n margin-left: auto;\n margin-right: auto;\n}\n.q_container {\n width:300px;\n}\n.question {\n border-radius: 5px 5px 0px 0px;\n width:300px;\n height:30px;\n background-color: #fc2244;\n padding: 4px;\n}\n.answer {\n border-radius: 0px 0px 5px 5px;\n width:300px;\n height:100px;\n display:none;\n background-color: #4477cc;\n overflow: hidden;\n padding: 4px;\n}\n</code></pre>\n\n<p><strong>JQuery</strong></p>\n\n<pre><code>$(document).ready(function() {\n $(\".question\").hover(function(e) {\n e.preventDefault();\n $(this).closest(\".q_container\").find(\".answer\").slideDown('fast');\n /*\n //Another Alternate way is:\n $(this).parent().find(\".answer\") .slideDown('fast'); \n */\n }, function(e) {\n\n e.preventDefault();\n $(this).closest(\".q_container\").find(\".answer\").slideUp('fast');\n\n /*\n //Another Alternate way is:\n $(this).parent().find(\".answer\") .slideUp('fast'); \n */\n });\n});\n</code></pre>\n\n<p><strong>DEMO:</strong> <a href=\"http://codebins.com/bin/4ldqp9t\" rel=\"nofollow\">http://codebins.com/bin/4ldqp9t</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T07:40:56.340",
"Id": "13974",
"ParentId": "13971",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "13972",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T03:26:02.990",
"Id": "13971",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"performance",
"html",
"css"
],
"Title": "jQuery substitute for multiple hovers"
}
|
13971
|
<p>The main advantage of this pattern is when I often create and destroy objects, which in this case are often used.</p>
<p>I made this because I needed to track several short timers at the same time, but it can also be used for stuff like missiles or else.</p>
<pre><code>#include <vector>
#include <queue>
#define itv(TYPE) std::vector<TYPE>::iterator
using namespace std;
template <class TYPE>
struct object_pool
{
std::vector<TYPE> pool;
std::queue<size_t> avail;
TYPE & operator[](const size_t & i) { return pool[i]; }
void add(size_t & pos)
{
if(avail.empty()) // no reusable object
{ pool.push_back(TYPE()); pos = pool.size()-1; }
else
{ pos = avail.back(); avail.pop(); }
}
void rem(size_t & a) { avail.push(a); }
size_t size() { return pool.size(); }
};
</code></pre>
<p>What do you think ?</p>
|
[] |
[
{
"body": "<p>Don't do this:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>In anything other than a toy this will cause problems. </p>\n\n<p>I don't like this:</p>\n\n<pre><code>#define itv(TYPE) std::vector<TYPE>::iterator\n</code></pre>\n\n<p>With C++11 this type if thing has been resolved by <code>auto</code>.</p>\n\n<p>I would also define the iterator in terms of the object pool:</p>\n\n<pre><code>template <class TYPE>\nstruct object_pool\n{\n typedef std::vector<TYPE>::iterator iterator;\n</code></pre>\n\n<p>I would hide the fact that internally the <code>object_pool</code> uses a vector and queue. I would then add the obligatory functions to extract information:</p>\n\n<pre><code>template <class TYPE>\nclass object_pool\n{\n std::vector<TYPE> pool;\n std::queue<size_t> avail;\n\n public:\n typedef std::vector<TYPE>::iterator iterator;\n typedef std::vector<TYPE>::const_iterator const_iterator;\n\n iterator begin() { return pool.begin();}\n iterator end() { return pool.end();}\n const_iterator begin() const { return pool.begin();}\n const_iterator end() const { return pool.end();}\n</code></pre>\n\n<p>To access elements I would also provide const version</p>\n\n<pre><code> TYPE& operator[](std::size_t index) { return pool[index];}\n TYPE& at(std::size_t index) { return pool.at(index);}\n\n TYPE const& operator[](std::size_t index) const { return pool[index];}\n TYPE const& at(std::size_t index) const { return pool.at(index);}\n</code></pre>\n\n<p>The methods that can be const should be const:</p>\n\n<pre><code> size_t size() const { return pool.size(); }\n // ^^^^^^^\n</code></pre>\n\n<p>The implementation details are fine. </p>\n\n<pre><code> void add(size_t & pos)\n {\n if(avail.empty()) // no reusable object\n { pool.push_back(TYPE()); pos = pool.size()-1; }\n else\n { pos = avail.back(); avail.pop(); }\n }\n void rem(size_t & a) { avail.push(a); }\n</code></pre>\n\n<p>I would change the add() so it returned pos:</p>\n\n<pre><code> size_t add();\n</code></pre>\n\n<p>Also the vector starts off very small and re-sizes to get bigger.<br>\nTo make sure that it does not re-size too often I would add a constructor that gives the vector a reasonable size to start with:</p>\n\n<pre><code>object_pool::object_pool()\n{\n pool.reserve(1000);\n}\n</code></pre>\n\n<p>But I think you are using the wrong technique.<br>\nI would use a pool allocator and plug it into the vector.</p>\n\n<p>You can read more about it here: <a href=\"https://stackoverflow.com/q/2984434/14065\">https://stackoverflow.com/q/2984434/14065</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T16:22:15.013",
"Id": "22663",
"Score": "0",
"body": "boost seems like a little complicated for what I want to do with do with it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T17:44:30.850",
"Id": "22671",
"Score": "1",
"body": "You don't need to use boost. But implementing an allocator would seem a better solution (and also quicker). Though it adds some extra complexity you probably don't need. You need to way complexity against the added advantage for your particular situation. Note: by learning how to use allocators makes your use of the STL more effective."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T05:15:18.053",
"Id": "13991",
"ParentId": "13979",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T19:19:35.117",
"Id": "13979",
"Score": "5",
"Tags": [
"c++",
"design-patterns",
"stl"
],
"Title": "Simple object pool template container in C++"
}
|
13979
|
<p>I have a map that I want to 'expand' into an infinite sequence in the following manner:</p>
<pre><code>{0 'zero 3 'three 10 'ten}
=>
('zero 'zero 'zero 'three 'three 'three 'three 'three 'three 'three 'ten 'ten 'ten ...)
</code></pre>
<p>The indexes of the map indicating the index of the sequence where the value should change.</p>
<p>The following code works, but it does not please me. Can this be written in a smarter way?</p>
<pre><code>(defn expand-map
[m]
(letfn [(em
[last-value indexes]
(let [value (m (first indexes))]
(if value
(lazy-seq (cons value (em value (rest indexes))))
(lazy-seq (cons last-value (em last-value (rest indexes)))))))]
(em 'zero (iterate inc 0))))
(take 20 (expand-map {0 'zero 3 'three 10 'ten}))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T21:04:59.637",
"Id": "22619",
"Score": "0",
"body": "oh, you want 'zero from 0th, then 'three from third, then 'ten from tenth?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T21:07:52.387",
"Id": "22620",
"Score": "0",
"body": "yes, another example would be {0 0 1 1 3 3} => (0 1 1 3 3 3 ...)"
}
] |
[
{
"body": "<p>It really depends on your specific goals. The code as it is is very\nlazy, but also recomputes quite a lot by accessing the map on every\nsingle step.</p>\n\n<p><code>(iterate inc 0)</code> can be more easily written as <code>(range)</code> as noted again\nbelow and the definition of <code>expand-map</code> is partially repetitive\n(<code>(lazy-seq (cons ...))</code> comes up twice, as does <code>(rest indexes)</code> -\ngenerally it's better to keep the amount of duplicate code to a minimum.</p>\n\n<p>The <code>'zero</code> initial value is hardcoded, which is not that nice for a\ngeneral solution, but apart from that it looks okay.</p>\n\n<hr>\n\n<p>I have two other rewritten options below with different degrees of\nlaziness and verboseness.</p>\n\n<p>For both options I suggest a different way of iterating over the keys,\nthat is, getting and sorting the keys of the input map once, then\nreusing it instead of looking up the current index that often.</p>\n\n<p>Thus, option one, lazier then the other one, using <code>repeat</code> to create\nthe sub-list with the indicated value, then concatenating it with the\nremainder.</p>\n\n<p>Also, since it's not indicated what should happen on an empty map\n(except the presented code defaulting to <code>'zero</code>); that could be\nindicated a bit nicer as well, by throwing a custom error perhaps.</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(defn expand-map-2 [m]\n (letfn [(aux [indexes]\n (let [index (first indexes)\n rest (next indexes)\n value (m index)]\n (if rest\n (lazy-cat (repeat (- (first rest) index) value) (aux rest))\n (repeat value))))]\n (aux (sort (or (keys m) (throw (Exception. \"No specification supplied.\")))))))\n</code></pre>\n\n<p>The other way, less lazy, but IMO a bit nicer assuming your input map\nisn't huge, is to precompute all lazy lists and concatenate them. Also\nuses the <code>mapcat</code> over two shifted maps. The\n<code>(concat (rest keys) [nil])</code> seems necessary since <code>mapcat</code> terminates\nearly instead of till all the collections are exhausted.</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(defn expand-map-3 [m]\n (let [keys (sort (or (keys m) (throw (Exception. \"No specification supplied.\"))))]\n (mapcat (fn [first second]\n (let [value (m first)]\n (if second (repeat (- second first) value) (repeat value))))\n keys (concat (rest keys) [nil]))))\n</code></pre>\n\n<hr>\n\n<p>Since this post was migrated, there are actually a number of existing\nsolutions here. I've already asked for one of them and got the go-ahead\nto incorporate it with an explanation of the solution.</p>\n\n<p><a href=\"https://codereview.stackexchange.com/a/13985/54571\">Courtesy of @amalloy</a>:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(defn expand-map-4 [m]\n (rest (reductions (fn [prev idx]\n (get m idx prev))\n 'zero\n (range))))\n</code></pre>\n\n<p>Benchmarked this solution seems very similar to the above ones (and the\ninitial code), but is much more concise. <code>range</code> will generate the the\ninfinite list instead of <code>(iterate inc 0)</code>, so that is already nice.\n<code>reductions</code> will return all intermediate results will reducing with the\nprovided function; since we start from <code>'zero</code> here, this works\nsimilarly to the code in the question (I'd rather replace this with\nsimilar behaviour to what I posted above, since it doesn't rely on the\nhard-coded <code>'zero</code> though). <code>get</code> is used instead of using the map\ndirectly, but that's not actually necessary. The first <code>rest</code> is used\nto discard the spurious initial value (the supplied <code>'zero</code>).</p>\n\n<p>With those remarks in mind, I'd suggest this amended version:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(defn expand-map-5 [m]\n (let [keys (or (keys m)\n (throw (Exception. \"No specification supplied.\")))]\n (rest (reductions (fn [prev idx]\n (m idx prev))\n (m (first (sort keys)))\n (range)))))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-01T17:16:40.183",
"Id": "106278",
"ParentId": "13982",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "106278",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T20:45:26.770",
"Id": "13982",
"Score": "8",
"Tags": [
"clojure"
],
"Title": "Expanding a map into an infinite sequence"
}
|
13982
|
<p>In re-writing my PHP framework vervPHP, I've created the following class:</p>
<pre><code>class storage {
private static $instance;
public $db = null; // Holds a database connection object
public $user = null; // Holds user related information for custom auth
public $data = array(); // Array of data for storage
private function __construct(){
// Create the default array in $this->data....
}
public static function singleton() {
if (!isset(self::$instance)) {
$className = __CLASS__;
self::$instance = new $className;
}
return self::$instance;
}
// Getters, Setters and other stuff follows...
}
</code></pre>
<p>When my framework starts up, it looks like this:</p>
<p>index.php:</p>
<pre><code>// Kick it off!
verv\init();
</code></pre>
<p>framework/verv/verv.php:</p>
<pre><code>function init() {
$verv = storage::singleton();
loadConfig($verv);
loadRequest($verv);
connectDB($verv);
authenticateUser($verv);
loadModule($verv);
loadTemplate($verv);
renderPage($verv);
}
</code></pre>
<p><code>$verv</code> is passed by reference - so any changes are saved as it moves around.</p>
<p>My question is, do I need the singleton portion? And basically, am I doing it "right"? The code in question works (albeit it needs a little tidying) but I want to make sure that my storage class is as robust and efficient as possible.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T21:08:21.247",
"Id": "22937",
"Score": "0",
"body": "I think you've misunderstood the concept of singleton here. From my understanding a singleton class should not be instantiated with the constructor and therefore should not have one. It should never even be used outside of a static scope. Now, as to your `init()` function. This looks like it should be the constructor of some class, I would consider setting `$verv` as a class property so that you don't have to pass that as a parameter each time. It will serve the same purpose. I have no real experience with the Singleton pattern, however, from everything I've read this explanation seems right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T03:29:33.450",
"Id": "33384",
"Score": "0",
"body": "You can mitigate the bad effects of using Singletons by passing the reference out to the \"leaf\" code through dependency injection and only have logic close to the core/base know about the Singleton. This makes it easier to get rid of the offending object later when you realize how hard it is to maintain a large project that uses it. However, it seems you have an intuition already, so why not avoid the pitfalls now?"
}
] |
[
{
"body": "<p>I think you are going to the wrong direction with this kind of aproach. First you are creating a Singleton while propably you don't need to use it. Second you are mixing things in one God object which is also a bad design in an object-oriented environment.\nAnd what is this init() function? Just laying around in a namespace alone in the dark? Bad design. Most beginner PHP programmers are don't know that passing by reference things are can really hurt performance and BTW objects are passed by not reference but an internal handler which will give you the possibility to modify (not unset or overwrite) that object.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T09:12:42.597",
"Id": "22641",
"Score": "1",
"body": "I think you may be getting confused by passing by reference (good!) versus returning by reference. Passing by reference is the whole point of Dependancy Injection, and is considered A Good Thing. Also, please check out http://codereview.stackexchange.com/questions/10060/review-of-my-php-framework-vervphp to see what it looked like before, and what feedback I recieved regarding it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T09:19:18.643",
"Id": "22643",
"Score": "0",
"body": "Passing by reference and dependency injection are two different things. Passing by reference is a type of argument handling in functions and methods provided by PHP, dependency injection is a design pattern what can be used in any programming language.\nWhen you say: public function __construct(ISameInterface $obj) {/* ... */} you are not passing by reference anything but you are using constructor injection."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T06:51:03.833",
"Id": "13994",
"ParentId": "13986",
"Score": "1"
}
},
{
"body": "<p>Because you are passing things in via dependency injection, it does render the singleton a bit pointless in the code you have shown. Normally, it is useful in that you can call the storage::singleton() method from anywhere and know that you will have the exact same object. However, this causes a problem because unit testing becomes difficult as you can't decouple the function from the singleton, so your code as it stands is far easier to test. </p>\n\n<p>You do however have the advantage with the singleton that other people using your framework can't wreck it by ignoring the dependency injection and just making a new instance of the storage class somewhere, so actually I think this is a good approach.</p>\n\n<p>I'm not quite sure why you have the page construction process contained within init() as you could really just have those raw function calls on the main index.php page. You appear to be already using a router pattern of some sort, so presumably index.php acts a single entry point anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-23T03:32:10.500",
"Id": "33385",
"Score": "0",
"body": "Maybe those people using the framework have a good reason to have two instances, and by forcing only one instance you can render your code useless for them."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T13:10:10.797",
"Id": "14008",
"ParentId": "13986",
"Score": "1"
}
},
{
"body": "<p>Read this post before using the singleton pattern: <a href=\"https://stackoverflow.com/a/4596323/1908639\">https://stackoverflow.com/a/4596323/1908639</a></p>\n\n<p>You might find that it increases your initial development speed; however, the downsides tend to increase with the size/complexity of the project. I have personally maintained code that used singletons, and I found it difficult to test/reuse. </p>\n\n<p>If you think there are any major advantages to the singleton approach, I would be interested in hearing them. I have not been able to find any beneficial use-cases in PHP web development, but I am definitely interested in hearing about them, if they exist.</p>\n\n<p>Also, passing objects by reference should not be necessary in PHP 5 (<a href=\"http://www.php.net/manual/en/migration5.oop.php\" rel=\"nofollow noreferrer\">source</a>):</p>\n\n<blockquote>\n <p>In PHP 5 there is a new Object Model. PHP's handling of objects has been completely rewritten, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object's identifier).</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-22T22:54:44.247",
"Id": "19875",
"ParentId": "13986",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-24T23:31:56.297",
"Id": "13986",
"Score": "5",
"Tags": [
"php",
"object-oriented",
"singleton",
"dependency-injection"
],
"Title": "Storage class, dependency injection and singletons"
}
|
13986
|
<p>I would like to optimize the code to be efficient. Basically the code finds and generates an Anova table with the p-value also computed.</p>
<p>I am inputting a text file with data delimited with commas.</p>
<p><strong>This is the main function that calls the methods in the library file:</strong></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 System.IO;
namespace OneWayAnovaTable
{
public partial class OneWayAnovaTable : Form
{
public OneWayAnovaTable()
{
InitializeComponent();
}
static string TSS, ESS, TotSS, TDF, EDF, TotDF, TMS, EMS, F, p;
private void ReadFile()
{
List<List<double>> numbers = new List<List<double>>();
foreach (string line in File.ReadAllLines(@"data.txt"))
{
var list = new List<double>();
foreach (string s in line.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries))
{
double i;
if (Double.TryParse(s, out i))
{
list.Add(i);
}
}
numbers.Add(list);
}
double[] rowTotal = new double[numbers.Count];
double[] squareRowTotal = new double[numbers.Count];
double[] rowMean = new double[numbers.Count];
int totalElements = 0;
int[] totalInRow = new int[numbers.Count()];
double grandTotalMean = 0;
double grandMean = 0;
double grandTotal=0;
for (int row = 0; row < numbers.Count; row++)
{
var values = numbers[row].ToArray();
rowTotal[row] = values.Sum();
squareRowTotal[row] = values.Select(v => v * v).Sum();
rowMean[row] = rowTotal[row] / values.Length;
totalInRow[row] += values.Length;
totalElements += totalInRow[row];
grandTotalMean += rowMean[row];
grandMean += rowMean[row]/numbers.Count;
}
for (int j=0; j<rowTotal.Length; j++)
{
grandTotal += rowTotal[j];
}
double sumOfSquares = OneWayAnovaClassLibrary.OneWayAnova.totalSumOfSquares(squareRowTotal, grandTotal, totalElements);
double treatmentSumOfSquares = OneWayAnovaClassLibrary.OneWayAnova.treatmentSumOfSquares(rowTotal, totalInRow, grandTotal, totalElements);
double errorSumOfSquares = OneWayAnovaClassLibrary.OneWayAnova.errorSumOfSquares(sumOfSquares, treatmentSumOfSquares);
double meanTreatmentSumOfSquares = OneWayAnovaClassLibrary.OneWayAnova.meanTreatmentSumOfSquares(treatmentSumOfSquares, totalInRow);
double meanErrorSumOfSquares = OneWayAnovaClassLibrary.OneWayAnova.meanErrorSumOfSquares(errorSumOfSquares, (numbers.Count-1), (totalElements-1));
double fStatistic = OneWayAnovaClassLibrary.OneWayAnova.testStatistic(meanTreatmentSumOfSquares, meanErrorSumOfSquares);
double pValue = OneWayAnovaClassLibrary.OneWayAnova.pValue(fStatistic, (numbers.Count - 1), (totalElements - (numbers.Count-1)));
TSS = treatmentSumOfSquares.ToString();
ESS = errorSumOfSquares.ToString();
TotSS = sumOfSquares.ToString();
TDF = (numbers.Count() - 1).ToString();
EDF = (totalElements - numbers.Count()).ToString();
TotDF = (totalElements - 1).ToString();
TMS = meanTreatmentSumOfSquares.ToString();
EMS = meanErrorSumOfSquares.ToString();
F = fStatistic.ToString();
p = pValue.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
ReadFile();
display();
}
private void display()
{
textBoxTSS.Text = TSS;
textBoxESS.Text = ESS;
textBoxTotSS.Text = TotSS;
textBoxTDF.Text = TDF;
textBoxEDF.Text = EDF;
textBoxTotDF.Text = TotDF;
textBoxTMS.Text = TMS;
textBoxEMS.Text = EMS;
textBoxF.Text = F;
textBoxp.Text = p;
}
}
}
</code></pre>
<p><strong>The library file is here:</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OneWayAnovaClassLibrary
{
public class OneWayAnova
{
public static double totalSumOfSquares(double[] squareRowTotal, double grandTotal, int totalOfAllElements)
{
double sumOfSquares = 0;
for (int i = 0; i < squareRowTotal.Length; i++)
{
sumOfSquares += squareRowTotal[i];
}
sumOfSquares = sumOfSquares - (grandTotal * grandTotal / totalOfAllElements);
return sumOfSquares;
}
public static double treatmentSumOfSquares(double[] rowTotal, int[] totalInRow, double grandTotal, int totalOfAllElements)
{
double treatmentSumOfSquares = 0;
for (int i = 0; i < totalInRow.Length; i++)
{
treatmentSumOfSquares += rowTotal[i] * rowTotal[i] / totalInRow[i];
}
treatmentSumOfSquares = treatmentSumOfSquares - (grandTotal * grandTotal / totalOfAllElements);
return treatmentSumOfSquares;
}
public static double errorSumOfSquares(double sumOfSquares, double treatmentSumOfSquares)
{
double errorSumOfSquares = 0;
return errorSumOfSquares = sumOfSquares - treatmentSumOfSquares;
}
public static double meanTreatmentSumOfSquares(double errorSumOfSquares, int[] totalInRow)
{
double meanTreatmentSumOfSquares = 0;
return meanTreatmentSumOfSquares = errorSumOfSquares / (totalInRow.Length - 1);
}
public static double meanErrorSumOfSquares(double errorSumOfSquares, int a, int b)
{
double meanErrorSumOfSquares = 0;
meanErrorSumOfSquares = errorSumOfSquares / (double)(b - a);
return meanErrorSumOfSquares;
}
public static double testStatistic(double meanTreatmentSumOfSquares, double meanErrorSumOfSquares)
{
return (meanTreatmentSumOfSquares / meanErrorSumOfSquares);
}
public static double pValue(double fStatistic, int degreeNum, int degreeDenom)
{
double pValue = 0;
pValue = integrate(0, fStatistic, degreeNum, degreeDenom);
return pValue;
}
public static double integrate(double start, double end, int degreeFreedomT, int degreeFreedomE)
{
int iterations = 100000;
double x, dist, sum = 0, sumT = 0;
dist = (end - start) / iterations;
for (int i = 1; i <= iterations; i++)
{
x = start + i * dist;
sumT += integralFunction(x - dist / 2, degreeFreedomT, degreeFreedomE);
if (i < iterations)
{
sum += integralFunction(x, degreeFreedomT, degreeFreedomE);
}
}
sum = (dist / 6) * (integralFunction(start, degreeFreedomT, degreeFreedomE) + integralFunction(end, degreeFreedomT, degreeFreedomE) + 2 * sum + 4 * sumT);
return sum;
}
public static double integralFunction(double x, int degreeFreedomT, int degreeFreedomE)
{
double temp=0;
temp = ((Math.Pow(degreeFreedomE, degreeFreedomE / 2) * Math.Pow(degreeFreedomT, degreeFreedomT / 2)) / (factorial(degreeFreedomE / 2 - 1) * factorial(degreeFreedomT / 2 - 1))) * (factorial(((degreeFreedomT + degreeFreedomE) / 2 - 1)))*((Math.Pow(x, degreeFreedomE / 2 - 1)) / (Math.Pow((degreeFreedomT + degreeFreedomE * x), ((degreeFreedomE + degreeFreedomT) / 2))));
return temp;
}
public static double factorial(double n)
{
if (n == 0)
{
return 1.0;
}
else
{
return n * factorial(n - 1);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T07:47:57.163",
"Id": "22628",
"Score": "0",
"body": "Quick question: How much data is expected to be in your file? In the millions? In the thousands?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T08:12:30.457",
"Id": "22630",
"Score": "0",
"body": "@davenewza: Data right now in the higher thousands. May be planning for millions of data in the following days to come."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T08:22:55.260",
"Id": "22632",
"Score": "0",
"body": "And the number of columns in each row?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T08:29:55.397",
"Id": "22633",
"Score": "0",
"body": "@davenewza: the number or rows and columns vary and may not be equal."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T08:32:39.093",
"Id": "22634",
"Score": "1",
"body": "Understood, but do you expect the number of columns to also possibly reach into the millions? The reason I ask these questions is because it is extremely important to understand the data before parallelism (for example, take note of my comment to ANeves's post)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T08:34:53.750",
"Id": "22635",
"Score": "1",
"body": "@davenewza: The number rows will not go to millions, will be in hundreds, while the columns could go to the millions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T07:11:20.657",
"Id": "22714",
"Score": "0",
"body": "@davenewza: any improvements you could work on?"
}
] |
[
{
"body": "<p>Use <a href=\"http://www.dotnetcurry.com/ShowArticle.aspx?ID=608\" rel=\"nofollow\">Parallel.For</a> instead of <code>for</code>, and the same for <code>foreach</code>.<br>\nExample:</p>\n\n<pre><code>var lines = File.ReadAllLines(\"data.txt\");\nList<List<double>> numbers = new List<List<double>>();\nchar[] separators = { ',', ' ' };\n/*System.Threading.Tasks.*/Parallel.ForEach<string>(lines, line => {\n var list = new List<double>();\n foreach (string s in line.Split(separators, StringSplitOptions.RemoveEmptyEntries)) {\n double i;\n if (Double.TryParse(s, out i)) {\n list.Add(i);\n }\n }\n numbers.Add(list);\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T08:21:11.437",
"Id": "22631",
"Score": "4",
"body": "This certainly could work, but it really depends on the data. If the inner loop is the expensive part (i.e. it runs through a huge number of costly iterations), then this method may work. If the inner loop is relatively light but the outer loop runs many times, then parallelizing it might not even be worth it (it could even be slower). Remember that when using Parallel.ForEach, there is additional overhead spent on each iteration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T18:03:34.737",
"Id": "22733",
"Score": "1",
"body": "I believe you will need to lock around the `numbers.Add(list)` line OR use one of the Concurrent collections. You cannot safely write to a List from two separate threads."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T06:54:25.063",
"Id": "22810",
"Score": "0",
"body": "This will only make it run slower. Splitting a single string is not an operation which deserves to be on a separate thread."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T07:47:01.140",
"Id": "22849",
"Score": "0",
"body": "@Groo I would really like to know why. If one reads hundreds of lines with millions of collumns (see OP's comment to the question), and splits+parses them into an unordered list of numbers, how can threading make it slower? Is the overhead that big that it is not offset by the time that it takes to do a split and a million parses? I don't see how."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T11:31:56.310",
"Id": "22870",
"Score": "1",
"body": "@ANeves: that's true, I didn't expect the number of columns to be that large, it's usually the other way around. But the main issue is that parsing is actually the simplest (and fastest) part of the algorithm anyway. I would use `File.ReadLines` to load lines sequentially and then process them on the fly, which would give more sense to multithreading. I actually suggested this to OP in his/her [previous question](http://codereview.stackexchange.com/questions/13834), but I see s/he has returned back to the initial approach."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T08:00:44.513",
"Id": "13995",
"ParentId": "13993",
"Score": "1"
}
},
{
"body": "<p>Some advice:</p>\n\n<ol>\n<li>Replace <code>File.ReadAllLines</code> with <code>File.ReadLines</code> β <strong>ReadAllLines will read all file content into memory before the iteration</strong>, and <code>foreach</code> is really designed for <code>IEnumerable</code>.</li>\n<li>Definitely replace <code>for (int row = 0; row < numbers.Count; row++)</code>, <code>for (int j=0; j<rowTotal.Length; j++)</code> and <code>for (int i = 1; i <= iterations; i++)</code> with PLinq as @ANeves suggested</li>\n<li>Not sure that replacing <code>foreach (string line in File.ReadAllLines(@\"data.txt\"))</code> will help you, as it is heavily dependent on disc I/O operations.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T15:52:53.717",
"Id": "14102",
"ParentId": "13993",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T06:35:06.630",
"Id": "13993",
"Score": "5",
"Tags": [
"c#",
"performance",
".net"
],
"Title": "Finding and generating an Anova table"
}
|
13993
|
<p>Here is the book question:</p>
<blockquote>
<p>Modify the <code>CatFile</code> function in the program so that it uses
<code>WriteConsole</code> rather than <code>WriteFile</code> when the standard output handle
is associated with a console.</p>
</blockquote>
<p>And here is my solution:</p>
<pre><code>static VOID CatFile(HANDLE hInFile, HANDLE hOutFile)
{
DWORD nIn, nOut;
TCHAR buffer[BUF_SIZE];
LPTSTR pBuffer = &buffer[0];
while (ReadFile(hInFile, buffer, BUF_SIZE, &nIn, NULL) &&
(nIn != 0) &&
(WriteFile(hOutFile, buffer, nIn, &nOut, NULL) || WriteConsole(hOutFile, pBuffer, _tcslen(pBuffer), &nOut, NULL)));
return;
}
</code></pre>
<p>The part from the <code>||</code> sign in the code above is my addition to the code.</p>
<p>My question is to know if that would work once <code>WriteFile</code> wouldn't be <code>TRUE</code> since <code>hOutFile</code> is a handle of a console?</p>
<p>Another part of the question is just about the <code>WriteConsole</code> function: are these the correct arguments?</p>
|
[] |
[
{
"body": "<p>From a quick thought - Shouldn't WriteFile actually work when hOutFile is the console?</p>\n\n<p>Otherwise I guess that you may need to check whether GetStdHandle(...) == hOutFile.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T09:21:34.057",
"Id": "13999",
"ParentId": "13996",
"Score": "0"
}
},
{
"body": "<p>No comment on what your call as I don't know what WriteFile() or WriteConsole() do.</p>\n\n<p>But that is seriously abusing the <code>&&</code> and <code>!!</code> operators.<br>\nI don't think I would ever let that code pass a review:</p>\n\n<pre><code>while (ReadFile(hInFile, buffer, BUF_SIZE, &nIn, NULL) &&\n (nIn != 0) &&\n (WriteFile(hOutFile, buffer, nIn, &nOut, NULL) || WriteConsole(hOutFile, pBuffer, _tcslen(pBuffer), &nOut, NULL)));\n\n// Why not write it like this:\n\n// While we manage to read a good value:\nwhile (ReadFile(hInFile, buffer, BUF_SIZE, &nIn, NULL) && (nIn != 0))\n{\n if (!( (WriteFile(hOutFile, buffer, nIn, &nOut, NULL))\n || (WriteConsole(hOutFile, pBuffer, _tcslen(pBuffer), &nOut, NULL))\n )\n )\n {\n // Write Error\n break;\n }\n}\n// Now check for read errors to report.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T20:58:45.767",
"Id": "14028",
"ParentId": "13996",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T08:13:08.833",
"Id": "13996",
"Score": "1",
"Tags": [
"c",
"windows",
"console"
],
"Title": "Is my WriteConsole solution correct?"
}
|
13996
|
<p>I think here is something wrong with code. I use a class with methods to get tenants from DB:</p>
<pre><code> public List<CrmTenant> GetAllTenants()
{
List<CrmTenant> tenantsList = new List<CrmTenant>();
try
{
var crmTenants =
from tenant in context.CrmTenant
select tenant;
if (crmTenants != null)
{
foreach (var tenant in crmTenants)
{
tenantsList.Add(tenant);
}
}
return tenantsList;
}
catch (Exception ex)
{
this.logger.Write("Failed to get all tenants from database.", "Exceptions", TraceEventType.Error, ex);
return null;
}
}
/// <summary>
/// Gets Tenant by name.
/// </summary>
/// <returns></returns>
public CrmTenant GetTenantByName(string tenantName)
{
CrmTenant crmTenant = null;
try
{
crmTenant =
(from customerCrm in context.CrmTenant
where customerCrm.TenantName == tenantName
select customerCrm).Single();
return crmTenant;
}
catch (Exception ex)
{
this.logger.Write(String.Format("Failed to get tenant '{0}' from database.", tenantName), "Exceptions", TraceEventType.Error, ex);
return null;
}
}
/// <summary>
/// Gets tenant by Username.
/// </summary>
/// <returns></returns>
public CrmTenant GetTenantByUserName(string userName)
{
CrmTenant crmTenant = null;
try
{
crmTenant =
(from customerCrm in context.CrmTenant
where customerCrm.Username == userName
select customerCrm).Single();
return crmTenant;
}
catch (Exception ex)
{
this.logger.Write(String.Format("Failed to get tenant by username '{0}' from database.", userName), "Exceptions", TraceEventType.Error, ex);
return null;
}
}
</code></pre>
<p>Here is call for methods</p>
<pre><code>// get tenant
var crmTenant = CrmServiceHandlerFactory.GetInstance().Resolve<TenantManager>().GetTenantByUserName(userName);
</code></pre>
<p>I am new in programming, could you please help me to improve this code</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T09:11:39.290",
"Id": "22640",
"Score": "0",
"body": "Why do you think there is something wrong with your code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T10:22:37.190",
"Id": "22757",
"Score": "0",
"body": "Because I have ten methods like GetTenantByName GetTenantByUserName GetTenantBySize GetTenantByIce and so on... I doubt that it's a good style... Or i'm wrong?"
}
] |
[
{
"body": "<p>I can see some room for improvement:</p>\n\n<ol>\n<li>Most importantly, you shouldn't hide exceptions like this. You should most likely let the exceptions bubble up and let the called decide what to do when an exception happens. And if you return <code>null</code>, it means you will either have to add <code>null</code> checks everywhere, or you will get <code>NullReferenceException</code> instead of the exception that actually caused the problem, which makes it harder to debug.</li>\n<li><p>You don't need to add items into the list one by one, you can do it all at once using <a href=\"http://msdn.microsoft.com/en-us/library/z883w3dc.aspx\" rel=\"nofollow\"><code>AddRange()</code></a>. Or even better, just use <a href=\"http://msdn.microsoft.com/en-us/library/bb342261.aspx\" rel=\"nofollow\"><code>ToList()</code></a>:</p>\n\n<pre><code>return crmTenants.ToList();\n</code></pre></li>\n<li><p>This one is really minor, but the query <code>from tenant in context.CrmTenant select tenant</code> can be simplified to just <code>context.CrmTenant</code>, the LINQ doesn't do anything useful there.</p></li>\n</ol>\n\n<p>#1 is by far the biggest issue, I think, because it shows an error in your design. #2 and #3 could just simplify your code a bit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T09:21:44.787",
"Id": "14000",
"ParentId": "13997",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "14000",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T08:29:59.540",
"Id": "13997",
"Score": "2",
"Tags": [
"c#",
".net",
"linq",
"classes"
],
"Title": "Class with methods to retrieve data with Linq to sql"
}
|
13997
|
<p>What do you think of my own implementation of the extension method <code>SelectMany</code>?
Motivating criticism is always welcome.</p>
<pre><code>public static IEnumerable<TResult> MySelectMany<T, TResult>(this IEnumerable<T> source, Func<T, IEnumerable<TResult>> selector)
{
var theList = new List<TResult>();
foreach (T item in source)
{
foreach (TResult inneritem in selector(item))
{
theList.Add(inneritem);
}
}
return theList as IEnumerable<TResult>;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T10:35:18.767",
"Id": "22646",
"Score": "1",
"body": "You're doing this just as a learning exercise, right? Otherwise, reimplementing framework code doesn't make much sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T10:40:13.193",
"Id": "22647",
"Score": "0",
"body": "Just to learn indeed. Fooling around with extension methods and delegates etc... :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T11:06:54.607",
"Id": "22651",
"Score": "2",
"body": "For a detailed explanation about how to implement all of LINQ extension methods, see [Jon Skeet's series Edulinq](http://msmvps.com/blogs/jon_skeet/archive/tags/Edulinq/default.aspx). Specifically, [part 9 is about `SelectMany()`](http://msmvps.com/blogs/jon_skeet/archive/2010/12/27/reimplementing-linq-to-objects-part-9-selectmany.aspx)."
}
] |
[
{
"body": "<p>The <code>as</code> cast in the return statement is entirely redundant, it doesnβt serve a purpose.</p>\n\n<p>Furthermore, The problem with this implementation is that itβs not lazy. You should use a <code>yield</code> generator instead.</p>\n\n<pre><code>public static IEnumerable<TResult> MySelectMany<T, TResult>(this IEnumerable<T> source, Func<T, IEnumerable<TResult>> selector)\n{\n foreach (T item in source)\n foreach (TResult inneritem in selector(item))\n yield return inneritem;\n}\n</code></pre>\n\n<p>If C# already had a <code>yield from</code> statement, this would be even shorter since you wouldnβt need to iterate the inner items explicitly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T10:40:25.687",
"Id": "14004",
"ParentId": "14002",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "14004",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-07-25T10:14:34.973",
"Id": "14002",
"Score": "1",
"Tags": [
"c#",
"reinventing-the-wheel",
"linq",
"extension-methods"
],
"Title": "My own implementation of Linq SelectMany extension method"
}
|
14002
|
<p>How do I better calculate the definite integral? I am using a function to integrate and another to find the factorial recursively.</p>
<p>I'l like to better the algorithm or the efficiency or even the accuracy for that matter.</p>
<pre><code> public static double testStatistic(double meanTreatmentSumOfSquares, double meanErrorSumOfSquares)
{
return (meanTreatmentSumOfSquares / meanErrorSumOfSquares);
}
public static double pValue(double fStatistic, int degreeNum, int degreeDenom)
{
double pValue = 0;
pValue = integrate(0, fStatistic, degreeNum, degreeDenom);
return pValue;
}
public static double integrate(double start, double end, int degreeFreedomT, int degreeFreedomE)
{
int iterations = 100000;
double x, dist, sum = 0, sumT = 0;
dist = (end - start) / iterations;
for (int i = 1; i <= iterations; i++)
{
x = start + i * dist;
sumT += integralFunction(x - dist / 2, degreeFreedomT, degreeFreedomE);
if (i < iterations)
{
sum += integralFunction(x, degreeFreedomT, degreeFreedomE);
}
}
sum = (dist / 6) * (integralFunction(start, degreeFreedomT, degreeFreedomE) + integralFunction(end, degreeFreedomT, degreeFreedomE) + 2 * sum + 4 * sumT);
return sum;
}
public static double integralFunction(double x, int degreeFreedomT, int degreeFreedomE)
{
double temp=0;
temp = ((Math.Pow(degreeFreedomE, degreeFreedomE / 2) * Math.Pow(degreeFreedomT, degreeFreedomT / 2)) / (factorial(degreeFreedomE / 2 - 1) * factorial(degreeFreedomT / 2 - 1))) * (factorial(((degreeFreedomT + degreeFreedomE) / 2 - 1)))*((Math.Pow(x, degreeFreedomE / 2 - 1)) / (Math.Pow((degreeFreedomT + degreeFreedomE * x), ((degreeFreedomE + degreeFreedomT) / 2))));
return temp;
}
public static double factorial(double n)
{
if (n == 0)
{
return 1.0;
}
else
{
return n * factorial(n - 1);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T07:28:57.950",
"Id": "22654",
"Score": "3",
"body": "There is no question here, only a task. Focus on a specific part and then a specific question related to it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T15:39:26.573",
"Id": "22661",
"Score": "1",
"body": "Have you considered caching the factorial calculation?"
}
] |
[
{
"body": "<p>Check source code of the <a href=\"http://www.gnu.org/software/gsl/manual/html_node/\" rel=\"nofollow\">GSL library</a> that is really well designed.\nIt includes implementations of many numerical integration algorithms.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T16:52:35.967",
"Id": "14050",
"ParentId": "14005",
"Score": "1"
}
},
{
"body": "<p>You could use a more advanced integral method. I'm guessing you use the rectangle rule, then there's the better approximation of the trapezoidal rule and a bunch of other methods. The better adaptive algorithms require derivatives of your function though and they get harder and harder to implement, of course. I implemented a bunch of them when I took numerical analysis, but then I used MATLAB and not C#.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Numerical_integration#Methods_for_one-dimensional_integrals\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Numerical_integration#Methods_for_one-dimensional_integrals</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T00:30:36.487",
"Id": "14060",
"ParentId": "14005",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T07:27:59.547",
"Id": "14005",
"Score": "3",
"Tags": [
"c#",
"algorithm",
".net",
"performance"
],
"Title": "Definite integral calculation in C#"
}
|
14005
|
<p>I'm trying to make a drop down menu with click event. I have this HTML structure:</p>
<pre><code><ul id="menubar">
<li class="menu1">
<a href="#">Menu 1</a>
<ul class="submenubar">
<li class="submenu1"><a href="#">Submenu 1</a></li>
<li class="submenu1"><a href="#">Submenu 1</a></li>
</ul>
</li>
<li class="menu2">
<a href="#">Menu 2</a>
<ul class="submenubar">
<li class="submenu2"><a href="#">Submenu 2</a></li>
</ul>
</li>
<li class="menu3">
<a href="#">Menu 3</a>
<ul class="submenubar">
<li class="submenu3"><a href="#">Submenu 3</a></li>
<li class="submenu3"><a href="#">Submenu 3</a></li>
</ul>
</li>
</ul>β
</code></pre>
<p>I want to avoid the double drop down, so I made this script:</p>
<pre><code>$(document).ready(function(){
$('li.submenu1').hide();
$('li.menu1').click(function(e){
$(this).find('li.submenu1', this).slideToggle('fast');
$('li.submenu2').hide();
$('li.submenu3').hide();
e.stopPropagation();
})
$('li.submenu2').hide();
$('li.menu2').click(function(e){
$(this).find('li.submenu2', this).slideToggle('fast');
$('li.submenu1').hide();
$('li.submenu3').hide();
e.stopPropagation();
})
$('li.submenu3').hide();
$('li.menu3').click(function(e){
$(this).find('li.submenu3', this).slideToggle('fast');
$('li.submenu1').hide();
$('li.submenu2').hide();
e.stopPropagation();
})
})
</code></pre>
<p>Is there any way to simplify the code? Perhaps some auto-increment tricks will help.</p>
|
[] |
[
{
"body": "<p>Probably something like this would enable you to extract it. Basically I'd suggest looping through hiding everything then setting the one you want to open, you could be clever and check if the menu selected is already one, but hopefully this will give you the idea:</p>\n\n<pre><code>$(\"menubar ul\").each(function(){\n $(\"li\", this).click({\n $(\"menubar ul\").each(function(){\n $(\"li ul\", this).hide()\n })\n $(\"ul\",this).toggle(...\n })\n})\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T10:27:11.390",
"Id": "14007",
"ParentId": "14006",
"Score": "1"
}
},
{
"body": "<p>this should probably do what you want</p>\n\n<pre><code><ul id=\"menubar\">\n <li class=\"menu\">\n <a href=\"#\">Menu 1</a>\n <ul class=\"submenubar\">\n <li class=\"submenu1\"><a href=\"#\">Submenu 1</a></li>\n <li class=\"submenu1\"><a href=\"#\">Submenu 1</a></li>\n </ul>\n </li>\n <li class=\"menu\">\n <a href=\"#\">Menu 2</a>\n <ul class=\"submenubar\">\n <li class=\"submenu2\"><a href=\"#\">Submenu 2</a></li>\n </ul>\n </li>\n <li class=\"menu\">\n <a href=\"#\">Menu 3</a>\n <ul class=\"submenubar\">\n <li class=\"submenu3\"><a href=\"#\">Submenu 3</a></li>\n <li class=\"submenu3\"><a href=\"#\">Submenu 3</a></li>\n </ul>\n </li>\n</ul>β\n\n\n\n$('.menu a').click(function(){\n $('.menu ul').slideUp();\n $(this).next().slideDown();\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T20:56:53.520",
"Id": "14027",
"ParentId": "14006",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T10:09:38.193",
"Id": "14006",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "jQuery auto increment for class name"
}
|
14006
|
<p>I have the following datastructure to perform a longest-match lookup via nested dicts. For example. <code>cs['a b c d']</code> with <code>a</code> and <code>a b c</code> being in the structure will return <code>a b c</code> and the remainder <code>d</code>.</p>
<p>I wonder if there's a better way to implement the <code>_lookup</code> method and possible the <code>__setitem__</code> method. I'm also not completely sure if the way <code>__getitem__</code> works (returning a tuple with the data in the structure and the remainder of the input) isn't a bit confusing when used with the <code>[]</code> operator.</p>
<pre><code>class CommandStorage(object):
"""Stores multi-part commands.
Performs fast lookups returning the command and any arguments which were
not part of the command.
"""
def __init__(self, commands={}):
self._root = {}
self._commands = {}
for cmd, func in commands:
self[cmd] = func
def _lookup(self, line):
parts = line.split(' ')
found = None
found_container = None
container = self._root
command_parts = 0
for i, part in enumerate(parts):
if part not in container:
return found_container, found, parts[command_parts:]
container = container[part]
if None in container:
found_container = container
found = container[None]
command_parts = i + 1
return found_container, found, parts[command_parts:]
def __setitem__(self, cmd, func):
container = self._root
parts = cmd.split(' ')
for part in parts:
container = container.setdefault(part, {})
if None in container:
raise ValueError('Command %s already exists' % cmd)
container[None] = func
self._commands[cmd] = func
def __getitem__(self, line):
return self._lookup(line)[1:]
def __contains__(self, item):
cmd, args = self[item]
return cmd is not None and not args
def __delitem__(self, cmd):
if cmd not in self:
raise KeyError(cmd)
container = self._lookup(cmd)[0]
del container[None]
del self._commands[cmd]
def __iter__(self):
return iter(self._commands)
def __len__(self):
return len(self._commands)
def __nonzero__(self):
return bool(self._commands)
def iterkeys(self):
return self._commands.iterkeys()
def iteritems(self):
return self._commands.iteritems()
def itervalues(self):
return self._commands.itervalues()
def __repr__(self):
return '<CommandStorage(%r)>' % self._commands.keys()
</code></pre>
<p>The full code (with a doctest) is in <a href="https://gist.github.com/3178148" rel="nofollow">this gist</a> as the doctest is not really relevant for the question</p>
|
[] |
[
{
"body": "<pre><code>class CommandStorage(object):\n \"\"\"Stores multi-part commands.\n\n Performs fast lookups returning the command and any arguments which were\n not part of the command.\n \"\"\"\n\n def __init__(self, commands={}):\n self._root = {}\n self._commands = {}\n</code></pre>\n\n<p>Do you really need to store all the data twice?</p>\n\n<pre><code> for cmd, func in commands:\n</code></pre>\n\n<p>That should be <code>commands.items()</code>, guess you've never used the parameter</p>\n\n<pre><code> self[cmd] = func\n\n def _lookup(self, line):\n parts = line.split(' ')\n found = None\n found_container = None\n container = self._root\n command_parts = 0\n for i, part in enumerate(parts):\n if part not in container:\n return found_container, found, parts[command_parts:]\n container = container[part]\n</code></pre>\n\n<p>The recommended way to structure something like this to catch the KeyError, so:</p>\n\n<pre><code>try:\n container = container[part]\nexcept KeyError:\n return found_container, found, parts[command_parts:]\nelse:\n proceed\n</code></pre>\n\n<p>As it stands, your code looks up the <code>container[part]</code> twice.</p>\n\n<pre><code> if None in container:\n</code></pre>\n\n<p>Using None to store the actual value is counter-intuitive. That's not what None usually means.</p>\n\n<pre><code> found_container = container\n found = container[None]\n command_parts = i + 1\n</code></pre>\n\n<p>Having these three pieces of data feels ugly.</p>\n\n<pre><code> return found_container, found, parts[command_parts:]\n</code></pre>\n\n<p>I think the problem is your data structure. Your collection of dicts of dicts of dicts is tricky to navigate. </p>\n\n<pre><code> def __setitem__(self, cmd, func):\n container = self._root\n parts = cmd.split(' ')\n for part in parts:\n</code></pre>\n\n<p>I'd combine these last two lines</p>\n\n<pre><code> container = container.setdefault(part, {})\n if None in container:\n raise ValueError('Command %s already exists' % cmd)\n container[None] = func\n self._commands[cmd] = func\n\n def __getitem__(self, line):\n return self._lookup(line)[1:]\n</code></pre>\n\n<p>I think this is a bad idea. This function doesn't act like [] typically acts in python. So just make this a regular method</p>\n\n<pre><code> def __contains__(self, item):\n def __delitem__(self, cmd):\n def __iter__(self):\n def __len__(self):\n def __nonzero__(self):\n def iterkeys(self):\n def iteritems(self):\n def itervalues(self):\n</code></pre>\n\n<p>You've implemented all these functions to make it act like a dictionary. But its not a dictionary. Unless the object is designed to provide the features of a dictionary, don't attempt to provide the dictionary interface. </p>\n\n<pre><code> def __repr__(self):\n return '<CommandStorage(%r)>' % self._commands.keys()\n</code></pre>\n\n<p>Here's how I'd approach it. Don't use nested dicts, just store everything in one dict. <code>__setitem__</code> becomes trivial:</p>\n\n<pre><code>def __setitem__(self, cmd, func):\n parts = tuple(cmd.split(' '))\n if parts in self._commands:\n raise ValueError('Command %s already exists' % cmd)\n else:\n self._commands[parts] = func\n</code></pre>\n\n<p>Then, _lookup becomes:</p>\n\n<pre><code>def _lookup(self, line):\n parts = tuple(line.split(' '))\n # start with longest match, work backwards\n # first match found will be longest match\n for index in xrange(len(parts), -1, -1):\n try:\n function = self._commands[parts[:index]]\n except KeyError:\n pass # no match found, try next one\n else:\n break # match, stop search\n else:\n function = None # if all else fails, report None as function\n\n return function, list(parts[index:])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T08:59:57.930",
"Id": "22715",
"Score": "0",
"body": "\"Do you really need to store all the data twice?\" - it makes things much easier and there won't be tons of entries so I'd say it's worth the additional memory used. Of course it's not necessary when switching to a single dict instead of the nested ones. Thanks for the detailed answer!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T10:09:38.167",
"Id": "22716",
"Score": "0",
"body": "https://github.com/ThiefMaster/Flask-IRC/blob/ff949d7e8bebff9496f51923abf1d0db6e6f9f14/flask_irc/structs.py is the new version - much more readable :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T05:58:45.367",
"Id": "14041",
"ParentId": "14021",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14041",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T19:42:58.020",
"Id": "14021",
"Score": "2",
"Tags": [
"python",
"lookup"
],
"Title": "Longest-match lookup via nested dicts"
}
|
14021
|
<p>My job required me to learn jQuery the last couple of weeks, but it's a mess and I do not know how to structure my code in an acceptable manner. I come from a Java and PHP background and have never touched JavaScript before.</p>
<p>I've searched the web for some guidelines, but I could not find anything of real value.</p>
<pre><code>function answer(id, value) {
$("input#" + id).val(value);
}
$("table.grid").ready(function() {
if ($.browser.msie && $.browser.version == "7.0") {
var z = 1000;
$("table, tr, th, td, div").each(function() {
$(this).css("z-index", z);
z -= 10;
});
}
$("td[rowspan=2]").parent().addClass("no-border");
$("td.answer-head").prevAll("td.radio").each(function(index) {
$(this).addClass("answer-tail");
});
$("td.radio").click(function() {
var $that = $(this);
var $left = $that.prevAll("td.radio").andSelf();
var $right = $that.nextAll("td.radio");
var $parent = $that.parent();
var $cousin = null;
if ($parent.children().first().attr("rowspan") != undefined) {
$cousin = $parent.next("tr").children("td.radio").eq($left.length - 1);
} else if ($parent.prev("tr").children().first().attr("rowspan") != undefined) {
$cousin = $parent.prev("tr").children("td.radio").eq($left.length - 1);
}
if ($cousin !== null) {
$left = $left.add($cousin).add($cousin.prevAll("td.radio"));
$right = $right.add($cousin.nextAll("td.radio"));
}
$left.each(function(index) {
var $that = $(this);
if ($that.hasClass("answer-head")) {
$that.addClass("click-head");
} else if ($that.hasClass("answer-tail")) {
$that.addClass("click-tail");
} else {
$that.addClass("click");
}
});
$right.each(function(index) {
$(this).removeClass("click-head").removeClass("click-tail").removeClass("click");
});
}).hover(function() {
var $that = $(this);
var $left = $that.prevAll("td.radio").andSelf();
var $right = $that.nextAll("td.radio");
var $parent = $that.parent();
var $cousin = null;
if ($parent.children().first().attr("rowspan") != undefined) {
$cousin = $parent.next("tr").children("td.radio").eq($left.length - 1);
} else if ($parent.prev("tr").children().first().attr("rowspan") != undefined) {
$cousin = $parent.prev("tr").children("td.radio").eq($left.length - 1);
}
if ($cousin !== null) {
$left = $left.add($cousin).add($cousin.prevAll("td.radio"));
$right = $right.add($cousin.nextAll("td.radio"));
}
var $help = $that.add($cousin).find("div.help").first();
$help.css("display", "inline-block");
$left.each(function(index) {
$that = $(this);
if ($that.hasClass("answer-head")) {
$that.addClass("hover-head");
} else if ($that.hasClass("answer-tail")) {
$that.addClass("hover-tail");
} else {
$that.addClass("hover");
}
});
}, function() {
var $that = $(this);
var $all = $that.siblings("td.radio").andSelf();
var $parent = $that.parent();
if ($parent.children().first().attr("rowspan") != undefined) {
$all = $all.add($parent.next("tr").children("td.radio"));
} else if ($parent.prev("tr").children().first().attr("rowspan") != undefined) {
$all = $all.add($parent.prev("tr").children("td.radio"));
}
$all.find("div.help").css("display", "none");
$all.each(function(index) {
$(this).removeClass("hover-head").removeClass("hover-tail").removeClass("hover");
});
});
});
</code></pre>
<p>Above are my hundred lines of code. The script does exactly what I want to do, but it does look ugly, doesn't it? Could you provide a guide/tutorial on how to structure this mess up or give me some pointers?</p>
|
[] |
[
{
"body": "<p>once you define a group of objects with jquery, you only have to loop through them if you want each one to do something different. </p>\n\n<p>the <code>each</code> function actually loops through each item, allowing you do do something different to each object.</p>\n\n<p>for example, you put</p>\n\n<pre><code>$all.find(\"div.help\").css(\"display\", \"none\");\n\n $all.each(function(index) {\n $(this).removeClass(\"hover-head\").removeClass(\"hover-tail\").removeClass(\"hover\");\n });\n</code></pre>\n\n<p>but while your looping with the <code>each</code> function, you are doing the exact same thing to every object, so the loop is not needed. you can use:</p>\n\n<pre><code>$all.find(\"div.help\").css(\"display\", \"none\").removeClass(\"hover-head\").removeClass(\"hover-tail\").removeClass(\"hover\");\n</code></pre>\n\n<p>and to make it even simpler, with many jquery functions, you can seperate multiple classes and ids with a space and actually shrink all of that code to this</p>\n\n<pre><code>$all.find(\"div.help\").css(\"display\", \"none\").removeClass(\"hover-head hover-tail hover\");\n</code></pre>\n\n<p>and to take it one step further, display none can be achieved with hide() - and you can display items with show()</p>\n\n<pre><code>$all.find(\"div.help\").hide().removeClass(\"hover-head hover-tail hover\");\n</code></pre>\n\n<p>EDIT: TO HELP CLARIFY TO YOUR RESPONSE</p>\n\n<p>you can try this, its hard for me to test without all of your working code.</p>\n\n<pre><code>$(\"td.radio\").click(function() {\n var $that = $(this);\n\n doStuff($that,'click');\n $that.nextAll(\"td.radio\").removeClass(\"click-head click-tail click\"); \n\n}).hover(function() {\n var $that = $(this);\n\n doStuff($that, 'hover');\n var $help = $that.add($cousin).find(\"div.help\").first();\n $help.css(\"display\", \"inline-block\");\n\n\n}\n// rest of your code\n</code></pre>\n\n<p>then add this function</p>\n\n<pre><code>function doStuff(eL , which){\n var $that=$(eL);\n var $left = $that.prevAll(\"td.radio\").andSelf();\n var $right = $that.nextAll(\"td.radio\");\n var $parent = $that.parent();\n var $cousin = null;\n\n if ($parent.children().first().attr(\"rowspan\") != undefined) {\n $cousin = $parent.next(\"tr\").children(\"td.radio\").eq($left.length - 1);\n } else if ($parent.prev(\"tr\").children().first().attr(\"rowspan\") != undefined) {\n $cousin = $parent.prev(\"tr\").children(\"td.radio\").eq($left.length - 1);\n }\n\n if ($cousin !== null) {\n $left = $left.add($cousin).add($cousin.prevAll(\"td.radio\"));\n $right = $right.add($cousin.nextAll(\"td.radio\"));\n }\n\n $left.each(function(index) {\n var $that = $(this);\n\n if ($that.hasClass(\"answer-head\")) {\n $that.addClass( which + \"-head\");\n } else if ($that.hasClass(\"answer-tail\")) {\n $that.addClass( which + \"-tail\");\n } else {\n $that.addClass( which );\n }\n });\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T20:49:52.700",
"Id": "22697",
"Score": "0",
"body": "Thank you for your input! I will definitely make changes regarding that, but I'm also thinking about the overall structure. I have a bit of duplicated code in `.click()` and `.hover()`. How would I go about defining a function which returns `$left`, `$right` and in some cases `$cousin` following the jQuery style?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T21:16:32.137",
"Id": "22699",
"Score": "0",
"body": "i wouldnt return the values like your asking. i would write the function to perform the things you want done.see my edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T23:45:07.227",
"Id": "22708",
"Score": "0",
"body": "Thank you again. I will show my refactored version tomorrow and see if it's any better. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T20:39:03.103",
"Id": "14026",
"ParentId": "14022",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14026",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T20:10:32.530",
"Id": "14022",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "New at jQuery, lack of structure"
}
|
14022
|
<p>Im trying to teach myself enough to start using more OOP in php. This is what Ive come up with. Is there any reason why any of this is done wrong, or should be done another way?</p>
<pre><code> class workers {
private $name;
function __construct($name){
$this->name=$name;
}
function setName($name){
$this->name=$name;
}
function doPrint($who){
print $who->name . ' is ' . $who->isWhat() .'<br>';
}
}
class boss extends workers{
function isWhat(){
return 'the boss';
}
}
class bee extends workers{
function isWhat(){
return 'not the boss';
}
}
$theboss =new boss('gordon');
$thebee= new bee('johnny');
workers::doPrint($theboss);
workers::doPrint($thebee);
$theboss->setName('johnny');
$thebee->setName('gordon');
workers::doPrint($theboss);
workers::doPrint($thebee);
</code></pre>
<p>prints:</p>
<pre><code>gordon is the boss
johnny is not the boss
johnny is the boss
gordon is not the boss
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T19:46:03.877",
"Id": "22688",
"Score": "2",
"body": "note: make it `isBoss`, and return a boolean."
}
] |
[
{
"body": "<p>I would set the workers class as <code>abstract</code> (as pointed out by Andreas). </p>\n\n<p>Also, I would use a shared member variable in the parent class which is set in each child's constructor. Also, I wouldn't use a static function to print the object as a string, that's more suited for <code>__toString()</code>. </p>\n\n<pre><code>abstract class workers {\n private $name; \n private $the_boss = false;\n\n function __construct($name){\n $this->name = $name;\n }\n\n function setName($name){\n $this->name=$name; \n }\n\n function __toString(){\n return $this->name . ' is ' . ( $this->the_boss ? '' : 'not ' ).'the boss<br>';\n }\n}\n\nclass boss extends workers {\n function __construct( $name) {\n parent::__construct( $name);\n $this->the_boss = true;\n }\n}\n\nclass bee extends workers{\n function __construct( $name) {\n parent::__construct( $name);\n }\n}\n</code></pre>\n\n<p>As you can see from <a href=\"http://viper-7.com/temrMB\" rel=\"nofollow\">the demo</a>, this produces the same functionality as your original code. </p>\n\n<p>An added benefit is the magic method <code>__toString()</code>, which allows you to do this:</p>\n\n<pre><code>echo $theboss;\necho $thebee;\n</code></pre>\n\n<p>Which causes PHP to invoke that method and print the string returned by <code>__toString()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T19:41:28.643",
"Id": "22689",
"Score": "0",
"body": "Thank you. i like the __toString bit. that will be very helpful in the future."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T19:33:22.633",
"Id": "14024",
"ParentId": "14023",
"Score": "1"
}
},
{
"body": "<p>you should use an abstract class and an interface. also define the doPrint method as static when you want to call it static.</p>\n\n<pre><code>abstract class worker {\n\n /*...*/\n\n public static function doPrint(worker_interface $who) {\n\n /*...*/\n }\n}\n\ninterface worker_interface {\n\n public function isWhat();\n public function setName($name);\n}\n\nclass boss extends worker implements worker_interface {\n\n\n public function isWhat() {\n\n return 'the boss';\n }\n}\n\nclass bee extends worker implements worker_interface {\n\n\n public function isWhat() {\n\n return 'not the boss';\n }\n}\n</code></pre>\n\n<p>define the type for all methods you are passing worker instances to like in <code>doPrint</code></p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>alternatively you could also just add an abstract function instead of using an interface</p>\n\n<pre><code>abstract class worker {\n\n /*...*/\n\n public static function doPrint(worker $who) {\n\n /*...*/\n }\n\n public abstract function isWhat();\n}\n\nclass boss extends worker {\n\n\n public function isWhat() {\n\n return 'the boss';\n }\n}\n\nclass bee extends worker {\n\n\n public function isWhat() {\n\n return 'not the boss';\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T19:37:49.187",
"Id": "22690",
"Score": "1",
"body": "I agree. Although Johnny Craig's original post would work, this way is better because its easier to understand if you have tried to implement polymorphism in other languages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T19:39:54.977",
"Id": "22691",
"Score": "1",
"body": "also it avoids wrong types to be passed to a function which then may result in a \"method not found\" or \"not an object\"-like error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T19:43:41.967",
"Id": "22692",
"Score": "0",
"body": "it would seem as that i am actually adding more code this way, that is considered good practice for readability. am i correct? also, by doing this, would you recommend to call new worker(), or new worker_interface()"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T19:44:43.877",
"Id": "22693",
"Score": "1",
"body": "you cannot instansiate an interface."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T19:44:51.780",
"Id": "22694",
"Score": "1",
"body": "you can't do both of them. abstract classes and interfaces cannot be instaciated. you do `new boss;` and `new bee;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T20:06:37.620",
"Id": "22695",
"Score": "0",
"body": "ok. i got both methods to work. but like the second method, as it is less code. i have a question. if i omit `public abstract function isWhat();` from `abstract class worker` it still works fine. is it there for readability only?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T20:14:33.690",
"Id": "22696",
"Score": "0",
"body": "no, but that way you can define ie. `function test(worker $x) { echo $x->isWhat(); }` and be sure the method isWhat() is available on all values (objects) passed to the function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T18:59:09.367",
"Id": "22932",
"Score": "0",
"body": "@johnnycraig: Andreas mentioned it, but it was not explained explicitly. The reason this is considered good practice, even though it adds more code, is that subclasses MUST use the functionality described in their interface or abstract classes. This ensures that someone looking at these classes will always know how these classes are related and will know what methods are allowed. It also allows them to do cool things like typecast parameters as `worker` instead of `bee` so that any subclass can be passed as a parameter, which allows for better extensibility. There are many more reasons too."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T19:34:28.267",
"Id": "14025",
"ParentId": "14023",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "14025",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T19:24:51.413",
"Id": "14023",
"Score": "0",
"Tags": [
"php",
"object-oriented"
],
"Title": "advice on polymorphism"
}
|
14023
|
<p>I have written a module in my application that makes extensive use of dynamic LINQ to produce Linq/SQL queries based on user interface selection.
Currently, the Linq-SQL translation is resulting in very unoptimised query results, so I am looking at ways to get LINQ to improve the SQL that it is producing.</p>
<p>The following is a typical scenario:</p>
<p>Firstly, the user interface controls are selected, resulting in a LINQ statement of:</p>
<pre><code>Company_contacts.Any(Cust_order_header.Any(Order_time >= @0))
</code></pre>
<p>The table relations are as following:</p>
<ul>
<li><code>Companies 1-*</code></li>
<li><code>Contacts 1-*</code></li>
<li><code>Cust_order_header</code></li>
</ul>
<p>The <code>Cust_order_header</code> contains the datetime field <code>Order_time</code>.</p>
<p>Don't worry about <code>@0</code> - that is a dynamic Linq parameter that is passed in containing the datetime object.</p>
<p>The query translates to:</p>
<blockquote>
<p>Give me all companies that have placed orders within the last (insert days based on datetime) days</p>
</blockquote>
<p>This results in a query that takes 5 minutes to complete, and kicks the hell out of the server.</p>
<p>The SQL it has created (which I have retrieved using <code>((ObjectQuery)groupQuery).ToTraceString()</code>) is:</p>
<pre><code>SELECT *
FROM [dbo].[Companies] AS [Extent1]
WHERE EXISTS (SELECT
1 AS [C1]
FROM ( SELECT
[Extent2].[Company_cont_key] AS [Company_cont_key]
FROM [dbo].[Company_contacts] AS [Extent2]
WHERE [Extent1].[Company_reference] = [Extent2].[Company_reference]
) AS [Project1]
WHERE EXISTS (SELECT
1 AS [C1]
FROM [dbo].[Cust_order_header] AS [Extent3]
WHERE ([Project1].[Company_cont_key] = [Extent3].[Company_cont_key]) AND ([Extent3].[Order_time] >= convert(datetime, '2012-05-20 00:00:00.000', 121))
)
)
</code></pre>
<p>Now, firstly - there are no <code>join</code>s in there, which leads me to think that the SQL it is producing is significantly unoptimised.</p>
<p>AS, if I do to the following in SQL Management Studio manually:</p>
<pre><code>SELECT *
FROM [dbo].[Companies] co
join [dbo].[Company_contacts] cc on co.Company_reference = cc.Company_reference
join [Cust_order_header] coh on coh.Company_cont_key = cc.Company_cont_key
WHERE [Order_time] >= convert(datetime, '2012-05-20 00:00:00.000', 121)
</code></pre>
<p>Then it's < 1s.</p>
<p>So, I have spent 3 weeks putting together my Dynamic-LINQ based user controls/solution; getting rid of it isn't an option.</p>
<p>I should also mention I am using an SQL2000 database. There is nothing I can do about this by the way.</p>
<p>Whilst playing around with the SQL to see if I can get improvements, I have noticed that bizarrely if I change the operator from '>' as it should be to '<', which takes the set of rows I was to ignore, it returns 18k rows (instead of the intended 300) but only takes 2 seconds instead of 4 minutes for the smaller query.</p>
<p>I'm wondering what the options are, or specifically how I should go about configuring LINQ to do things a bit better. I'm even starting to wonder if it's my dynamic LINQ extension code that is unoptimised (downloaded from <a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx" rel="nofollow">here</a>).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T17:07:53.277",
"Id": "22700",
"Score": "0",
"body": "How do you actually generate the LINQ query?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T17:18:39.177",
"Id": "22701",
"Score": "0",
"body": "Can you clarify what ORM you are using? More than one uses LINQ. Is this entity framework?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T17:57:02.610",
"Id": "22702",
"Score": "0",
"body": "The LINQ query is generated using the dynamic linq library in a generic context. Therefore the line is : DataContext.CreateObjectSet<T>().AsQueryable().Where<T>(queryString, paramArray); The ORM is Entity Framework. Beta 5.0"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T18:33:44.797",
"Id": "22703",
"Score": "0",
"body": "What happens if you construct the linq query manually (without using DLINQ), what SQL is generated? Does that query perform? If so, then it's the translation of the string value to the expression. Not sure how to improve this though :-("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T19:54:31.497",
"Id": "22704",
"Score": "0",
"body": "Thanks for the suggestion Maarten, I tried that and it produced the same statement. In a bizarre progression though if I change the datetime operator to '<=' instead of the intended '>=' it takes 2s, and returns 11k rows.. the original >= is 300 rows over 6 minutes. The db is SQL2000. ideas? (updated post too)"
}
] |
[
{
"body": "<p><code>Company_contacts.Any(x => x.Company_contacts.Cust_order_header.Any(y => y.Order_time >= @0))</code></p>\n\n<p>That should put the joins in for you. Right now it is not referencing the objects you use in the query through their relationships so it is writing the SQL out as though they were subqueries.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T21:03:09.020",
"Id": "22705",
"Score": "0",
"body": "Are you sure that holds true for dynamic linq? The statement above is the raw query string that is passed to the dynamic linq extension method and therefore doesn't need to have embedded variable declarations. I have tried the query that you have written too (outside of dLINQ) and printed the SQL through '.ToTraceString()' - it has the same generated SQL which produces adverse results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T21:32:48.653",
"Id": "22706",
"Score": "0",
"body": "+1 as your comments about subqueries triggered me to add the joins explicitly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T20:06:01.927",
"Id": "14030",
"ParentId": "14029",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T16:59:25.220",
"Id": "14029",
"Score": "5",
"Tags": [
"sql",
"performance",
"linq"
],
"Title": "Producing queries based on user interface selection"
}
|
14029
|
<p>I'm looking for a new job, and a company who had a role I was going for asked me to do a programming exercise. It consisted of making a web application of two or more pages that took a person's name and a number, and then rendered the number converted to words. I sent it off and they replied saying that the code wasn't of the level they required so I'm hoping that you could help me and have a look at it so I know what I need to improve on.</p>
<p>It's a .Net 4 C# web application using Nunit for the unit tests, and I'm allowing the user to enter numbers up to a quadrillion (using the short scale), and a maximum of 13 decimals.</p>
<p><a href="https://docs.google.com/open?id=0B5RUjBhNMH9vY2UtUDk3MkNXYjg" rel="nofollow">The zip of the full solution can be downloaded here.</a></p>
<p><strong>aspx page:</strong></p>
<pre><code><%@ Page Title="Programming exercise" Language="C#" MasterPageFile="/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Exercise._Default" ViewStateMode="Disabled" ValidateRequest="false" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:PlaceHolder ID="NameAndNumberForm" runat="server">
<h1>Exercise programming exercise</h1>
<p>
Please enter your name and a number.
</p>
<fieldset>
<label for="NameTextBox">Name:</label>
<asp:TextBox ID="NameTextBox" runat="server"></asp:TextBox>
<label for="NumberTextBox">Number:</label>
<asp:TextBox ID="NumberTextBox" runat="server"></asp:TextBox>
<asp:Label ID="ValidationError" runat="server" Visible="false" CssClass="error"></asp:Label>
<asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click" />
</fieldset>
</asp:PlaceHolder>
<asp:PlaceHolder ID="SuccessMessage" runat="server" Visible="false">
<h1>Thank you</h1>
<p>
Name entered:
<br />
<asp:Literal ID="Name" runat="server" />
<br /><br />
Number entered:
<br />
<asp:Literal ID="Number" runat="server" />
</p>
</asp:PlaceHolder>
<asp:PlaceHolder ID="ErrorMessage" runat="server" Visible="false">
<p class="error">
Oops, something went wrong. Please try again later.
</p>
</asp:PlaceHolder>
</asp:Content>
</code></pre>
<p><strong>Code behind:</strong></p>
<pre><code>using System;
using Common;
namespace Exercise
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
string numberAsWords = String.Empty;
decimal? decimalNumber = DecimalValidator.Validate(NumberTextBox.Text);
if (decimalNumber != null && decimalNumber < 1000000000000000000m)
{
decimal number = (decimal)decimalNumber;
try
{
numberAsWords = NumberToWordsConverter.Convert(number);
Name.Text = Server.HtmlEncode(NameTextBox.Text);
Number.Text = numberAsWords;
NameAndNumberForm.Visible = false;
SuccessMessage.Visible = true;
}
catch
{
// the relevant exceptions should be caught and logged, but didn't do it for this exercise
NameAndNumberForm.Visible = false;
ErrorMessage.Visible = true;
}
}
else
{
ValidationError.Visible = true;
ValidationError.Text = "Please enter a valid number";
}
}
}
}
</code></pre>
<p><strong>Decimal validator:</strong></p>
<pre><code>using System;
using System.Globalization;
namespace Common
{
public static class DecimalValidator
{
public static decimal? Validate(string input)
{
// trim any whitespace from the number
input = input.Replace(" ", String.Empty);
decimal number;
if (Decimal.TryParse(input,
NumberStyles.Number,
CultureInfo.CurrentCulture,
out number))
{
return number;
}
return null;
}
}
}
</code></pre>
<p><strong>Number to words converter:</strong></p>
<pre><code>using System;
namespace Common
{
public static class NumberToWordsConverter
{
public static string Convert(decimal number)
{
if (number == 0)
return "ZERO";
if (number < 0)
return "MINUS " + Convert(Math.Abs(number));
string words = String.Empty;
long intPortion = (long)number;
decimal fraction = (number - intPortion);
int decimalPrecision = GetDecimalPrecision(number);
fraction = CalculateFraction(decimalPrecision, fraction);
long decPortion = (long)fraction;
words = IntToWords(intPortion);
if (decPortion > 0)
{
words += " POINT ";
words += IntToWords(decPortion);
}
return words.Trim();
}
public static string IntToWords(long number)
{
if (number == 0)
return "ZERO";
if (number < 0)
return "MINUS " + IntToWords(Math.Abs(number));
string words = "";
if ((number / 1000000000000000) > 0)
{
words += IntToWords(number / 1000000000000000) + " QUADRILLION ";
number %= 1000000000000000;
}
if ((number / 1000000000000) > 0)
{
words += IntToWords(number / 1000000000000) + " TRILLION ";
number %= 1000000000000;
}
if ((number / 1000000000) > 0)
{
words += IntToWords(number / 1000000000) + " BILLION ";
number %= 1000000000;
}
if ((number / 1000000) > 0)
{
words += IntToWords(number / 1000000) + " MILLION ";
number %= 1000000;
}
if ((number / 1000) > 0)
{
words += IntToWords(number / 1000) + " THOUSAND ";
number %= 1000;
}
if ((number / 100) > 0)
{
words += IntToWords(number / 100) + " HUNDRED ";
number %= 100;
}
if (number > 0)
{
if (words != String.Empty)
words += "AND ";
var unitsMap = new[] { "ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN" };
var tensMap = new[] { "ZERO", "TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY" };
if (number < 20)
words += unitsMap[number];
else
{
words += tensMap[number / 10];
if ((number % 10) > 0)
words += "-" + unitsMap[number % 10];
}
}
return words.Trim();
}
private static int GetDecimalPrecision(decimal number)
{
return (Decimal.GetBits(number)[3] >> 16) & 0x000000FF;
}
private static decimal CalculateFraction(int decimalPrecision, decimal fraction)
{
switch(decimalPrecision)
{
case 1:
return fraction * 10;
case 2:
return fraction * 100;
case 3:
return fraction * 1000;
case 4:
return fraction * 10000;
case 5:
return fraction * 100000;
case 6:
return fraction * 1000000;
case 7:
return fraction * 10000000;
case 8:
return fraction * 100000000;
case 9:
return fraction * 1000000000;
case 10:
return fraction * 10000000000;
case 11:
return fraction * 100000000000;
case 12:
return fraction * 1000000000000;
case 13:
return fraction * 10000000000000;
default:
return fraction * 10000000000000;
}
}
}
}
</code></pre>
<p>These are the unit tests, I'm only including the method names for brevity:</p>
<pre><code>public void Add_DecimalNumber_ReturnDecimal(string number, decimal expected)
public void Add_Integer_ReturnDecimal(string number, decimal expected)
public void Add_NumberWithThousandSeparators_ReturnDecimal(string number, decimal expected)
public void Add_NumberWithSpaces_ReturnDecimal(string number, decimal expected)
public void Add_NegativeNumber_ReturnDecimal(string number, decimal expected)
public void Add_String_ReturnNull(string number, decimal? expected)
public void Add_SingleNumber_ReturnString(decimal number, string expected)
public void Add_TeenNumber_ReturnString(decimal number, string expected)
public void Add_TensNumber_ReturnString(decimal number, string expected)
public void Add_HundredsNumber_ReturnString(decimal number, string expected)
public void Add_ThousandsNumber_ReturnString(decimal number, string expected)
public void Add_MillionssNumber_ReturnString(decimal number, string expected)
public void Add_BillionssNumber_ReturnString(decimal number, string expected)
public void Add_TrillionssNumber_ReturnString(decimal number, string expected)
public void Add_QuadrillionssNumber_ReturnString(decimal number, string expected)
public void Add_OneDecimalNumber_ReturnString(decimal number, string expected)
public void Add_TwoDecimalNumber_ReturnString(decimal number, string expected)
public void Add_ThreeDecimalNumber_ReturnString(decimal number, string expected)
public void Add_FourDecimalNumber_ReturnString(decimal number, string expected)
public void Add_FiveDecimalNumber_ReturnString(decimal number, string expected)
public void Add_SixDecimalNumber_ReturnString(decimal number, string expected)
public void Add_SevenDecimalNumber_ReturnString(decimal number, string expected)
public void Add_EightDecimalNumber_ReturnString(decimal number, string expected)
public void Add_NineDecimalNumber_ReturnString(decimal number, string expected)
public void Add_TenDecimalNumber_ReturnString(decimal number, string expected)
public void Add_ElevenDecimalNumber_ReturnString(decimal number, string expected)
public void Add_TwelveDecimalNumber_ReturnString(decimal number, string expected)
public void Add_ThirteenDecimalNumber_ReturnString(decimal number, string expected)
public void Add_NegativeNumber_ReturnString(decimal number, string expected)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T01:35:22.690",
"Id": "22710",
"Score": "0",
"body": "I've noticed that I forgot to remove the top 4 lines from IntToWords, I'll leave it in though so you can judge the code that I sent off."
}
] |
[
{
"body": "<p>I'm going to focus only on <code>IntToWords()</code>, nothing else (although I think using ASP.NET MVC is considered a better practice than plain ASP.NET).</p>\n\n<p>I can see several problems with that code:</p>\n\n<ol>\n<li>You repeat yourself too much. All the code from thousands up to quadrillions follows the same pattern.</li>\n<li>You allocate the map arrays over and over. You should probably put them in a static field and initialize them only once.</li>\n<li>You're doing quite a lot string concatenation, which creates quite a lot unnecessary garbage. You should use <code>StringBuilder</code> instead.</li>\n<li>When you extract smaller parts of the number, you then send them to the full <code>IntToWords()</code>, which then unnecessarily checks for quadrillions, β¦, thousands. Extracting a method for the part that computes the small numbers would help you with that.</li>\n</ol>\n\n<p>My solution would look like this:</p>\n\n<pre><code>private static readonly string[] UnitsMap = new[]\n{\n \"ZERO\", \"ONE\", \"TWO\", \"THREE\", \"FOUR\", \"FIVE\", \"SIX\", \"SEVEN\", \"EIGHT\", \"NINE\", \"TEN\",\n \"ELEVEN\", \"TWELVE\", \"THIRTEEN\", \"FOURTEEN\", \"FIFTEEN\", \"SIXTEEN\", \"SEVENTEEN\",\n \"EIGHTEEN\", \"NINETEEN\"\n};\n\nprivate static readonly string[] TensMap = new[]\n{\n \"ZERO\", \"TEN\", \"TWENTY\", \"THIRTY\", \"FORTY\",\n \"FIFTY\", \"SIXTY\", \"SEVENTY\", \"EIGHTY\", \"NINETY\"\n};\n\nprivate static readonly string[] ScaleMap = new[]\n{ \"\", \" THOUSAND\", \" MILLION\", \" BILLION\", \" TRILLION\", \" QUADRILLION\" };\n\nstatic IEnumerable<int> SplitIntoThousands(long number)\n{\n while (number != 0)\n {\n yield return (int)(number % 1000);\n number /= 1000;\n }\n}\n\nstatic string SmallNumberToWords(int number)\n{\n string result = null;\n\n if (number > 0)\n {\n if (number >= 100)\n {\n var hundrets = SmallNumberToWords(number / 100);\n var tens = SmallNumberToWords(number % 100);\n\n result = hundrets + \" HUNDRED\";\n\n if (tens != null)\n result += ' ' + tens;\n }\n else if (number < 20)\n result = UnitsMap[number];\n else\n {\n result = TensMap[number / 10];\n if ((number % 10) > 0)\n result += \"-\" + UnitsMap[number % 10];\n }\n }\n\n return result;\n}\n\npublic static string NumberToWords(long number)\n{\n if (number == 0)\n return \"ZERO\";\n\n if (number < 0)\n return \"MINUS \" + IntToWords(-number);\n\n var thousands = SplitIntoThousands(number).ToArray();\n\n var result = new StringBuilder();\n\n for (int i = thousands.Length - 1; i >= 0; i--)\n {\n var word = SmallNumberToWords(thousands[i]);\n\n if (word != null)\n {\n if (result.Length > 0)\n {\n if (i == 0)\n result.Append(\" AND \");\n else\n result.Append(' ');\n }\n result.Append(word);\n result.Append(ScaleMap[i]);\n }\n }\n\n return result.ToString();\n}\n</code></pre>\n\n<p>It still partially has problems 3 and 4, but in a much smaller amount and I think eliminating them completely would make the code too complicated (though in the case of problem 3, it could still be worth it, if this is performance-critical code).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T23:45:32.817",
"Id": "22748",
"Score": "0",
"body": "Also, forgot to say, it said to use the language you had most experience with so I did it with web forms as I haven't got as much experience of MVC yet. For any new projects I'd definitely use MVC with Razor though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T10:32:43.367",
"Id": "14043",
"ParentId": "14033",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "14043",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T00:46:36.557",
"Id": "14033",
"Score": "3",
"Tags": [
"c#",
".net",
"unit-testing",
"interview-questions",
"numbers-to-words"
],
"Title": "Convert number to words (web application)"
}
|
14033
|
<p>General advice for a change. This is an implementation of message queues that I'm going to use for some work on an actors model library.</p>
<pre><code>(defclass message-queue ()
((messages :accessor messages :initarg :messages :initform nil)
(last-cons :accessor last-cons :initarg :last-cons :initform nil
:documentation "Cached end of the list")
(len :accessor len :initarg :len :initform 0
:documentation "Cached message queue length. Modified by enqueue and dequeue")
(lock :initform (bt:make-lock) :accessor lock
:documentation "Lock for this message queue")
(max-len :accessor max-len :initarg :max-len :initform nil
:documentation "If present, queue maintains at most this many elements")
(flag :initform (bt:make-condition-variable) :accessor flag
:documentation "Condition variable used to notify that a message was enqueued")))
(defun make-queue (&optional max-len)
(make-instance 'message-queue :max-len max-len))
(defmethod full-p ((queue sized-queue))
(with-slots (len max-len)
(and max-len (>= len max-len))))
(defmethod empty-p ((queue message-queue))
(= (len queue) 0))
(defmethod enqueue (object (queue message-queue))
"Adds an element to the back of the given queue in a thread-safe way."
(with-slots (lock messages max-len len flag last-cons) queue
(with-lock-held (lock)
(let ((o (list object)))
(cond ((empty-p queue)
(setf messages o
last-cons messages
len 1))
((full-p queue)
(pop messages)
(setf (cdr last-cons) o
last-cons o))
(t (setf (cdr last-cons) o
last-cons o)
(incf len)))))
(condition-notify flag)
messages))
(defmethod dequeue ((queue message-queue) &optional (timeout 0))
"Pops a message from the given queue in a thread-safe way.
If the target queue is empty, blocks until a message arrives.
If timeout is not zero, errors after timeout."
(with-slots (messages lock flag len) queue
(with-timeout (timeout)
(with-lock-held (lock)
(unless messages (condition-wait flag lock))
(decf len)
(pop messages)))))
(defmethod dequeue-no-hang ((queue message-queue))
"Pops a message from the given queue in a thread-safe way.
If the target queue is empty, returns NIL.
The second value specifies whether an item was found in queue (this is meant
to disambiguate the situation where a queue contains the message NIL)"
(with-slots (messages lock flag len) queue
(with-lock-held (lock)
(if messages
(progn
(decf len)
(values (pop messages) t))
(values nil nil)))))
</code></pre>
|
[] |
[
{
"body": "<p>I noticed you defined full read/write accessors on all the slots on your message queue class, yet you bypass all of that and just use with-slots. Are you planning on exporting those accessors as part of the API? It seems like you wouldn't want to encourage people to monkey with those slot values, so probably not. You could also drop :initarg from everything but max-len.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-26T15:20:22.813",
"Id": "17963",
"ParentId": "14036",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T02:47:28.103",
"Id": "14036",
"Score": "3",
"Tags": [
"common-lisp",
"queue"
],
"Title": "Message queues in Common Lisp"
}
|
14036
|
<p>A while ago I used this code to load content into a <code>div</code> using jQuery <code>load</code>. I repeated the code for all the clicks to load different pages in the same <code>div</code>.</p>
<p>Is there any other way to do this?</p>
<pre><code>$("#button1").click(function(){
$('#div1').load('page1.php');
});
$("#button2").click(function(){
$('#div1').load('page2.php');
});
<div id="div1"> </div>
</code></pre>
|
[] |
[
{
"body": "<h3>Option 1:</h3>\n\n<p>If your buttons and pages are actually numbered like that, you can simply extract the number from the ID:</p>\n\n<pre><code>var $container = $('#div1');\n\n$('[id^=button]').click(function() {\n $container.load('page' + this.id.match(/\\d+$/)[0] + '.php');\n});\n</code></pre>\n\n<hr>\n\n<h3>Option 2:</h3>\n\n<p>If that was just an example, but in reality your naming scheme is not so predictable, you can keep an object map with all the appropriate URLs:</p>\n\n<pre><code>var $container = $('#div1'),\n map = {\n button1: 'page1',\n button2: 'page2'\n // and so on...\n };\n\n$('[id^=button]').click(function() {\n $container.load( map[ this.id ] );\n});\n</code></pre>\n\n<hr>\n\n<h3>Option 3:</h3>\n\n<p>You could store the page URL in the HTML:</p>\n\n<pre><code><div id=\"button1\" data-page=\"page1\"></div>\n<div id=\"button2\" data-page=\"page2\"></div>\n</code></pre>\n\n<p>and then use that in your JavaScript:</p>\n\n<pre><code>var $container = $('#div1');\n\n$('[id^=button]').click(function() {\n $container.load( $(this).attr('data-page') );\n});\n</code></pre>\n\n<p>I personally dislike this method, since it puts behavioral stuff in your HTML.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T13:26:19.140",
"Id": "22721",
"Score": "0",
"body": "I like the 3rd method best, since it allows you to give your PHP files better names than numbering them, it places the all the relevant data into the HTML (where is belongs) and if you ever change any links you don't need to touch the JavaScript."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T13:27:26.737",
"Id": "22722",
"Score": "0",
"body": "NB: I just saw an error in your case 3: You are using classes in the HTML, but are selecting by ID in the script."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T17:47:44.963",
"Id": "22730",
"Score": "0",
"body": "@RoToRa - Thanks for spotting that. Updated. I personally prefer using classes, but since the OP is using IDs I'll stick to that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T07:11:48.367",
"Id": "22755",
"Score": "0",
"body": "I'd probably add a class to the html and select using that, instead of using a slow attribute selector."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T03:55:00.607",
"Id": "14038",
"ParentId": "14037",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "14038",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T03:11:00.520",
"Id": "14037",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Loading content into a div"
}
|
14037
|
<p>In the code below , i'm only able to get PHP arrays in javascript to work when I hard code the value . Is this the only way to get it to work, or is their a way to copy the entire PHP array into Javacript . Right now I'm tempted to just create a function chart() for each set of PHP array values. As in rather then writing function chart(a) , I might write function chart1() , function chart2(), function chart3()... </p>
<pre><code><?php
// Configuration
$hostname = 'host';
$username = 'user';
$password = 'pass';
$database = 'db';
$score = 'A' ;
$secretKey = "myKey"; // Change this value to match the value stored in the client javascript below
//$ValueD = 20 ; // this works
//$ValueA ;
try {
$dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password);
echo "Connected to database"; // check for connection
//$dbh->exec("UPDATE Quiz1 SET $score = 1 WHERE Question = 1"); // THIS DOES NOT
//$dbh->exec("UPDATE Quiz1 SET B = 1 WHERE Question = 1"); // THIS WORKS
/*
function getFruit($conn) {
$sql = 'SELECT A, B, C, D FROM Quiz1 WHERE QUESTION = 1';
foreach ($conn->query($sql) as $row) {
// print $row['B'] . "\t";
// print $row['A'] . "\t";
// print $row['B] . "\n";
global $ValueA , $ValueB , $ValueC , $ValueD ;
$ValueA = $row['A'];// with this I can see the value , but it wont show up in the chart
$ValueB = $row['B'] ;
$ValueC = $row['C'] ;
$ValueD = $row['D'] ;
//echo $ValueA ;
}
}*/
function getFruit($conn) {
$sql = 'SELECT A, B, C, D , AnswerA , AnswerB, AnswerC, AnswerD FROM Quiz1 ';
foreach ($conn->query($sql) as $row) {
// print $row['B'] . "\t";
// print $row['A'] . "\t";
// print $row['B] . "\n";
global $ValueA , $ValueB , $ValueC , $ValueD , $AnswerA , $AnswerB, $AnswerC, $AnswerD ;
$ValueA[] = $row['A'];// with this I can see the value , but it wont show up in the chart
$ValueB[] = $row['B'] ;
$ValueC[] = $row['C'] ;
$ValueD[] = $row['D'] ;
$AnswerA[] = $row['AnswerA'];// with this I can see the value , but it wont show up in the chart
$AnswerB[] = $row['AnswerB'] ;
$AnswerC[] = $row['AnswerC'] ;
$AnswerD[] = $row['AnswerD'] ;
//echo $ValueA ;
}
}
//for ( i = 0 , i < $AnswerA.length , i++;){
//echo ($AnswerA[1])
//}
getFruit($dbh);
for ( $i = 0; $i <= 10; $i++){
//$h = ",";
$temp = (($AnswerA[$i]));
echo $temp . ",";
}
//print (array_values($AnswerA));
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// load each var
function chart0(a){
//(array_values($array))
// var VaNum = parseFloat(Va);
var AnswerA1 = '<?php echo ($AnswerA[0]); ?>';
//var AnswerA = AnswerAt.split(" ");
var AnswerB1 = '<?php echo ($AnswerB[0]); ?>';
//var AnswerB = AnswerBt.split(" ");
var AnswerC1 = '<?php echo ($AnswerC[0]); ?>';
//var AnswerC = AnswerCt.split(" ");
var AnswerD1 = '<?php echo ($AnswerD[0]); ?>';
var AnswerAt = '<?php echo array_values($AnswerA); ?>';
var AnswerA = AnswerAt.split(" ");
var AnswerBt = '<?php echo array_values($AnswerB); ?>';
var AnswerB = AnswerBt.split(" ");
var AnswerCt = '<?php echo array_values($AnswerC); ?>';
var AnswerC = AnswerCt.split(" ");
var AnswerDt = '<?php echo array_values($AnswerD); ?>';
var AnswerD = AnswerDt.split(" ");
var Vat = '<?php echo array_values($ValueA); ?>';
var Va1 = '<?php echo ($ValueA[0]); ?>';
var Vb1 = '<?php echo ($ValueB[0]); ?>';
var Vc1 = '<?php echo ($ValueC[0]); ?>';
var Vd1 = '<?php echo ($ValueD[0]); ?>';
var VaNum = parseFloat(Va1);
var VbNum = parseFloat(Vb1);
var VcNum = parseFloat(Vc1);
var VdNum = parseFloat(Vd1);
/* var VbNum = Vb[a];
var VcNum = Vc[a];
var VdNum = Vd[a];*/
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart($width,$height) {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
[AnswerA1, VaNum],
[AnswerB1, VbNum],
[AnswerC1, VcNum],
[AnswerD1, VdNum]
//crap , where not getting the number data here
//['Pepperoni', 2]
]);
// Set chart options
var options = {'title': 'Quiz Results',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div' + a));
chart.draw(data, options);
}
}
chart0(0);
</script>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T04:41:03.110",
"Id": "22711",
"Score": "0",
"body": "As you can see I've already tried to combine the array values and run split(), but this hasn't worked ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T06:08:04.087",
"Id": "22713",
"Score": "7",
"body": "My suggestion is still json_encode. Have you read the first section of http://codereview.stackexchange.com/a/13915/7308 ? You can basically build the data into an array and then dump it into JS with `var x = <?php echo json_encode($data); ?>;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T18:43:43.543",
"Id": "22735",
"Score": "0",
"body": "OK, I tired Json before, but I tired ruining a split on it ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T19:03:18.587",
"Id": "22736",
"Score": "0",
"body": "Connected to database Catchable fatal error: Argument 1 passed to getFruit() must be an instance of PDO, null given, called in path~to~file/index.php on line 57 and defined in path~to~file/index.php on line 48"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T19:03:30.227",
"Id": "22737",
"Score": "0",
"body": "thats the error i'm getting right now"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T04:56:40.337",
"Id": "22753",
"Score": "0",
"body": "That means that whatever is being passed as the first param to getFruit is not an instance of PDO but it needs to be."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T09:20:56.337",
"Id": "22756",
"Score": "0",
"body": "I settled on using an implode function along with a split for time being, this is far from the best solution, but its the best I can do for now ."
}
] |
[
{
"body": "<p>This is the solution I came up with </p>\n\n<p>// in Javascript</p>\n\n<pre><code>var ArrayA = '<?php echo implode(\",\",$AnswerA); ?>';\n var Aname = ArrayA.split(\",\");\n</code></pre>\n\n<p>I know this isn't the best way to do it,but it works </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T08:45:31.967",
"Id": "14068",
"ParentId": "14039",
"Score": "0"
}
},
{
"body": "<p>First off, why are you defining your functions in the try block? This makes your try/catch statement harder to read due to length and heavy indentation. Remove the functions from the try block.</p>\n\n<p>And be consistent with your style. I'm seeing many inconsistencies here. For instance, you normally put your opening braces \"{\" on the same line as the preceding function or keyword, but on your catch block its on a newline. There's nothing wrong with either way, but you should pick one and stick with it. This makes me think you just copy-pasted this from somewhere without understanding it. Never copy-paste a code snippet into your own code, especially if you don't understand it. Take the time to type it out. Even if that means you have to alt-tab to the source repeatedly to get it right. This ensures you at least know the syntax so you can use it again if necessary. The best thing to do is google it, or look it up on PHP documentation to fully understand it before using it.</p>\n\n<p>As Corbin pointed out, the best bet would be to use JSON as it is native to JS. I'm not sure what your comment means, \" I tired Json before, but I tired ruining a split on it \". What does this mean? I'm assuming some of the confusion is because of possible typos, but I don't know. The only reason I can think of for this not to work is that your PHP version may not support it, which means it is quite old and you should definitely think about upgrading. Otherwise the example Corbin gave should do the trick.</p>\n\n<p>Also, don't use globals. These are bad. If you need a variable outside the current scope, pass it to the session, or make it a return value in a function.</p>\n\n<p>What's with the parenthesis on `$temp? And why is the variable even necessary? You only use it to echo it out again... Just echo it immediately, like you did above that line. By the way, those parenthesis on echo are also unnecessary, but again this is an inconsistency. Some of your echo statements have them, others do not. Again either way would have been fine, so long as it was consistent.</p>\n\n<pre><code>$temp = (($AnswerA[$i]));//These are unnecessary\necho $temp . \",\";\n</code></pre>\n\n<p>In the future, when posting code, separate the sources. For instance, here it would have been beneficial to separate the \"working\" code from the commented out \"non-working\" code. This would have given us an idea of what you had tried without competing with the actual information we needed to see what the program was doing. I gave up about halfway through. Not just because of this, but because of all the things I've mentioned above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T19:16:26.313",
"Id": "23139",
"Score": "0",
"body": "The JS code is from the Google Charts API , and the other stuff is somewhat from a PDO tutorial , although I wrote everything aside from the basic connection code . I'm not sure why but I tired using JSON and it didn't work , the solution I came up with was to inplode the arrays and then run splits to break them apart back into arrays . \n\nThis is a temp fix, which i will update in the future once I have a better grasp on this"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T20:49:13.377",
"Id": "14178",
"ParentId": "14039",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T04:39:58.433",
"Id": "14039",
"Score": "1",
"Tags": [
"javascript",
"php"
],
"Title": "Have to hardcode Array values when using PHP arrays in JS"
}
|
14039
|
<p>Can you please check if I've written the code correctly?</p>
<p>The task was:</p>
<ul>
<li>Calculate the user's month of birth as a a number, where January = 0 through to December = 11. </li>
<li>Take the string entered </li>
<li>Get the substring, being the first three characters </li>
<li>Convert to uppercase </li>
<li>Find the starting location of the three-letter abbreviation in the month abbreviations string, and divide this by 3 (this is not the only way to find the month number, but it allows us to practice searching in a string)</li>
</ul>
<p></p>
<pre><code>var year = prompt('Enter year of birth as a 4 digit integer');
var month = prompt('Enter the name of the month of birth');
// Chop everything after the first 3 characters and make it uppercase
month = month.substring(0,3).toUpperCase();
// Store your array in months, differently named than the month input
var months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT",
"NOV", "DEC"];
// We then use array.indexOf() to locate it in the array
var pos = months.indexOf(month);
if (pos >= 0) {
// valid month, number is pos
}
var date = prompt('Enter day of birth as an integer');
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T11:33:17.393",
"Id": "22718",
"Score": "2",
"body": "@Zirak I've run it, and it works properly. But As I've said, I'm new to programming, and I want to make sure I've covered everything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T11:44:47.070",
"Id": "22720",
"Score": "0",
"body": "@ThiefMaster thanks for that, but I have to write what I know and I'm not familiar with the code you've wrote :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T17:51:43.397",
"Id": "22731",
"Score": "0",
"body": "\"... and make it lowercase\" vs. `.toUpperCase()`. Which one is it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T04:46:24.090",
"Id": "22752",
"Score": "0",
"body": "@JosephSilber - Sorry, my mistake, it's to uppercase."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T06:39:26.443",
"Id": "22754",
"Score": "0",
"body": "@GeorgeLi The last bullet seems to imply that the month names are to be stored in a string, not an array - is that required?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T12:36:43.407",
"Id": "22761",
"Score": "0",
"body": "@Inkbug - You know what, you are right. Thanks for that! Could you please double check if I had made any other mistakes so far? Also could you please iterate how exactly you store the month names in a string?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T13:40:40.637",
"Id": "22762",
"Score": "0",
"body": "@GeorgeLi \"JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T13:54:50.080",
"Id": "22763",
"Score": "0",
"body": "@Inkbug - Thanks for your reply, but I'm not exactly following :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T14:00:26.580",
"Id": "22764",
"Score": "0",
"body": "@GeorgeLi The string I posted are the names of the months stored in a string. Use the [`indexOf`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/indexOf) method on it, to find the correct location of the month, and divide by three."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T14:01:21.523",
"Id": "22765",
"Score": "0",
"body": "@GeorgeLi I hope that is helpful, as I won't be available in the next day or so."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T14:11:18.660",
"Id": "22766",
"Score": "0",
"body": "@Inkbug - Thanks for that. I'm very new to JS, therefore the reason for my questions. Is there any alternative method I can contact you regarding more JS queries?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T14:12:45.213",
"Id": "22768",
"Score": "0",
"body": "@GeorgeLi I won't be at my computer in the next 24 hours - after that I'll try to post a detailed answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T14:16:07.737",
"Id": "22769",
"Score": "0",
"body": "@Inkbug No problem, thanks for your patience and help! My twitter is (@georgeli92). Maybe we can chat through that or other ways, it seems easier."
}
] |
[
{
"body": "<p>Everything looks good. </p>\n\n<p>That said, <a href=\"http://kangax.github.com/es5-compat-table/#showold\" rel=\"nofollow\"><code>array.indexOf</code> wasn't supported in Internet Explorer until version 9.</a></p>\n\n<p>If you need that support, the Mozilla Developer Network has a <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf#Compatibility\" rel=\"nofollow\">handy function you can include in your code to provide support for those browsers:</a></p>\n\n<pre><code>if (!Array.prototype.indexOf) {\n Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {\n \"use strict\";\n if (this == null) {\n throw new TypeError();\n }\n var t = Object(this);\n var len = t.length >>> 0;\n if (len === 0) {\n return -1;\n }\n var n = 0;\n if (arguments.length > 0) {\n n = Number(arguments[1]);\n if (n != n) { // shortcut for verifying if it's NaN\n n = 0;\n } else if (n != 0 && n != Infinity && n != -Infinity) {\n n = (n > 0 || -1) * Math.floor(Math.abs(n));\n }\n }\n if (n >= len) {\n return -1;\n }\n var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);\n for (; k < len; k++) {\n if (k in t && t[k] === searchElement) {\n return k;\n }\n }\n return -1;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T00:24:32.153",
"Id": "22749",
"Score": "0",
"body": "Thanks for your reply Danny.\n\nLet me get this straight, var index = array.indexOf(2); should be included in my script?\n\nSo it would look like this:\n\n `var index = array.indexOf(2);\n var pos = months.indexOf(month);\n if (pos >= 0) {\n }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T03:29:40.897",
"Id": "22750",
"Score": "0",
"body": "@GeorgeLi - No, you would actually keep your code the same, but instead add the provided block of code above your current code. (See updated answer). That said, if this code is for a class and your teacher didn't say anything about this, your original code is _probably_ correct enough."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T03:37:18.143",
"Id": "22751",
"Score": "0",
"body": "Thanks for that. It's just a tasks I'm doing from an online tutorial. I probably won't need to include it.\n\nAnyhow, so my code fits all the requirements of the task? I just want to double check."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T13:32:38.443",
"Id": "14045",
"ParentId": "14044",
"Score": "5"
}
},
{
"body": "<p>Here is the whole code; explanations after it.</p>\n\n<pre><code>(function () {\n\n var year, month, months, pos, date;\n\n year = prompt( \"Enter year of birth as a 4 digit integer\" );\n month = prompt( \"Enter the name of the month of birth\" );\n\n months = \"JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC\";\n\n pos = months.indexOf( month.substring( 0, 3 ).toUpperCase() );\n\n if ( pos === -1 ) {\n alert( \"Invalid month name: \" + month );\n } else {\n alert( \"Month number: \" + ( 1 + pos / 3 ) );\n }\n\n date = prompt( \"Enter day of birth as an integer\" );\n})();\n</code></pre>\n\n<hr>\n\n<pre><code>(function () {\n...\n})();\n</code></pre>\n\n<p>The above code is called an <a href=\"http://benalman.com/news/2010/11/immediately-invoked-function-expression/\" rel=\"nofollow\">Immediately-Invoked Function Expression (IIFE)</a>, and is used to not pollute the global namespace with all of our variables. Variables declared with a <code>var</code> are only accessible inside the IIFE. Other styles of IIFEs are also used (such as with a semicolon before it), however this is what I prefer.</p>\n\n<pre><code> var year, month, months, pos, date;\n</code></pre>\n\n<p>It is considered good practice to put all variable declarations at the top. This makes for better minification (when the code is used in production), and to prevent errors do to misunderstanding of <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Statements/var#var_hoisting\" rel=\"nofollow\">variable hoisting</a>.</p>\n\n<pre><code> year = prompt( \"Enter year of birth as a 4 digit integer\" );\n month = prompt( \"Enter the name of the month of birth\" );\n</code></pre>\n\n<p>For a better user experience, it might have been better to use a form, but I don't think that would be worth the effort. Note in addition that I standardized the quotes (<code>\"</code> everywhere), and that I used spaces inside parentheses (different coding styles differ; this is my preferred one).</p>\n\n<pre><code> months = \"JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC\";\n</code></pre>\n\n<p>This is the names of the month (first three letters) in one string.</p>\n\n<pre><code> pos = months.indexOf( month.substring( 0, 3 ).toUpperCase() );\n</code></pre>\n\n<p>This gets the (zero based) location of the searched month. Note that your way is more robust (for example, try an input of <kbd>Unjvember</kbd>), but that this seems to be what was asked for.</p>\n\n<pre><code> if ( pos === -1 ) {\n alert( \"Invalid month name: \" + month );\n } else {\n alert( \"Month number: \" + ( 1 + pos / 3 ) );\n }\n</code></pre>\n\n<p>The requirements didn't ask explicitly for an <code>alert</code> telling the number, but I put it in anyway.</p>\n\n<pre><code> date = prompt( \"Enter day of birth as an integer\" );\n</code></pre>\n\n<p>This (and the first prompt for a year) was in your original code, so I left it in (formatted).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T11:53:22.863",
"Id": "14117",
"ParentId": "14044",
"Score": "1"
}
},
{
"body": "<p>I think you're commenting way too much. Comments that just repeat what the code is doing without any more insight just serve to confuse the reader more; for example, saying that <code>toUpperCase()</code> makes the string uppercase when the function name already makes that clear isn't very helpful.</p>\n\n<p>If you're writing these comments to help you remember what functions do, kind of like notes, then I guess that's fine. But when you start writing code other people will read, remember to leave that stuff out.</p>\n\n<hr>\n\n<p>Your code right now doesn't handle a user's mistakes very well. If I were to write some junk input by accident (like 'banana'), then I'd have no way to go back and fix things. Here I used infinite <code>while</code> loops that only exit when the input is legit:</p>\n\n<pre><code>var year, month, day;\nvar months = [\"JAN\", \"FEB\", \"MAR\", \"APR\", \"MAY\", \"JUN\", \"JUL\", \"AUG\", \"SEP\", \"OCT\", \"NOV\", \"DEC\"];\n\nwhile (true) {\n year = parseInt(prompt('Enter year of birth as a 4 digit integer'));\n\n /* Check that YEAR is a 4-digit number. */\n if (year && (year + \"\").length === 4) {\n break; /* This will exit out of this infinite loop. */\n }\n}\n\nwhile (true) {\n month = prompt('Enter the name of the month of birth');\n month = month.substring(0,3).toUpperCase();\n\n /* Check that MONTH is an actual month (within MONTHS.) */\n if (months.indexOf(month) >= 0) {\n break;\n }\n}\n\nwhile (true) {\n day = prompt('Enter day of birth as an integer');\n\n /* Check that DAY is between 1 and 31. */\n if (day >= 1 && day <= 31) {\n break;\n }\n}\n\nalert(\"Your birthday: \"+ month +\" \"+ day +\" \"+ year);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T18:40:42.280",
"Id": "14119",
"ParentId": "14044",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "14117",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T11:23:21.737",
"Id": "14044",
"Score": "3",
"Tags": [
"javascript",
"strings",
"beginner",
"datetime"
],
"Title": "Calculating user birth information"
}
|
14044
|
<p>I am interested in finding out what is the correct way of implementing error handling for this situation in C#.</p>
<p>The system tries to do an operation. If the operation succeeded (returns a non-error code), the system logs in a log database that the operation was succesfull. If the operation returns a error code or something caused an exception <strong>before</strong> the operation, the system will log an error. However, if the an error is caught when logging, the system shouldn't log an error in the database.</p>
<p>I am using C#. The following code is what I have used until now, but I don't know if it is the best practice in this situation.</p>
<pre><code>int response = -1; //some error code
try
{
//some code to prepare the operation - may cause exceptions
response = DoOperation();
//some code to clean after the operation - may cause exceptions
}
catch
{
//error handling
}
try
{
if (response > 0) //non-error code
//log event in database
else
//log event error in database
}
catch
{
//logging error handling
}
</code></pre>
<p>Do you have any suggestions for improving my code?</p>
<p>Note: The catch blocks include in the original code handling specific errors, I just used a general catch blocks for code simplicity in my question.</p>
|
[] |
[
{
"body": "<p>You could combine the try-catch blocks:</p>\n\n<pre><code>int response = -1; //some error code\nvar logging = false;\ntry\n{\n //some code to prepare the operation - may cause exceptions\n response = DoOperation();\n //some code to clean after the operation - may cause exceptions\n\n logging = true;\n if (response > 0) //non-error code\n //log event in database\n else\n //log event error in database\n}\ncatch\n{\n if(logging)\n //logging error handling\n else\n //error handling\n}\n</code></pre>\n\n<p>Even better, if you know the logging could throw a particular type of exception that the other operations will not, then catch just that exception and handle it as a logging exception, and let all others trickle down to a general catch:</p>\n\n<pre><code>int response = -1; //some error code\n\ntry\n{\n //some code to prepare the operation - may cause exceptions\n response = DoOperation();\n //some code to clean after the operation - may cause exceptions\n\n if (response > 0) //non-error code\n //log event in database\n else\n //log event error in database\n}\ncatch(LoggingSpecificException)\n{\n //logging error handling\n}\ncatch\n{\n //error handling\n}\n</code></pre>\n\n<p>As far as the general strategy, it doesn't look too bad. Getting a \"return status code\" from a method is more than a little outdated (try-throw-catch was designed to replace this style of method return), but there's a lot of \"legacy code\" out there, and some built-in methods still return values that indicate failure. The return value of DoOperation(), if any, should be its conceptual \"product\"; data produced by DoOperation as the result of a computation. If DoOperation, conceptually, doesn't make any such calculation, it would be better conceptually (and thus from an understandability standpoint) to return void and instead throw exceptions on errors. However, you'd have to throw and catch multiple types of exceptions, or keep track of multiple states instead of just \"logging\". </p>\n\n<p>Also, I don't know if you simply omitted it for the operation, but I would think that knowledge of exactly what went wrong might be good to know, and so any general catch should be <code>catch(Exception ex)</code> or similar to allow use of exception data when handling the error.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T15:10:59.513",
"Id": "22725",
"Score": "0",
"body": "The `DoOperation()` is legacy code. The problem is that there isn't just one `DoOperation()`; it's just an generalization for many operations done in a system. In some cases, the return code reflects if the operation could be made or not. But in others the DoOperation returns some codes for partial success; for example some actions failed but others before them not. The actions that failed are sufficiently unimportant to not cause the need of rollback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T16:32:35.680",
"Id": "22726",
"Score": "1",
"body": "\"it's just an generalization for many operations done in a system\" maybe Chain of Responsibility pattern may help?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T14:36:03.990",
"Id": "22770",
"Score": "0",
"body": "Thanks for the info. I checked chain of responsability pattern and it's just what I needed to improve other parts of the code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T14:47:47.573",
"Id": "14048",
"ParentId": "14046",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "14048",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T13:35:49.550",
"Id": "14046",
"Score": "2",
"Tags": [
"c#",
"exception",
"error-handling"
],
"Title": "Suggestions for improving error handling"
}
|
14046
|
<p>I setup simple CRUD in Django</p>
<pre><code>from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseRedirect
from intentions.models import User,Prayer,Intention
from intentions.forms import IntentionForm, DeleteIntentionForm
def index(request):
intentions = Intention.objects.all();
return render_to_response('intentions/templates/index.html',
{'intentions': intentions},
context_instance=RequestContext(request)
)
def show(request, id):
try:
intention = Intention.objects.get(pk=id)
except Intention.DoesNotExist:
return render_to_response('intentions/templates/404_show.html')
return render_to_response('intentions/templates/show.html',
{'intention': intention, 'delete_form': DeleteIntentionForm(instance=intention)},
context_instance=RequestContext(request)
)
def new(request):
if request.method == 'POST': # If the form has been submitted...
form = IntentionForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
intention = form.save()
return HttpResponseRedirect(reverse_lazy('intention-show', args=[intention.id])) # Redirect after POST
else:
form = IntentionForm() # An unbound form
return render_to_response('intentions/templates/form.html',
{'form': form, 'form_url': reverse_lazy('intention-new')},
context_instance=RequestContext(request)
)
def edit(request, id):
intention = Intention.objects.get(pk=id)
if request.method == 'POST': # If the form has been submitted...
form = IntentionForm(request.POST, instance=intention) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
intention = form.save()
return HttpResponseRedirect(reverse_lazy('intention-show', args=[intention.id])) # Redirect after POST
else:
intention = Intention.objects.get(pk=id)
form = IntentionForm(instance=intention) # An unbound form
return render_to_response('intentions/templates/form.html',
{'form': form, 'form_url': reverse_lazy('intention-edit', args=[intention.id])},
context_instance=RequestContext(request)
)
def delete(request, id):
if request.method == 'POST':
try:
intention = Intention.objects.get(pk=id)
except Intention.DoesNotExist:
return render_to_response('intentions/templates/404_show.html')
intention.delete()
return HttpResponseRedirect('/')
else:
return render_to_response('intentions/templates/404_show.html')
</code></pre>
<p>I see some fragments for refactor, but I am newbie in Python and Django and I would like to get advices from more experienced users about refactoring this code too.</p>
|
[] |
[
{
"body": "<p>1.Using <code>render</code> shortcut function is more preferable than <code>render_to_response</code>. The difference is explained on <a href=\"https://stackoverflow.com/a/5154458/455833\">SO</a> </p>\n\n<pre><code>def index(request):\n intentions = Intention.objects.all();\n return render('intentions/templates/index.html', {'intentions': intentions})\n</code></pre>\n\n<p>2.Then django has another shortcut <a href=\"http://django.me/get_object_or_404\" rel=\"nofollow noreferrer\"><code>get_object_or_404</code></a></p>\n\n<pre><code>intention = get_object_or_404(Intention, pk=id)\n</code></pre>\n\n<p>It raises 404 Exception which is processed by middleware. You don't need to call custom <code>HttpRequest</code> for that. </p>\n\n<p>3.Here lazy version <code>reverse_lazy</code> is redundant. Call <code>reverse</code> instead.</p>\n\n<pre><code>return HttpResponseRedirect(reverse_lazy('intention-show', args=[intention.id])) # Redirect after POST\n</code></pre>\n\n<p>4.You also can look through <a href=\"https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-editing/\" rel=\"nofollow noreferrer\">CBV</a>. Django offers for you some base class to handle forms. It may reduce your code. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T05:44:40.297",
"Id": "14067",
"ParentId": "14047",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14067",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T14:19:14.473",
"Id": "14047",
"Score": "2",
"Tags": [
"python",
"django"
],
"Title": "Need advice of refactoring views.py"
}
|
14047
|
<p>I am currently writing a rather large client-side JS application which is made of of multiple modules, each in different files (before compiling). I am using Node.js to build the final script based on all the individual modules. </p>
<p>For the script to work properly all modules must be added in the proper order, so they can access any modules they depend on. One way to solve this is by maintaining an array of all the modules in the correct order to be inserted. I find that limiting though, having to add each file manually and in the correct position.</p>
<p>I have come up with a different solution to this, and would love to get some feedback on it.</p>
<p>First I have one wrapper file, which is wraped around all the modules. Looks like this:</p>
<pre><code>(function( ns ){
var module = window[ns] = {
_modules: window[ns] && window[ns]._modules || {},
exports: function( name, mod ){
this._modules[name] = mod;
},
require: function( name ){
var mod = this._modules[name];
if(!mod) throw new Error(name + ' module not found');
return mod;
}
};
MODULES_INSERT
})( '_myCoolApp' );
</code></pre>
<p>Where it says "MODULES_INSERT" is where the modules get inserted.</p>
<p>Now inside the individual modules it looks something like this:</p>
<pre><code>// export this module
module.exports('view', View);
function View(){ etc.. }
// import other module
var util = module.require('util');
</code></pre>
<p>And finally I have my build script (node.js) which adds all the modules/files, and orders them based on any module.requires they contain in their code, ensuring that all dependencies are loaded before they are required:</p>
<pre><code>for(i in srcFiles){
file = srcFiles[i];
var content = fs.readFileSync(file.src);
content = '(function(){\n' + content;
content = content + '})();\n';
// find any module dependencies
var match, requires = [], regex = /module.require\(['"]([^'"]+)/g;
while(match = regex.exec(content)){
requires.push(match[1]);
}
file.requires = requires;
file.content = content;
}
for(i in srcFiles){
file = srcFiles[i];
recurse(file);
}
function recurse(file){
if(!file) return;
if(file.requires.length > 0) {
file.requires.forEach(function(req){
recurse(srcFiles[req]);
});
}
if(!file.added) results.push(file.content);
file.added = true;
}
code = results.join('');
code = wrapper.replace('MODULES_INSERT', code);
</code></pre>
<p>Is this solution way overkill? One downside I see to this, is what happens when two files require each other, which gets loaded first? Is there a more effective solution for this?</p>
|
[] |
[
{
"body": "<p>I have an experience with requirejs as a dependency management framework, it allows the compiling on the server side with the following snippet </p>\n\n<pre><code>node r.js -o path/to/buildconfig.js\n</code></pre>\n\n<p>the config</p>\n\n<pre><code>// **r.js** configuration\n({\n appDir : \"../\",\n baseUrl: \"js\",\n dir : \"../target\",\n\n modules: [\n { name: \"app\" }\n ],\n\n optimize : \"uglify\",\n optimizeCss: \"standard\",\n\n preserveLicenseComments: false,\n findNestedDependencies: true,\n skipModuleInsertion: false,\n\n uglify: {\n gen_codeOptions : {},\n do_toplevel : {},\n ast_squeezeOptions: {},\n ast_lift_variables: {}\n },\n\n paths : {\n \"jquery\" : \"../../lib/jquery\",\n // .. and so on\n\n }\n})\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T15:21:58.563",
"Id": "14300",
"ParentId": "14049",
"Score": "1"
}
},
{
"body": "<p>Your approach is sound. <a href=\"https://github.com/jrburke/r.js\" rel=\"nofollow noreferrer\">The optimizer of RequireJS called r.js</a> also scans the code for calls to methods with a special name (define and require) to detect dependencies.</p>\n\n<p>You can see how this detection works in the file <a href=\"https://github.com/jrburke/r.js/blob/9e51c128bff26ffe294333c112b82e7c258ef831/build/jslib/transform.js\" rel=\"nofollow noreferrer\">transform.js</a>. As you can see, this optimizer uses a JavaScript parser, which is more reliable than using regular expressions: for example, your regular expression may match a call in a comment, which would be skipped using a parser.</p>\n\n<p>There is another way to declare dependencies for RequireJS though, which is described in the <a href=\"https://github.com/amdjs/amdjs-api/wiki/AMD\" rel=\"nofollow noreferrer\">Asynchronous Module Definition</a> specification: wrap each module in a call to a function and list the dependencies explicitly in an array.</p>\n\n<p>You may also be interested in the use of <a href=\"https://codereview.stackexchange.com/questions/14153/usability-of-api-to-declare-modules-in-javascript\">a simpler pattern for the declaration of modules, independently of the loader used</a>.</p>\n\n<p>With regards to circular dependencies (\"when two files require each other\"), there are two ways to handle them:</p>\n\n<ul>\n<li>detect them and fail, forcing the developer to avoid them in their code</li>\n<li>load one of the two modules with only parts of their dependencies, which requires extra care from developers: they can no longer be sure that all dependencies are available when the module runs, and must check before calling methods and accessing properties on required objects </li>\n</ul>\n\n<p>Both approaches have drawbacks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T20:07:03.223",
"Id": "14308",
"ParentId": "14049",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14308",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T15:24:19.837",
"Id": "14049",
"Score": "2",
"Tags": [
"javascript",
"node.js"
],
"Title": "Build process for compiling client JS modules into one script"
}
|
14049
|
<p>I am trying to eliminate unwanted namespaces, and I know there's a better way to do this. This code works, but it's remedial and redundant.</p>
<pre><code>string sPattern = "xmlns:d5p1=\"http://www.w3.org/2001/XMLSchema-instance\" d5p1:nil=\"true\"";
string sPattern2 = "d5p1:nil=\"true\" xmlns:d5p1=\"http://www.w3.org/2001/XMLSchema-instance\"";
string sPattern3 = "xmlns:d2p1=\"http://www.w3.org/2001/XMLSchema-instance\" d2p1:nil=\"true\"";
string[] fString = new string[sentences.Count()];
//foreach (string str in sentences)
for(int i=0; i < sentences.Count(); i++)
{
Console.WriteLine("{0,24}", sentences[i]); // lines 0-24.
if(System.Text.RegularExpressions.Regex.IsMatch(sentences[i], sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
Console.WriteLine(" (match for '{0}' found)", sPattern);
eString = sentences[i].Replace(sPattern, "");
}
else if(System.Text.RegularExpressions.Regex.IsMatch(sentences[i], sPattern2, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
Console.WriteLine(" (match for '{0}' found)", sPattern2);
eString = sentences[i].Replace(sPattern2, "");
}
else if (System.Text.RegularExpressions.Regex.IsMatch(sentences[i], sPattern3, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
Console.WriteLine(" (match for '{0}' found)", sPattern3);
eString = sentences[i].Replace(sPattern3, "");
}
else
{
Console.WriteLine();
eString = sentences[i];
}
fString[i] = eString;
}
// ok, let's look at the end result
foreach(string s in fString)
{
Console.WriteLine(s);
}
// stop the app from shutting down before seeing results
Console.ReadLine();
</code></pre>
|
[] |
[
{
"body": "<p>Well, the first thing I'd do is put the patterns in a list, and loop through matching them. The second thing would be general cleanup; use namespaces where you can, one-liner if/else clauses don't need braces, use var where the type is obvious, etc etc. This gets rid of that if-elseif structure and makes the code much more concise.</p>\n\n<p>As far as merging the patterns, you could match on a combination of two: </p>\n\n<ul>\n<li><code>\"xmlns:(d5p1|d2p1)=\\\".*?\\\"\"</code> (we don't care what the exact namespace definition is, just don't match greedily)</li>\n<li><code>\"(d5p1|d2p1):nil=\\\"true\\\"\"</code></li>\n</ul>\n\n<p>If either of these patterns match, replace the matching text with an empty string:</p>\n\n<pre><code> List<string> patterns = new List<string>{\n \"xmlns:(d5p1|d2p1)=\\\".*?\\\"\",\n \"(d5p1|d2p1):nil=\\\"true\\\"\",\n };\n\n var output = new string[sentences.Count()];\n for(int i=0; i < sentences.Count(); i++)\n {\n Console.WriteLine(\"{0,24}\", sentences[i]); // 24 chars, left-justified.\n var formattedSentence = sentences[i]; \n\n foreach(var pattern in patterns)\n {\n var len = formattedSentence.Length;\n formattedSentence = Regex.Replace(formattedSentence, pattern, String.Empty,\n RegexOptions.IgnoreCase)\n\n if(formattedSentence.Length != len)\n Console.WriteLine(\" (match for '{0}' found)\", pattern); \n }\n\n //Finally, this may have left some unneeded whitespace which we can consolidate.\n formattedSentence = Regex.Replace(formattedSentence, \" +\", \" \");\n\n output[i] = formattedSentence;\n }\n\n\n // ok, let's look at the end result\n foreach(var sentence in output)\n Console.WriteLine(sentence); \n</code></pre>\n\n<p>One last thing. Hungarian notation - putting some type-specific flag at the beginning of your variable names - is EVIL in virtually any language used in an IDE, including .NET languages. IntelliSense tells you all you need to know about an object's type, if it happens to not be obvious via context; you shouldn't put it in the variable name. If you do, and the type changes, the variable name is now inconsistent and every usage of it needs to change (a task made easier by refactoring assistants like ReSharper, but if you have that you have absolutely no need for Hungarian).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T21:15:29.977",
"Id": "22739",
"Score": "0",
"body": "Brilliantly said Keith S., I'll incorporate your suggestions subito pronto!:-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T19:01:39.463",
"Id": "22779",
"Score": "2",
"body": "Don't forget to upvote and accept if this helped! We work for rep around here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T15:18:19.580",
"Id": "22800",
"Score": "0",
"body": "sorry Keith I tried, but I'm so wet behind the ears here, i didn't have enough privileges to do so!:-|"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T00:34:38.023",
"Id": "22950",
"Score": "0",
"body": "Ok, Keith--I was able to upvote you today--as I finally have enough points! Thanks again. Your suggestions were very helpful."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T20:43:40.217",
"Id": "14052",
"ParentId": "14051",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "14052",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T19:56:39.263",
"Id": "14051",
"Score": "3",
"Tags": [
"c#",
"regex",
"xsd",
"namespaces"
],
"Title": "Eliminating unwanted namespaces"
}
|
14051
|
<p>I am writing a program for my trading application. Over the months the program has been growing steadily, and what is used to be a small program now I would call a medium size program (about 1000-2000 lines in total), and it will keep growing as I add more features to it. It has grown to a point where it start to get difficult to read my code. </p>
<p>Below is a small part of the code from my over program. It is particularly nasty because I have a lot of calculations involved. What I think the following code is especially hard to read is because there are many similarities in blocks but differ from a plus (+) or minus (-) sign, so I cannot easily chunk it to new methods (refactoring). Should I just group the code into like 20-30 lines or so together and declare a new method? Then I will have many small methods which it is only be called in one place, which I think it defeat the purpose of a new method.</p>
<p>I have been reading extension method or so but I don't know if it is easy to apply to my program.</p>
<pre><code>public class CVB
{
public Bar bar = new Bar();
public class Bar
{
public DateTime startTime;
public DateTime endTime;
public double open;
public double high;
public double low;
public double close;
public double bestBid;
public double bestAsk;
public int volume;
public int delta;
public int accVolume;
public DateTime lastPrintTime;
public DateTime lastMarcoTime;
public string writeLine = null;
public List<string> outputString = new List<string>();
public Boolean validBarWrite = false;
}
public Info info = new Info();
public class Info
{
public string symbol = null;
public string exchange = null;
public string finalSymbol = null;
public int CVBSize = 200;
public double tickSize;
public int largeSizeLimit = 50;
public Boolean realtimeChart = false;
public int realtimeChartTimer = 2000;
}
// more variables not included here....
public Boolean initialise = false;
public List<Level2> ask = new List<Level2>();
public List<Level2> bid = new List<Level2>();
public List<Level2> largeSize = new List<Level2>();
public class Level2
{
public double price { get; set; }
public int size { get; set; }
public Level2(double price, int size)
{
this.price = price;
this.size = size;
}
}
class SortAscending : IComparer<Level2>
{
public int Compare(Level2 x, Level2 y)
{
if (x.price > y.price) return 1;
else if (x.price < y.price) return -1;
else return 0;
}
}
class SortDecending : IComparer<Level2>
{
public int Compare(Level2 x, Level2 y)
{
if (x.price < y.price) return 1;
else if (x.price > y.price) return -1;
else return 0;
}
}
public static void processLine(ref Output output, ref CVB[] cvb, int c)
{
double bidDistance;
double askDistance;
int oldProcessVolume; // use to hold the previous volume, use to calculate the overflow when the CVB limit is reached
int temp;
double outputPrice = output.price;
cvb[c].bar.writeLine = null;
//////////convert the tick file into constant volume
if (cvb[c].initialise == false) //dont worry about the first bar, it is bugged, the number can be comeing from anywhere, not just trade
{
cvb[c].bar.startTime = output.time;
cvb[c].bar.open = output.price;
cvb[c].bar.high = output.price;
cvb[c].bar.low = output.price;
cvb[c].initialise = true;
}
if (output.price > 0 || output.type == "Volume")
{
switch (output.type)
{
case "Trade":
Beginning:
oldProcessVolume = cvb[c].bar.volume;
cvb[c].bar.volume = cvb[c].bar.volume + output.volume;
if (output.price > cvb[c].bar.high)
cvb[c].bar.high = output.price;
if (output.price < cvb[c].bar.low)
cvb[c].bar.low = output.price;
cvb[c].bar.close = output.price;
if (cvb[c].bar.bestAsk != 0 || cvb[c].bar.bestBid != 0) //not at the start of the program
{
bidDistance = output.price - cvb[c].bar.bestBid;
askDistance = cvb[c].bar.bestAsk - output.price;
if (bidDistance - askDistance > 0.00000001) //trade closer to ask
{
cvb[c].bar.delta = cvb[c].bar.delta + output.volume;
if (output.volume > cvb[c].info.largeSizeLimit)
{
temp = cvb[c].largeSize.Where(x => Math.Abs(x.price - outputPrice) < 0.00000001).Sum(y => y.size); //extract the last volume
cvb[c].largeSize.RemoveAll(x => Math.Abs(x.price - outputPrice) < 0.00000001);
cvb[c].largeSize.Add(new Level2(output.price, temp + output.volume));
}
if (cvb[c].bar.volume >= cvb[c].info.CVBSize) // volume is filled
{
output.volume = cvb[c].bar.volume - cvb[c].info.CVBSize; // cap the volume of the bar to the size of CVB, any overflow is put into the next bar
cvb[c].bar.delta = cvb[c].bar.delta - output.volume;
temp = cvb[c].ask.Where(x => Math.Abs(x.price - outputPrice) < 0.0000001).Sum(yield => yield.size); //extract the last size on the ask, because we want accurate bid size and ask size when the bar is finish
cvb[c].ask.RemoveAll(x => Math.Abs(x.price - outputPrice) < 0.00000001);
temp = temp - (cvb[c].info.CVBSize - oldProcessVolume);
cvb[c].bar.accVolume = cvb[c].bar.accVolume + (cvb[c].info.CVBSize - oldProcessVolume);
if (temp > 0)
cvb[c].ask.Add(new Level2(output.price, temp));
cvb[c].bar.validBarWrite = true;
writeToString(ref output, ref cvb, c);
goto Beginning;
}
}
if (askDistance - bidDistance > 0.00000001) //trade closer to bid
{
cvb[c].bar.delta = cvb[c].bar.delta - output.volume;
if (output.volume > cvb[c].info.largeSizeLimit)
{
temp = cvb[c].largeSize.Where(x => Math.Abs(x.price - outputPrice) < 0.00000001).Sum(y => y.size);
cvb[c].largeSize.RemoveAll(x => Math.Abs(x.price - outputPrice) < 0.00000001);
cvb[c].largeSize.Add(new Level2(output.price, temp - output.volume));
}
if (cvb[c].bar.volume >= cvb[c].info.CVBSize) // volume is filled
{
output.volume = cvb[c].bar.volume - cvb[c].info.CVBSize;
cvb[c].bar.delta = cvb[c].bar.delta + output.volume;
temp = cvb[c].bid.Where(x => Math.Abs(x.price - outputPrice) < 0.0000001).Sum(yield => yield.size); //extract the last size on the ask
cvb[c].bid.RemoveAll(x => Math.Abs(x.price - outputPrice) < 0.00000001);
temp = temp - (cvb[c].info.CVBSize - oldProcessVolume);
cvb[c].bar.accVolume = cvb[c].bar.accVolume + (cvb[c].info.CVBSize - oldProcessVolume);
if (temp > 0)
cvb[c].bid.Add(new Level2(output.price, temp));
cvb[c].bar.validBarWrite = true;
writeToString(ref output, ref cvb, c);
goto Beginning;
}
}
if (Math.Abs(bidDistance - askDistance) < 0.00000001)
{
if (cvb[c].bar.volume >= cvb[c].info.CVBSize) // volume is filled
{
output.volume = cvb[c].bar.volume - cvb[c].info.CVBSize;
cvb[c].bar.accVolume = cvb[c].bar.accVolume + (cvb[c].info.CVBSize - oldProcessVolume);
cvb[c].bar.validBarWrite = true;
writeToString(ref output, ref cvb, c);
goto Beginning;
}
}
} //end if (output.price != 0)
break;
case "Ask":
cvb[c].ask.RemoveAll(x => Math.Abs(x.price - outputPrice) < 0.00000001);
cvb[c].bid.RemoveAll(x => x.price >= outputPrice - 0.00000001);
if (output.volume > 0)
cvb[c].ask.Add(new Level2(output.price, output.volume));
break;
case "BestAsk":
cvb[c].bar.bestAsk = output.price;
cvb[c].ask.RemoveAll(x => x.price <= outputPrice + 0.000000001);
cvb[c].bid.RemoveAll(x => x.price >= outputPrice - 0.00000001);
if (output.volume > 0)
cvb[c].ask.Add(new Level2(output.price, output.volume));
break;
case "Bid":
cvb[c].bid.RemoveAll(x => Math.Abs(x.price - outputPrice) < 0.00000001);
cvb[c].ask.RemoveAll(x => x.price <= outputPrice + 0.000000001); //eliminate the chance the bid is higher than the old ask size
if (output.volume > 0)
cvb[c].bid.Add(new Level2(output.price, output.volume));
break;
case "BestBid":
cvb[c].bar.bestBid = output.price;
cvb[c].bid.RemoveAll(x => x.price >= outputPrice - 0.00000001);
cvb[c].ask.RemoveAll(x => x.price <= outputPrice + 0.000000001); //eliminate the chance the bid is higher than the old ask size
if (output.volume > 0)
cvb[c].bid.Add(new Level2(output.price, output.volume));
break;
case "Volume":
cvb[c].bar.accVolume = output.volume;
break;
} //switch (output.type)
}
if (cvb[c].info.realtimeChart == true && output.time > cvb[c].bar.lastPrintTime.AddMilliseconds(cvb[c].info.realtimeChartTimer)) //update the string for the last bar
{
cvb[c].bar.validBarWrite = false;
writeToString(ref output, ref cvb, c);
}
cvb[c].bar.lastPrintTime = output.time;
}
// more methods below
}
</code></pre>
<p>Nearly every variable I have starts with <code>cvb[c].something....</code> and is is hurting my readability for the code. I came from a VB background which I have <code>with / end with</code> to improves my readability. There is nothing in C# that is similar to VB <code>with / end with</code>. I read about other threads where they use </p>
<pre><code>var p = this.StatusProgressBar;
p.IsIndeterminate = false;
p.Visibility = Visibility.Visible;
...
</code></pre>
<p>but you can't limit the scope of <code>p</code> within a certain place in the function, which I don't like.</p>
<p>The code for write to string </p>
<pre><code>public static void writeToString(ref Output output, ref CVB[] cvb, int c)
{
string bidString = null;
string askString = null;
string largeSizeString = null;
double bestAsk = 0;
double bestBid = 0;
double processTickSize = cvb[c].info.tickSize;
string timeFmt = "yyyy/MM/dd HH:mm:ss.fff";
int currentBarBidAskSize = cvb[c].minimumWallSize;
cvb[c].wallPrice[0] = 0;
cvb[c].bar.endTime = output.time;
//output all the info into the text file
SortDecending sortDecending = new SortDecending();
cvb[c].bid.Sort(sortDecending);
SortAscending sortAscending = new SortAscending();
cvb[c].ask.Sort(sortAscending);
cvb[c].largeSize.Sort(sortAscending);
for (int i = 0; i < 10; i++)
{
if (i < cvb[c].ask.Count && cvb[c].ask[i].price < cvb[c].ask[0].price + (20 * cvb[c].info.tickSize))
{
askString = askString + "," + cvb[c].ask[i].price.ToString() + "," + cvb[c].ask[i].size.ToString();
}
else
{
askString = askString + ",0,0"; //pad it until 10 size is shown
}
}
for (int i = 0; i < 10; i++)
{
if (i < cvb[c].bid.Count && cvb[c].bid[i].price > cvb[c].bid[0].price - (20 * cvb[c].info.tickSize))
{
bidString = bidString + "," + cvb[c].bid[i].price.ToString() + "," + cvb[c].bid[i].size.ToString();
}
else
{
bidString = bidString + ",0,0"; //pad it until 10 size is shown
}
}
for (int i = 0; i < cvb[c].largeSize.Count; i++)
{
largeSizeString = largeSizeString + "," + cvb[c].largeSize[i].price.ToString() + "," + cvb[c].largeSize[i].size.ToString();
}
cvb[c].largeSize.Clear();
if (cvb[c].ask.Count > 0)
bestAsk = cvb[c].ask[0].price;
if (cvb[c].bid.Count > 0)
bestBid = cvb[c].bid[0].price;
int askSum5 = cvb[c].ask.Where(x => x.price >= bestAsk && x.price < bestAsk + (5 * processTickSize)).Sum(y => y.size);
int bidSum5 = cvb[c].bid.Where(x => x.price <= bestBid && x.price > bestBid - (5 * processTickSize)).Sum(y => y.size);
int askSum10 = cvb[c].ask.Where(x => x.price >= bestAsk && x.price < bestAsk + (10 * processTickSize)).Sum(y => y.size);
int bidSum10 = cvb[c].bid.Where(x => x.price <= bestBid && x.price > bestBid - (10 * processTickSize)).Sum(y => y.size);
cvb[c].bar.writeLine = string.Format("`{0},{1},{2},{3},{4},{5},ASK:{6},BID:{7},{8:0.##},{9:0.##},{10:0.##},{11:0.##},largeSize:{12}",
cvb[c].bar.endTime.ToString(timeFmt),
cvb[c].bar.open,
cvb[c].bar.high,
cvb[c].bar.low,
cvb[c].bar.close,
cvb[c].bar.accVolume,
askString,
bidString,
(double)cvb[c].bar.delta / cvb[c].info.CVBSize, //delta ratio
(double)Math.Log10(Math.Abs((cvb[c].bar.endTime.AddMilliseconds(10) - cvb[c].bar.startTime).TotalSeconds)), //bar duration in seconds, TAKE LOG, when the HH:mm time has fixed, then no need to get the abs value
(double)Math.Sign(askSum5 - bidSum5) * (Math.Max(askSum5, bidSum5) / (Math.Min(askSum5, bidSum5) + 0.0001)) - (Math.Sign(askSum5 - bidSum5)), //size ratio price5
(double)Math.Sign(askSum10 - bidSum10) * (Math.Max(askSum10, bidSum10) / (Math.Min(askSum10, bidSum10) + 0.0001)) - (Math.Sign(askSum10 - bidSum10)),
largeSizeString);
if (cvb[c].info.realtimeChart == false || cvb[c].bar.validBarWrite == true)
{
cvb[c].bar.open = cvb[c].bar.close;
cvb[c].bar.high = cvb[c].bar.open;
cvb[c].bar.low = cvb[c].bar.open;
cvb[c].bar.volume = 0;
cvb[c].bar.delta = 0;
cvb[c].bar.startTime = cvb[c].bar.endTime;
}
}
</code></pre>
<p>Any suggestions on improving the readability of my code? Should I add more comment in my code? It looks like a complete mess for anyone who doesn't know the function of the code. I have read somewhere that you should not need to add comments on the code if your code is structure well, just a header. My code is definitely not structured well but I don't know where to start improving it. Now I understand my code, but 6 months from now it will be a complete mess for me to look at the code again.</p>
|
[] |
[
{
"body": "<p>Ideas:</p>\n\n<p><em>Do</em> create methods and call them. That does <em>not</em> defeat... And it's easy - just select that code and click: Refactor -> Extractmethod.</p>\n\n<p>Create <em>classes</em> and so, your variables will not pollute other classes with their names.</p>\n\n<p>You <em>can</em> create one method for the two parts you mentioned, which differ by +/-. Just have an extra argument for the method: an <code>int</code> that will either be 1 or -1...</p>\n\n<p>When creating new classes - you can put them in new files, and even in new folders (just right-click the project in solution explorer...) But beware - when creating new items in those folders - the namespace will be different. (But you can change it.)</p>\n\n<p>And, when everything else fails - use <code>#region</code> - <code>#endregion</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T18:44:14.617",
"Id": "14055",
"ParentId": "14054",
"Score": "1"
}
},
{
"body": "<p>You have a lot of classes nested under another class. Why not pull these out into their own files? It will greatly simplify the parent class.</p>\n\n<p>Also, a perfect example of where you should be creating other methods comes in your very large conditional block. Why not pull out the long if..else statement into a separate method? That will make the switch block much easier to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T19:14:34.590",
"Id": "22741",
"Score": "0",
"body": "This is a common practice in Java to make \"subclasses\" which is a concept that C# does not have. A lot of Java gone C#.NET guys do this often not realizing it doesn't do anything different once compiled if it were in a stand alone file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T22:45:33.033",
"Id": "22742",
"Score": "0",
"body": "@ bort, i have deliberately nest the class together, as i feel like they should somehow group together. Before hand, i have only one 'CVB' class with 50 variables in it, i have create subclasses so i can group them meaningfully. If i break the subclass into separate class, i will need to pass like 10 variables for each method, and since i pass the same variables all the time, i feel like group them together is better, please comment on it, as i have develop my own style all myself. i like to know how other people are doing it. thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T18:12:49.167",
"Id": "22777",
"Score": "0",
"body": "@clayton you have to understand that classes are not there to \"group variables meaningfully\", they're there to help you extract and define (and then divide and conquer) some functionality."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T18:49:17.547",
"Id": "14056",
"ParentId": "14054",
"Score": "1"
}
},
{
"body": "<p>There are a few things you can do here.</p>\n\n<ol>\n<li>Put each class in its own file. You don't really want to have to look through all of the class definitions to get to the code you care about. Typically every public class should have its own .cs file.</li>\n<li>Definitely split code out into smaller methods. Each method you write should have exactly <strong>one</strong> purpose. Take for example your processLine method - processing an entire line of text is made up of several different operations. You can split out an Initialize method, and each logical operation should go into its own method.</li>\n<li>Creating methods that are only called from one place is still a good thing. If you name your methods appropriately, it means you can look at the code and just read the name of the method to know what it's doing. As it is now, we can look at your code, but we have no idea why you're adding or subtracting any two numbers. We don't know what overall operation each block of code is computing or what it is really trying to calculate - simple methods can fix that.</li>\n<li>Rename your variables. The parameter 'c' is meaningless - what is 'c'? Looking through the method, you can't tell what it is or what it's used for. cvb is the same - you should give that array a meaningful name</li>\n<li>If you're going to be using the same array item over and over (cvb[c] for example) it can be more readable to extract it to its own variable. Save cvb[c] in a variable with a meaningful name so you don't have to look at the bracket syntax all over.</li>\n<li>Create a constant for 0.00000001 and give the const a name to describe what that number is being used for. Why are you comparing to that number? The name of your constant should answer that question.</li>\n</ol>\n\n<p>There are probably a few other things that you could dig into, but these are where I would start.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T22:31:12.747",
"Id": "22743",
"Score": "0",
"body": "thank you for your comment, i try to answer your comment 1. in my main program, i have about 10 cs file already, this is just one of the cs file. should i really try break up into smaller pieces? then i would like upwards of 40-50 cs file and then the number of cs files inself becomes a mess. 2 & 3. will do so, thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T22:38:41.610",
"Id": "22744",
"Score": "0",
"body": "4. i actually have a reason for it. CVB stands for constantVolumeBar and c is short ofr contract number. if i have the whole thing, that would mean constantVolumebar[contactNumber].whatever, each variable will be like 20-30 character long, and it just goes really bad. 5. this is similar to 4. if i get a good meaningful name, it will be like 10-20 characters long, if i just use a single letter 'p' for example, i am only saving 3-4 letters, please comment on it. 6. will do so, maybe i should create a method around it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T18:50:42.800",
"Id": "14057",
"ParentId": "14054",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p><em>Please</em> refactor out the GOTOs into normal loops with conditions! :) PS: there is a 'goto case' that should have been used here instead of adding a label under the case, but I <em>still</em> would not recommend using it if you are going for readability and maintainability.</p></li>\n<li><p>Consider refactoring out each actionable block into a separate method, and have the method names reflect it's action (i.e. 'FindLargestTrade', 'GetPreviousOverflowVolume', 'GetTradeCap' etc..)</p></li>\n<li><p>Prefer using member variables in your classes to passing variables to each method (if all your class methods can be declared static, you might as well be writing in C)</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T19:04:35.513",
"Id": "14058",
"ParentId": "14054",
"Score": "0"
}
},
{
"body": "<p>You obviously don't do enough encapsulation. I see at least three classes with no behaviour (<code>Bar</code>, <code>Level2</code> and <code>Info</code>), your \"main\" class (<code>CVB</code>) contains only static method... it does not seem like good OOP for me (and when we are talking C# we should mostly talk OOP).</p>\n\n<p>Let's try to fix it, one thing at a time.</p>\n\n<pre><code>public static void processLine(ref Output output, ref CVB[] cvb, int c)\n</code></pre>\n\n<p>Why are <code>output</code> and <code>cvb</code> <code>ref</code>, if it's not assigned anywhere in code? It should not be. Only things that implies assignment is <em>call</em> to <code>writeToString(ref output, ref cvb, c);</code>, which should not modify anything, because it's only writing. You have not included your code, but let's assume that it's not doing any assignments inside too. So we get rid of those <code>ref</code>s.</p>\n\n<p>Next thing in here: you're passing in an array of <code>CVB</code>s and some <code>c</code>, most likely an index. But everywhere in method (with exception to calls to <code>writeString</code>) you're using <code>cvb[c]</code>. So we can safely extract it into temporary variable. Let's call it <code>cvbEl</code>, for the lack of best option.</p>\n\n<pre><code>var cvbEl = cvb[c];\n</code></pre>\n\n<p>Another \"safe\" extraction is to put your <code>0.00000001</code> into a (class-level) constant, which we will name <code>Tolerance</code>, because as far as I can see, it is a floating-point comparison tolerance.</p>\n\n<pre><code>const double Tolerance = 0.00000001;\n</code></pre>\n\n<p>Now I'll do some strange thing: I'll extract your call to <code>writeString</code> to variable. I do this only because it is the only thing that operates with <code>cvb</code> and <code>c</code> and I can not make any decision about it without seeing it first. So I'll just save entire call for later.</p>\n\n<pre><code>Action writeToStringCall = () => writeToString(ref output, ref cvb, c);\n</code></pre>\n\n<p>And now, thanks to this, all our code operates on <code>cvbEl</code>. So we can safely move it to <code>CVB</code> instance method, because all this processing is coupled to single instance of <code>CVB</code>. Let's call this method <code>Process</code> (of course, all the code inside it does not use <code>cvbEl</code>, but uses implicit <code>this</code>. Now, all that's left of yours <code>processLine</code> is:</p>\n\n<pre><code>public static void processLine(Output output, CVB[] cvb, int c)\n{\n var cvbEl = cvb[c];\n Action writeToStringCall = () => writeToString(ref output, ref cvb, c);\n cvbEl.Process(output, writeToStringCall);\n}\n</code></pre>\n\n<p>In fact, it could be an one-liner if inlined all the variables, but I leave them as is for the sake of readability.</p>\n\n<p>Next thing: you should extract every case in your switch as a separate method. Look at it now:</p>\n\n<pre><code>switch (output.type)\n{\n case \"Trade\":\n Trade(output, writeToStringCall);\n break;\n case \"Ask\":\n Ask(output);\n break;\n case \"BestAsk\":\n BestAsk(output);\n break;\n case \"Bid\":\n Bid(output);\n break;\n case \"BestBid\":\n BestBid(output);\n break;\n case \"Volume\":\n Volume(output);\n break;\n}\n</code></pre>\n\n<p>In fact, repeating pattern (for every type of <code>Output</code> call a method passing <code>output</code> inside) clearly calls for some inheritance on <code>Output</code> side: you should have several different <code>Output</code> classes, subtyped after your <code>Output.Type</code>, with method <code>ProcessSmth(CVB)</code>, which should have processing related to that type of output. Having that you would replace this whole switch with <code>output.ProcessSmth(this)</code>. But I won't do that now, and instead concentrate of contents of there methods (although they are already pretty small and readable, with exception of <code>Trade</code>).</p>\n\n<pre><code>private void Volume(Output output)\n{\n bar.accVolume = output.volume;\n}\n</code></pre>\n\n<p>Already nothing to do here.</p>\n\n<pre><code>ask.RemoveAll(x => x.price <= outputPrice + 0.000000001)\n</code></pre>\n\n<p>This line is repeated three times (although I suppose that third one is a mistake), so we extract it into method, also giving it meaningful name (<code>RemoveAllAsksLessThan</code>). We repeat same operation for remaining <code>RemoveAll</code>s. Let's look what's left of these:</p>\n\n<pre><code>private void BestBid(Output output)\n{\n bar.bestBid = output.price;\n RemoveAllBidsGreaterThan(output.price);\n RemoveAllAsksLessThan(output.price);\n\n if (output.volume > 0)\n bid.Add(new Level2(output.price, output.volume));\n}\n\nprivate void Bid(Output output)\n{\n RemoveAllBidsEqualTo(output.price);\n RemoveAllAsksLessThan(output.price);\n\n if (output.volume > 0)\n bid.Add(new Level2(output.price, output.volume));\n}\n\nprivate void BestAsk(Output output)\n{\n bar.bestAsk = output.price;\n RemoveAllBidsGreaterThan(output.price);\n RemoveAllAsksLessThan(output.price);\n\n if (output.volume > 0)\n ask.Add(new Level2(output.price, output.volume));\n}\n\nprivate void Ask(Output output)\n{\n RemoveAllAsksEqualTo(output.price);\n RemoveAllBidsGreaterThan(output.price);\n\n if (output.volume > 0)\n ask.Add(new Level2(output.price, output.volume));\n}\n</code></pre>\n\n<p>All that's left is <code>Trade</code>. Most of it happens only when <code>bar.bestAsk != 0 || bar.bestBid != 0</code>. Let's invert that <code>if</code> so we don't have to think what happens if both bests are 0 (because we simply return at that, don't leave us hanging!).</p>\n\n<pre><code>if (bar.bestAsk == 0 && bar.bestBid == 0)\n return;\n</code></pre>\n\n<p>(BTW, you forgot your tolerance check)</p>\n\n<pre><code>if (output.price > bar.high)\n bar.high = output.price;\n</code></pre>\n\n<p>You do that for every run you got thru your <code>Beginning:</code> label, but in fact it won't change: neither <code>output.price</code> nor <code>bar.high</code> are changed elsewhere in this method. So we can safely move this operation <em>above</em> <code>Beginning:</code>. Same goes for <code>bar.low</code>, <code>bar.close</code>, <code>bidDistance</code> and <code>askDistance</code>.</p>\n\n<p>Then we convert your <code>goto</code> into common-knowledge <code>while(true)</code>. To do that we simply replace <code>Beginning</code> with <code>while(true)</code>, enclose all code below in loop, add <code>return</code> in the end, and <code>continue</code> instead of every <code>goto</code>.</p>\n\n<p>Inside loop we have three <code>if</code>s. If we look closely, we'll see that they are mutually exclusive. We will mark it explicitly, so we don't have to guess. If we follow this line of thought, we'll see that every time we don't hit <code>continue</code> inside our <code>if</code> we can safely return from call. So let's invert those conditions too.</p>\n\n<p>What we've now come to?</p>\n\n<pre><code>public static void processLine(Output output, CVB[] cvb, int c)\n{\n var cvbEl = cvb[c];\n Action writeToStringCall = () => writeToString(ref output, ref cvb, c);\n cvbEl.Process(output, writeToStringCall);\n}\n\npublic void Process(Output output, Action writeToStringCall)\n{\n bar.writeLine = null;\n\n //////////convert the tick file into constant volume\n\n if (initialise == false) //dont worry about the first bar, it is bugged, the number can be comeing from anywhere, not just trade\n {\n bar.startTime = output.time;\n bar.open = output.price;\n bar.high = output.price;\n bar.low = output.price;\n initialise = true;\n }\n\n if (output.price > 0 || output.type == \"Volume\")\n {\n switch (output.type)\n {\n case \"Trade\":\n Trade(output, writeToStringCall);\n break;\n case \"Ask\":\n Ask(output);\n break;\n case \"BestAsk\":\n BestAsk(output);\n break;\n case \"Bid\":\n Bid(output);\n break;\n case \"BestBid\":\n BestBid(output);\n break;\n case \"Volume\":\n Volume(output);\n break;\n }\n }\n\n if (info.realtimeChart && output.time > bar.lastPrintTime.AddMilliseconds(info.realtimeChartTimer)) //update the string for the last bar\n {\n bar.validBarWrite = false;\n writeToStringCall();\n }\n\n bar.lastPrintTime = output.time;\n}\n\nprivate void Volume(Output output)\n{\n bar.accVolume = output.volume;\n}\n\nprivate void BestBid(Output output)\n{\n bar.bestBid = output.price;\n RemoveAllBidsGreaterThan(output.price);\n RemoveAllAsksLessThan(output.price);\n\n if (output.volume > 0)\n bid.Add(new Level2(output.price, output.volume));\n}\n\nprivate void Bid(Output output)\n{\n RemoveAllBidsEqualTo(output.price);\n RemoveAllAsksLessThan(output.price);\n\n if (output.volume > 0)\n bid.Add(new Level2(output.price, output.volume));\n}\n\nprivate void BestAsk(Output output)\n{\n bar.bestAsk = output.price;\n RemoveAllBidsGreaterThan(output.price);\n RemoveAllAsksLessThan(output.price);\n\n if (output.volume > 0)\n ask.Add(new Level2(output.price, output.volume));\n}\n\nprivate void Ask(Output output)\n{\n RemoveAllAsksEqualTo(output.price);\n RemoveAllBidsGreaterThan(output.price);\n\n if (output.volume > 0)\n ask.Add(new Level2(output.price, output.volume));\n}\n\nprivate void Trade(Output output, Action writeToStringCall)\n{\n var oldProcessVolume = bar.volume; // use to hold the previous volume, use to calculate the overflow when the CVB limit is reached\n if (output.price > bar.high)\n bar.high = output.price;\n if (output.price < bar.low)\n bar.low = output.price;\n bar.close = output.price;\n\n var bidDistance = output.price - bar.bestBid;\n var askDistance = bar.bestAsk - output.price;\n\n while(true)\n {\n bar.volume = bar.volume + output.volume;\n\n if (bar.bestAsk == 0 && bar.bestBid == 0)\n return;\n\n int temp;\n if (bidDistance - askDistance > Tolerance) //trade closer to ask\n {\n bar.delta = bar.delta + output.volume;\n\n if (output.volume > info.largeSizeLimit)\n {\n temp = largeSize.Where(x => ToleratedEquals(x.price, output.price)).Sum(y => y.size);\n largeSize.RemoveAll(x => ToleratedEquals(x.price, output.price));\n largeSize.Add(new Level2(output.price, temp + output.volume));\n }\n\n if (bar.volume < info.CVBSize)\n return;\n\n output.volume = bar.volume - info.CVBSize;\n bar.delta = bar.delta - output.volume;\n\n temp = ask.Where(x => ToleratedEquals(x.price, output.price)).Sum(yield => yield.size);\n RemoveAllAsksEqualTo(output.price);\n temp = temp - (info.CVBSize - oldProcessVolume);\n bar.accVolume = bar.accVolume + (info.CVBSize - oldProcessVolume);\n\n if (temp > 0)\n ask.Add(new Level2(output.price, temp));\n\n bar.validBarWrite = true;\n writeToStringCall();\n\n continue;\n }\n\n if (askDistance - bidDistance > Tolerance) //trade closer to bid\n {\n bar.delta = bar.delta - output.volume;\n\n if (output.volume > info.largeSizeLimit)\n {\n temp = largeSize.Where(x => ToleratedEquals(x.price, output.price)).Sum(y => y.size);\n largeSize.RemoveAll(x => ToleratedEquals(x.price, output.price));\n largeSize.Add(new Level2(output.price, temp - output.volume));\n }\n\n if (bar.volume < info.CVBSize)\n return;\n\n output.volume = bar.volume - info.CVBSize;\n bar.delta = bar.delta + output.volume;\n\n temp = bid.Where(x => ToleratedEquals(x.price, output.price)).Sum(yield => yield.size);\n RemoveAllBidsEqualTo(output.price);\n temp = temp - (info.CVBSize - oldProcessVolume);\n bar.accVolume = bar.accVolume + (info.CVBSize - oldProcessVolume);\n\n if (temp > 0)\n bid.Add(new Level2(output.price, temp));\n\n bar.validBarWrite = true;\n writeToStringCall();\n\n continue;\n }\n\n if (ToleratedEquals(bidDistance, askDistance))\n {\n if (bar.volume < info.CVBSize)\n return;\n\n output.volume = bar.volume - info.CVBSize;\n bar.accVolume = bar.accVolume + (info.CVBSize - oldProcessVolume);\n\n bar.validBarWrite = true;\n writeToStringCall();\n\n continue;\n }\n return;\n }\n}\n\nprivate static bool ToleratedEquals(double x, double y)\n{\n return Math.Abs(x - y) < Tolerance;\n}\n\nprivate void RemoveAllAsksEqualTo(double outputPrice)\n{\n ask.RemoveAll(x => ToleratedEquals(x.price, outputPrice));\n}\n\nprivate void RemoveAllAsksLessThan(double outputPrice)\n{\n ask.RemoveAll(x => x.price <= outputPrice + Tolerance);\n}\n\nprivate void RemoveAllBidsGreaterThan(double outputPrice)\n{\n bid.RemoveAll(x => x.price >= outputPrice - Tolerance);\n}\n\nprivate void RemoveAllBidsEqualTo(double outputPrice)\n{\n bid.RemoveAll(x => Math.Abs(x.price - outputPrice) < Tolerance);\n}\n</code></pre>\n\n<p>With exception of <code>Trade</code> that still need improvement, and where you can apply same process, it seems to me that we've done pretty good work here.</p>\n\n<p>But I must repeat: with exception of one operation (moving <code>process</code> inside <code>CVB</code> instance) all we've done here is a function-based refactoring. As it's already said here, we might be as well programming in C or JS. I would highly recommend you to rethink your approach into more object-oriented one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T22:59:25.143",
"Id": "22745",
"Score": "0",
"body": "thank you very much, i like to comment on your answer but your answer is too long (a good thing) and not sectioned, maybe i do a follow up thread with your recommendations. i give you the tick for the best answer. thank you"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T20:34:18.227",
"Id": "14059",
"ParentId": "14054",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "14059",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-26T18:39:57.517",
"Id": "14054",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Program for a trading application"
}
|
14054
|
<p>I needed to write a function today in JavaScript that would return all elements based on a given attribute. </p>
<p>e.g retrieve all elements that have an id attribute in them. </p>
<p>The function I wrote for this is as follows:</p>
<pre><code>function getElements(attrib) {
// get all dom elements
var elements = document.getElementsByTagName("*");
// initialize array to put matching elements into
var foundelements = [];
// loop through all elements in document
for (var i = 0; i < elements.length; i++) {
// check to see if element has any attributes
if (elements[i].attributes.length > 0) {
// loop through element's attributes and add it to array if it matches attribute from argument
for (var x = 0; x < elements[i].attributes.length; x++) {
if (elements[i].attributes[x].name === attrib) {
foundelements.push(elements[i]);
}
}
}
}
return foundelements;
}
</code></pre>
<p>Looking at this, I am sure it could be written a great deal better. Any feedback would be much appreciated!</p>
|
[] |
[
{
"body": "<p>I'm not too familiar with JS, so just three generic notes:</p>\n\n<ol>\n<li><p>It seems to me that the <code>elements[i].attributes.length > 0</code> check is unnecessary because the statements inside the following <code>for</code> loop won't if <code>elements[i].attributes.length</code> is zero.</p></li>\n<li><p>Consider creating local variables for <code>elements[i]</code> and <code>elements[i].attributes</code>. It would remove some duplication.</p>\n\n<pre><code>for (var i = 0; i < elements.length; i++) {\n var currentElement = elements[i];\n var currentAttributes = currentElement.attributes;\n for (var x = 0; x < currentAttributes.length; x++) {\n if (currentAttributes[x].name === attrib) {\n foundelements.push(currentElement);\n }\n }\n}\n</code></pre></li>\n<li><p>It might be easier with jQuery: <a href=\"https://stackoverflow.com/q/696968/843804\">find element by attribute</a>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T16:40:35.303",
"Id": "22773",
"Score": "0",
"body": "I didn't realize that the check in your first note was unnecessary, I thought the interpreter might throw an error if it tried to loop something that wasn't an array. Your second note helped make my code more readable. Thank palacint!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T18:07:31.970",
"Id": "22897",
"Score": "0",
"body": "@JohnH `element.attributes` is never an array; it's an array-like object. But even when there are 0 attributes, it is set to an object with a length of 0. So, the first comparison of the loop would return `false` without error."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T01:26:52.143",
"Id": "14062",
"ParentId": "14061",
"Score": "3"
}
},
{
"body": "<h3>querySelectorAll</h3>\n\n<p>First off, if you're only dealing with relatively modern browsers (basically anything above IE7), you can use <a href=\"https://developer.mozilla.org/en/DOM/Document.querySelectorAll\"><code>querySelectorAll</code></a>, which is the fastest and easiest method to go about this:</p>\n\n<pre><code>document.querySelectorAll('[' + attrib + ']');\n</code></pre>\n\n<p>Here's the fiddle: <a href=\"http://jsfiddle.net/rc6Pq/\">http://jsfiddle.net/rc6Pq/</a></p>\n\n<hr>\n\n<h3>Sizzle</h3>\n\n<p>If you're stuck having to support IE7 and below, then you might as well just include the <a href=\"http://sizzlejs.com/\">Sizzle selector engine</a>, since you're bound to be using some additional selectors in the future. Once you include the Sizzle script in your page, you could then just use it in a similar fashion to the native <code>querySelectorAll</code>:</p>\n\n<pre><code>Sizzle('[' + attrib + ']');\n</code></pre>\n\n<p>Here's the fiddle: <a href=\"http://jsfiddle.net/rc6Pq/1/\">http://jsfiddle.net/rc6Pq/1/</a></p>\n\n<hr>\n\n<h3>jQuery</h3>\n\n<p>If you're already using <a href=\"http://jquery.com/\">jQuery</a> on the page, you don't have to use Sizzle separately, since jQuery has Sizzle incorporated within it. If that's the case, just use this:</p>\n\n<pre><code>$('[' + attrib + ']').get();\n</code></pre>\n\n<p>Here's the fiddle: <a href=\"http://jsfiddle.net/rc6Pq/2/\">http://jsfiddle.net/rc6Pq/2/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T16:36:41.423",
"Id": "22772",
"Score": "0",
"body": "This helped a great deal Joseph, thank you for your input!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T02:48:42.983",
"Id": "14063",
"ParentId": "14061",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "14063",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T01:06:24.087",
"Id": "14061",
"Score": "8",
"Tags": [
"javascript",
"dom"
],
"Title": "JavaScript function to get DOM elements by any attribute"
}
|
14061
|
<p>Is large use of closures actually a bad thing for readability and maintainability of the code? For example, consider the following code with (comments removed on purpose):</p>
<pre><code>$withMobile = function($c) { return $c->getMobile() !== null; };
$extractAll = function($c) { return $c; };
$extractId = function($c) { return $c->getId(); };
$allUniqueCustomers = $data->customers->filter($withMobile)->map($extractAll);
$customersIds = $allUniqueCustomers->filter($withMobile)->map($extractId)->toArray();
$isNew = function($c) use($customersIds) { return !in_array($c->getId(), $customersIds); };
foreach($data->tags as $tag) :
foreach($tag->getCustomers()->filter($isNew)->filter($withMobile) as $newCustomer) :
$allUniqueCustomers->add($newCustomer);
endforeach;
endforeach;
$sanitize = function($m) { return preg_replace("/^(\+|00)/", '', $m); };
$extractMobile = function($c) use($sanitize) { return $sanitize($c->getMobile()); };
// Unique sanitized phone numbers of customers merged with customers from tags
$customersMobiles = $allUniqueCustomers->map($extractMobile);
</code></pre>
<p>It looks good to me. But i love closures.</p>
<p>Would you consider this a nightmare to maintain and change in future in respect of traditional more verbose programming with loops?</p>
|
[] |
[
{
"body": "<p>It's not that bad β one can quickly grasp what it is doing and where is it going, which should be good news. I would personally recommend however the following when dealing with closures:</p>\n\n<ul>\n<li>If the closure is only to be used once, hardcode it into the arguments. That way it's a bit easier to follow, since the logic of the closure is right there to be read instead of having to track down the variable to see what it does.</li>\n<li>If the closure is to be used multiple times, consider rewriting it into a \"full blown\" function of the application instead, it will be easier to follow since the function is not being created on the fly and easier to maintain since it's part of the official API, so to speak.</li>\n</ul>\n\n<p>Here's the possible alternative I would suggest:</p>\n\n<pre><code>$allUniqueCustomers = $data->customers->filter(\n function($c) { \n //Filter by mobile\n return $c->getMobile() !== null; \n }\n )\n ->map(\n function($c) { \n //Get all\n return $c; \n }\n );\n\n\n$customersIds = $allUniqueCustomers->filter(\n function($c) { \n //Filter by mobile\n return $c->getMobile() !== null; \n }\n )\n ->map(\n function($c) { \n //Extract by id\n return $c->getId(); \n }\n )\n ->toArray();\n\nforeach($data->tags as $tag) :\n $newCustomers = $tag->getCustomers()->filter(\n function($c) use($customersIds) { \n //Filter by new customers with mobile\n return ((!in_array($c->getId(), $customersIds)) && ($c->getMobile() !== null)); \n }\n );\n\n foreach($newCustomers as $newCustomer) :\n $allUniqueCustomers->add($newCustomer);\n endforeach;\n\nendforeach;\n\n// Unique sanitized phone numbers of customers merged with customers from tags\n$customersMobiles = $allUniqueCustomers->map(\n function($c) { \n //Get mobile and sanitize\n return preg_replace(\"/^(\\+|00)/\", '', $c->getMobile());\n }\n );\n</code></pre>\n\n<p>I would also advise against using the <a href=\"http://php.net/manual/en/control-structures.alternative-syntax.php\" rel=\"nofollow\">alternative syntax</a> you have on the foreach in your application logic and save it for exclusively templating/mixing html with php only, but I left it there untouched since I suppose that's a matter of taste.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T02:55:06.977",
"Id": "22791",
"Score": "0",
"body": "Thanks, good answer. The only bad thing with hardcoding into arguments is the indentation. Pretty ugly :/ but anyway, thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T02:57:24.423",
"Id": "22792",
"Score": "0",
"body": "Yeah, lots of white space, it does seem messier at first, but one grows to like it. I think it's easier to read in any case."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T02:34:50.647",
"Id": "14092",
"ParentId": "14064",
"Score": "0"
}
},
{
"body": "<p>Lambda/anonymous functions and closures are not sophisticated enough in PHP to really be reliable at this moment, and probably wont be any time soon, if ever. They are usually too bulky to be worthwhile and typically can be replaced with a normal function or loop and be easier to read and quicker to process.</p>\n\n<p>The most common way to use a lambda function, and about the only way I find acceptable, is as a callback function, which is typically called in line. But that's a matter or preference. There are other cases where they are acceptable, but, as traditional closures as seen in other languages, they fall short.</p>\n\n<p>If you are planning on using a lambda function or closure more than once, then you have just defeated their purpose. As Mahn pointed out, these functions are not compiled at runtime, instead they are compiled on each use. This makes running them costly. At this point you might as well have just created a traditional function. Which, by the way, is essentially what you are doing anyways by defining them as variables before using them, only backwards. The only difference is that you are running that function twice instead of once and defining it for use in the local scope only, which is the same thing as defining a function within another function, which most people consider bad taste.</p>\n\n<p>While these examples can be followed easily enough, I don't think that makes true usages \"easy\" to read. Sure you can figure out what's going on, but the longer they are the more difficult it becomes.</p>\n\n<p>Would I consider this a nightmare? No. Would I thank you for doing this? No. In my opinion it is much better to follow a sequence of functions than read through a list of lambda functions. And no offense to Mahn, but his I would find a nightmare trying to maintain. Mostly due to his indentations though...</p>\n\n<p>Also, as Mahn pointed out, why are you declaring your foreach loops that way? Traditionally that format is only used in templates.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T21:03:53.987",
"Id": "22936",
"Score": "0",
"body": "Thanks. Got it. About foreach... yes i know it's used mainly with HTML (i'm using a template engine btw). Dunno, sometimes i write it that way..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T21:12:06.420",
"Id": "22938",
"Score": "0",
"body": "@Gremo: Well, as long as your consistent. Just figured I'd let you know it looked odd in that context :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T21:27:04.283",
"Id": "22941",
"Score": "0",
"body": "Legit question :) to me it seems more clean where the foreach loop ends (same as `endif;`). Isn't it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T22:16:48.443",
"Id": "22944",
"Score": "0",
"body": "@Gremo: Sure is"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T20:05:28.257",
"Id": "14176",
"ParentId": "14064",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14176",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T03:34:09.347",
"Id": "14064",
"Score": "3",
"Tags": [
"php"
],
"Title": "Closures power and concise style vs readability and maintainability?"
}
|
14064
|
<p>I've been working on a simple program to output values to the console as a learning project, and I stumbled across an article advising against using 2D containers, suggesting to simulate them instead with a 1D vector/container. I immediately proceeded to try to create a ridiculous class that converted input X and Y values into the correct position in the class's vector member. This class had a lot of redundant code, and eventually I realized that I was losing the value of the simplicity of the container having only one dimension by requiring two dimensions to input into the container. Instead I decided to move that math to other functions and just take a single input into the vector inside the class. </p>
<p>The following code is an attempt at a SimpleContainer class. I realize that I am reinventing the wheel here, but this is just a project to aid the learning process for me. I'm trying to learn C++ best practices, and things like good code layout and readability. I know that this class is missing some important optimization and features, and I think I'm doing unnecessary copying, but it would be very helpful for me to have a breakdown of what I'm doing right and wrong. This is also my first experience with using templates, but thankfully the code compiles, so I think I'm doing it right. </p>
<pre><code>#include <iostream> //Needed for std::cout and std::endl
#include <vector> //Needed for std::vector and others
//These values are arbitrary and are only used when computing the
//screen size for things like memory allocation for the Container
#define CONSOLEWIDTH 80;
#define CONSOLEHEIGHT 25;
//The purpose of this class is to have an easy way to input variables and objects into a container,
//sometimes a large number of them at a time, and then retrieve and print them easily as well.
//Templating the class allows the input and printing of ints and chars very easily
//You could input objects, but some of the functions may not work with the code as written
template <class myType>
class SimpleContainer
{
public:
//I think there are other ways to do the following but I don't know them
SimpleContainer(int containerSize, myType defaultValue)
{
classVector.resize(containerSize);
for(int i = 0; i < containerSize; i++)
{
classVector[i] = defaultValue;
}
}
//Simply looks at the classVector size and returns (used for iterating over it)
int getSize();
//The setValue function sets the value at specified container position
void setValue(int containerPosition, myType inputValue);
//I feel like I'm missing a reference here but <myType>& threw an error
void inputEntireVector(std::vector<myType> inputVector);
//You have to compute the X and Y positions outside of this function if you want
//to simulate a 2D matrix
myType getValue (int containerPosition);
//Prints the entire contents of the container starting from vector.begin()
//I think this will only work with ints and chars, and with ints over 9 it will
//mess up the alignment of the console view
void printContainer();
private:
std::vector<myType> classVector;
};
template<class myType>
int SimpleContainer<myType>::getSize()
{
return classVector.size();
}
template<class myType>
void SimpleContainer<myType>::setValue(int containerPosition, myType inputValue)
{
classVector.erase(classVector.begin() + containerPosition);
//vector.insert() takes for its third argument a value for the number of times to
//insert the input value
int numInputCopies = 1;
classVector.insert(classVector.begin() + containerPosition, numInputCopies, inputValue);
}
template<class myType>
void SimpleContainer<myType>::inputEntireVector(std::vector<myType> inputVector)
{
classVector.swap(inputVector);
}
template<class myType>
myType SimpleContainer<myType>::getValue(int containerPosition)
{
return classVector[containerPosition];
}
template<class myType>
void SimpleContainer<myType>::printContainer()
{
for(int i = 0; i < classVector.size(); i++)
{
std::cout << classVector[i];
}
}
//Runs some basic interactions with the Container
void sampleContainerInterfacing();
int main()
{
sampleContainerInterfacing();
return 0;
}
void sampleContainerInterfacing()
{
//Setting integers for the view width and height to input into Container
//Uses them immediately to do the math to figure out Container size
int width = CONSOLEWIDTH;
int height = CONSOLEHEIGHT;
int containerSize = width*height;
SimpleContainer<int> mySimpleContainer(containerSize, 0);
//Outputs one console screen worth of 0's
mySimpleContainer.printContainer();
std::cout << mySimpleContainer.getSize() << std::endl;
//Defining these variables to aid readability of the 2D matrix math
int position;
int posY = 5;
int posX = 7;
//The position in the container equals the width * the desired y position
//plus the desired x position, -1 because it starts counting with 0
position = width * posY + posX - 1;
mySimpleContainer.setValue(position, 5);
std::cout << mySimpleContainer.getValue(position) << std::endl;
//Now contains the input variable
mySimpleContainer.printContainer();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T16:59:43.663",
"Id": "22774",
"Score": "0",
"body": "If you are simulating a 2D vector with a 1D vector, you should still be able to use the 2D syntax `m[1][1]`."
}
] |
[
{
"body": "<h3>Simple Review of code</h3>\n\n<p>In this pass I will do a simple review of the code you have written.<br>\nI think there are some problems with the design of your interface but I will deal with those completely separately so this part of the review is solely on the code you have written and assumes that the interface is good.</p>\n\n<p>You don't need to comment why you are including header files.</p>\n\n<pre><code>#include <iostream> //Needed for std::cout and std::endl\n#include <vector> //Needed for std::vector and others\n</code></pre>\n\n<p>Don't use macros.</p>\n\n<pre><code>#define CONSOLEWIDTH 80;\n#define CONSOLEHEIGHT 25;\n</code></pre>\n\n<p>These macros have no scope (are all scope depending on how you look at it). Thus you are polluting the namespace. It would be preferable to use <code>int const</code> value. Personally I would make them <code>static</code> members of the class. This allows you to define them inline.</p>\n\n<pre><code>class sampleContainerInterfacing\n{\n static int const ConsoleWidth = 80;\n static int const ConsoleHeight = 25;\n</code></pre>\n\n<p>The vector already has a constructor that initializes all values:<br>\n<a href=\"http://www.sgi.com/tech/stl/Vector.html\" rel=\"nofollow\">http://www.sgi.com/tech/stl/Vector.html</a></p>\n\n<p>Also note sizes are usually defined via <code>std::size_t</code> as this can never be negative.</p>\n\n<pre><code> //I think there are other ways to do the following but I don't know them\n SimpleContainer(int containerSize, myType defaultValue)\n {\n classVector.resize(containerSize);\n\n for(int i = 0; i < containerSize; i++)\n {\n classVector[i] = defaultValue;\n }\n }\n</code></pre>\n\n<p>Try this:</p>\n\n<pre><code> SimpleContainer(std::size_t size, myType defaultValue)\n : classVector(size, defaultValue)\n {}\n</code></pre>\n\n<p>This function is simple enough that I would inline it.</p>\n\n<pre><code> int getSize();\n</code></pre>\n\n<p>Same comment as constructor. Use std::size_t to indicate a position in the container. </p>\n\n<pre><code> void setValue(int containerPosition, myType inputValue);\n</code></pre>\n\n<p>I am not sure I agree with your implementation of setValue(). The call to erase() removes tha value from the array. This will cause the vector to copy all the elements (above <code>containerPosition</code>) down one position (that could be a huge number of copies if the type is not a POD. Then you insert a value back into the location which causes all the elements (from <code>containerPosition</code>) to copied back up 1 position.</p>\n\n<pre><code>template<class myType>\nvoid SimpleContainer<myType>::setValue(int containerPosition, myType inputValue)\n{\n classVector.erase(classVector.begin() + containerPosition);\n\n //vector.insert() takes for its third argument a value for the number of times to\n //insert the input value\n int numInputCopies = 1;\n classVector.insert(classVector.begin() + containerPosition, numInputCopies, inputValue);\n}\n</code></pre>\n\n<p>Personally I would just overwrite the value in the container:</p>\n\n<pre><code>void setValue(int containerPosition, myType inputValue) {classVector[containerPosition] = inputValue;}\n</code></pre>\n\n<p>Personally I would also pass by (const) reference. The error was probably caused because you did not match the declaration and definition (ie you needed to add the <code>&</code> to both locations).</p>\n\n<pre><code> //I feel like I'm missing a reference here but <myType>& threw an error\n template<class myType>\n void SimpleContainer<myType>::inputEntireVector(std::vector<myType> inputVector)\n {\n classVector.swap(inputVector);\n }\n</code></pre>\n\n<p>But you are using swap() on the internal array (which is a valid technique) but requires you to make the copy first so that you don't destroy the original array. What it comes down to is that you need to copy the values from the input into the array. There are two ways to do this.</p>\n\n<ul>\n<li>Assignment: (Pass parameter by const reference then use assignment)</li>\n<li>Copy and Swap: (Pass parameter by value (thus doing an implicit copy) then call swap()</li>\n</ul>\n\n<p>Same comment as above: Parameter should be std::size_t and its simple enough to put inline.</p>\n\n<pre><code> //You have to compute the X and Y positions outside of this function if you want\n //to simulate a 2D matrix\n myType getValue (int containerPosition);\n</code></pre>\n\n<p>Sure: This is fine. But I would pass the stream the the values are printed on as a parameter (thus you are not hard coding it to std::cout).</p>\n\n<pre><code> //Prints the entire contents of the container starting from vector.begin()\n //I think this will only work with ints and chars, and with ints over 9 it will\n //mess up the alignment of the console view\ntemplate<class myType>\nvoid SimpleContainer<myType>::printContainer()\n{\n for(int i = 0; i < classVector.size(); i++)\n {\n std::cout << classVector[i]; // Note no space between elements.\n }\n}\n</code></pre>\n\n<p>But if you are going to do that then you should also provide an overload of <code>operator<<(std::ostream& stream, SimpleContainer& data)</code> that calls this method.</p>\n\n<p>Traditionally it is more usual to provide iterators that allow the user to control how much of the array they want to print. Then you can copy the whole array with:</p>\n\n<pre><code>std::copy(con.begin(), con.end(), std::ostream_iterator<type>(std::cout, \", \"));\n</code></pre>\n\n<p>Thus I would write the print like this:</p>\n\n<pre><code>template<class myType>\ninline void SimpleContainer<myType>::printContainer(std::ostream& stream)\n{\n for(int i = 0; i < classVector.size(); i++)\n {\n stream << classVector[i]; // Note no space between elements (like original)\n }\n // Or you can use std::copy()\n // std::copy(classVector.begin(), classVector.end(),\n // std::ostream_iterator<type>(stream, \"\"/*No Space*/));\n}\n\ntemplate<class myType>\ninline std::ostream& operator<<(std::ostream& stream, impleContainer<myType> const& data)\n{\n data.printContainer(stream);\n return stream;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T10:55:42.437",
"Id": "22868",
"Score": "0",
"body": "This post was very helpful, thank you! I didn't realize a couple of things until reading your post. First that vector::erase made copies of the information, and second, that you can define static values inline in classes. I appreciate your time looking at my code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T17:33:17.473",
"Id": "14081",
"ParentId": "14065",
"Score": "3"
}
},
{
"body": "<h3>Interface:</h3>\n<p>Even though you are implementing the 2D array as a large 1D array. The user of the array is still expecting to be able to index into the array using the normal array notation.</p>\n<pre><code> Matrix m(2,3); // 2D array size 2,3 (default constructed).\n\n m[1][2] = 4;\n</code></pre>\n<p>You do not want to move the calculation of the position outside the container. If you do this you are exposing implementation details of how the container is built and requiring the user to understand things about the layout of your container. This binds your hands for future modifications and thus breaks encapsulation.</p>\n<p>It is technically possible to use the [] to do this. But it is not obvious for beginners (as <code>operator[]</code> can only take 1 parameter) and thus we will use () to simulate the 2D accesses (as this makes the code easier to write).</p>\n<pre><code>// The usage of the code will look like this.\n// It is not a massive change and people will understand it easily.\n// Also the user of the array does not need to know how it is layed out.\nm(1,2) = 4;\n</code></pre>\n<p>So your first pass of the interface should look like this:</p>\n<pre><code>template <class myType>\nclass SimpleContainer\n{\n std::vector<myType> data;\n std::size_t xSize;\n std::size_t ySize;\n public:\n SimpleContainer(std::size_t xs, std::size_t ys, myType const& defaultValue = myType())\n : data(xs * ys, defaultValue)\n , xSize(xs)\n , ySize(ys)\n {}\n\n myType& operator()(std::size_t x, std::size_t y) {return data[y*xSize + x];}\n myType const& operator()(std::size_t x, std::size_t y) const {return data[y*xSize + x];}\n};\n</code></pre>\n<p>Notice I have written two versions of <code>operator()</code>. Both return references to the internal members but one version returns a const reference and is also marked as const.</p>\n<p>The normal version:</p>\n<pre><code> myType& operator()(std::size_t x, std::size_t y)\n</code></pre>\n<p>Allows read/write access to the elements in the array. Because it returns a reference any mutations I do to this object will be reflected in the container copy.</p>\n<pre><code>m(4,5) = 6; // Will modify the container version to be 6\n</code></pre>\n<p>The const version:</p>\n<pre><code>myType const& operator()(std::size_t x, std::size_t y) const\n</code></pre>\n<p>Allows read only access to the object. This is useful as it allows you to pass your container as a const reference to functions and still access the data. And the compiler will guarantee that the access to the data does not modify it.</p>\n<p>If you want to add the ability to do <code>m[1][2]</code> to your container then read this article: <a href=\"https://stackoverflow.com/questions/3755111/how-do-i-define-a-double-brackets-double-iterator-operator-similar-to-vector-of/3755221#3755221\">https://stackoverflow.com/questions/3755111/how-do-i-define-a-double-brackets-double-iterator-operator-similar-to-vector-of/3755221#3755221</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T10:54:07.773",
"Id": "22867",
"Score": "0",
"body": "Thank you. This was very succinct and completely explained the logical failure on my part. Also as a result of your post, I now understand operator overloading in classes in C++ which hadn't really clicked before. Much appreciated!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T17:50:13.147",
"Id": "14082",
"ParentId": "14065",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "14082",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T03:34:39.903",
"Id": "14065",
"Score": "2",
"Tags": [
"c++",
"template",
"vectors",
"container"
],
"Title": "Simple container class with templates"
}
|
14065
|
<p>I needed to IP block something in nginx and I ended up with duplicated <code>proxy_forward</code> code. How can I refactor and un-duplicate this?</p>
<pre><code>server{
location /admin{
allow 123.90.250.0/24;
allow 123.66.148.0/24;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://foo;
}
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://foo;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You may move proxy settings to 'server' block. But proxy_pass should stay at 'location' block</p>\n\n<pre><code>upstream foo {\n server 127.0.0.1:8080;\n}\n\nserver{\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header Host $http_host;\n proxy_redirect off;\n\n location /admin {\n allow 123.90.250.0/24;\n allow 123.66.148.0/24;\n proxy_pass http://foo;\n }\n\n location / {\n proxy_pass http://foo;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T09:24:33.933",
"Id": "14069",
"ParentId": "14066",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14069",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T03:45:03.713",
"Id": "14066",
"Score": "2",
"Tags": [
"nginx"
],
"Title": "Unduplicating prox_pass in nginx location blocks"
}
|
14066
|
<p>I need to define custom calendars and, in particular, test a <code>DateTime</code> for being a holiday. My current code is shown below. Is there a more concise/better way of doing this, preferably without sacrificing performance?</p>
<pre><code>let private isHoliday2011 (dt:DateTime) =
match dt.DayOfWeek with
| DayOfWeek.Saturday | DayOfWeek.Sunday ->
match (dt.Month, dt.Day) with
| (3,5) -> false
| _ -> true
| _ ->
match dt.Month with
| 1 ->
match dt.Day with
| 3 | 4 | 5 | 6 | 7 | 10 -> true
| _ -> false
| 2 ->
match dt.Day with
| 23 -> true
| _ -> false
| 3 ->
match dt.Day with
| 7 | 8 -> true
| _ -> false
| 5 ->
match dt.Day with
| 2 | 9 -> true
| _ -> false
| 6 ->
match dt.Day with
| 13 -> true
| _ -> false
| 11 ->
match dt.Day with
| 4 -> true
| _ -> false
| _ -> false
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T17:38:01.167",
"Id": "22775",
"Score": "0",
"body": "I think your code is as good as it gets. All the other answers involving data structures sacrifice performance for no real gain in clarity. To tweak your code for clarity, you could try merging match statements, this should not have any performance effects, e.g. https://gist.github.com/3189294"
}
] |
[
{
"body": "<p>I think using a list would be better - something like</p>\n\n<pre><code>let holidays = (1,3)::(1,4)::...\nlet isHoliday2011 (dt:DateTime) =\n let d,m = dt.Month, dt.Day\n holidays |> List.exists (fun (mm,dd) -> m=mm && d=dd)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T10:06:58.347",
"Id": "14071",
"ParentId": "14070",
"Score": "1"
}
},
{
"body": "<p>If you need to check for holidays repeatedly, I would go for <a href=\"http://msdn.microsoft.com/en-us/library/ee353619.aspx\" rel=\"nofollow\">Set</a> and flatten pattern matching blocks for readability:</p>\n\n<pre><code>let holidays = set [ 1, 3; 1, 4; 1, 5; 1, 6; 1, 7; 1, 10 // month, day\n 2, 23\n 3, 7; 3, 8\n 5, 2; 5, 9\n 6, 13\n 11, 4\n ]\n\nlet private isHoliday2011 (dt: DateTime) =\n match dt.DayOfWeek, dt.Month, dt.Day with\n | DayOfWeek.Saturday, m, d | DayOfWeek.Sunday, m, d -> m <> 3 || d <> 5 \n | _, m, d -> Set.contains (m, d) holidays\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T16:14:59.467",
"Id": "22771",
"Score": "0",
"body": "+1 `DayOfWeek.Saturday, m, d | DayOfWeek.Sunday, m, d` could be shortened (slightly) to `(DayOfWeek.Saturday | DayOfWeek.Sunday), m, d`. No need to bind `m` and `d` on both sides of `|`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T11:05:37.093",
"Id": "14072",
"ParentId": "14070",
"Score": "2"
}
},
{
"body": "<p>I think the fastest, cleanest way you could check a large number of dates would be to memoize your date-checking function using a HashSet. Using <code>HashSet<T></code> instead of the F# <code>set</code> is a better choice here because lookup is <code>O(1)</code> instead of <code>O(log n)</code> -- and you don't have to worry about mutability because the <code>HashSet</code> is never updated after it's created.</p>\n\n<pre><code>let isHoliday2011Memo =\n let holidays2011 =\n let jan1 = System.DateTime (2011, 1, 1)\n [| for i = 0 to 364 do\n yield jan1.AddDays <| float i |]\n |> Array.choose (fun day ->\n if isHoliday2011 day then\n Some day.DayOfYear\n else None)\n\n let holidayDaysOf2011 = System.Collections.Generic.HashSet<_> (holidays2011)\n\n fun (dt : DateTime) ->\n holidayDaysOf2011.Contains <| dt.DayOfYear\n</code></pre>\n\n<p>For even more speed, you could pre-compute the dates (using your function) -- and it means you don't need to include your date-computing function in your release code, because dates won't be calculated at run-time:</p>\n\n<pre><code>let isHoliday2011Precomputed =\n let holidayDaysOf2011 =\n System.Collections.Generic.HashSet<_> (\n [|1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 15; 16; 22; 23; 29; 30; 36; 37; 43; 44; 50;\n 51; 54; 57; 58; 65; 66; 67; 71; 72; 78; 79; 85; 86; 92; 93; 99; 100; 106;\n 107; 113; 114; 120; 121; 122; 127; 128; 129; 134; 135; 141; 142; 148; 149;\n 155; 156; 162; 163; 164; 169; 170; 176; 177; 183; 184; 190; 191; 197; 198;\n 204; 205; 211; 212; 218; 219; 225; 226; 232; 233; 239; 240; 246; 247; 253;\n 254; 260; 261; 267; 268; 274; 275; 281; 282; 288; 289; 295; 296; 302; 303;\n 308; 309; 310; 316; 317; 323; 324; 330; 331; 337; 338; 344; 345; 351; 352; 358;\n 359; 365; |])\n\n fun (dt : DateTime) ->\n holidayDaysOf2011.Contains <| dt.DayOfYear\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T14:20:07.523",
"Id": "14078",
"ParentId": "14070",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T09:41:16.837",
"Id": "14070",
"Score": "2",
"Tags": [
"algorithm",
"f#"
],
"Title": "Is there a better way of defining custom calendars?"
}
|
14070
|
<p>I have a set of <code>if</code>/<code>else</code> statements that trigger certain actions. As a first step, I was thinking about moving the logic in each <code>if</code> statement to be its own function, but are there any recommendations on what design patterns can help clean this code up?</p>
<p>I guess I am trying to see if there is a cleaner way to determine what the next action/command should be based on a set of criteria. I see people recommend the Command pattern, but how does one abstract the logic in the <code>if</code>-statement to begin with?</p>
<pre><code>function WaterRetriever(largeBucketSize, smallBucketSize, waterSize) {
var buckets = {};
if (waterSize > largeBucketSize) {
throw new Error("The buckets are not large enough.");
}
buckets.firstContainer = new Bucket(largeBucketSize);
buckets.secondContainer = new Bucket(smallBucketSize);
this.getWaterFromLake = function () {
var maxSteps = 25,
step = 1;
buckets.firstContainer.fill();
while (step <= maxSteps && buckets.firstContainer.getCurrentAmount() !== waterSize) {
if (buckets.firstContainer.isFull() && buckets.secondContainer.isEmpty()) {
buckets.firstContainer.transferTo(buckets.secondContainer);
} else if (buckets.secondContainer.isFull() && buckets.firstContainer.hasCapacityAvailable()) {
buckets.secondContainer.empty();
buckets.firstContainer.transferTo(buckets.secondContainer);
} else if (buckets.firstContainer.isEmpty() && buckets.secondContainer.hasCapacityAvailable()) {
buckets.firstContainer.fill();
} else if (buckets.firstContainer.isFull() && buckets.secondContainer.hasCapacityAvailable()) {
buckets.firstContainer.transferTo(buckets.secondContainer);
}
console.log(buckets.firstContainer.getCurrentAmount() + ", " + buckets.secondContainer.getCurrentAmount());
step = step + 1;
}
if (step > maxSteps) {
console.log("could not find a solution within the steps limit...");
}
};
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T03:41:03.960",
"Id": "22758",
"Score": "0",
"body": "Have a look at [The Clean Code Talks](http://www.youtube.com/watch?v=4F72VULWFvc)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T03:42:03.233",
"Id": "22759",
"Score": "0",
"body": "I'm not quite sure what the end goal is, but how about keeping an `Array` of buckets and just looping through until you find two you can transfer between?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T03:42:18.293",
"Id": "22760",
"Score": "0",
"body": "Does this one answer your question - http://stackoverflow.com/questions/4168285/refactor-if-statement-to-use-appropriate-pattern"
}
] |
[
{
"body": "<p>In this case, in every step you could do:</p>\n\n<pre><code>buckets.secondContainer.empty();\nbuckets.firstContainer.transferTo(buckets.secondContainer);\nbuckets.firstContainer.fill();\n</code></pre>\n\n<p>Then inside each function you could test if there is anything to do and if not, return.</p>\n\n<pre><code>void Empty()\n{\n if(this.isEmpty()) return;\n ...\n}\nvoid TransferTo(Bucket dest)\n{\n if(this.isEmpty() || dest.isFull()) return;\n ...\n}\nvoid Fill()\n{\n if(this.isFull()) return;\n}\n</code></pre>\n\n<p>That should give you the same behaviour without all the if/elses. The checks could also be performed in the main loop but I assume you are already checking for them inside the functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T04:27:14.077",
"Id": "14074",
"ParentId": "14073",
"Score": "0"
}
},
{
"body": "<p>I found your conditions to be a little confusing. It was hard for me to understand the rules of what is going on by just a quick glance. In this simple case, you don't necessarily need to create more abstraction, just be more clear about presenting the rules.</p>\n\n<p>One way to make your code more readable is to try and avoid an if/else maze if a series of ifs could suffice instead. There's a certain amount of personal preference to that, however, when there are many if/else's, your brain has to stack up and keep track of all the previous conditions. It's better to check a condition, then handle it immediately and return to a higher scope instead of nesting further. By not nesting further, you can \"forget\" about it and simply move on to the next condition.</p>\n\n<p>A trivial example example:</p>\n\n<pre><code>function describeHeight(person) {\n var height = person.height;\n if (height < 4) {\n console.log('short');\n }\n else if (height >= 4 && height < 6) {\n console.log('average');\n }\n else if (height >= 6 && height < 8) {\n console.log('tall');\n }\n else {\n console.log('giant!!!');\n }\n}\n</code></pre>\n\n<p>Versus:</p>\n\n<pre><code>function describeHeight(person) {\n var height = person.height;\n if (height >= 8) {\n console.log('giant!!!');\n return;\n }\n if (height >= 6) {\n console.log('tall');\n return;\n }\n if (height >= 4) {\n console.log('average');\n return;\n }\n console.log('short');\n}\n</code></pre>\n\n<p>Not the best example, perhaps. But I feel like the second version is easier to read. See how the first example has more nesting, and the second has less?</p>\n\n<p>In your example, I would try to simplify the rules. The logic may not be correct here, because I don't exactly understand your rules, but something like this may be easier to read:</p>\n\n<pre><code>while (step++ <= maxSteps) {\n // Check if container has the appropriate amount of water.\n if (buckets.firstContainer.getCurrentAmount() === waterSize) {\n break;\n }\n\n // If first container is empty, then fill it.\n if (buckets.firstContainer.isEmpty()) {\n buckets.firstContainer.fill();\n continue;\n }\n\n // If first container is full, fill up the second container if there's room.\n if (buckets.firstContainer.isFull() && buckets.secondContainer.hasCapacityAvailable()) {\n buckets.firstContainer.transferTo(buckets.secondContainer);\n continue;\n }\n\n // If second container is full, dump it out, and try to fill up the first container if there's room.\n if (buckets.secondContainer.isFull() && buckets.firstContainer.hasCapacityAvailable()) {\n buckets.secondContainer.empty();\n buckets.firstContainer.transferTo(buckets.secondContainer);\n continue;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T14:12:33.077",
"Id": "22767",
"Score": "0",
"body": "+1 good sample - clean === `if (buckets.firstContainer.getCurrentAmount() === waterSize) {`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T19:53:04.267",
"Id": "22780",
"Score": "0",
"body": "+1 as well... I updated my code to use a series of IF statements instead of if/else. Like you mentioned, it's a small thing and can be subjective, but I agree that it makes a difference."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T04:32:08.597",
"Id": "14075",
"ParentId": "14073",
"Score": "3"
}
},
{
"body": "<p>I created an action handler class that just executes the next step.. It may be overkill, but this project is for learning purposes anyway...</p>\n\n<p>Would something like this be more readable than my original code?</p>\n\n<pre><code>function calculateSteps() {\n var maxSteps = 100,\n step = 1;\n\n while (step <= maxSteps && !isCalculationDone()) {\n bucketActionHandler.executeNextStep();\n createSnapshot();\n step = step + 1;\n\n }\n\n if (step > maxSteps) {\n console.log(\"could not find a solution within the steps limit...\");\n }\n amplify.publish(events.calculationCompleted, snapshots);\n\n}\n\nfunction BucketActionHandler(containers, size) {\n var buckets = containers,\n waterSize = size,\n waterSizeSmallContainerOffset = waterSize - containers.secondContainer.getCurrentAmount();\n\n function shouldFinalRetrievalByDumpingExtra() {\n return buckets.firstContainer.getCurrentAmount() === waterSize && buckets.secondContainer.isFull();\n }\n\n function shouldTransferToSmallBucket() {\n return buckets.firstContainer.isFull() && !buckets.secondContainer.isFull();\n }\n\n function shouldFillLargeContainer() {\n return buckets.firstContainer.isEmpty() && buckets.secondContainer.hasCapacityAvailable();\n }\n\n function firstContainerTargetOffsetReached() {\n return buckets.firstContainer.getCurrentAmount() === waterSizeSmallContainerOffset;\n }\n\n function shouldTransferFromLargeToSmallBucket() {\n return buckets.secondContainer.isFull() && buckets.firstContainer.hasCapacityAvailable();\n }\n\n this.executeNextStep = function () {\n if (shouldTransferToSmallBucket()) {\n buckets.firstContainer.transferTo(buckets.secondContainer);\n return;\n }\n\n if (shouldFinalRetrievalByDumpingExtra()) {\n buckets.secondContainer.empty();\n return;\n }\n\n if (shouldFillLargeContainer()) {\n buckets.firstContainer.fill();\n return;\n }\n\n\n if (firstContainerTargetOffsetReached && buckets.secondContainer.isEmpty()) {\n buckets.secondContainer.fill();\n return;\n }\n\n if (firstContainerTargetOffsetReached() && buckets.secondContainer.isFull()) {\n buckets.secondContainer.transferTo(buckets.firstContainer);\n return;\n }\n\n if (shouldTransferFromLargeToSmallBucket()) {\n buckets.secondContainer.empty();\n buckets.firstContainer.transferTo(buckets.secondContainer);\n return;\n }\n };\n buckets.firstContainer.fill();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T19:56:16.417",
"Id": "14087",
"ParentId": "14073",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T03:39:05.743",
"Id": "14073",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Finding a way to obtain some volume of water using a large and small bucket"
}
|
14073
|
<p>I have following model and database created using Entity Framework. Is it proper TPT Inheritance?</p>
<p>Is it possible to make the base class as <strong>abstract</strong>?</p>
<p>Model</p>
<p><img src="https://i.stack.imgur.com/ecczh.jpg" alt="enter image description here"></p>
<p>Database</p>
<p><img src="https://i.stack.imgur.com/bO6ak.jpg" alt="enter image description here"></p>
<p>CODE</p>
<pre><code>namespace LijosEF
{
public partial class Book
{
public override void Sell()
{
this.AvailabilityStatus = "BookSOLD";
}
}
public partial class DigitalDisc
{
public override void Sell()
{
this.AvailabilityStatus = "DiscSOLD";
}
}
public partial class SellingItem
{
public virtual void Sell()
{
//Do nothing
}
}
}
</code></pre>
<p>Client</p>
<pre><code>namespace LijosEF
{
class Program
{
static string connectionStringVal;
static void Main(string[] args)
{
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = ".";
sqlBuilder.InitialCatalog = "LibraryReservationSystem";
sqlBuilder.IntegratedSecurity = true;
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = "System.Data.SqlClient";
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
entityBuilder.Metadata = @"res://*/MyModelFirstTest.csdl|res://*/MyModelFirstTest.ssdl|res://*/MyModelFirstTest.msl";
connectionStringVal = entityBuilder.ToString();
//AddBook();
//AddDisc();
//MakePurchase();
int billAmount = GetTotalPurchaseValue(1);
}
private static void AddBook()
{
using (var db = new MyModelFirstTestContainer(connectionStringVal))
{
Book book = new Book();
book.AvailabilityStatus = "Available";
book.Price = 150;
book.Title = "Maths Easy";
db.SellingItems.AddObject(book);
db.SaveChanges();
}
}
private static void MakePurchase()
{
using (var db = new MyModelFirstTestContainer(connectionStringVal))
{
DigitalDisc disc = db.SellingItems.OfType<DigitalDisc>().FirstOrDefault(p => p.Artist == "Turtle Violin");
disc.Sell(); //Changes State
Book book = db.SellingItems.OfType<Book>().FirstOrDefault(p => p.Title == "Maths Easy");
book.Sell(); //Changes State
Purchase purchase = new Purchase();
purchase.Date = DateTime.Now;
purchase.SellingItems.Add(book);
purchase.SellingItems.Add(disc);
db.Purchases.AddObject(purchase);
db.SaveChanges();
}
}
private static int GetTotalPurchaseValue(int purchaseID)
{
using (var db = new MyModelFirstTestContainer(connectionStringVal))
{
var purchase = db.Purchases.FirstOrDefault(p => p.PurchaseId == purchaseID);
if( purchase == null)
{
return 0;
}
var total = purchase.SellingItems.Sum(x => Convert.ToInt32(x.Price));
return total;
}
}
private static void AddDisc()
{
using (var db = new MyModelFirstTestContainer(connectionStringVal))
{
DigitalDisc disc = new DigitalDisc();
disc.AvailabilityStatus = "Available";
disc.Price = 300;
disc.Artist = "Turtle Violin";
db.SellingItems.AddObject(disc);
db.SaveChanges();
}
}
}
}
</code></pre>
<p>REFERENCE:</p>
<ol>
<li><p><a href="https://stackoverflow.com/questions/4254182/inheritance-vs-enum-properties-in-the-domain-model/4259033#comment15499738_4259033">https://stackoverflow.com/questions/4254182/inheritance-vs-enum-properties-in-the-domain-model/4259033#comment15499738_4259033</a></p></li>
<li><p><a href="https://stackoverflow.com/questions/11683536/entity-framework-get-subclass-objects-in-repository#comment15499860_11683536">https://stackoverflow.com/questions/11683536/entity-framework-get-subclass-objects-in-repository#comment15499860_11683536</a></p></li>
<li><p><a href="https://softwareengineering.stackexchange.com/questions/158472/why-should-i-add-check-constraint">https://softwareengineering.stackexchange.com/questions/158472/why-should-i-add-check-constraint</a></p></li>
</ol>
|
[] |
[
{
"body": "<p>Yes, it is a proper TPT inheritance and yes, you can mark your base class as abstract.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T07:48:17.530",
"Id": "14097",
"ParentId": "14077",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14097",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T13:56:21.023",
"Id": "14077",
"Score": "1",
"Tags": [
"c#",
".net",
"object-oriented",
"entity-framework"
],
"Title": "Is it proper TPT Inheritance"
}
|
14077
|
<p>I'm learning Python by converting a BASIC (BlitzPlus) program I wrote based on article at <a href="http://gamedeveloper.texterity.com/gamedeveloper/201002?pg=42#pg43" rel="nofollow">http://gamedeveloper.texterity.com/gamedeveloper/201002?pg=42#pg43</a> for random dungeon generation.</p>
<p>I've basically used Google and trial and error to get this script to where it is now (which is a working program).</p>
<p>However, I'd like to know if it's "Pythonic" or just a hybrid BASIC to Python translation. </p>
<p>Thanks in advance for any advice.</p>
<pre><code># Random Dungeon - use TKInter to draw
from Tkinter import *
import random
master=Tk()
random.seed()
def notConnected(x,y):
uncon=False
if (cellArray[x,y]['u']==0) and (cellArray[x,y]['d']==0) and (cellArray[x,y]['l']==0) and (cellArray[x,y]['r']==0):
uncon=True
return uncon
def pickNeighbour(x,y,d):
done=0
tries=0
while done==0:
if d==1:
if y>0:
if notConnected(x,y-1):
cellArray[x,y]['u']=cellArray[x,y-1]['n']
cellArray[x,y-1]['d']=cellArray[x,y]['n']
newx=x
newy=y-1
done=1
else:
d+=1
if d==5:
d=1
tries+=1
if tries==4:
done=2
else:
d+=1
if d==5:
d=1
if d==2:
if x<cellsX-1:
if notConnected(x+1,y):
cellArray[x,y]['r']=cellArray[x+1,y]['n']
cellArray[x+1,y]['l']=cellArray[x,y]['n']
newx=x+1
newy=y
done=1
else:
d+=1
if d==5:
d=1
tries+=1
if tries==4:
done=2
else:
d+=1
if d==5:
d=1
if d==3:
if y<cellsY-1:
if notConnected(x,y+1):
cellArray[x,y]['d']=cellArray[x,y+1]['n']
cellArray[x,y+1]['u']=cellArray[x,y]['n']
newx=x
newy=y+1
done=1
else:
d+=1
if d==5:
d=1
tries+=1
if tries==4:
done=2
else:
d+=1
if d==5:
d=1
if d==4:
if x>0:
if notConnected(x-1,y):
cellArray[x,y]['l']=cellArray[x-1,y]['n']
cellArray[x-1,y]['r']=cellArray[x,y]['n']
newx=x-1
newy=y
done=1
else:
d+=1
if d==5:
d=1
tries+=1
if tries==4:
done=2
else:
d+=1
if d==5:
d=1
if done==1:
return newx,newy
elif done==2:
return -1,-1
def drawCells():
offsetX=10
offsetY=10
for y in range(cellsY):
for x in range(cellsX):
#draw cells grid
x0=(x*50)+offsetX
y0=(y*50)+offsetY
x1=x0+49
y1=y0+49
canvas.create_rectangle(x0,y0,x1,y1)
canvas.create_text(x0+23,y0+22,text=str(cellArray[x,y]['n']).zfill(2))
#draw rooms
if not(notConnected(x,y)):
rx0=x0+10
ry0=y0+10
rx1=rx0+29
ry1=ry0+29
canvas.create_rectangle(rx0,ry0,rx1,ry1,outline='red')
#draw connections
if cellArray[x,y]['r']!=0:
cx0=rx1
cy0=ry0+15
cx1=rx1+21
cy1=cy0
canvas.create_line(cx0,cy0,cx1,cy1,width=5)
if cellArray[x,y]['d']!=0:
cx0=rx0+15
cy0=ry1
cx1=cx0
cy1=ry1+21
canvas.create_line(cx0,cy0,cx1,cy1,width=5)
#main program
cellsX=10
cellsY=10
done=False
cellArray={}
fillPercent=80
gridWidth=(cellsX*50)
gridHeight=(cellsY*50)
count=-1
connected=0
canvas=Canvas(master,width=gridWidth+50,height=gridHeight+100)
canvas.pack()
for y in range(cellsY):
for x in range(cellsX):
count+=1
cellArray[x,y]={'x':x,'y':y,'u':0,'d':0,'l':0,'r':0,'n':count}
#pick random start cell and direction
rx=random.randint(0,cellsX-1)
ry=random.randint(0,cellsY-1)
rd=random.randint(1,4)
startCell='Start cell: '+str(cellArray[rx,ry]['n'])
connected+=1
while not(done):
nx,ny=pickNeighbour(rx,ry,rd)
if nx==-1:
#see what percent filled
pcf=int(float(connected)/float(cellsX*cellsY)*100)
if pcf>=fillPercent:
endCell='End cell: '+str(cellArray[rx,ry]['n'])
done=True
else:
found=False
while not(found):
rx=random.randint(0,cellsX-1)
ry=random.randint(0,cellsY-1)
if not(notConnected(rx,ry)):
found=True
else:
rx=cellArray[nx,ny]['x']
ry=cellArray[nx,ny]['y']
connected+=1
rd=random.randint(1,4)
drawCells()
canvas.create_text(10,gridHeight+30,text=startCell,justify='right',anchor=W)
canvas.create_text(10,gridHeight+60,text=endCell,justify='right',anchor=W)
master.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T20:22:03.263",
"Id": "22804",
"Score": "3",
"body": "First thought? Separation of concerns. Generating a random dungeon does not equal drawing a random dungeon. Separate your functionality into a part that generates a data structure that represents a dungeon and a part that turns that data structure into a graphical representation. The code will be cleaner, easier to debug, and (not just more pythonic, but) have a better design in general."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T20:25:32.467",
"Id": "22805",
"Score": "2",
"body": "Second thought? I see that you're repeating a lot of code. If you find yourself typing (almost) the same code over and over again (my rule of thumb is three or more times) try and see if you can 1) do it in a loop. 2) create a separate function that contains that code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T11:46:29.953",
"Id": "22820",
"Score": "1",
"body": "Thanks for the replies everyone. I will take those on board and try to make it a proper Python program. In the BASIC version (which I need to look at again), the generation functions became an 'include' file, with main program handling drawing sprites etc to make the dungeon look nice.\nThat's my aim with this version as well (probably in PyGame), but thought I'd nail the generation first (and simple drawing in Tkinter)."
}
] |
[
{
"body": "<p>It reads very much as a Basic program, but it's a reasonable first(ish) python program.</p>\n\n<p>Steps to improve it:\nTurn your existing global code into a \"main\" function, and call it via</p>\n\n<pre><code>if __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>Move all your global variables into the main function. You'll have to add a load of parameters to other functions, which seems like a backward step, but it'll help. You'll notice a lot of repeated parameters, which indicates they should be packaged together into a structure of some sort.</p>\n\n<p>Concerning the cellArray map, the items are currently a dictionary of exits, id and position. Instead, make it into a <code>Cell</code> class with separate position and connections objects. As an added bonus, it even has a method <code>notConnected()</code>, although please change it's name to something positive, using not(notConnected()) is confusing. Other 'obvious' structures are the maze, xy coordinate, display.</p>\n\n<p>PickNeighbour is far more involved than it needs to be. Creating an <code>InBounds</code> function will simplify it a bit, creating a map from direction to \"cell offset\" will flatten it to just a general case.</p>\n\n<p>Apart from the above:</p>\n\n<ul>\n<li>Separate out your functions into ones that do a single thing, rather\nthan several.</li>\n<li>Use constants for your \"magic numbers\". </li>\n<li>You can return different types from functions, so use <code>None</code> as a\n'failure' value (even <code>()</code>), rather than a tuple with an invalid first item. This will test to false.</li>\n</ul>\n\n<p>Because I was in the mood, I adapted your program to how I'd do it. It's a bit over-engineered and it's not 'there' yet, but should give you several ideas.</p>\n\n<pre><code># Random Dungeon - use TKInter to draw\nfrom tkinter import *\nimport random\n\nclass Cell:\n def __init__( self, pos = None ):\n self.pos = pos\n self.connection = {}\n def IsConnected( self ):\n return len( self.connection ) > 0\n\ndef ShiftPosition( pos, offset, scale = (1,1) ):\n (x,y) = pos\n (ox,oy) = offset\n (sx,sy) = (scale,scale) if type(scale) != type(()) else scale\n return (x+ox*sx),(y+oy*sy)\n\nclass CellExits:\n def __init__( self, offsets, side = 0 ):\n if ( len(offsets) % 2 ) != 0:\n raise IndexError\n self.side = side\n self.offsets = offsets\n self.side_count = len( self.offsets )\n def __len__( self ):\n return self.side_count\n def Set( self, side ):\n self.side = side%self.side_count\n def Next( self ):\n self.Set( self.side + 1 )\n def Offset( self ):\n return self.offsets[self.side]\n def BackOffset( self ):\n back_offset = (self.side + self.side_count//2)%self.side_count\n return self.offsets[back_offset]\n\nclass CellMaze:\n def __init__( self, side_x, side_y, cell_exits ):\n self.side_x = side_x\n self.side_y = side_y\n self.cell_exits = cell_exits\n self.cellArray = {}\n def Cell( self, pos ):\n if self.InBounds(pos):\n return self.cellArray[pos]\n return None\n def __len__( self ):\n return len( self.cellArray )\n def Cells( self ):\n for cell in self.cellArray.values():\n yield cell\n def InBounds( self, pos ):\n return pos in self.cellArray\n def RandomPosition( self, connected = True ):\n while True:\n rx = random.randrange( self.side_x )\n ry = random.randrange( self.side_y )\n rpos = (rx,ry)\n cell = self.Cell( rpos )\n if self.InBounds( rpos ) and ( cell.IsConnected() == connected ):\n break\n return rpos\n def SetRandomDirection( self ):\n rd = random.randrange( len(self.cell_exits) )\n self.cell_exits.Set( rd )\n def TryDirection( self, pos ):\n offset = self.cell_exits.Offset()\n newpos = ShiftPosition( pos, offset )\n if self.InBounds( newpos ):\n if not self.cellArray[newpos].IsConnected():\n backoffset = self.cell_exits.BackOffset()\n self.cellArray[pos].connection[ offset ] = newpos\n self.cellArray[newpos].connection[ backoffset ] = pos\n return newpos\n return None\n def PickNeighbour( self, pos ):\n self.SetRandomDirection()\n for tries in range( len( self.cell_exits ) ):\n newpos = self.TryDirection( pos )\n if newpos:\n return newpos\n self.cell_exits.Next()\n return None\n\ndef CreateRectangularMaze( side_x, side_y ):\n offsets = [ (0,-1), (1,0), (0,1), (-1,0) ]\n cell_exits = CellExits( offsets )\n maze = CellMaze( side_x, side_y, cell_exits )\n for y in range( side_y ):\n for x in range( side_x ):\n pos = (x,y)\n maze.cellArray[pos] = Cell( pos )\n return maze\n\ndef CreateMaze( side_x, side_y, ShapeGenerator ):\n target_fill_percent = 80\n maze = ShapeGenerator( side_x, side_y )\n #pick random start cell\n startpos = rpos = maze.RandomPosition( False )\n connected = 1\n done = False\n while not(done):\n newpos = maze.PickNeighbour( rpos )\n if newpos:\n rpos = newpos\n connected += 1\n else:\n #see what percent filled\n pcf = 100*connected/len(maze)\n if pcf >= target_fill_percent:\n done = True\n else:\n rpos = maze.RandomPosition( True )\n return maze,startpos,rpos\n\nclass Rect:\n def __init__( self, l, t, r = None, b = None ):\n if r is None:\n self.rect = ( l[0], l[1], t[0], t[1] )\n else:\n self.rect = ( l, t, r, b )\n def MidPoint( self ):\n ( l, t, r, b ) = self.rect\n return ( l + r )/2,( t + b )/2\n def TopLeft( self ):\n return self.rect[0],self.rect[1]\n def BottomRight( self ):\n return self.rect[2],self.rect[3]\n\nclass GameBoard:\n BORDER = 10\n LINE_HEIGHT = 30\n CELL_SIZE = 50\n CELL_BORDER = 5\n STATUS_LINES = 3\n def __init__( self, cellx, celly ):\n self.master = Tk()\n grid_w = cellx*self.CELL_SIZE\n grid_h = celly*self.CELL_SIZE\n width = 2*self.BORDER+grid_w\n status_start = 2*self.BORDER+grid_h\n status_height = self.STATUS_LINES*self.LINE_HEIGHT\n #\n self.grid_area = Rect(self.BORDER,self.BORDER,self.BORDER+grid_w,self.BORDER+grid_h)\n self.status_area = Rect(self.BORDER,status_start,self.BORDER+grid_w,status_start+status_height)\n self.canvas = Canvas( self.master, width=width,\n height = self.BORDER+status_start+status_height )\n self.canvas.pack()\n def Run( self ):\n self.master.mainloop()\n def StatusText( self, line, text ):\n xy = ShiftPosition( self.status_area.TopLeft(), (0,line*self.LINE_HEIGHT) )\n self.canvas.create_text( xy, text = text, anchor = W )\n def DrawConnections( self, cell, rect ):\n start = rect.MidPoint()\n #draw connections\n for direction in cell.connection:\n end = ShiftPosition( start, direction, self.CELL_SIZE )\n self.canvas.create_line( start, end, width = 5 )\n def DrawCellLabels( self, cell, text, rect ):\n if cell.IsConnected():\n start = ShiftPosition( rect.TopLeft(), (1,1), self.CELL_BORDER )\n end = ShiftPosition( rect.BottomRight(), (1,1), -self.CELL_BORDER )\n self.canvas.create_rectangle( start, end, fill=\"yellow\", outline=\"red\" )\n self.canvas.create_text( rect.MidPoint(), text=text )\n def DrawCells( self, maze ):\n origin = self.grid_area.TopLeft()\n for cell in maze.Cells():\n x,y = cell.pos\n xy0 = ShiftPosition( origin, (x,y), self.CELL_SIZE )\n xy1 = ShiftPosition( xy0, (1,1), self.CELL_SIZE )\n self.canvas.create_rectangle( xy0, xy1 )\n self.DrawConnections( cell, Rect(xy0, xy1) )\n for cell in maze.Cells():\n x,y = cell.pos\n xy0 = ShiftPosition( origin, (x,y), self.CELL_SIZE )\n xy1 = ShiftPosition( xy0, (1,1), self.CELL_SIZE )\n self.DrawCellLabels( cell, str(cell.pos), Rect(xy0, xy1) )\n\n#main program\ndef main():\n random.seed()\n cellsX = 10\n cellsY = 10\n maze,startpos,endpos = CreateMaze( cellsX, cellsY, CreateRectangularMaze )\n g = GameBoard( cellsX, cellsY )\n g.DrawCells( maze )\n g.StatusText( 1, 'Start cell: ' + str(startpos) )\n g.StatusText( 2, 'End cell: '+str(endpos) )\n g.Run()\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T09:22:58.437",
"Id": "14114",
"ParentId": "14079",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T15:33:29.307",
"Id": "14079",
"Score": "2",
"Tags": [
"python"
],
"Title": "Random dungeon generator"
}
|
14079
|
<p>I have a serious nesting of <code>if</code>s in a helper code and I would like to making cleaner. I would like to avoid <code>case</code> if possible as well.</p>
<p>I know there is probably a more object-oriented approach to this but I can't seem to know how.</p>
<p>I'm flooded with stuff like this:</p>
<pre><code> def print_flight_options_status(invitation)
if invitation.group.travel_class == 'none'
not_allowed
elsif invitation.refused_flight_options?
not_needed
elsif invitation.selected_flights?
waiting_reservation
elsif invitation.flight_options.empty?
not_sent_yet
elsif invitation.requested_more_flight_options?
rejected
else
waiting_guest_input
end
end
def print_event_terms_status(invitation)
if invitation.event_terms_status.nil?
"<span class='grey_highlight pj_cat'>Aguardando</span>"
elsif invitation.accepted_event_terms?
"<span class='green_highlight pj_cat'>Aceito</span>"
elsif invitation.rejected_event_terms?
"<span class='red_highlight pj_cat'>Declinado</span>"
elsif invitation.cancelled_event_terms?
"<span class='yellow_highlight pj_cat'>Cancelado</span>"
end.html_safe
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T18:07:04.593",
"Id": "22776",
"Score": "0",
"body": "If the return values are mutually exclusive, it seems like it would make more sense to have print_flight_options_status contain a symbol that is updated by the various things you are querying."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T17:37:27.600",
"Id": "22890",
"Score": "0",
"body": "You're right, this would probably be cleaner, but the complexity would not be much reduced."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T19:39:28.797",
"Id": "23141",
"Score": "0",
"body": "`print_flight_options_status` looks fantastic as it is, I wouldn't write it as in-line `if`s. At most, to reduce the line-count, I'd use `if condition then value ... `, but it won't look as nice. In `print_event_terms_status` I'd just use helpers for the HTML tags instead of building them by hand."
}
] |
[
{
"body": "<p>There is a <code>case</code>-variant which may be a bit better:</p>\n\n<pre><code>x = ''\ncase \n when x == 'xxy'\n puts '=xxy'\n when x.empty?\n puts 'is empty'\n else\n puts \"well, I don't know, what it is\"\n end\n</code></pre>\n\n<p>In your case, you could use:</p>\n\n<pre><code>def print_flight_options_status(invitation)\n case\n when invitation.group.travel_class == 'none'\n not_allowed\n when invitation.refused_flight_options?\n not_needed\n when invitation.selected_flights?\n waiting_reservation\n when invitation.flight_options.empty?\n not_sent_yet\n when invitation.requested_more_flight_options?\n rejected\n else\n waiting_guest_input\n end\n end \n</code></pre>\n\n<hr>\n\n<p>You may also define a kind of <code>with</code>-statement:</p>\n\n<pre><code>module With\n def with(&block)\n self.instance_eval &block\n end\nend\n\n['a', ''].each{|test|\n test.extend(With)\n p test.with{\n if empty? \n :empty\n elsif self == 'a'\n :a\n else\n :else\n end\n } \n}\n</code></pre>\n\n<p>In your case:</p>\n\n<pre><code>def print_flight_options_status(invitation)\n invitation.extend(With)\n invitation.with{\n if group.travel_class == 'none'\n not_allowed\n elsif refused_flight_options?\n not_needed\n elsif selected_flights?\n waiting_reservation\n elsif flight_options.empty?\n not_sent_yet\n elsif requested_more_flight_options?\n rejected\n else\n waiting_guest_input\n end\n }\n end \n</code></pre>\n\n<p>Advantage: You don't need to repeat <code>invitation.</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T17:51:07.607",
"Id": "14083",
"ParentId": "14080",
"Score": "2"
}
},
{
"body": "<p>I prefer this style:</p>\n\n<pre><code> def print_flight_options_status(invitation)\n return not_allowed if invitation.group.travel_class == 'none'\n return not_needed if invitation.refused_flight_options?\n return waiting_reservation if invitation.selected_flights?\n return not_sent_yet if invitation.flight_options.empty?\n return rejected if invitation.requested_more_flight_options?\n\n waiting_guest_input\n end\n</code></pre>\n\n<p>UPD</p>\n\n<p>About second code-snippet. I think in this case you can use decorators (for example <a href=\"https://github.com/jcasimir/draper\" rel=\"nofollow\">draper</a>) for invitations, so:</p>\n\n<pre><code>def print_event_terms_status(invitation)\n InvitationDecorator.decorate(invitation).status_in_html\nend\n</code></pre>\n\n<p>Where <code>InvitationDecorator</code>:</p>\n\n<pre><code>class InvitationDecorator < Draper::Base\n def status_in_html\n if invitation.event_terms_status.nil?\n \"<span class='grey_highlight pj_cat'>Aguardando</span>\"\n ...\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T19:41:00.460",
"Id": "23142",
"Score": "1",
"body": "The problem with inline return + conditionals is that the exit points of the method grow up... I know it's a common pattern in Ruby but personally I consider it dubious."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T18:11:48.720",
"Id": "14085",
"ParentId": "14080",
"Score": "4"
}
},
{
"body": "<p>IMHO both variants look ok regarding ifs. They clearly express business logic and well formatted. Maybe I'd separate a bit markup from UI Logic:</p>\n\n<pre><code>def print_event_terms_status(invitation)\n span = \n ->(cls, text) { \"<span class='#{class} pj_cat'>#{text}</span>\".html_safe }\n if invitation.event_terms_status.nil?\n span['grey_highlight', 'Aguardando']\n elsif invitation.accepted_event_terms?\n span['green_highlight', 'Aceito']\n elsif invitation.rejected_event_terms?\n span['red_highlight', 'Declinado']\n elsif invitation.cancelled_event_terms?\n span['yellow_highlight', 'Cancelado']\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T21:14:43.130",
"Id": "14422",
"ParentId": "14080",
"Score": "1"
}
},
{
"body": "<p>The point of CSS is to decouple the presentation from the logic. Therefore, you should not hard-code colours into the CSS class names. Each colour should be mentioned just once, in the style rule only:</p>\n\n<pre><code>.pj_cat.pending {\n background-color: gray;\n}\n.pj_cat.accepted {\n background-color: green;\n}\n.pj_cat.rejected {\n background-color: red;\n}\n.pj_cat.cancelled {\n background-color: yellow;\n}\n</code></pre>\n\n<p>Otherwise, if the site's colour theme ever changes, the code is going to be confusing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-09T04:37:47.947",
"Id": "93066",
"ParentId": "14080",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14085",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T17:13:23.217",
"Id": "14080",
"Score": "2",
"Tags": [
"ruby"
],
"Title": "Printing flight statuses"
}
|
14080
|
<p>After posting a question about <a href="https://stackoverflow.com/questions/11680176/alphanumeric-hash-a-z-0-9">Alphanumeric Hash generation</a> on StackOverflow, the most helpful answer was to change the conversion method from pulling 5-bit chunks of a binary hash value, to instead changing the number to base-36. </p>
<p>This is pretty straightforward; find the quotient and remainder of the number divided by 36, encode the remainder as the next most significant digit of the result, then repeat with the quotient.</p>
<p>Sounds great, except that if I want to start with an integer hash 128 bits or greater, I can't just use the divide operator. In that case, I have to use "long division":</p>
<pre><code>Decimal:
18 R 3
__
5)93
-5
43
-40
3
Binary:
00010010 R 11
________
0101)01011101
-0101
0000110
-0101
00011
</code></pre>
<p>So, to base-36-encode a large integer, stored as a byte array, I have the following method, which performs the basic iterative algorithm for binary long division, storing the result in another byte array and returning the modulus as an output parameter:</p>
<pre><code>public static byte[] DivideBy(this byte[] bytes, ulong divisor, out ulong mod, bool preserveSize = true)
{
//the byte array MUST be little-endian here or the operation will be totally fubared.
var bitArray = new BitArray(bytes);
ulong buffer = 0;
byte quotientBuffer = 0;
byte qBufferLen = 0;
var quotient = new List<byte>();
//the bitarray indexes its values in little-endian fashion;
//as the index increases we move from LSB to MSB.
for (var i = bitArray.Count - 1; i >= 0; --i)
{
//The basic idea is similar to decimal long division;
//starting from the most significant bit, take enough bits
//to form a number divisible by (greater than) the divisor.
buffer = (buffer << 1) + (ulong)(bitArray[i] ? 1 : 0);
if (buffer >= divisor)
{
//Now divide; buffer will never be >= divisor * 2,
//so the quotient of buffer / divisor is always 1...
quotientBuffer = (byte)((quotientBuffer << 1) + 1);
//then subtract the divisor from the buffer,
//to produce the remainder to be carried forward.
buffer -= divisor;
}
else
//to keep our place; if buffer < divisor,
//then by definition buffer / divisor == 0 R buffer.
quotientBuffer = (byte)(quotientBuffer << 1);
qBufferLen++;
if (qBufferLen == 8)
{
//preserveSize forces the output array to be the same number of bytes as the input;
//otherwise, insert only if we're inserting a nonzero byte or have already done so,
//to truncate leading zeroes.
if (preserveSize || quotient.Count > 0 || quotientBuffer > 0)
quotient.Add(quotientBuffer);
//reset the buffer
quotientBuffer = 0;
qBufferLen = 0;
}
}
//and when all is said and done what's left in our buffer is the remainder.
mod = buffer;
//The quotient list was built MSB-first, but we can't require
//a little-endian array and then return a big-endian one.
return quotient.AsEnumerable().Reverse().ToArray();
}
</code></pre>
<p>... which is then used by the (now pretty simple) base-36 encoder algorithm to iteratively divide the number by 36:</p>
<pre><code>public static string ToBase36String(this IEnumerable<byte> toConvert, bool bigEndian = false)
{
//the "alphabet" for base-36 encoding is similar in theory to hexadecimal,
//but uses all 26 English letters a-z instead of just a-f.
var alphabet = new[]
{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z'
};
//most .NET-produced byte arrays are "little-endian" (LSB first),
//but MSB-first is more natural to read bitwise left-to-right;
//here, we can handle either way.
var bytes = bigEndian
? toConvert.Reverse().ToArray()
: toConvert.ToArray();
var builder = new StringBuilder();
while (bytes.Any(b => b > 0))
{
ulong mod;
bytes = bytes.DivideBy(36, out mod);
builder.Insert(0,alphabet[mod]);
}
return builder.ToString();
}
</code></pre>
<p>It's... passable, I guess. An N-bit number of initial magnitude M encodes in Nlog<sub>36</sub>M time which is pretty efficient, all things considered. Is there a faster basic method, or any glaring efficiency issues (I am doing a lot of conversions; byte array, to bit array, producing a list, reversing it, then converting to array)? </p>
<p>The division algorithm also doesn't handle division by a divisor longer than 64 bits (thus taking a byte array for the divisor), nor can it handle signed arithmetic. Are there any simple improvements to let it do so?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T12:41:43.393",
"Id": "22797",
"Score": "0",
"body": "could you show us some sample input and output so we can verify our solutions? At the moment I'm not sure how many bytes will normally be in `toConvert`..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T16:44:23.770",
"Id": "425981",
"Score": "0",
"body": "You can simplify your alphabet using a char array.... var alphabet = \"0123456789abcdefghijklmnopqrstuvwxyz\".ToCharArray();"
}
] |
[
{
"body": "<p>Have you considered using <code>System.Numerics.BigInteger</code> to avoid having to do the math yourself?</p>\n\n<p><code>BigInteger.DivRem</code> even allows you to do both calculations at once.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T22:01:37.850",
"Id": "22781",
"Score": "0",
"body": "I did not consider that because I didn't know it existed. Probably should have; BigInteger's been a thing since I was in high school."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T22:17:00.903",
"Id": "22784",
"Score": "0",
"body": "@KeithS: Not the most commonly known thing since it lives in a non-standard library."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T21:38:09.690",
"Id": "14088",
"ParentId": "14084",
"Score": "9"
}
},
{
"body": "<p>If performance means <em>anything</em> to you, use <a href=\"http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.divrem.aspx\" rel=\"noreferrer\"><code>BigInteger.DivRem</code></a>, as Guvante suggested (don't forget to add <code>System.Numerics</code> to your project references and using directives). </p>\n\n<p>As an added bonus, <code>BigInteger</code> <strong>can</strong> handle both <em>negative divisors</em> and <em>arbitrarily large divisors</em> (tested it with a 128 bit long divisor, worked fine).</p>\n\n<p>There are a few other improvements to be made to your code. You needn't define a char array for the alphabet, better just use a string constant - you can still access the characters by index. Also, avoid converting to <code>IEnumerable<byte></code> from <code>byte[]</code> reversing and going back again. Instead, let the <code>toConvert</code> parameter be of type <code>byte[]</code> from the beginning and then, if needed, reverse it using <code>Array.Reverse</code> (it actually mutates the array, so you don't need to assign a new one).</p>\n\n<p>Putting it all together:</p>\n\n<p><strong>Usage</strong></p>\n\n<pre><code>byte[] bytes = Encoding.UTF8.GetBytes(\"A test 1234\"); // I assume that's how you were converting \nstring hash = bytes.ToBase36String(); // from string to byte[] anyway.. \n</code></pre>\n\n<hr>\n\n<p><strong>Code</strong></p>\n\n<pre><code>public static string ToBase36String(this byte[] toConvert, bool bigEndian = false)\n{\n const string alphabet = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n if (bigEndian) Array.Reverse(toConvert); // !BitConverter.IsLittleEndian might be an alternative\n BigInteger dividend = new BigInteger(toConvert);\n var builder = new StringBuilder();\n while (dividend != 0)\n {\n BigInteger remainder;\n dividend = BigInteger.DivRem(dividend, 36, out remainder);\n builder.Insert(0, alphabet[Math.Abs(((int)remainder))]);\n } \n return builder.ToString();\n}\n</code></pre>\n\n<h1>Performance</h1>\n\n<p>The difference is huge (running without the debugger, compiled in release configuration, timed with a <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx\" rel=\"noreferrer\"><code>System.Diagnostics.Stopwatch</code></a>; <em><code>i7@2.8GHz</code></em>).</p>\n\n<p>With eleven characters of input running one million times, <code>BigInteger</code> is 7.5 times faster:</p>\n\n<p><img src=\"https://i.stack.imgur.com/LO5Dx.png\" alt=\"first benchmark\"></p>\n\n<p>The difference is amplified when feeding it longer strings, as shown in this example with an input of 34 chars at one hundred thousand iterations (13.5 times faster):</p>\n\n<p><img src=\"https://i.stack.imgur.com/DCGQe.png\" alt=\"second benchmark\"></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-14T07:00:46.790",
"Id": "23766",
"Score": "0",
"body": "This doesn't work when the `dividend` is negative once created from the byte array, as the loop never runs :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-14T07:52:15.327",
"Id": "23768",
"Score": "0",
"body": "@Strelok sorry, I only tested it with real strings. it was easy to fix though: just change the condition to `!= 0` instead of `> 0` and use `Math.Abs` to get a valid index for the alphabet array (I assume that's the behaviour you want). If my answer has been of any help, an upvote would be greatly appreciated."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T14:12:59.770",
"Id": "14101",
"ParentId": "14084",
"Score": "10"
}
},
{
"body": "<p><strong>edit3</strong>: I've created a full-fledged RadixEncoding (both encoding and decoding) class that will accept any base and can handle the ending zero bytes. <a href=\"https://stackoverflow.com/questions/14110010/base-n-encoding-of-a-byte-array/\">I posted it in Q&A form on StackOverflow</a></p>\n\n<p>@codesparkle's implementation can be improved some more (performance wise).</p>\n\n<p><strong>edit2</strong>: I've come across an issue with using BigInt. While BigInt works fine for text, <strong>it will lose precision</strong> when dealing with raw bytes that end in more than one (or two) zero bytes (in Base36's case anyway). Eg, if you fed ToBase36String {0xFF,0xFF,0x00,0x00} you would actually lose that last byte (MSB) in the resulting Base36 encoded string (\"1ekf\"). Due to how BigInt works around the \"sign\" of a BigInt value, if you were to feed the encoder with {0xFF,0x7F,0x00} the zero byte will be lost (\"pa7\"). See: <a href=\"http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx</a> (search for \"positive values in which the most significant bit of the last byte in the byte array would ordinarily be set should include an additional byte whose value is 0\")</p>\n\n<p>Instead of using a StringBuilder, Inserting each digit at index 0, and having to deal with byte swaping the input, one can use a generic List of char, which we Add to and Reverse at the end of the procedure.</p>\n\n<p><strong>edit</strong>: Whoops. When I was running this on actual big endian data, I realized you still had to reverse the array at one point...but the operation can be held off until the end. So if the byte array is big endian, you actually <strong>wouldn't</strong> have to Reverse the result, saving even more processing time. I've updated the code with the needed fixes</p>\n\n<p>Using BigInteger.IsZero is also less computationally intensive (simple == condition under the hood) than BigInteger's greater-than operator, which calls CompareTo(BigInteger) underneath the hood.</p>\n\n<pre><code>using System;\nusing System.Numerics;\n\nconst int kByteBitCount= 8; // number of bits in a byte\nconst string kBase36Digits= \"0123456789abcdefghijklmnopqrstuvwxyz\";\n// constants that we use in ToBase36CharArray\nstatic readonly double kBase36CharsLengthDivisor= Math.Log(kBase36Digits.Length, 2);\nstatic readonly BigInteger kBigInt36= new BigInteger(36);\n\npublic static string ToBase36String(this byte[] bytes, bool bigEndian=false)\n{\n // Estimate the result's length so we don't waste time realloc'ing\n int result_length= (int)\n Math.Ceiling(bytes.Length * kByteBitCount / kBase36CharsLengthDivisor);\n // We use a List so we don't have to CopyTo a StringBuilder's characters\n // to a char[], only to then Array.Reverse it later\n var result= new System.Collections.Generic.List<char>(result_length);\n\n var dividend= new BigInteger(bytes);\n // IsZero's computation is less complex than evaluating \"dividend > 0\"\n // which invokes BigInteger.CompareTo(BigInteger)\n while (!dividend.IsZero)\n {\n BigInteger remainder;\n dividend= BigInteger.DivRem(dividend, kBigInt36, out remainder);\n int digit_index= Math.Abs((int)remainder);\n result.Add(kBase36Digits[digit_index]);\n }\n\n // orientate the characters in big-endian ordering\n if(!bigEndian)\n result.Reverse();\n // ToArray will also trim the excess chars used in length prediction\n return new string(result.ToArray());\n}\n</code></pre>\n\n<p>Compared to @codesparkle's \"A test 1234\", 1,000,000 iterations:</p>\n\n<pre><code>His: 3.593306\nMine: 2.6857364\n</code></pre>\n\n<p>Compared to @codesparkle's \"A test 1234. Made slightly larger!\", 100,000 iterations:</p>\n\n<pre><code>His: 1.5366169\nMine: 1.1814889\n</code></pre>\n\n<p>My CPU is an i7 860 @2.80GHz. The code was tested in a Release x64 build (ran by itself, not under a debugger) using Stopwatch for timing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T05:41:34.537",
"Id": "31985",
"Score": "0",
"body": "Nothing special, but provided the reverse process in answering this question: http://stackoverflow.com/a/14079018/444977"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T10:56:07.973",
"Id": "32009",
"Score": "1",
"body": "So I can't comment on @codesparkle's answer yet (not enough rep I suppose) but I've come across an issue with using BigInt. While BigInt works fine for text, **it will lose precision** when dealing with raw bytes that end in more than two zero bytes (in Base36's case anyway). Eg, if you fed ToBase36String {0xFF,0xFF,0x00,0x00} you would actually lose that last byte (MSB) in the resulting Base36 encoded string (\"1ekf\"). I don't know how likely it is that the two final bytes in whichever hash algo you use would generate two nulls, but it's an edge case to definitely consider with this solution."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T04:02:03.013",
"Id": "20014",
"ParentId": "14084",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "14088",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T18:11:29.573",
"Id": "14084",
"Score": "6",
"Tags": [
"c#",
"algorithm",
"bitwise"
],
"Title": "Base-36 encoding of a byte array"
}
|
14084
|
<p>So here we are, using a <code>StringBuilder</code> to build an email body. I know there's a lot on StackOverflow and endless debate/discussion around how best to concatenate strings.</p>
<ul>
<li>Can this be done in fewer lines of code in C#?</li>
<li>Can this be done better using templating?</li>
</ul>
<p>My goals are readability and maintainability.</p>
<pre><code>StringBuilder msgBody = new StringBuilder();
msgBody.AppendLine("Deleted Order Item Information");
msgBody.AppendLine("------------------------------------");
msgBody.AppendLine();
msgBody.AppendLine("Delete Date: {0}".FormatWith(orderDetail.DeletedDate.FormatDateTime(dtFormat)));
msgBody.AppendLine("Delete Comment: {0}".FormatWith(orderDetail.DeletedComment));
msgBody.AppendLine();
msgBody.AppendLine("Order #: {0}".FormatWith(order.ID.ToString()));
msgBody.AppendLine("Order Date: {0}".FormatWith(order.SubmitDate.FormatDateTime(dtFormat)));
msgBody.AppendLine("Order Name: {0}".FormatWith(order.Name));
msgBody.AppendLine("Order Comment: {0}".FormatWith(order.Comment));
msgBody.AppendLine("Department: {0}".FormatWith("{0} - {1}".FormatWith(orderDetail.Department, orderDetail.DepartmentDesc)));
msgBody.AppendLine();
msgBody.AppendLine("Item Number: {0}".FormatWith(orderDetail.StockNumber));
msgBody.AppendLine("Quantity: {0}".FormatWith(orderDetail.Quantity));
msgBody.AppendLine("Rush: {0}".FormatWith((orderDetail.Rush.ToYesNo())));
msgBody.AppendLine("Item Name: {0}".FormatWith(item.Name));
msgBody.AppendLine("Item Desc: {0}".FormatWith(item.Description1));
msgBody.AppendLine(" {0}".FormatWith(item.Description2));
msgBody.AppendLine("Stock: {0}".FormatWith((orderDetail.Stock.ToYesNo())));
msgBody.AppendLine("Item Comment: {0}".FormatWith(orderDetail.Comment));
</code></pre>
|
[] |
[
{
"body": "<p>I have used one template engine in <a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged 'c#'\" rel=\"tag\">c#</a> by name <a href=\"https://github.com/formosatek/dotliquid/wiki/DotLiquid-for-Developers\" rel=\"nofollow\">DotLiquid</a> to resolve similar problems. </p>\n\n<ol>\n<li>Readability: You <strong>have to extract your message template from the code</strong> to separate file. The template itself will lives its own life, usually independently from the code. </li>\n<li>Maintainability: \n<ul>\n<li><em>Collect all required parameters and conditions in one place</em>. Having conditions in your message tends to be next step in real message processing. By the way, anonymous classes from DotLiquid work well with your <a href=\"/questions/tagged/linq\" class=\"post-tag\" title=\"show questions tagged 'linq'\" rel=\"tag\">linq</a>. </li>\n<li>Then: template processing, message composing, and and putting it to queue to sent it. Sending operation itself could be time consuming and quite tricky</li>\n</ul></li>\n</ol>\n\n<p>Thus I have handled <em>hundreds</em> of template based messages with rich HTML per day. Obviously, if you're going to write next smtp monster, you'll write a more perfomance optimal solution. But using such template engine is good place to start.</p>\n\n<p>And here is a code snippet:</p>\n\n<pre><code>// Template itself, assume that is has been loaded from file\nvar messageTemplate = \n@\"Deleted Order Item Information\n------------------------------------ \n\nDelete Date: {{Date}}\nDelete Comment: {{DeletedComment}}\n⦠other text\";\n\n// Parses and compiles the template\nvar template = DotLiquid.Template.Parse(messageTemplate);\n\n// Renders the output\nvar messageBody = template.Render(DotLiquid.Hash.FromAnonymousObject(\n // Parameters\n new {\n Date = DateTime.Today,\n DeletedComment = \"Some Comment\"\n }));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T05:03:49.997",
"Id": "14095",
"ParentId": "14089",
"Score": "6"
}
},
{
"body": "<p>Take a look at: <a href=\"http://razorengine.codeplex.com/\" rel=\"nofollow\">http://razorengine.codeplex.com/</a></p>\n\n<p>As they say it is: \"A templating engine built upon Microsoft's Razor parsing technology.\"</p>\n\n<p>Quick example:</p>\n\n<pre><code>var modelData = new { Name = \"Cookie Monster\", Message = \"Cookieees!!!\" };\nstring template = \"@Model.Name says: '@Model.Message'\";\nstring result = Razor.Parse(template, modelData);\n\n//result: Cookie Monster says: 'Cookieees!!!'\n</code></pre>\n\n<p>And of course you can have razor script files (*.cshtml) and maybe use them something like this:</p>\n\n<pre><code> var modelData = new { Name = \"Cookie Monster\", Message = \"Cookieees!!!\" };\n string template = File.OpenText(Server.MapPath(\"~/templates/template.cshtml\")).ReadToEnd();\n string result = Razor.Parse(template, modelData);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T21:25:57.920",
"Id": "14109",
"ParentId": "14089",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-27T22:54:07.377",
"Id": "14089",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Building an email body"
}
|
14089
|
<p>I am building a dynamic site. All data will be served through an index.php in my webroot, using jquery to update the content. In webroot, I have a folder 'i/' which contains the files I want to include. The main include files contain code which will be used on every page: globals.php, globals.css, globals.js, etc. plus library files, such as jquery.js. Then there are secondary includes that are used depending on the section or topic that has been loaded: topic1.php, topic1.css, topic1.js, etc.</p>
<p>I have written the following php function to call all the files that need to be declared in the head (stylesheets and javascript for now, but wanted to make it easy to add more filetypes in the future), allowing globals.php to be included before the html tag (and will probably include topics.php from inside globals.php). However, I'm not really sure if this is a very efficient function, or if there is a better way to do what I'm trying to:</p>
<pre><code>function getIncludes($topic){
$type=array("css","js");
$library=array("js"=>array("jquery"));
$scope=array("globals",$topic);
foreach($type as $ext){
$includes=array();
if(array_key_exists($ext, $library)){
foreach ($library[$ext] as $file){
array_push($includes, $file);
}
}
foreach($scope as $file){
array_push($includes, $file);
}
foreach($includes as $file){
if(file_exists('i/'.$file.'.'.$ext)){
if($ext=="css"){
echo '<link rel="stylesheet" type="text/css" href="i/'.$file.'.'.$ext.'" />';
}
if($ext=="js"){
echo '<script type="text/javascript" src="i/'.$file.'.'.$ext.'"></script>';
}
}
}
}
}
</code></pre>
<p>Is this a good way of achieving my goal, or can I do better?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T01:01:42.170",
"Id": "22789",
"Score": "0",
"body": "Your function has a syntax error, and [it doesn't output anything](http://codepad.org/Mxo4yoGN). What's the desired output?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T03:06:01.943",
"Id": "22793",
"Score": "0",
"body": "Thanks for pointing out the syntax error, it's fixed now. I had missed an opening bracket on one of the foreach statements. The code is supposed to look for all script files which need to be linked to in the <head> (.js and .css for now), and write the html code for each one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T03:12:04.513",
"Id": "22795",
"Score": "0",
"body": "Oh, and it won't output anything unless it's run from a folder containing a subfolder named \"i\" which contains at least one .js or .css file named either \"globals\" or a name passed to the $topic variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T14:45:06.450",
"Id": "22799",
"Score": "0",
"body": "something is also wrong with my multidimensional array reference ($library[\"js\"][\"jquery\"]), but I can't figure out what it is. The script works for globals/$topic.css/js, but it's not including jquery.js, and I think it's because I'm not referencing it properly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T15:56:24.367",
"Id": "22801",
"Score": "0",
"body": "Ok, I figured out the problem with the multi-dimensional array (I needed to use array_key_exists instead of in_array), and the whole code now works as intended. However, I'd still like to make sure this is actually a good way of gathering and adding includes."
}
] |
[
{
"body": "<p>Don't make your directory structure so vague. Coming into this with no knowledge of your system how am I supposed to know what the \"i\" directory is? Just call it includes. Also, it is usually a good idea to separate your files based on their types so that they are easier to find. There are many common project directory structures out there. For instance I'm using something similar to Zend's. It looks similar to this.</p>\n\n<pre><code>/root\n /application\n /configs\n /models\n /views\n /controllers\n /data\n /cache\n /logs\n /public\n /js\n /css\n /images\n</code></pre>\n\n<p>I hope those file names don't indicate that you are actually using globals... There are much better ways to get \"global\" scope variables without ever using global. Sessions for instance. Globals, in my opinion, should eventually be deprecated. They are an old feature that has been proven faulty and replaced.</p>\n\n<p><code>array_push()</code> is another old function. Though there is nothing wrong with it, the preferred way to do it now is like so.</p>\n\n<pre><code>$includes[] = $file;\n</code></pre>\n\n<p>What you are trying to do is usually done with templates rather than PHP. For instance, you'd have a single HTML file with these includes in it already then dynamically change the contents with PHP. For those files that use the <code>$topic</code> variable, you would just perform a check to make sure it exists before including it via PHP. So a very basic template might look like this.</p>\n\n<pre><code><html>\n<head>\n<title></title>\n<script type=\"text/javascript\" src=\"i/globals.js\"></script>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"i/globals.css\" />\n\n<!-- SPECIFIC INCLUDES -->\n\n<?php if( is_file( \"i/$topic.js\" ) : ?>\n<script type=\"text/javascript\" src=\"i/<?php echo $topic.js; ?>\"></script>\n<?php endif; ?>\n\n<?php if( is_file( \"i/$topic.css\" ) : ?>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"i/<?php echo $topic.css; ?>\" />\n<?php endif; ?>\n\n<!-- SPECIFIC INCLUDES -->\n\n</head>\n<body>\n<?php if( is_file( \"i/$topic.php\" ) ) { include \"i/$topic.php\"; } ?>\n</body>\n</html>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T17:13:45.003",
"Id": "22927",
"Score": "0",
"body": "thanks for all the input, I've actually been brainstorming a reworking of my framework, so these are some good tips. No, I am not using \"globals\" here in the sense of built in php globals, but rather as my own code which is meant to be used globally, that is, on every page."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T17:07:12.470",
"Id": "14172",
"ParentId": "14091",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14172",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T00:41:56.863",
"Id": "14091",
"Score": "0",
"Tags": [
"php"
],
"Title": "php function for gathering includes...is there a better way than this?"
}
|
14091
|
<p>I want to allow users to share documents (and other stuff) in a database-driven application.</p>
<p>I have designed the following schema to allow for this (PostgreSQL). Some of the tables like <code>Party</code> are skeletal for simplicity.</p>
<p>Diagram (minus lookup tables):</p>
<p><img src="https://i.stack.imgur.com/QCiax.png" alt="Diagram" /></p>
<p>A lookup table for party types:</p>
<pre><code>create table partyType(
id int not null primary key,
description text not null
);
insert into partyType values (1, 'Individual');
insert into partyType values (2, 'Organization');
</code></pre>
<p>A party is an individual or organization, such as a user or customer:</p>
<pre><code>create table party(
id serial primary key,
type int not null,
name text not null,
foreign key (type) references partyType (id)
);
</code></pre>
<p>A party has many email addresses, and an email address can belong to multiple parties (such as "Barb and Jim Jones"):</p>
<pre><code>create table emailAddress(
id serial primary key,
address text not null
);
create table partyEmailAddress(
partyId int not null,
emailAddressId int not null,
primary key (partyId, emailAddressId),
foreign key (partyId) references party (id),
foreign key (emailAddressId) references emailAddress (id)
);
</code></pre>
<p>An item can be private or explicitly shared, or public but unlisted, or public and listed:</p>
<pre><code>create table visibilityType(
id int not null primary key,
description text not null
);
insert into visibilityType values (1, 'Private / Explicit');
insert into visibilityType values (2, 'Public Unlisted');
insert into visibilityType values (3, 'Public Listed');
</code></pre>
<p>Someone with whom you share an item can be a viewer, commenter (can view too), or editor:</p>
<pre><code>create table sharingRoleType(
id int not null primary key,
description text not null
);
insert into sharingRoleType values (1, 'Viewer');
insert into sharingRoleType values (2, 'Commenter');
insert into sharingRoleType values (3, 'Editor');
</code></pre>
<p>An item is the thing that you are sharing (this will be an actual type like Document later):</p>
<pre><code>create table item(
id serial primary key,
ownerId int not null,
visibilityType int not null default 1,
publicRoleType int not null default 1 comment 'the role, if the item is public',
onlyOwnerCanChangePermissions boolean not null default true,
foreign key (ownerId) references party (id),
foreign key (visibilityType) references visibilityType (id)
foreign key (publicRoleType) references sharingRoleType (id)
);
</code></pre>
<p>Do you have a more succinct name than <code>onlyOwnerCanChangePermissions</code>? In <code>gdocs</code>, either only the owner can change permissions, or you can allow other editors to change permissions and add other users.</p>
<p>The below allows an item to be shared with many, and for a party (via their email) to have many items shared with it.</p>
<pre><code>create table itemShare(
itemId int not null,
emailAddressId int not null,
roleType int not null default 1,
primary key (itemId, emailAddressId),
foreign key (itemId) references item (id),
foreign key (emailAddressId) references emailAddress (id),
foreign key (roleType) references sharingRoleType (id)
);
</code></pre>
<ol>
<li><p>Should <code>item.ownerId</code> be removed from item and added as a role type, and be added as an "automatic" <code>itemShare</code>? It would be easier to query for all docs that a user has access to this way.</p>
</li>
<li><p>Is <code>item.publicRoleType</code> correct, seeing as it's only used if the item is public? It seems somewhat denormalized. I could move <code>visibilityType</code> to <code>itemShare</code>, get rid of <code>publicRoleType</code>, and make email addy nullable on <code>itemShare</code>.</p>
</li>
</ol>
<p>Alternative schema - improved?</p>
<p><a href="https://i.stack.imgur.com/FlRSM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FlRSM.jpg" alt="enter image description here" /></a><br />
<sub>(source: <a href="https://snag.gy/zbQwx.jpg" rel="nofollow noreferrer">snag.gy</a>)</sub></p>
|
[] |
[
{
"body": "<p>I would definitely rename <code>onlyOwnerCanChangePermissions</code>, maybe to <code>permissive</code> or <code>restrictPermissions</code> or something like that.</p>\n\n<p>I would also definitely remove <code>item.ownerId</code>, create a new RoleType <code>owner</code> and propagate an <code>itemShare</code> entry. I also think that <code>itemShare</code> is a rather bad name and should be renamed to something like <code>permission</code> or <code>accessList</code>.</p>\n\n<p>Get rid of <code>item.publicRoleType</code> and use <code>itemShare</code> instead. This could also simplify your code e.g. you only have to check <code>itemShare</code> for the access. But i would use an <code>AnonymousUser</code> instead of making the emailAddresse <code>nullable</code>.</p>\n\n<p>I think a better name for <code>sharingRoletype</code> would be just <code>roleType</code> as a role is not necessarily related to sharing.</p>\n\n<p><code>item.visibilityType</code> doesn't really fit into <code>itemShare</code> as <code>itemShare</code> defines permissions (what and who could do what with the document) for users. But you could create a <code>SystemUser</code> and merge <code>visibilityType</code> and <code>sharingRoleType</code> but this isn't a good fit either.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T17:29:58.357",
"Id": "23006",
"Score": "0",
"body": "Hi Ulrich. Thanks for the comments. \n\nHow would the schema look for the permission table? Would I have a PublicListed email address that it points to? And a PublicUnlisted one? Cheers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T22:17:34.193",
"Id": "23156",
"Score": "0",
"body": "@NeilMcGuigan this is a really good question. As I said it isn't a good fit in my opinion to combine the `permission` table and `visibilityType`. I would rather keep them seperated but rename `item.visibilityType` to `item.visibiltiy`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T04:02:22.043",
"Id": "14159",
"ParentId": "14093",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-07-28T02:53:16.043",
"Id": "14093",
"Score": "6",
"Tags": [
"sql",
"mysql",
"postgresql"
],
"Title": "Schema for Google Docs-like sharing"
}
|
14093
|
<p>I use a global variable to fit my need:</p>
<pre><code>scores = {}
def update():
global scores
# fetch data from database
scores = xxx
class MyRequestHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
def choice_with_score(items):
# return a key related to scores
return key
def get_key():
global scores
return choice_with_score(scores)
self.write('%s' % get_key())
self.finish()
if __name__ == '__main__':
# initially update
update()
app = tornado.web.Application([
(r'.*', MyRequestHandler),
])
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(port)
ioloop = tornado.ioloop.IOLoop.instance()
# background update every x seconds
task = tornado.ioloop.PeriodicCallback(
update,
15 * 1000)
task.start()
ioloop.start()
</code></pre>
<p>Here, the function <code>update()</code> gets new data instead of updating in every incoming request, which is why I use a global variable.</p>
<p><strong>Are there other ways to do the same work?</strong></p>
|
[] |
[
{
"body": "<p>You could use a class to keep your <code>scores</code> inside a defined scope and not use the globals. This way it's fairly easy to test and you don't have to deal globals. All you need to ensure is that you always pass the same instance. You could probably do it using some sort Singleton patterns.</p>\n\n<pre><code>import tornado\nimport tornado.web\n\n# I hate the name manager but couldn't come up with something good fast enough.\nclass ScoreManager(object):\n def __init__(self):\n self._scores = {}\n\n def fetch_from_database(self):\n # fetch from database\n self._scores = {'key': 'score'}\n\n def get_all(self):\n return self._scores\n\nclass MyRequestHandler(tornado.web.RequestHandler):\n # this is the way to have sort of a constructor and pass parameters to a RequestHandler\n def initialize(self, score_manager):\n self._score_manager = score_manager\n\n @tornado.web.asynchronous\n def get(self):\n def choice_with_score(items):\n # return a key related to scores\n return key\n\n def get_key():\n global scores\n return choice_with_score(self._score_manager)\n\n self.write('%s' % get_key())\n self.finish()\n\nif __name__ == '__main__':\n # initially update\n score_manager = ScoreManager()\n score_manager.fetch_from_database()\n\n app = tornado.web.Application([\n (r'.*', MyRequestHandler, dict(score_manager=score_manager)), # these params are passed to the initialize method.\n ])\n\n http_server = tornado.httpserver.HTTPServer(app)\n http_server.listen(port)\n ioloop = tornado.ioloop.IOLoop.instance()\n\n # background update every x seconds\n task = tornado.ioloop.PeriodicCallback(\n update,\n 15 * 1000)\n task.start()\n\n ioloop.start()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-13T07:39:31.083",
"Id": "69702",
"ParentId": "14094",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T04:38:35.750",
"Id": "14094",
"Score": "5",
"Tags": [
"python",
"tornado"
],
"Title": "Is there a better way to do get/set periodically in tornado?"
}
|
14094
|
<p>I need to write some code that checks thousands of websites, to determine if they are in English or not.
Below is the source code. Any improvements would be appreciated.</p>
<pre><code>import nltk
import urllib2
import re
import unicodedata
ENGLISH_STOPWORDS = set(nltk.corpus.stopwords.words('english'))
NON_ENGLISH_STOPWORDS = set(nltk.corpus.stopwords.words()) - ENGLISH_STOPWORDS
STOPWORDS_DICT = {lang: set(nltk.corpus.stopwords.words(lang)) for lang in nltk.corpus.stopwords.fileids()}
def get_language(text):
words = set(nltk.wordpunct_tokenize(text.lower()))
return max(((lang, len(words & stopwords)) for lang, stopwords in STOPWORDS_DICT.items()), key=lambda x: x[1])[0]
def checkEnglish(text):
if text is None:
return 0
else:
text = unicode(text, errors='replace')
text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore')
text = text.lower()
words = set(nltk.wordpunct_tokenize(text))
if len(words & ENGLISH_STOPWORDS) > len(words & NON_ENGLISH_STOPWORDS):
return 1
else:
return 0
def getPage(url):
if not url.startswith("http://"):
url = "http://" + url
print "Checking the site ", url
req = urllib2.Request(url)
try:
response = urllib2.urlopen(req)
rstPage = response.read()
except urllib2.HTTPError, e:
rstPage = None
except urllib2.URLError, e:
rstPage = None
except Exception, e:
rstPage = None
return rstPage
def getPtag(webPage):
if webPage is None:
return None
else:
rst = re.search(r'<p\W*(.+)\W*</p>', webPage)
if rst is not None:
return rst.group(1)
else:
return rst
def getDescription(webPage):
if webPage is None:
return None
else:
des = re.search(r'<meta\s+.+\"[Dd]escription\"\s+content=\"(.+)\"\s*/*>', webPage)
if des is not None:
return des.group(1)
else:
return des
def checking(url):
pageText = getPage(url)
if pageText is not None:
if checkEnglish(getDescription(pageText)) == 1:
return '1'
elif checkEnglish(getPtag(pageText)) == 1:
return '1'
elif checkEnglish(pageText) == 1:
return '1'
else:
return '0'
else:
return 'NULL'
if __name__ == "__main__":
f = open('sample_domain_list.txt').readlines()
s = open('newestResult.txt', "w")
for line in f[:20]:
url = line.split(',')[1][1:-1]
check = checking(url)
s.write(url + ',' + check)
s.write('\n')
print check
# f.close()
s.close()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-16T13:57:47.007",
"Id": "23972",
"Score": "0",
"body": "Does your code work as you intend it to? What problems do you see with it? (To help us focus on those...)"
}
] |
[
{
"body": "<p>Some of your functions behave a bit unconventionally.</p>\n<p><code>checkEnglish()</code> only returns 1 or 0. It would be clearer to return <code>True</code> or <code>False</code>, and rename the function to <code>isEnglish()</code>.</p>\n<hr />\n<p><code>getPage()</code> won't allow retrieval of HTTPS URLs. I would avoid trying to be "helpful" by automatically mangling the URL, unless such mangling was really smart and thorough (as good as the intelligence in your browser's address bar). By the way, URI schemes are case insensitive (<a href=\"https://www.rfc-editor.org/rfc/rfc3986#section-3.1\" rel=\"nofollow noreferrer\">RFC 3986 Sec 3.1</a>).</p>\n<p>In <code>getPage()</code>, you swallow exceptions. That's not good practice, but if you're going to do it, do it succinctly:</p>\n<pre><code>def getPage(url):\n print "Checking the site ", url\n req = urllib2.Request(url)\n try:\n response = urllib2.urlopen(req)\n return response.read()\n except:\n return None\n</code></pre>\n<hr />\n<p>In <code>getPtag()</code> and <code>getDescription()</code>, avoid nesting:</p>\n<pre><code>def getPtag(webPage):\n if webPage is None:\n return None\n match = re.search(r'<p\\W*(.+)\\W*</p>', webPage)\n if not match:\n return None\n return match.group(1)\n</code></pre>\n<p>In general, HTML is case insensitive, so use case-insensitive regular expression matching (or an HTML parser).</p>\n<hr />\n<p>Your <code>checking()</code> function could use some improvement:</p>\n<ul>\n<li><p>Returning strings <code>'1'</code>, <code>'0'</code>, or <code>'NULL'</code> is really weird. Returning <code>True</code>, <code>False</code>, or <code>None</code> would make more sense.</p>\n</li>\n<li><p>The name of the function is weird. It should be something like <code>isEnglishUrl()</code>.</p>\n</li>\n<li><p>Prefer to return early, and express the cascade more simply.</p>\n<pre><code> def isEnglishUrl(url):\n pageText = getPage(url)\n if pageText is None:\n return None\n return isEnglish(getDescription(pageText)) or \\\n isEnglish(getPtag(pageText)) or \\\n isEnglish(pageText)\n</code></pre>\n<p>If <code>getPage()</code> hadn't swallowed exceptions in the first place, then <code>isEnglishUrl()</code> wouldn't have to deal with that pesky <code>if pageText is None</code>. Instead, it could just let the exception propagate and let its caller deal with it, for more flexibility with less code.</p>\n</li>\n</ul>\n<hr />\n<p>Since Python 2.5, the preferred way to open and close files is using a <code>with</code> block:</p>\n<pre><code>RESULT_STR = { True: '1', False: '0', None: 'NULL' }\nwith open('sample_domain_list.txt') as f:\n with open('newestResult.txt', 'w') as s:\n for line in f.readlines()[:20]:\n url = line.split(',')[1][1:-1]\n eng = isEnglishUrl(url)\n s.write("%s,%s\\n" % (url, RESULT_STR[eng]))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T22:17:18.803",
"Id": "35786",
"ParentId": "14098",
"Score": "3"
}
},
{
"body": "<ol>\n<li>Use <code>BeautifulSoup</code> to strip the JS, HTML, and CSS formatting.</li>\n<li>Use <code>urllib</code> instead of <code>urllib2</code>.</li>\n</ol>\n\n<p></p>\n\n<pre><code>from bs4 import BeautifulSoup\nfrom urllib import urlopen\nurl = \"http://stackoverflow.com/help/on-topic\"\n\ndef getPage(url) \n html = urlopen(url).read()\n soup = BeautifulSoup(html)\n\n# remove all script and style elements\n for script in soup([\"script\", \"style\"]):\n script.extract() # remove\n\n# get text\n text = soup.get_text()\n return text\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-05T19:37:03.613",
"Id": "83328",
"ParentId": "14098",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T07:57:33.870",
"Id": "14098",
"Score": "2",
"Tags": [
"python",
"parsing",
"natural-language-processing"
],
"Title": "NLTK language detection code in Python"
}
|
14098
|
<p>I have written a generic <code>Collection</code> class which allows me to add and remove items from an encapsulated <code>std::list</code>. The collection will raise an event when an item has been added or removed.</p>
<p>Normally I would have derived this class from the <code>std::list</code>, but I have been strongly recommended against doing so for various reasons. I still need to be able to iterate over the collection, however, and one way of doing so was exposing <code>begin</code> and <code>end</code> methods, returning a vanilla STL iterator:</p>
<pre><code>template <typename T>
class Collection
{
public:
typename std::list<T*>::iterator begin()
{
return _items.begin();
}
void Add(T* item)
{
_items.push_back(item);
...
}
private:
std::list<T*> _items;
};
</code></pre>
<p>Is this a proper way of encapsulating an STL container while retaining the ability to iterate over it?</p>
|
[] |
[
{
"body": "<p>Yes.</p>\n\n<p>But you also want to expose the types of the iterator:</p>\n\n<pre><code>template <typename T>\nclass Collection\n{\n // Since we are going to mention the container type\n // in multiple places actually give it a shorter name.\n // This also helps if you change the container type\n // as you only have to change the type in one place.\n typedef typename std::list<T*> Cont;\n public:\n // Expose your iterator types.\n // That way people don't need to know that you are\n // using a list (thus allowing you to change it in the future)\n // to use your iterators.\n typedef typename Cont::iterator iterator;\n typedef typename Cont::const_iterator const_iterator;\n\n\n // Now iterators can use your types.\n iterator begin() {items.begin();}\n iterator end() {items.end();}\n\n // Sometimes also useful to expose the const versions.\n const_iterator begin() const {items.begin();}\n const_iterator end() const {items.end();} \n\n void Add(T* item)\n {\n items.push_back(item);\n }\n\n private:\n\n Cont items;\n};\n</code></pre>\n\n<h3>Other notes:</h3>\n\n<p>Be careful using a '_' as the first character of an identifier. Most of them are reserved and unless you know all the rules (and everybody in your company does) you may accidentally end up in hot water.</p>\n\n<p>PS. You are OK with <code>_items</code>. I just prefer never to use them (As the first character).</p>\n\n<p>Container class are designed to hold objects, but you are storing pointers.<br>\nThe question now becomes who owns the pointer (as they are responsible for deleting the pointer). This is compounded by your add() interface which also passes a pointer.</p>\n\n<p>In modern C++ you very rarely see RAW pointers being passed around.</p>\n\n<p>How we change the interface will depend on how you expect it to be used. But I assume you are dynamically allocating the object and passing the ownership to the container. In this case I would change the interface to:</p>\n\n<pre><code>void add(std::unique_ptr<T> item)\n// C++03 does not have std::unique_ptr you will need to use std::auto_ptr\n// void add(std::auto_ptr<T> item)\n// Basically it is the same thing but the unique_ptr requires an explicit move.\n</code></pre>\n\n<p>This indicates to the reader and the container that you are passing ownership to the container and it is responsible for deleting the pointer. Note: you will now have to make sure that the destructor correctly destroys the pointers. Also note that because you define the destructor to do some real work you also need to make sure you obey the rule of three (as the default copy constructor and assignment operator will not work correctly).</p>\n\n<p>All this has been encapsulated in the boost ptr container(s).</p>\n\n<p>Take a look at:</p>\n\n<pre><code>boost::ptr_list<T>\n</code></pre>\n\n<p>This is a list that holds pointers to <code>T</code> and as such the items are correctly polymorphic. The container takes ownership of the pointers and will correctly destroy them when the container is destroyed. And finally the container exposes its members via reference to the underlying object and thus works very well with the std:: algorithms.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T15:49:19.003",
"Id": "22816",
"Score": "0",
"body": "Thank you for your valuable input! I will be wrapping the iterators and it was not my intentiont of giving ownership to the collection, so I will take to not to pass raw pointers around. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T19:10:33.077",
"Id": "22819",
"Score": "1",
"body": "If you are **NOT** giving ownership to the collection. Then the interface should be designed to accept a reference not a pointer. You can store a pointer in the list but it should be passed as a reference to the Collection."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T18:56:54.710",
"Id": "14104",
"ParentId": "14099",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "14104",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T12:35:02.857",
"Id": "14099",
"Score": "2",
"Tags": [
"c++"
],
"Title": "Collection in C++"
}
|
14099
|
<p>I am new to<code>boost::thread</code> and am making a producer-consumer with a <code>Monitor</code>. This is how I've coded it so far:</p>
<pre><code>//{ Declarations in header
private:
boost::condition_variable _condition;
boost::mutex _mutex;
std::deque<RawMatrix*> _queue;
boost::detail::atomic_count _count;
//}
void MatrixMonitor::deposit(RawMatrix* rawMatrix){
boost::unique_lock<boost::mutex> lock(_mutex);
_condition.wait(lock, boost::bind(std::less_equal<int>(), boost::ref(_count), max));
_queue.push_back(rawMatrix);
++_count;
_condition.notify_one();
}
RawMatrix* MatrixMonitor::withdraw(){
boost::unique_lock<boost::mutex> lock(_mutex);
_condition.wait(lock, boost::bind(std::greater_equal<int>(), boost::ref(_count), min));
RawMatrix* elem = _queue.front();
_queue.pop_front();
--_count;
_condition.notify_one();
return elem;
}
</code></pre>
<p>So far I've written the <code>Producer</code> like this:</p>
<pre><code>void MatrixProducer::produce(){
while(true){
boost::mutex::scoped_lock lock(_mutex);
RawMatrix* matrix = rawMatrix();
_monitor->deposit(matrix);
boost::this_thread::sleep(boost::posix_time::milliseconds(sleep_msecs));
}
}
boost::thread& MatrixProducer::start(){
_thread = boost::thread(boost::bind(&MatrixProducer::produce, this));
return _thread;
}
RawMatrix* MatrixProducer::rawMatrix(){/*Generates and returns a matrix*/}
</code></pre>
<p>The <code>Consumer</code>:</p>
<pre><code>boost::thread& MatrixConsumer::start(){
_thread = boost::thread(boost::bind(&MatrixConsumer::consume, this));
return _thread;
}
void MatrixConsumer::consume(){
while(true){
boost::mutex::scoped_lock lock(_mutex);
RawMatrix* matrix = _monitor->withdraw();
_matrix->deposit(Matrix);
boost::this_thread::sleep(boost::posix_time::milliseconds(sleep_msecs));
}
}
</code></pre>
<p>Is this okay? Also, who will have the ownership of this: <code>Producer</code> or <code>Consumer</code> and <code>Monitor</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T19:08:36.393",
"Id": "22802",
"Score": "1",
"body": "We can review the first part of the code here. But this is probably not the best site to ask `ho`w to do something; first its off-topic but secondly there are fewer experts roaming around (and thus you may not get a good answer). So ask the `how` question on SO to get the best answers."
}
] |
[
{
"body": "<p>Why do you insist on putting the '<em>' on members. It makes them look so ugly. Also most identifiers beginning with '</em>' are reserved so you need to be careful. If you must use decade old conventions (that have been abandoned) to identify members use 'm_` as the prefix.</p>\n\n<p>The reason I hate them is for this:</p>\n\n<pre><code>--_count;\n\n// That is ugly and harder to read than:\n\n--count; // but that's just an opionon.\n // The bit about being reserved is a problem though.\n // and if you use leading underscores you should understand\n // all the associated rules.\n</code></pre>\n\n<p>Curious where max/min come from?</p>\n\n<pre><code>_condition.wait(lock, boost::bind(std::less_equal<int>(), boost::ref(_count), max));\n // ^^^^^\n</code></pre>\n\n<p>Passing RAW pointers around is not common in C++ (unlike C).<br>\nNormally you wrap a pointer inside a smart pointer object to indicate ownership semantics (and thus who is responsible for deleting the object).</p>\n\n<pre><code>// No indication of ownership is retained or passed the the moniter.\n// So we have no idea who should delete rawMatrix?\n//\n// Have you passed ownership to the moniter or is the caller retaining ownership\n// If the owner retains ownership when does he delete it?\nvoid MatrixMonitor::deposit(RawMatrix* rawMatrix){\n\n\n// I suppose you have to return a pointers as you were passed a pointer.\n// but now the caller has no idea weather he should delete the pointer he\n// is given or if the pointer is still owned by somebody else.\nRawMatrix* MatrixMonitor::withdraw(){\n</code></pre>\n\n<p>Personally I would change the interface to make sure the ownership symantics are well defined. In this case I would pass ownership to the moniter and pass ownership out to the person withdrawing the item:</p>\n\n<pre><code>void MatrixMonitor::deposit(std::unique_ptr<RawMatrix> rawMatrix){\n\nstd::unique_ptr<RawMatrix> MatrixMonitor::withdraw(){\n</code></pre>\n\n<p>I think you want to separate producer and consumer from the Moniter. These are three different types of object. When you construct the producer/consumer you pass it a monitor object to use when it deposits/withdraws items.</p>\n\n<pre><code>int main()\n{\n MatrixMonitor monitor;\n Producer farmer(monitor); // Pass monitor by reference \n // So the farmer is adding to this moiter.\n Consumer shopper(moniter); // shooper uses the same monitor as the\n // farmer but because it is a consumer will\n // call withdraw() while the \n // farmer calles deposit()\n\n farmer.run();\n shopper.run();\n\n // don't forget to wait for the threads to exit.\n farmer.join();\n shopper.join();\n}\n</code></pre>\n\n<h3>Edit: Based on new code for Producer/Consumer</h3>\n\n<p>One would assume that the producer needs to finish at some point.<br>\nYou may want to change <code>while(true)</code> into <code>while(!finished)</code> or similar.</p>\n\n<pre><code>void MatrixProducer::produce(){\n while(true){\n</code></pre>\n\n<p>Don't see any need for this mutex.</p>\n\n<pre><code> boost::mutex::scoped_lock lock(_mutex);\n</code></pre>\n\n<p>Ownership semantics again. Who owns the generated matrix?</p>\n\n<pre><code> RawMatrix* matrix = rawMatrix();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T19:48:19.673",
"Id": "22803",
"Score": "0",
"body": "Please Check my edit. I'll focus on the Ptr issue. but I've added my current Producer consumer code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T19:21:23.023",
"Id": "14105",
"ParentId": "14100",
"Score": "1"
}
},
{
"body": "<p>When I wrote a similar class a few years ago, I found it was actually possible to:</p>\n\n<ol>\n<li>Make the collection type templated.</li>\n<li>Keep the queuing / threading logic in a non-templated base class so that it did not need to be exposed in the header file (unlikely the templated collection it was protecting which did).</li>\n</ol>\n\n<p>Of course it doesn't have to \"derive\", but separate concerns of the collection type and the locking logic.</p>\n\n<p>The other thing I have always implemented in this kind of collection is multi_push and multi_pop whereby a producer can add more than one item in a single locking action, and a consumer can similarly clear all the data to process rather than pull them off in ones.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T15:16:34.740",
"Id": "37958",
"ParentId": "14100",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T13:18:13.937",
"Id": "14100",
"Score": "2",
"Tags": [
"c++",
"multithreading",
"boost",
"producer-consumer"
],
"Title": "boost::thread producer consumer"
}
|
14100
|
<p>I'm a beginner in JavaScript. I wrote this code so the main image get set on whatever thumbnail image the user clicks. </p>
<p>And if the user didn't click on any image the main photo get changed every 10 seconds. </p>
<p>Here's my code (I feel like I'm doing some unnecessary work here in the timers but I can't figure it out): </p>
<p><strong>HTML:</strong></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Photo Gallery</title>
<link rel="stylesheet" href="style.css" />
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="mainContainer">
<div id="mainImage">
<img src="img/Flowers_by_Deidameia.jpg" />
</div>
<div id="thumbnails">
<img class="imgThumbnails" src="img/Flowers_by_Deidameia.jpg"/>
<img class="imgThumbnails" src="img/flower.jpg"/>
<img class="imgThumbnails" src="img/cone-flowers-preview.jpg" />
<img class="imgThumbnails" src="img/two_flowers.jpg" />
</div>
</div>
<div id="imgCaption">
</div>
</body>
</html>
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre><code>window.onload = function(){
var mainImage = document.getElementById("mainImage").getElementsByTagName("img")[0],
thumbnailImages = document.getElementById("thumbnails").getElementsByTagName("img"),
j = 0;
var startTimer = function(){
stillTimer = setInterval(function(){
j = (j < 3) ? ++j : 0 ;
mainImage.src = thumbnailImages[j].src;
}, 10000);
}
startTimer();
for(i = 0 ; i < thumbnailImages.length ; i++){
thumbnailImages[i].addEventListener("click", function(evt){
clearInterval(stillTimer);
mainImage.src = evt.target.src;
++j;
startTimer();
});
};
}
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>body {
margin: auto;
width: 800px;
height: 800px;
}
#mainContainer {
width: 760px;
height: 800px;
}
#mainImage {
margin: auto;
height: 560px;
}
#mainImage img {
margin: 10px;
width: 740px;
height: 540px;
}
#thumbnails {
padding-top: 10px;
height: 205px;
}
.imgThumbnails {
margin-left: 6px;
height: 186px;
width: 180px;
display: inline;
hover:
}
.imgThumbnails:hover {
cursor: pointer;
}
</code></pre>
|
[] |
[
{
"body": "<p>This code could use some changes</p>\n\n<ul>\n<li>Using <code>window.onload</code> is a bit old skool, consider using <a href=\"https://stackoverflow.com/a/559161/7602\">this</a>.</li>\n<li>If you put <code>id=\"mainImage\"</code> on the image instead of on the div, you can change your code to <code>var mainImage = document.getElementById(\"mainImage\");</code></li>\n<li><code>j = (j < 3) ? ++j : 0 ;</code> has the magic constant 3 , which really should point to <code>thumbnailImages.length</code></li>\n<li>stillTimer is a global, which is unnecessary. The following code would solve this:</li>\n</ul>\n\n<blockquote>\n<pre><code>function startTimer(){\n return setInterval(function(){\n j = (j < 3) ? ++j : 0 ;\n mainImage.src = thumbnailImages[j].src;\n }, 10 * 1000);\n} \n\nvar stillTimer = startTimer();\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T15:31:19.813",
"Id": "38327",
"ParentId": "14103",
"Score": "6"
}
},
{
"body": "<p>I'm not a JS guy, so I focus on your HTML and CSS.</p>\n\n<p><strong>HTML</strong></p>\n\n<ul>\n<li>You're using the HTML5 doctype, so you can safely ommit the <code>type</code>-attribute on the <code>script</code>-tag</li>\n<li>Add the viewport meta tag to the <code>head</code>-area to ensure correct viewport behavior on mobile devices:<br><code><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></code><br>(Note: I left out the self-closing <code>/</code> for the meta tag as well)</li>\n<li>Avoid using ID's excessively; Things like caption and even a gallery itself are likely to occur multiple times on the same page – Classes are more appropriate there</li>\n</ul>\n\n<p><strong>CSS:</strong></p>\n\n<ul>\n<li>You have an error in the <code>.imgThumbnails</code> -rule, where you use a <code>hover</code>-property; There is no such property!</li>\n<li>Side note: There is also no semi-colon. Although one can ommit the last semi-colon in a list of property-declarations, I highly encourage anyone not to do this. It just leads to unnecessary trouble</li>\n<li>You're using a lot of fixed widths and heights. This is very restrictive and should be avoided.</li>\n</ul>\n\n<p>Before I get deeper in to making suggestions on how to improve your code further, it would be great to have some kind of <a href=\"http://jsfiddle.net\" rel=\"nofollow\">demo</a>. This doesn't need to be a working example of your gallery, you can use placeholders instead of images.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-24T20:20:15.553",
"Id": "39995",
"ParentId": "14103",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T18:22:05.850",
"Id": "14103",
"Score": "6",
"Tags": [
"javascript",
"html",
"beginner",
"css"
],
"Title": "A script for a photo gallery/slideshow"
}
|
14103
|
<p>I have this function that calculates average. I don't want it to look like this. I am hoping for a less cliche average function because I see that most people's look like this.</p>
<pre><code>function mean(array) {
var num=0;
for (var i=1;i<=array.length;i++) num=num+array[i];
var divide=num/array.length;
alert(divide);
}β
</code></pre>
<p>Can anyone change this up to be better than before? It doesn't have to be more efficient but just look better.</p>
|
[] |
[
{
"body": "<p>First of all, your code is incorrect. Arrays have a starting index of <code>0</code>, not <code>1</code>. Furthermore, <code>array.length</code> is one more than the last filled index (because the length is 1 based, and the array is 0 based. Yes, this is confusing.) So you're starting by not including the first item, and then also adding up an undefined item.</p>\n\n<p>And what happens if you get an empty array? You divide by zero, which is MADNESS!! MADNESS I TELL YOU!</p>\n\n<p>Second, there's a reason the code looks the same as everywhere: You have followed the definition of the average; the sum of components divided by the number of components. There's no shame in this, you should actually be proud that you've managed to conform to the standard.</p>\n\n<p>If you really want, you can make the loop implicit. ES5 (ECMAScript 5, the latest js standard) defined an <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce\"><code>Array.prototype.reduce</code></a> function (click link for the reference.) It's a perfect fit for your needs, but doesn't change the core algorithm.</p>\n\n<p>Third, your <code>mean</code> function is doing something unexpected: Instead of just calculating the mean, it displays it as well. This does not follow expectations (or at least my expectation), as a function which calculates the mean should do that, and just that. That translates to a very important design aspect, which says that a function should do one thing, one thing only, and do it well. Because imagine if <code>Math.sqrt</code>, for instance, starts displaying the square roots instead of giving you them. Like division by zero, it's madness all over again!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T12:20:19.940",
"Id": "22814",
"Score": "0",
"body": "Example code would probably be nice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T16:33:07.983",
"Id": "22817",
"Score": "4",
"body": "@Inkbug Since the OP is new to js, imo it'd be better to let him try first before giving him an already baked solution"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-19T18:43:26.560",
"Id": "141265",
"Score": "0",
"body": "Dividing by 0 results in `Number.POSITIVE_INFINITY`, which is not altogether unreasonable, though `Number.NaN` would be more appropriate in this case."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T20:23:52.633",
"Id": "14107",
"ParentId": "14106",
"Score": "25"
}
},
{
"body": "<p>More efficient: No; More readable: Yes</p>\n\n<pre><code>function mean( list, more ) {\n\n if ( more ) {\n\n list = [].slice.call( arguments );\n\n } else if ( !list || list[0] === undefined ) return;\n\n var a = list,\n b = list.length;\n\n\n return (function execute() {\n\n if ( !a.length ) return 0;\n\n return ( a.pop() / b ) + execute();\n\n })();\n\n}\n</code></pre>\n\n<p>What this function basically does is use recursion to divide each number in the array by the length of the array. Since this is true...</p>\n\n<p>\\$\\dfrac{a + b + c}{d} = \\dfrac{a}{d} + \\dfrac{b}{d} + \\dfrac{c}{d}\\$</p>\n\n<p>I use that logic in the function and it works just fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T07:39:48.317",
"Id": "22811",
"Score": "0",
"body": "Though this is a nifty implementation, I feel that it would be a bad choice to ever actually put it in production code. Just my 2 cents though, I suppose."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T12:11:25.620",
"Id": "22813",
"Score": "0",
"body": "I know; that's why I mentioned it was less efficient. For loops are very fast so it's better to use (well, an improved version) of the OP's function than mine. But if he's looking for a different/readable way to write this, I think the above is the best way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T14:09:15.213",
"Id": "22815",
"Score": "6",
"body": "Your definition of elegant is obviously not the same as mine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T00:43:35.550",
"Id": "22832",
"Score": "6",
"body": "@David I think this is significantly less readable than a simple loop (and I suspect a large majority would agree). Fancy code is not always better code, especially when the fancy code is implementing a slower algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T10:26:43.343",
"Id": "22865",
"Score": "3",
"body": "Additionally to what has been said, I find this **far** less readable than the question's code. :( I also frown upon re-declaring the function `execute` on every call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T20:56:50.690",
"Id": "22904",
"Score": "0",
"body": "Also, despite the fact that the equations are _mathematically_ equivalent, they aren't (necessarily) equivalent _practically_ in computer terms. That is, they _may_ generate different results. This is, of course, because computers can't represent certain ratios very well (like, say, `5/3`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T22:20:15.237",
"Id": "22906",
"Score": "0",
"body": "@Corbin The OP said he wanted a better looking function regardless of efficiency. True, the function call is expensive, but as Zirak implied, it would be best to use the conventional function. Moreover, I wouldn't recommend anyone to use this in their own code for something as simple as average, but I'm simply giving him what he asked for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T00:07:26.513",
"Id": "22907",
"Score": "0",
"body": "@David Sometimes it's better to ignore the direct question and answer the underlying one, though that is of course just my opinion. He wants a \"less cliche\" implementation, but there are reasons why standard implementations become standard, and I feel that on a site dedicated to improving code quality, it would have been more appropriate to discuss that rather than offering a more complex, less efficient implementation. At the end of the day though, it comes down to opinion that I cannot backup with facts. For what it's worth, it was not me who -1'd, though to be honest, I did consider it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-11-07T17:04:32.053",
"Id": "341495",
"Score": "0",
"body": "I feel this implementation is unnecessarily complicated for the given task of writing more readable code. Also, you modify the array and use recursion, which isn't really necessary."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T21:18:13.280",
"Id": "14108",
"ParentId": "14106",
"Score": "1"
}
},
{
"body": "<p>Zirak's answer is all the advice you need, but since he didn't actually write any code, here's how I might re-write it.</p>\n\n<pre><code>function mean(arr) { // it's ok to use short variable names in short, simple functions\n // set all variables at the top, because of variable hoisting\n var i,\n sum = 0, // try to use informative names, not \"num\"\n len = arr.length; // cache arr.length because accessing it is usually expensive\n for (i = 0; i < len; i++) { // arrays start at 0 and go to array.length - 1\n sum += arr[i]; // short for \"sum = sum + arr[i];\"\n } // always use brackets. It'll save you headaches in the long run\n // don't mash your computation and presentation together; return the result.\n return sum / len;\n}\n</code></pre>\n\n<p>Note that this code is optimized for arrays with at least 1 element; if the majority of its uses are on 0-length arrays, you'd see a performance boost if you added a short return.</p>\n\n<p>Alternatively you can use Array.prototype.reduce. I highly recommend that you not use this method - while it is more \"unique\", it is also much harder to understand and much less efficient. And good code strives to be readable and efficient (and robust), not unique.</p>\n\n<pre><code>var mean = (function () { // Use an IIFE to get private storage\n // cache this function - it's very expensive to re-create it every time you call mean()\n function addLast(prev, current) {\n return prev + current;\n }\n // return an anonymous function. When we call mean(), this is what is called. The reason\n // we can't set it directly is because we need something with access to addLast, and we\n // don't want addLast in the global scope.\n return function (arr) {\n return arr.reduce(addLast, 0) / arr.length;\n };\n})(); // end of IIFE. executes the function and sets mean to the return value.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T10:30:13.667",
"Id": "22866",
"Score": "0",
"body": "+1, but I would do `sum += +arr[i]` to coerce a number out of the item. I also see no problem with returning `NaN` for an empty list - the mean of an empty list is actually **not** 0. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T14:11:56.037",
"Id": "22873",
"Score": "0",
"body": "@ANeves - `n / 0` is `Infinity`, not `NaN`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T17:42:31.540",
"Id": "22891",
"Score": "2",
"body": "@ANeves whether to coerce a number is certainly an important consideration, but my preference is to provide documentation and assume the caller reads it. Passing in something other than numbers is a caller error, and it's a bad idea to correct for some errors (`['1', '2', '3']`) but not all (`['thing']`). (actually, I don't think this function should be correcting any user errors, but we don't need to get into that). Also, it bothers me to take a (slight) performance hit in correct-use cases for the sake of code that doesn't even use the function correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T17:54:36.057",
"Id": "22894",
"Score": "0",
"body": "Well the mean of `[]` is neither `0` nor `Infinity`. `0` seemed like a convenient default to me, but I guess it would be more informative to return `NaN`. Any thoughts? If there's some consensus then I'll edit the code, if necessary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T08:05:30.233",
"Id": "22912",
"Score": "0",
"body": "@JosephSilber but it won't divide by 0, it divides by 1. So for an empty array, it returns 0/1 = 0. (0/N = NaN; N/0 = Infinity. 0/0 seems to be NaN too.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T08:07:58.653",
"Id": "22913",
"Score": "0",
"body": "@st-boost I agree."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T14:36:42.960",
"Id": "22924",
"Score": "0",
"body": "@ANeves - AFAIK, `0/N === 0`. See here: http://jsfiddle.net/up2yc/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T14:55:45.837",
"Id": "22925",
"Score": "0",
"body": "@JosephSilber Woops! Thanks for spotting. (so: `N/0 === Infinity`, `0/N === 0`, `0/0 === NaN`)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T08:21:57.373",
"Id": "22967",
"Score": "0",
"body": "Ok, I've thought about it some more and I think it isn't this function's place to provide a default value when none can be computed (and it's easy enough to write `mean(arr) || 0`). So I've removed the part that made `mean([])` return `0` instead of `NaN`. If anybody disagrees, please tell me so."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T07:52:34.387",
"Id": "14139",
"ParentId": "14106",
"Score": "8"
}
},
{
"body": "<p>Maybe use some array methods like <code>reduce</code>? This will add up all the elements, starting with an initial sum of 0 (the second argument to <code>reduce</code>), then the sum is divided by the array's length to compute the mean.</p>\n\n<pre><code>function mean(array) {\n const sum = array.reduce((a, b) => a + b, 0);\n return sum / array.length;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-11-07T19:16:26.050",
"Id": "341519",
"Score": "0",
"body": "`const` is an ECMAScript addition that was not available in 2012, when this question was posted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-11-07T19:17:11.787",
"Id": "341520",
"Score": "0",
"body": "It is available now, so I don't see the issue."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-11-07T19:19:44.983",
"Id": "341522",
"Score": "0",
"body": "[Reviewing old code according to modern standards can be acceptable.](https://codereview.meta.stackexchange.com/q/2169/9357) It's just a caveat that is worth noting in the interest of fairness."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-11-07T17:01:06.687",
"Id": "179840",
"ParentId": "14106",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14107",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T20:01:16.653",
"Id": "14106",
"Score": "8",
"Tags": [
"javascript",
"beginner"
],
"Title": "JavaScript function to calculate the average of an array"
}
|
14106
|
<pre><code>def json_response(response):
assert response.code == 200, 'bad http response'
return json.loads(response.body)
def custom_json_response(response):
response = json_response(response)
assert 'answer' in response, 'invalid custom json'
return response['answer']
</code></pre>
<p>The code looks straightforward but I wonder if there any chance to rewrite it to achieve the following:</p>
<ol>
<li>Replace <code>json_response</code> direct call with composition.</li>
<li>Code should not become a message from Sirius: everybody should still be able to understand it just without any efforts.</li>
<li>It should be robust (composition type safety) yet easy extensible.</li>
</ol>
<p>Any ideas?</p>
|
[] |
[
{
"body": "<p>I'm not sure I'm directly responding to your points, since I don't think I get what you're aiming for, but:</p>\n\n<ul>\n<li><p><code>assert</code>s shouldn't be used for these types of checks (I personally don't use them at all, but if you are going to use them, they're for checking invariants)</p></li>\n<li><p>As for what I <em>think</em> you were going for with your composition point, I would just have your second function take an already <code>json.loads</code>ed object (or the return value of your first function) passed in.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T04:15:28.083",
"Id": "14111",
"ParentId": "14110",
"Score": "0"
}
},
{
"body": "<p>I would not rely on <code>assert</code>. If Python is started with the -O option, then assertions will be stripped out and not evaluated. Better to raise an Exception here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-27T08:05:46.320",
"Id": "15970",
"ParentId": "14110",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-28T22:33:18.300",
"Id": "14110",
"Score": "2",
"Tags": [
"python",
"functional-programming"
],
"Title": "Safe composition in python"
}
|
14110
|
<p>If you use capturing parenthesis in the regular expression pattern in Python's <code>re.split()</code> function, it will include the matching groups in the result (<a href="http://docs.python.org/library/re.html#re.split" rel="nofollow">Python's documentation</a>).</p>
<p>I need this in my Clojure code and I didn't find an implementation of this, nor a Java method for achieving the same result.</p>
<pre><code>(use '[clojure.string :as string :only [blank?]])
(defn re-tokenize [re text]
(let [matcher (re-matcher re text)]
(defn inner [last-index result]
(if (.find matcher)
(let [start-index (.start matcher)
end-index (.end matcher)
match (.group matcher)
insert (subs text last-index start-index)]
(if (string/blank? insert)
(recur end-index (conj result match))
(recur end-index (conj result insert match))))
(conj result (subs text last-index))))
(inner 0 [])))
</code></pre>
<p>Example:</p>
<pre><code>(re-tokenize #"(\W+)" "...words, words...")
=> ["..." "words" ", " "words" "..." ""]
</code></pre>
<p>How could I make this simpler and / or more efficient (maybe also more Clojure-ish)?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-26T20:33:50.170",
"Id": "79236",
"Score": "3",
"body": "For what it's worth, [clojure.contrib.string/partition](http://clojuredocs.org/clojure_contrib/clojure.contrib.string/partition) does this exactly."
}
] |
[
{
"body": "<p>You can adjust you implementation to be a lazy-seq for some added performance:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(use '[clojure.string :as string :only [blank?]])\n\n(defn re-tokenizer [re text]\n (let [matcher (re-matcher re text)]\n ((fn step [last-index]\n (when (re-find matcher)\n (let [start-index (.start matcher)\n end-index (.end matcher)\n match (.group matcher)\n insert (subs text last-index start-index)]\n (if (string/blank? insert)\n (cons match (lazy-seq (step end-index)))\n (cons insert (cons match (lazy-seq (step end-index))))))))\n 0)))\n</code></pre>\n\n<p>This implementation will be more efficient as the results will only be calculated as needed. For instance if you only needed the first 10 results from a really long string you can use:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(take 10 (re-tokenize #\"(\\W+)\" really-long-string)\n</code></pre>\n\n<p>and only the first 10 elements will be computed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-30T10:47:19.290",
"Id": "16054",
"ParentId": "14113",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T08:49:34.703",
"Id": "14113",
"Score": "3",
"Tags": [
"python",
"regex",
"clojure"
],
"Title": "Implementation of Python's re.split in Clojure (with capturing parentheses)"
}
|
14113
|
<p>Below is an algorithm to generate all pairwise combinations for a set of random variables. <a href="http://en.wikipedia.org/wiki/All-pairs_testing" rel="nofollow">See here</a> for an explanation of what constitutes a minimal all-pairs set. The algorithm below works but I feel that it is inefficient. Any suggestions would be welcome.</p>
<pre><code>from operator import itemgetter
from itertools import combinations, product, zip_longest, chain, permutations
def pairwise(*variables, **kwargs):
num_vars = len(variables)
#Organize the variable states into pairs for comparisons
indexed_vars = sorted(
([(index, v) for v in vals] for index, vals in enumerate(variables)),
key=len,
reverse=True)
var_combos = combinations(range(num_vars), 2)
var_products = (product(indexed_vars[i], indexed_vars[j]) for i, j in var_combos)
vars = chain.from_iterable(zip_longest(*var_products))
#Initialize the builder list
builders = []
seen_pairs = set()
#Main algorithm loop
for pair in vars:
if not pair or pair in seen_pairs:
continue
d_pair = dict(pair)
#Linear search through builders to find an empty slot
#First pass: look for sets that have intersections
for builder in builders:
intersection = builder.keys() & d_pair.keys()
if len(intersection) == 1:
v = intersection.pop()
if builder[v] == d_pair[v]:
builder.update(d_pair)
#Update seen pairs
seen_pairs.update(combinations(builder.items(), 2))
break
else:
#Second Pass
for builder in builders:
intersection = builder.keys() & d_pair.keys()
if not len(intersection):
builder.update(d_pair)
#Update seen pairs
seen_pairs.update(combinations(builder.items(), 2))
break
else:
#No empty slots/pairs identified. Make a new builder
builders.append(d_pair)
seen_pairs.add(pair)
#Fill in remaining values
complete_set = set(range(num_vars))
defaults = {var[0][0]: var[0][1] for var in indexed_vars}
for builder in builders:
if len(builder) == num_vars:
yield tuple(val for index, val in sorted(builder.items()))
else:
for key in complete_set - builder.keys():
builder[key] = defaults[key]
yield tuple(val for index, val in sorted(builder.items()))
</code></pre>
<p>Usage Example:</p>
<pre><code>u_vars = [
[1, 2, 3, 4],
["A", "B", "C"],
["a", "b"],
]
result = list(pairwise(*u_vars))
print(result) #prints list of length 12
</code></pre>
|
[] |
[
{
"body": "<p>This is not generating correct pairwise combinations.</p>\n\n<p>Input data</p>\n\n<pre><code>[['Requests'],\n ['Create','Edit'],\n ['Contact Name','Email','Phone','Subject','Description','Status','Product Name','Request Owner','Created By','Modified By','Request Id','Resolution','To Address','Account Name','Priority','Channel','Category','Sub Category'],\n ['None','is','isn\\'t','contains','doesn\\'t contain','starts with','ends with','is empty','is not empty'],\n ['Contact Name','Email','Phone','Subject','Description','Status','Product Name','Request Owner','Mark Spam','Resolution','To Address','Due Date','Priority','Channel','Category','Sub Category']]\n</code></pre>\n\n<p>Result by Microsoft PICT</p>\n\n<p><a href=\"http://pastebin.com/cZdND9UA\" rel=\"nofollow\">http://pastebin.com/cZdND9UA</a></p>\n\n<p>Result by your code\n<a href=\"http://pastebin.com/EC6xv4vG\" rel=\"nofollow\">http://pastebin.com/EC6xv4vG</a></p>\n\n<p>This generates only for NONE in most of cases such as this</p>\n\n<p>Requests Create Account Name None Category\nRequests Create Account Name None Channel\nRequests Create Account Name None Description\nRequests Create Account Name None Due Date</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T17:24:52.927",
"Id": "23266",
"Score": "0",
"body": "Hmmm... I'm not sure why this is. When I was using smaller inputs, it was working fine. Let me find out what's wrong with it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T00:10:04.353",
"Id": "23286",
"Score": "0",
"body": "Apparently, the problem is nontrivial. I don't really have time to compare algorithms but here is a paper that I found useful: https://www.research.ibm.com/haifa/projects/verification/mdt/papers/AlgorithmsForCoveringArraysPublication191203.pdf"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T01:40:51.623",
"Id": "23288",
"Score": "0",
"body": "Every other generator except PICT, I have tested failed in large sets not in small sets. Yes the problem is nontrivial one. I also working on it. If I port that algorithm I will post it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T02:18:33.767",
"Id": "23290",
"Score": "0",
"body": "That would be awesome. I think the main problem is the heuristic I'm using to determine the order in which I add items to the array. I reformulated the code (same algorithm, just neater code) in the answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-06T04:14:48.340",
"Id": "14364",
"ParentId": "14120",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T20:02:46.787",
"Id": "14120",
"Score": "7",
"Tags": [
"python",
"algorithm",
"combinatorics"
],
"Title": "Pairwise Combinations Generator"
}
|
14120
|
<p>I have just written a solution to the following problem: </p>
<blockquote>
<p>We all know the classic "guessing game" with higher or lower prompts. lets do a role reversal; you create a program that will guess numbers between 1-100, and respond appropriately based on whether users say that the number is too high or too low. Try to make a program that can guess your number based on user input and great code!</p>
</blockquote>
<p>I would like suggestions on how I can make my solution less complicated and if there is a more efficient way to solve the problem.</p>
<p>Here is my implementation. I have tried to implement a binary search strategy to solve the problem.</p>
<pre><code>public class Guesser
{
private List<int> _possibleAnswers = new List<int>();
private bool _isCorrectNumber = false;
private bool _higher = false;
private int _numberOfGuesses = 0;
private int _answer;
public Guesser(int min, int max)
{
for (var i = min; i <= max; i++)
_possibleAnswers.Add(i);
}
public void Guess()
{
while (!_isCorrectNumber)
{
var middleOfAnswers = _possibleAnswers.Max() - (_possibleAnswers.Count / 2);
Console.WriteLine("Is the number {0}?", middleOfAnswers);
var hint = Console.ReadLine().ToLower();
_isCorrectNumber = hint.Equals("yes");
if (_isCorrectNumber)
{
_answer = middleOfAnswers;
continue;
}
_higher = hint.ToLower().Equals("higher");
if (_higher)
{
var count = _possibleAnswers.FindIndex(guess => guess.Equals(middleOfAnswers)) + 1;
_possibleAnswers.RemoveRange(0, count);
}
else
{
var startIndex = _possibleAnswers.FindIndex(guess => guess.Equals(middleOfAnswers));
var count = _possibleAnswers.FindIndex(guess => guess.Equals(_possibleAnswers.Max())) - startIndex + 1;
_possibleAnswers.RemoveRange(startIndex, count);
}
_numberOfGuesses++;
}
Console.WriteLine("The number was {0} and it took me {1} guess{2}",
_answer, _numberOfGuesses, _numberOfGuesses > 1 ? "es" : string.Empty);
}
}
</code></pre>
<p>Any suggestions on how I can improve this would be great. I'd also like to know if I have understood the concept behind a binary search and implemented it correctly.</p>
|
[] |
[
{
"body": "<p>It seems to me that you understand the concept correctly, but your implementation is horrible. That's because you don't need the whole <code>_possibleAnswers</code> list at all, you should just keep two numbers: the lower bound and the upper bound, you can compute everything you need from that.</p>\n\n<p>There are also some smaller issues:</p>\n\n<ol>\n<li><p>Don't use <code>Max()</code> if you know that the maximum number will be always the last one. You can instead use <code>Last()</code>, that will be much faster. And a something similar applies to the way you compute <code>count</code> in the <code>else</code> branch: you already know that <code>FindIndex()</code> will return the index of the last item in the list, you don't need to walk the list twice for that.</p></li>\n<li><p>C# is not Java, you should use <code>==</code> to compare <code>string</code>s instead of <code>Equals()</code>, it's much more readable.</p></li>\n<li><p>You won't need <code>_isCorrectNumber</code>, if you use <code>break</code> instead of <code>continue</code>. That would make your code shorter and less confusing. (I thought something like βwait, why does he continue when he wants to end iterating?β when I read that part of the code.)</p></li>\n</ol>\n\n<p>Binary search should take only <em>O</em>(log <em>n</em>) time, but your code is <em>O</em>(<i>n</i><sup>2</sup> log <em>n</em>), which is really bad. The <em>n</em><sup>2</sup> part is caused by using <code>Max()</code> inside of the <code>FindIndex()</code> lambda, if you fixed that by simply computing the <code>Max()</code> once before calling <code>FindIndex()</code> (which is still horrible, see #1 above), it would make your code <em>O</em>(<i>n</i> log <em>n</em>), although that is still bad.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T09:33:24.680",
"Id": "22864",
"Score": "1",
"body": "Thanks svick, I got caught up in reading about the binary search on wikipedia where it says you need an ordered list and didn't actually realise I could use it in this case without. I will implement your suggestions later and update, thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T17:04:47.293",
"Id": "22879",
"Score": "0",
"body": "Sorry if this seems like a silly question but what is meant by O(n log n)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T17:17:03.910",
"Id": "22884",
"Score": "0",
"body": "You mean you don't know the big O notation? In that case, read [this answer on SO](http://stackoverflow.com/a/487278/41071), it explains in quite a detail, but in plain English. If you want to write fast algorithms, it's quite important to understand the time complexity (which is what the big O represents here) of the algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T17:32:36.900",
"Id": "22887",
"Score": "0",
"body": "No I hadn't heard of it before, thanks for the link."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T18:59:55.647",
"Id": "22899",
"Score": "0",
"body": "I made some of the changes you suggested here: https://gist.github.com/f5f7e57353e78ede7433"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T12:06:40.267",
"Id": "63694",
"Score": "0",
"body": "The update is much improved. A few points: You can so without bools for `_isCorrectGuess` and `_higher` (good practice to say `_isHigher` so we know it's a boolean) - just `while(true){}` and `if(hint == \"higher\")`. Input valuation - I would consider an if/else if structure to check `hint` as lower, higher then yes (as this is least likely so why check unless the hint is not low/high), then the final else might ask the user to try again with valid input. At the moment input of foo will be interpreted as lower."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-05T10:46:50.583",
"Id": "360930",
"Score": "0",
"body": "`C# is not Java, you should use == to compare strings instead of Equals(), it's much more readable.` Please come to my work and tell that to everyone else here. I work in `Equals()` territory :("
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T20:52:46.303",
"Id": "14122",
"ParentId": "14121",
"Score": "4"
}
},
{
"body": "<p>Here is my version. I made it a bit more \"functional\" - less state, more static (not to be confused with noise). I have two methods instead of one; An <code>enum</code> helps me pack an open-ended input (a string of arbitrary length) into what I really want (tri-state). I tried to minimize RAM usage by initializing the dictionary and the list of allowed keywords only once. At this small size, the dictionary is not a perfect choice in terms of run time; two plain arrays would do a better job, but it is a premature optimization.</p>\n\n<p>The code is also slightly more unit-test friendly since it takes <code>Console.In</code> and <code>Console.Out</code> as parameters. I am still not perfectly happy with the code though. The body of the <code>Guess</code> method should be shorter; the logic and the textual \"UI\" is still not well separated, plus the language for interacting with a user is not that great. ideally the \"engine\" would be completely separated from \"reporting\".</p>\n\n<pre><code>namespace CodeReview\n{\n using System;\n using System.Collections.Generic;\n using System.Diagnostics.Contracts;\n using System.IO;\n using System.Linq;\n\n internal enum Direction : short\n {\n Lower = -1,\n Equal = 0,\n Higher = 1\n }\n\n public class Guesser\n {\n // Perhaps an overkill? \n private static readonly Dictionary<string, Direction> inputToDirection = new Dictionary<string,Direction>()\n {\n { \"e\", Direction.Equal},\n { \"equal\", Direction.Equal},\n { \"h\", Direction.Higher},\n { \"higher\", Direction.Higher},\n { \"l\", Direction.Lower},\n { \"lower\", Direction.Lower},\n };\n\n private static readonly string inputChoices = String.Join(\", \", inputToDirection.Keys.OrderBy(v=>v));\n\n public static void Guess(int min, int max)\n {\n Guess(min: min, max: max, input: Console.In, output: Console.Out);\n }\n\n // This method exists for testability. Num steps should start with 1.\n public static void Guess(int min, int max, TextReader input, TextWriter output, int numSteps = 1)\n {\n Contract.Requires(min >= 0, \"Lower bound cannot be negative.\");\n Contract.Requires(max >= 0, \"Upper bound cannot be negative.\");\n Contract.Requires(min <= max, \"Upper bound cannot be less than the lower bound.\");\n\n if (min == max)\n {\n output.Write(\"The answer must be \");\n output.WriteLine(min);\n output.WriteLine(\"It took \" + numSteps + \" steps to solve.\");\n return;\n }\n\n int middle = (min + max) / 2;\n output.WriteLine(\"Is the number {0} (lower|l equal|e, or higher|h?\", middle);\n Direction direction = ScanDirection(input: input, output: output);\n if (direction == Direction.Equal)\n {\n output.WriteLine(\"It took \" + numSteps + \" steps to solve.\");\n return;\n }\n\n if (direction == Direction.Higher)\n {\n min = middle;\n }\n else\n {\n max = middle;\n }\n\n Guess(min, max, input, output, numSteps + 1);\n }\n\n // A persistent user can turn this method into an infinite loop.\n private static Direction ScanDirection(TextReader input, TextWriter output)\n {\n string hint = Console.ReadLine().Trim().ToLower();\n\n Direction result;\n if (inputToDirection.TryGetValue(key: hint, value: out result))\n {\n return result;\n }\n\n output.WriteLine(\"Come again? The choices are: {0}.\", inputChoices);\n return ScanDirection(input: input, output: output);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-14T22:39:28.127",
"Id": "23824",
"Score": "0",
"body": "that's an interesting version, nice to see a recursive implementation and the fact that input and output are passed in as parameters, keeping it nice and flexible. The answer would be even more helpful with an explanation of the changes you made."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-14T21:35:24.930",
"Id": "14673",
"ParentId": "14121",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14122",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T20:25:39.847",
"Id": "14121",
"Score": "4",
"Tags": [
"c#",
"game",
"binary-search"
],
"Title": "Number-guessing game in C#"
}
|
14121
|
<p>Part of an application that I am building in CakePHP 2.1 needs to send out an e-mail based on a template from a database. The end user is able to set the from, reply to, to, cc, and bcc addresses. Because the user could enter just about anything, I need to process those addresses into a usable array that I can pass to <code>CakeEmail</code>. To this end, I wrote the following code and I want to make sure that it is efficient before I put it into production use (and possibly write a tutorial about it).</p>
<pre><code><?php
$parseAddress = function(&$address) {
preg_match_all('/"(.*?)"\s*\<(.*?)\>/', $address, $matches); // Check if $address is in the format ""Test Address" <test@example.com>". TODO: Make the quotes optional.
if (!is_array($matches) || !isset($matches[1]) || empty($matches[1]) || !isset($matches[2]) || empty($matches[2]) || is_null(array_filter($matches))) {
return $address; // Return the plain e-mail address if name is not provided
}
$parsedAddress = array();
for ($i = 0; $i < count($matches[0]); $i++) {
$parsedAddress[$matches[2][$i]] = $matches[1][$i]; // Add e-mail address to array as "email => name"
}
$addressCSV = str_getcsv($address); // Split e-mail addresses into array - seems to automatically strip anything between "<" and ">" characters
foreach($addressCSV as $key => $val) {
if (!filter_var($val, FILTER_VALIDATE_EMAIL)) { // Take advantage of afformentioned stripping by filtering out everything that is not an e-mail address
unset($addressCSV[$key]); // Remove the array value that is not an e-mail address
}
}
return array_merge($addressCSV, $parsedAddress); // Join the parsed e-mail addresses with the filtered addresses and return the resulting array
};
echo $parseAddress('test@address.tld'); // returns (string) "test@address.tld"
echo $parseAddress('"Test Address" <test@example.com>, test@address.tld, "Smith, John"<jsmith@example.com>'); // returns (array) [0 => "test@address.tld", "test@example.com" => "Test Address", "jsmith@example.com" => "Smith, John"]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T17:19:47.457",
"Id": "23228",
"Score": "0",
"body": "Our team was kicked off the project due to budget concerns before I got the chance to refactor this code. Oh well."
}
] |
[
{
"body": "<p>Alright, I have a number of suggestions. Some of which will invalidate others. The reason I'm keeping these \"invalid\" bits in is because they are just good practice and I'm trying to pass that along. In order to get the most from this you will have to read all the way through.</p>\n\n<p>First off, why are you using lambda functions (also known as anonymous functions or closures)? This seems completely unnecessary. The thing to keep in mind about lambda functions is that they are not compiled at run time. This means that they should be used sparingly because each time they are called they must be compiled separately. Lambda functions should really only be used for callbacks. Though I'll be honest, I don't even use them then. They tend to make the functions they are used in bulky and therefore difficult to read. In the five, almost six, years I've been doing this I've never once used, or needed, lambda functionality. Best to just use a real function and set a return value. Though that may just be an opinion.</p>\n\n<p>REGEX should only be used as a last resort. Yes it is much more powerful than any of the simpler string functions, but because of that power it requires more processing power as well, and is therefore usually slower. So, if you can do the same thing with a simpler function, it is more than likely better. For instance, you could use <code>explode()</code> here to separate the initial string by spaces to get the first name, last name, and email addresses. If multiple addresses are used you can use <code>explode()</code>'s limiter to only return 3 elements, then use <code>explode()</code> again on the email section. This appears to be what you are doing anyways and is more than likely quicker. Though you may not notice a difference unless you are doing it thousands of times. Besides, REGEX is almost impossible to read and if not documented properly just looks like a foreign language to those of us who come after you and try to figure out what it does. REGEX is another one of those things I've hardly ever needed to have, there is almost always another way.</p>\n\n<pre><code>$matches = explode( ' ', $address, 3 );\nlist( $firstName, $lastName, $addresses ) = $matches;//for illustration purposes only\n$addresses = trim( $addresses, '<>' );//remove those brackets before exploding\n$addresses = explode( ', ', $addresses );//could use str_getcsv() here if you wanted\n</code></pre>\n\n<p>Because <code>explode()</code> always creates an array unless the string passed to it was empty, you can now just check that the result isn't FALSE and then check the array's size to determine if the only thing it contains is an address. This looks much better than that long list of confusing if arguments.</p>\n\n<pre><code>if( $matches === FALSE ) {\n return FALSE;\n}\nif( count( $matches ) == 1 ) {\n return $address;\n}\n</code></pre>\n\n<p>By the way, you should still validate and sanitize the address with <code>filter_var()</code> in the above scenario. Validate with <code>FILTER_VALIDATE_EMAIL</code> and sanitize with <code>FILTER_SANITIZE_EMAIL</code>. I believe you can even do both at once. Well, I know you can, but I'm not sure if it will return FALSE if its not valid, so you may have to play around with it.</p>\n\n<pre><code>$email = filter_var( $address, FILTER_VALIDATE_EMAIL | FILTER_SANITIZE_EMAIL );\n</code></pre>\n\n<p>For and while loops declare the functions passed to them as parameters on each iteration, so using <code>count()</code> as a parameter here is inefficient. This value isn't going to change so it should be declared before the loop. Foreach is the only loop that doesn't have this issue, though it is still better, in my opinion, to separate functions from foreach loops as well.</p>\n\n<pre><code>$length = count( $matches[ 0 ] );\nfor( $i = 0; $i < $length; $i++ ) {\n</code></pre>\n\n<p>Although, I believe you could get away with just using <code>array_combine()</code> here instead of a loop.</p>\n\n<pre><code>$parsedAddress = array_combine( $matches[ 2 ], $matches [ 1 ] );\n</code></pre>\n\n<p><code>str_getcsv()</code> may do what you want, but only because it is a hack. CSV stands for \"Comma Separated Values\" and is used to store and read data separated by commas. I think, though I can't find it documented anywhere, that I remember reading somewhere that it also uses angle brackets \"<>\" to separate groups and that is why this works, though I'm not sure. I'm honestly not sure why this works, but you should not rely on hacks to get a job done. What if that function changes? Then if you ever upgrade your server you will be stuck trying to figure out how to fix it, or someone else with less knowledge of how this works will. Besides, you've already gotten those email addresses into an array, why do it again? Just use <code>array_keys()</code> on <code>$parsedAddress</code> to get an array of email addresses. Better yet, while you are looping over <code>$matches</code> the first time and setting them, why not just use <code>filter_var()</code> there? Or if you end up using the <code>array_combine()</code> example, you could use <code>array_map()</code> to apply a callback function, in this case <code>filter_var()</code>, to the <code>array_keys()</code>. You've not just doubled the work here, but quadrupled it. You loop over <code>$matches</code>, then you loop over <code>$addressCSV</code>, then when you merge them, PHP loops over both arrays again to find the differences.</p>\n\n<p>Last thing. Why are you referencing <code>$address</code>? I can find no instance where you are changing its value. This is also unnecessary, and, in my opinion, is a big no-no. Variable referencing is a powerful tool, but, like most powerful tools, it does have some drawbacks. The biggest one is that they are difficult to spot and therefore make troubleshooting difficult. Another is that they aren't well known. So while I can spot this, someone else may have never seen it before. After all, it is just an ampersand and not an actual function that they can easily look up.</p>\n\n<p>I hope this all helps. If you need any clarification, just ask.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T17:21:36.100",
"Id": "22928",
"Score": "0",
"body": "Thanks for your feedback @showerhead! Here is my response/resoning: (1) I am using a lambda because this being called from a class method and is only used in that method. (2) I used a regular expression because that is what I know and it seemed the simplest way. (3) How much faster (or slower) would using `explode` be? (4) I am not too concerned with validation since (a) a limited set of users will enter this data and (b) CakePHP handles this automatically. (5) Never thought about this - I have always done it that way. (6) Yeah I know it is a hack - a dirty one"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T17:25:30.540",
"Id": "22929",
"Score": "0",
"body": "(7) I referenced `address` because originally it was being modified before I refactored that part of the code out. I have since removed that which the provided code does not reflect. I will take your suggestions into consideration and maybe use them to further refactor this code. Thanks again!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T18:30:19.357",
"Id": "22931",
"Score": "0",
"body": "@Joseph: Looks like it could be made into a private method with the same results, but again, this might be preference. Just keep in mind they shouldn't be used repeatedly as this defeats their purpose. I can't tell you for sure how much difference `explode()` would make. You can use `microtime()` to test it. I do know that REGEX functions tend to run slower. However, if you are doing multiple things that is impossible with string functions or very much more complicated, then REGEX is an acceptable alternative. Just document what its doing, not everyone agrees that REGEX is simple ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-05T17:18:28.197",
"Id": "23227",
"Score": "0",
"body": "I'm marking this as accepted since nobody else chimed in."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T16:31:03.317",
"Id": "14170",
"ParentId": "14127",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14170",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-29T23:46:06.227",
"Id": "14127",
"Score": "2",
"Tags": [
"php"
],
"Title": "Process list of e-mail addresses in PHP 5.3"
}
|
14127
|
<p>So I feel like I'm a good coder, but that's from my point of view. Can you take a look at my code and give me some tips or criticize me on my code. Or give me some tips or things to add or make things smaller.</p>
<p>console class</p>
<pre><code> public class console {
public static void main(String[] args) {
//makes the window/console
window console=new window();
}
}
</code></pre>
<p>window class</p>
<pre><code> import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//the main terminal
public class window extends JFrame{
//variables
static JTextArea window;
JTextField input;
//main window for commands and shit
public window(){
//super because it is
super("my Java Console");
//able to call c.parse
final findCommand c=new findCommand();
//the input is set and shit
input = new JTextField();
input.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
input.setText("");
c.parse(event.getActionCommand());
}
}
);
add(input, BorderLayout.NORTH);
//this window is set and shit
window = new JTextArea();
window.setEditable(false);
add(new JScrollPane(window));
setSize(300,150);
setVisible(true);
}
}
</code></pre>
<p>displayInWindow class</p>
<pre><code> public class displayInWindow {
//display stuff in the window in the window class
public static void display(String s){
//the JTextArea is the window and one long continues sentence but with \n
window.window.append(s+"\n");
}
}
</code></pre>
<p>findCommand class</p>
<pre><code> public class findCommand {
//finds out what command to run
public void parse(String s){
//deletes spaces before and after
s=s.trim();
//splits into an array
String[] cmd=s.split(" ");
//depending on the length of the string array to find how many parameters it has
if(cmd.length==2){
switch(cmd[0].toLowerCase()){
//the print command
case "print":displayInWindow.display(cmd[1]);break;
//gets a variable that was set
case "get":displayInWindow.display(basicCommands.get(cmd[1]));
}
}else if(cmd.length==3){
//switch is set to the first one and set to lowercase
switch(cmd[0].toLowerCase()){
//add
case "add":displayInWindow.display(basicCommands.add(cmd[1], cmd[2]));break;
//subtract
case "subtract":displayInWindow.display(basicCommands.subtract(cmd[1], cmd[2]));break;
//multiply
case "multiply":displayInWindow.display(basicCommands.multiply(cmd[1],cmd[2]));break;
//divide
case "divide":displayInWindow.display(basicCommands.divide(cmd[1],cmd[2]));break;
//remainder
case "remainder":displayInWindow.display(basicCommands.remainder(cmd[1], cmd[2]));break;
//power
case "power":displayInWindow.display(basicCommands.power(cmd[1], cmd[2]));break;
//set
case "set":displayInWindow.display(basicCommands.set(cmd[1],cmd[2]));break;
}
//switch is set to the middle parameter and no need to set it to lowercase
switch(cmd[1]){
//adds
case "+":displayInWindow.display(basicCommands.add(cmd[0], cmd[2]));break;
//subtracts
case "-":displayInWindow.display(basicCommands.subtract(cmd[0], cmd[2]));break;
//multiplys
case "*":displayInWindow.display(basicCommands.multiply(cmd[0],cmd[2]));break;
//divides
case "/":displayInWindow.display(basicCommands.divide(cmd[0],cmd[2]));break;
//finds the remainder
case "%":displayInWindow.display(basicCommands.remainder(cmd[0], cmd[2]));break;
//set
case "=":displayInWindow.display(basicCommands.set(cmd[0],cmd[2]));break;
}
}else{
if(basicCommands.variables.containsKey(s)){
//if what typed in is a variable
displayInWindow.display(s+" is "+basicCommands.variables.get(s) );
}else{
//if it is just random typing it displays it
displayInWindow.display(cmd[0]);
}
}
}
</code></pre>
<p>basicCommands class</p>
<pre><code>import java.util.Hashtable;
public class basicCommands {
//hashtable for set and get
public static Hashtable variables =new Hashtable();
//adds 2 variables
public static String add(String num1,String num2){
try{
try{
if(num1.contains(".")||num2.contains(".")){
return(num1+" + "+num2+" = "+Double.toString(Double.parseDouble(num1)+Double.parseDouble(num2)));
}else{
return(num1+" + "+num2+" = "+Integer.toString(Integer.parseInt(num1)+Integer.parseInt(num2)));
}
}catch(Exception e){
if(variables.get(num1).toString().contains(".")||variables.get(num2).toString().contains(".")){
return(num1+" + "+num2+" = "+num2+Double.toString(Double.parseDouble(variables.get(num1).toString())+Double.parseDouble(variables.get(num2).toString())));
}else{
return(num1+" + "+num2+" = "+Integer.toString(Integer.parseInt(variables.get(num1).toString())+Integer.parseInt(variables.get(num2).toString())));
}
}
}catch(Exception e){
if(variables.containsKey(num1)){
if(variables.get(num1).toString().contains(".")||num2.contains(".")){
return(num1+" + "+num2+" = "+Double.toString(Double.parseDouble(variables.get(num1).toString())+Double.parseDouble(num2)));
}else{
return(num1+" + "+num2+" = "+Integer.toString(Integer.parseInt(variables.get(num1).toString())+Integer.parseInt(num2)));
}
}else{
if(num1.contains(".")||variables.get(num2).toString().contains(".")){
return(num1+" + "+num2+" = "+Double.toString(Double.parseDouble(num1))+Double.parseDouble(variables.get(num2).toString()));
}else{
return(num1+" + "+num2+" = "+Integer.toString(Integer.parseInt(num1)+Integer.parseInt(variables.get(num2).toString())));
}
}
}
}
//subtracts 2 variables
public static String subtract(String num1,String num2){
try{
try{
if(num1.contains(".")||num2.contains(".")){
return(num1+" - "+num2+" = "+Double.toString(Double.parseDouble(num1)-Double.parseDouble(num2)));
}else{
return(num1+" - "+num2+" = "+Integer.toString(Integer.parseInt(num1)-Integer.parseInt(num2)));
}
}catch(Exception e){
if(variables.get(num1).toString().contains(".")||variables.get(num2).toString().contains(".")){
return(num1+" - "+num2+" = "+Double.toString(Double.parseDouble(variables.get(num1).toString())-Double.parseDouble(variables.get(num2).toString())));
}else{
return(num1+" - "+num2+" = "+Integer.toString(Integer.parseInt(variables.get(num1).toString())-Integer.parseInt(variables.get(num2).toString())));
}
}
}catch(Exception e){
if(variables.containsKey(num1)){
if(variables.get(num1).toString().contains(".")||num2.contains(".")){
return(num1+" - "+num2+" = "+Double.toString(Double.parseDouble(variables.get(num1).toString())-Double.parseDouble(num2)));
}else{
return(num1+" - "+num2+" = "+Integer.toString(Integer.parseInt(variables.get(num1).toString())-Integer.parseInt(num2)));
}
}else{
if(num1.contains(".")||variables.get(num2).toString().contains(".")){
return(num1+" - "+num2+" = "+Double.toString(Double.parseDouble(num1)-Double.parseDouble(variables.get(num2).toString())));
}else{
return(num1+" - "+num2+" = "+Integer.toString(Integer.parseInt(num1)-Integer.parseInt(variables.get(num2).toString())));
}
}
}
}
//multiplys 2 variables
public static String multiply(String num1,String num2){
try{
try{
if(num1.contains(".")||num2.contains(".")){
return(num1+" * "+num2+" = "+Double.toString(Double.parseDouble(num1)*Double.parseDouble(num2)));
}else{
return(num1+" * "+num2+" = "+Integer.toString(Integer.parseInt(num1)*Integer.parseInt(num2)));
}
}catch(Exception e){
if(variables.get(num1).toString().contains(".")||variables.get(num2).toString().contains(".")){
return(num1+" * "+num2+" = "+Double.toString(Double.parseDouble(variables.get(num1).toString())*Double.parseDouble(variables.get(num2).toString())));
}else{
return(num1+" * "+num2+" = "+Integer.toString(Integer.parseInt(variables.get(num1).toString())*Integer.parseInt(variables.get(num2).toString())));
}
}
}catch(Exception e){
if(variables.containsKey(num1)){
if(variables.get(num1).toString().contains(".")||num2.contains(".")){
return(num1+" * "+num2+" = "+Double.toString(Double.parseDouble(variables.get(num1).toString())*Double.parseDouble(num2)));
}else{
return(num1+" * "+num2+" = "+Integer.toString(Integer.parseInt(variables.get(num1).toString())*Integer.parseInt(num2)));
}
}else{
if(num1.contains(".")||variables.get(num2).toString().contains(".")){
return(num1+" * "+num2+" = "+Double.toString(Double.parseDouble(num1)*Double.parseDouble(variables.get(num2).toString())));
}else{
return(num1+" * "+num2+" = "+Integer.toString(Integer.parseInt(num1)*Integer.parseInt(variables.get(num2).toString())));
}
}
}
}
//divides 2 variables
public static String divide(String num1,String num2){
try{
try{
if(num1.contains(".")||num2.contains(".")){
return(num1+" / "+num2+" = "+Double.toString(Double.parseDouble(num1)/Double.parseDouble(num2)));
}else{
if(Double.parseDouble(num1)%Double.parseDouble(num2)==0){
return(num1+" / "+num2+" = "+Integer.toString(Integer.parseInt(num1)/Integer.parseInt(num2)));
}else{
return(num1+" / "+num2+" = "+Double.toString(Double.parseDouble(num1)/Double.parseDouble(num2)));
}
}
}catch(Exception e){
if(variables.get(num1).toString().contains(".")||variables.get(num2).toString().contains(".")){
return(num1+" / "+num2+" = "+Double.toString(Double.parseDouble(variables.get(num1).toString())/Double.parseDouble(variables.get(num2).toString())));
}else{
if(Double.parseDouble(variables.get(num1).toString())%Double.parseDouble(variables.get(num2).toString())==0){
return(num1+" / "+num2+" = "+Integer.toString(Integer.parseInt(variables.get(num1).toString())/Integer.parseInt(variables.get(num2).toString())));
}else{
return(num1+" / "+num2+" = "+Double.toString(Double.parseDouble(variables.get(num1).toString())/Double.parseDouble(variables.get(num2).toString())));
}
}
}
}catch(Exception e){
if(variables.containsKey(num1)){
if(variables.get(num1).toString().contains(".")||num2.contains(".")){
return(num1+" / "+num2+" = "+Double.toString(Double.parseDouble(variables.get(num1).toString())/Double.parseDouble(num2)));
}else{
if(Double.parseDouble(variables.get(num1).toString())%Double.parseDouble(num2)==0){
return(num1+" / "+num2+" = "+Integer.toString(Integer.parseInt(variables.get(num1).toString())/Integer.parseInt(num2)));
}else{
return(num1+" / "+num2+" = "+Double.toString(Double.parseDouble(variables.get(num1).toString())/Double.parseDouble(num2)));
}
}
}else{
if(num1.contains(".")||variables.get(num2).toString().contains(".")){
return(num1+" / "+num2+" = "+Double.toString(Double.parseDouble(num1)/Double.parseDouble(variables.get(num2).toString())));
}else{
if(Double.parseDouble(num1)%Double.parseDouble(variables.get(num2).toString())==0){
return(num1+" / "+num2+" = "+Integer.toString(Integer.parseInt(num1)/Integer.parseInt(variables.get(num2).toString())));
}else{
return(num1+" / "+num2+" = "+Double.toString(Double.parseDouble(num1)/Double.parseDouble(variables.get(num2).toString())));
}
}
}
}
}
//finds the remainder
public static String remainder(String num1,String num2){
try{
try{
if(Double.parseDouble(num1)%Double.parseDouble(num2)==0){
return(num1+" % "+num2+" = "+Integer.toString(0));
}else{
return(num1+" % "+num2+" = "+Integer.toString((int) (Double.parseDouble(num1)%Double.parseDouble(num2))));
}
}catch(Exception e){
if(Double.parseDouble(variables.get(num1).toString())%Double.parseDouble(variables.get(num2).toString())==0){
return(num1+" % "+num2+" = "+Integer.toString(0));
}else{
return(num1+" % "+num2+" = "+Integer.toString((int) (Double.parseDouble(variables.get(num1).toString())%Double.parseDouble(variables.get(num2).toString()))));
}
}
}catch(Exception e){
if(variables.containsKey(num1)){
if(Double.parseDouble(variables.get(num1).toString())%Double.parseDouble(num2)==0){
return(num1+" % "+num2+" = "+Integer.toString(0));
}else{
return(num1+" % "+num2+" = "+Integer.toString((int)(Double.parseDouble(variables.get(num1).toString())%Double.parseDouble(num2))));
}
}else{
if(Double.parseDouble(num1)%Double.parseDouble(variables.get(num2).toString())==0){
return(num1+" % "+num2+" = "+Integer.toString(0));
}else{
return(num1+" % "+num2+" = "+Integer.toString((int)(Double.parseDouble(num1)%Double.parseDouble(variables.get(num2).toString()))));
}
}
}
}
//powers the first one to the second one
public static String power(String num1,String num2){
try{
try{
if(Math.floor(Math.pow(Double.parseDouble(num1), Double.parseDouble(num2)))==Math.pow(Double.parseDouble(num1), Double.parseDouble(num2))){
return(num1+" ^ "+num2+" = "+Integer.toString((int)(Math.pow(Double.parseDouble(num1), Double.parseDouble(num2)))));
}else{
return(num1+" ^ "+num2+" = "+Double.toString(Math.pow(Double.parseDouble(num1), Double.parseDouble(num2))));
}
}catch(Exception e){
if(Math.floor(Math.pow(Double.parseDouble(variables.get(num1).toString()), Double.parseDouble(variables.get(num2).toString())))==Math.pow(Double.parseDouble(variables.get(num1).toString()), Double.parseDouble(variables.get(num2).toString()))){
return(num1+" ^ "+num2+" = "+Integer.toString((int)(Math.pow(Double.parseDouble(variables.get(num1).toString()), Double.parseDouble(variables.get(num2).toString())))));
}else{
return(num1+" ^ "+num2+" = "+Double.toString(Math.pow(Double.parseDouble(variables.get(num1).toString()), Double.parseDouble(variables.get(num2).toString()))));
}
}
}catch(Exception e){
if(variables.containsKey(num1)){
if(Math.floor(Math.pow(Double.parseDouble(variables.get(num1).toString()), Double.parseDouble(num2)))==Math.pow(Double.parseDouble(variables.get(num1).toString()), Double.parseDouble(num2))){
return(num1+" ^ "+num2+" = "+Integer.toString((int)(Math.pow(Double.parseDouble(variables.get(num1).toString()), Double.parseDouble(num2)))));
}else{
return(num1+" ^ "+num2+" = "+Double.toString(Math.pow(Double.parseDouble(variables.get(num1).toString()), Double.parseDouble(num2))));
}
}else{
if(Math.floor(Math.pow(Double.parseDouble(num1), Double.parseDouble(variables.get(num2).toString())))==Math.pow(Double.parseDouble(num1), Double.parseDouble(variables.get(num2).toString()))){
return(num1+" ^ "+num2+" = "+Integer.toString((int)(Math.pow(Double.parseDouble(num1), Double.parseDouble(variables.get(num2).toString())))));
}else{
return(num1+" ^ "+num2+" = "+Double.toString(Math.pow(Double.parseDouble(num1), Double.parseDouble(variables.get(num2).toString()))));
}
}
}
}
//set something in the hashtable
public static String set(String num1,String num2){
variables.put(num1, num2);
return(num1+" was set to "+num2);
}
//gets something in a hashtable
public static String get(String num1){
try{
return (variables.get(num1).toString());
}catch(NullPointerException e){
return(num1+" was not set to anything.");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T05:24:27.390",
"Id": "22838",
"Score": "5",
"body": "Consistent spacing and indenting will help you and the reviewers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T07:01:47.260",
"Id": "22872",
"Score": "2",
"body": "Look at [Joshua Bloch book](http://java.sun.com/docs/books/effective/), and compare your work and his advices, about switch, StringBulder, catch use, control and other professional practices"
}
] |
[
{
"body": "<p>Some tips:</p>\n\n<ul>\n<li>In Java there is a convention - names of classes start with uppercase letter</li>\n<li>Instance variables like <code>JTextArea</code> etc. should be private and not static. Static fields should be used very rarely.</li>\n<li>Every Swing component should be created and changed on EDT. Starting point for Swing applications usually looks like this:</li>\n</ul>\n\n<hr>\n\n<pre><code> public static void main(String[] args) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n MyFrame frame = new MyFrame();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setVisible(true);\n }\n });\n }\n</code></pre>\n\n<ul>\n<li>Use proper variable names: if I see variable 'window' I think that it's of type <code>JFrame</code>, <code>JDialog</code>, <code>JWindow</code> etc. for <code>JTextField</code> it can be something like 'commandTF', 'commandField', etc.</li>\n<li>Use IDE and use formatter (<a href=\"http://eclipse.org/\">Eclipse</a>, <a href=\"http://netbeans.org/\">Netbeans</a>, etc.)</li>\n<li><code>displayInWindow</code> is unnecessary - too little functionality. You'll end up with so called \"spaghetti-code\"</li>\n<li>Usually if you have many switch statements with many close in concept cases - replace it with polymorphism (<code>enum</code>s are also useful)</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T15:07:23.647",
"Id": "14148",
"ParentId": "14130",
"Score": "5"
}
},
{
"body": "<p><em>@Xeon</em> mentioned some good point, and here are some other:</p>\n\n<ol>\n<li><p>Comment like this does not help too much:</p>\n\n<pre><code>//splits into an array\nString[] cmd=s.split(\" \");\n</code></pre>\n\n<p>If somebody knows Java they understand the code, so the comment is only duplication and noise. Further reading: <em>Clean Code by Robert C. Martin, Chapter 4: Comments</em></p></li>\n<li><p>In your code <code>String.split</code> does not handle well if users put two or more spaces between the arguments. I'd use Guava's <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Splitter.html\" rel=\"nofollow noreferrer\"><code>Splitter</code></a> here. It could <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Splitter.html#trimResults%28%29\" rel=\"nofollow noreferrer\"><code>trimResults</code></a> and <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Splitter.html#omitEmptyStrings%28%29\" rel=\"nofollow noreferrer\"><code>omitEmptyStrings</code></a>.</p></li>\n<li><p>I'm not completely sure if it could help or not, but I'd check <a href=\"http://commons.apache.org/cli/\" rel=\"nofollow noreferrer\">Apache Commons CLI</a> and try to parse the arguments with this library. The <a href=\"http://commons.apache.org/cli/api-1.1/org/apache/commons/cli/OptionBuilder.html#hasArgs%28int%29\" rel=\"nofollow noreferrer\"><code>hasArgs(int num)</code></a> method looks promising. Further reading: <em>Effective Java, 2nd Edition, Item 47: Know and use the libraries</em></p></li>\n<li><p>Instead of the <code>Hashtable</code> use <code>HashMap</code> (with type parameters): </p>\n\n<pre><code>Map<String, String> variables = new HashMap<String, String>();\n</code></pre>\n\n<p>See: <a href=\"https://stackoverflow.com/questions/40471/differences-between-hashmap-and-hashtable\">Differences between HashMap and Hashtable?</a></p></li>\n<li><p>The methods in the <code>BasicCommands</code> class have lots of <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow noreferrer\">smells</a>:</p>\n\n<ol>\n<li>It's hard to follow because it uses exceptions for ordinary control flow. (<em>Effective Java, 2nd Edition, Item 57: Use exceptions only for exceptional conditions</em>)</li>\n<li>It contains lots of duplication. For example, <code>num1 + \" + \" + num2 + \" = \"</code> should be extracted out to a <code>resultPrefix</code> local variable.</li>\n<li>It uses floating point variables where you may need exact results. (<em>Effective Java, 2nd Edition, Item 48: Avoid float and double if exact answers are required</em>; <a href=\"https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency\">Why not use Double or Float to represent currency?</a>)</li>\n</ol>\n\n<p>Using <code>BigDecimal</code>s would reduce the necessary code dramatically since it could store non-integer values, so it handles doubles and integers too, therefore you can omit a few conditions. </p>\n\n<pre><code>public static String add(final String num1, final String num2) {\n final BigDecimal resolvedNum1 = resolveNumber(num1);\n final BigDecimal resolvedNum2 = resolveNumber(num2);\n\n return String.format(\"%s + %s = %s\", num1, num2, resolvedNum1.add(resolvedNum2));\n}\n\nprivate static BigDecimal resolveNumber(final String number) {\n final String value = variables.get(number);\n if (value != null) {\n return new BigDecimal(value);\n }\n return new BigDecimal(number);\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T12:55:02.353",
"Id": "14167",
"ParentId": "14130",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T02:24:18.807",
"Id": "14130",
"Score": "2",
"Tags": [
"java",
"parsing",
"swing"
],
"Title": "Can you guys look at my java project and give me some tips?"
}
|
14130
|
<p>Here is my method:</p>
<pre><code>// can change
DWORD step[2] = { 0xAC, 0x723A };
packageType = 1;
DWORD computeLevel(DWORD blockNum)
{
DWORD num = (blockNum / 0x70E4) * step[1];
if (blockNum < 0x70E4)
return num + step[0];
return (1 << packageType) + num;
}
</code></pre>
<p>I am trying to optimize this for speed, as it gets called about 300,000 times and one little operation could add alot of time on. If I change the blockStep to just constant values, this makes it much, much faster. The problem is, is that they can change so I cannot make it const. Also, if I just have it return a straight up 0, no comparisons, it saves my code around 1 minute, 30 seconds, so this function is really slowing me down.</p>
<p>Also, it would be nice if this function could also be enhanced. I already tried by best, but it would be great if it can get better.</p>
<pre><code>DWORD computeLevel0(DWORD blockNum)
{
WORD quotient1 = (blockNum / 0xAA);
BYTE quotient2 = (blockNum / 0x70E4);
DWORD num = quotient1 * 0xAC;
// optimizations (0 comparison)
WORD mult1 = quotient1;
mult1 |= mult1 >> 8;
mult1 |= mult1 >> 4;
mult1 |= mult1 >> 2;
mult1 |= mult1 >> 1;
mult1 &= 1;
BYTE mult2 = quotient2;
mult2 |= mult2 >> 4;
mult2 |= mult2 >> 2;
mult2 |= mult2 >> 1;
mult2 &= 1;
num += ((quotient2 + 1) << packageType) * mult1;
num += (((1 << packageType)) * mult2) * mult1;
return num;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T06:19:48.550",
"Id": "22842",
"Score": "1",
"body": "Are there any characteristics of blockNum that we need to be aware of? Occurs sequentially with no gaps? Essentially random on each call? Only in a specific range?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T06:29:22.283",
"Id": "22844",
"Score": "0",
"body": "blockNum will always be less than 0xFFFFFF. Yes, it is pretty much random on each call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T07:54:57.933",
"Id": "22850",
"Score": "0",
"body": "I don't think any of your hand optimizations are actually providing you with a benefit. This kind of macro optimization is ultimately self defeating and usually leads to slower code as you confuse the compiler optimizer which is a million times better than you at optimizations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T08:07:03.300",
"Id": "22854",
"Score": "0",
"body": "After my analysis (see below). This code is contributing to 0.0001% of the execution time. Any time spent trying to optimize this is a complete and utter waste of time. Write it as clearly as possible without regard for optimization. Anything you do will have **ZERO** affect on the run time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T08:37:01.047",
"Id": "22859",
"Score": "1",
"body": "There are at least 2 bugs in your code (initializing byte to value that is too large for the type and accessing the `step` array out of bounds). Fix those bugs first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T09:05:06.347",
"Id": "22863",
"Score": "0",
"body": "I'm sorry, I has those because I quickly put that in and didn't copy and paste my exact code. I have updated it."
}
] |
[
{
"body": "<p>I'll expand on this later when I get a chance, but something immediately jumps out at me:</p>\n\n<pre><code>DWORD num = (blockNum / 0x70E4) * step[2];\nif (blockNum < 0x70E4)\n</code></pre>\n\n<p>You could rearrange this and potentially save a few operations:</p>\n\n<pre><code>DWORD computeLevel(DWORD blockNum)\n{\n\n if (blockNum < 0x70E4) {\n //if blockNum < 0x70e4, (blockNum / 0x70e4) == 0, thus num == 0.\n return step[1];\n }\n\n DWORD num = (blockNum / 0x70E4) * step[2];\n\n return (1 << packageType) + num;\n\n}\n</code></pre>\n\n<p>Depending on compiler optimization, how the CPU pipelines, and what the bytecode generated is, this might not make a difference, but it's worth a try. Also, if that branch isn't taken very often, this isn't going to make a significant difference.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T07:13:08.423",
"Id": "22846",
"Score": "0",
"body": "Thanks for the repsonse, but I cannot do that. If (blockNum < 0x70E4) is true, than it return 'num + step[1]', so 'num' must be calculated before."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T07:18:11.347",
"Id": "22847",
"Score": "2",
"body": "@hetelek But num is guaranteed to be 0 in that situation. For any two ints, x, y, if x < y, x / y = 0. Like 3/5, or 100/101. For all z, 0 * z = 0, thus, if the condition is true, num = 0."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T07:05:55.960",
"Id": "14137",
"ParentId": "14133",
"Score": "3"
}
},
{
"body": "<p>The best optimization you can do is write code that works.</p>\n\n<p>It makes it infinitely faster:</p>\n\n<pre><code>BYTE step[2] = { 0xAC, 0x723A };\n\n DWORD num = (blockNum / 0x70E4) * step[2];\n // ^^^^^^^ Broken. Undefined behavior.\n // The rest of the code is invalid.\n</code></pre>\n\n<p>Second I don't believe your numbers:</p>\n\n<blockquote>\n <p>1 minute, 30 seconds for 300,000 calls.</p>\n</blockquote>\n\n<p>That's an awfully slow machine. 90 seconds for 300,000 calls or 3,333 calls a second. Even unoptimized this code runs (300,000) in less then 1/100 of a second on my machine when fully optimized it is closer to 1/1000 of a second.</p>\n\n<p>So it is not this code that is causing you to slow down. But the result of this code may be affecting the call path inside your application and causing other more costly code to be executed.</p>\n\n<p>Since this code takes 1/1000 of a second of the 90 second total. It is contributing to 0.0001% of the execution time. This is so insignificant that you should not even be trying to optimize this part of the code.</p>\n\n<p>My test code:</p>\n\n<pre><code>#include <iostream>\n#include <time.h>\n#include <vector>\n#include <algorithm>\n\nint step[2] = { 0xAC, 0x723A };\nint packageType = 1;\n\nint computeLevel(int blockNum)\n{\n int num = (blockNum / 0x70E4) * step[1]; // changed.\n if (blockNum < 0x70E4)\n return num + step[0]; // changed\n return (1 << packageType) + num;\n}\n\n\n// Add this to pre-vent the code being optimized to zero.\nint result = 0;\nint check = 0;\nint doComputeLevel(int blockNum)\n{\n result += computeLevel(blockNum);\n ++check;\n}\n\n\nint main()\n{\n // Set up random test data\n std::vector<int> data;\n data.reserve(300010);\n for(int loop = 0;loop < 300000;++loop)\n { \n data.push_back(rand());\n } \n\n // Run the test\n clock_t t = clock();\n std::for_each(data.begin(), data.end(), doComputeLevel);\n clock_t e = clock();\n\n // print the results;\n std::cout << (e-t) << std::endl;\n std::cout << (e-t)*1.0/CLOCKS_PER_SEC << std::endl;\n std::cout << data.size() << \" : \" << check << \" : \" << result << std::endl;\n}\n\n> g++ -O3 t.cpp\n> ./a.out\n1812 TICKS\n0.001812 TIME in seconds\n300000 : 300000 : 62755196 iterations : check of iterations : result\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T07:56:25.357",
"Id": "22851",
"Score": "0",
"body": "It also calls other methods 300,000 times. I'm just saying that's how much it takes off of the whole process, as there are many other functions being called, not just this one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T07:58:29.177",
"Id": "22852",
"Score": "1",
"body": "@hetelek: I understand this. It is your other functions that are taking the time not this one. Making this return 0 just means you execute another path through the other code that is less expensive. This code is not causing any significant cost."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T08:13:17.693",
"Id": "22855",
"Score": "0",
"body": "Would it help if I posted all the functions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T08:18:07.360",
"Id": "22856",
"Score": "2",
"body": "It would probably help you a lot to learn to use the profiling tools provided by MS. They will point you at any bottlenecks that need optimizations. The most affective optimizations are done at the algorithm level not at the micro `what instruction should I use` level."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T08:35:13.810",
"Id": "22858",
"Score": "1",
"body": "And the other broken thing: Initializing `BYTE` to `0x723A`, which is too large for the type."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T07:50:01.230",
"Id": "14138",
"ParentId": "14133",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "14138",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T05:21:50.107",
"Id": "14133",
"Score": "0",
"Tags": [
"c++",
"optimization"
],
"Title": "How can I optimize this for speed? (C++)"
}
|
14133
|
<p>I hava a collection of schedules - <code>EventSchedules</code>. I want to select from this collection today, tomorrow and after tomorrow schedules. The day start from 06:00 and end 6:00 of next day. </p>
<p>Examples:</p>
<ul>
<li>For today the query return events start in range: 30 July 2012 06:00 - 31 July 2012 06:00</li>
<li>For tomorrow the range is: 31 July 2012 06:00 - 01 August 2012 06:00</li>
</ul>
<p>Any advice for refactoring this code? </p>
<pre><code>private void FillSchedulesByFilter()
{
var filterTimeStart = DateTime.Today.AddHours(6);
var filterTimeEnd = filterTimeStart.AddDays(1);
TodayGroupedSchedules = EventScheduleList.Where(s => s.RecurrenceStart >= filterTimeStart &&
s.RecurrenceStart < filterTimeEnd).
GroupBy(p => p.BasePlace);
filterTimeStart = filterTimeStart.AddDays(1);
filterTimeEnd = filterTimeEnd.AddDays(1);
TomorrowGroupedSchedules = EventScheduleList.Where(s => s.RecurrenceStart >= filterTimeStart &&
s.RecurrenceStart < filterTimeEnd).
GroupBy(p => p.BasePlace);
filterTimeStart = filterTimeStart.AddDays(1);
filterTimeEnd = filterTimeEnd.AddDays(1);
AfterTomorrowGroupedSchedules = EventScheduleList.Where(s => s.RecurrenceStart >= filterTimeStart &&
s.RecurrenceStart < filterTimeEnd).
GroupBy(p => p.BasePlace);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T07:59:03.373",
"Id": "22853",
"Score": "0",
"body": "What kind of collection is `EventScheduleList`? Does performance matter to you or is readability more important? How big is the collection? Is it already sorted?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T08:21:18.417",
"Id": "22857",
"Score": "0",
"body": "It's collection of `EventSchedule` - my class that contain schedule of event: start,end, event name, and other infroamtion. Collection is not big( max 100 records)."
}
] |
[
{
"body": "<p>I can see two issues with your code:</p>\n\n<ol>\n<li><p>It doesn't work. Because the local variables <code>filterTimeStart</code> and <code>filterTimeEnd</code> are put in the closure, and the <code>Where()</code> lambdas are executed only when you iterate the resulting enumerables, all of your schedules will be the same as <code>AfterTomorrowGroupedSchedules</code>, because the last value assigned to the locals will be used. You can fix this by using <code>ToArray()</code>.</p></li>\n<li><p>It's not <a href=\"http://en.wikipedia.org/wiki/DRY\" rel=\"nofollow\">DRY</a>. The whole LINQ expression is always exactly the same and the interval is always one day. You should extract that into another method.</p></li>\n</ol>\n\n<p>The modified code:</p>\n\n<pre><code>private IEnumerable<IGrouping<string, EventSchedule>> GroupedSchedulesForADay(\n DateTime filterTimeStart)\n{\n return EventScheduleList.Where(\n s => s.RecurrenceStart >= filterTimeStart &&\n s.RecurrenceStart < filterTimeStart.AddDays(1))\n .GroupBy(p => p.BasePlace)\n .ToArray();\n}\n\nprivate void FillSchedulesByFilter()\n{\n var filterTimeStart = DateTime.Today.AddHours(6);\n\n TodayGroupedSchedules = GroupedSchedulesForADay(filterTimeStart);\n\n filterTimeStart = filterTimeStart.AddDays(1);\n\n TomorrowGroupedSchedules = GroupedSchedulesForADay(filterTimeStart);\n\n filterTimeStart = filterTimeStart.AddDays(1);\n\n AfterTomorrowGroupedSchedules = GroupedSchedulesForADay(filterTimeStart);\n}\n</code></pre>\n\n<p>Technically, the <code>ToArray()</code> is not necessary anymore, because each invocation of the <code>GroupedSchedulesForADay()</code> method has its own local variable, but I think it's still a good idea.</p>\n\n<p>Also, I was worried that <code>AddHours(6)</code> wouldn't work correctly in the days where daylight saving time changes, but it seems it does work.</p>\n\n<p>If the collection was big, it could make sense to iterate it just once, instead of three times, and build the three collections manually item by item, but it seems that's not necessary here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T08:23:36.230",
"Id": "14140",
"ParentId": "14135",
"Score": "4"
}
},
{
"body": "<p>First of all, don't reuse variables to hold values that represent different things. That only makes your code even more confusing to read, especially if it spans many lines. You should declare a variable for each different use you have (a set of variables for today, tomorrow and after tomorrow). That might be a sign to move some code into a separate function in those cases.</p>\n\n<p>The query is the same all around, only the date ranges change so you should put them into a function to minimize repetition.</p>\n\n<p>I would write it like this:</p>\n\n<pre><code>private IEnumerable<IGrouping<string, EventSchedule>>\n GetGroupedSchedulesForDay(DateTime day)\n{\n var start = day.Date.AddHours(6);\n var end = start.AddDays(1);\n\n return // This is in query syntax, doesn't really matter which syntax you use\n from eventSchedule in EventScheduleList\n where eventSchedule.RecurrenceStart >= start\n && eventSchedule.RecurrenceStart < end\n group eventSchedule by eventSchedule.BasePlace;\n}\n\nprivate void FillSchedulesByFilter()\n{\n var today = DateTime.Today;\n TodayGroupedSchedules = GetGroupedSchedulesForDay(today);\n\n var tomorrow = today.AddDays(1);\n TomorrowGroupedSchedules = GetGroupedSchedulesForDay(tomorrow);\n\n var afterTomorrow = today.AddDays(2);\n AfterTomorrowGroupedSchedules = GetGroupedSchedulesForDay(afterTomorrow);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T08:45:25.623",
"Id": "22861",
"Score": "0",
"body": "Not reusing variables would also βaccidentallyβ solve the issue of all lambdas referencing the same variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T08:48:00.913",
"Id": "22862",
"Score": "0",
"body": "I wouldn't say accidentally solve that issue with the closures, more like deliberately avoiding it all together. ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T08:40:10.653",
"Id": "14141",
"ParentId": "14135",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "14140",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T06:39:42.537",
"Id": "14135",
"Score": "0",
"Tags": [
"c#",
"linq",
"scheduled-tasks"
],
"Title": "Collection of schedules"
}
|
14135
|
<p>I have been looking at a couple of different approaches on how I can notify the UI about messages coming from the ViewModel, and wanted to see if this seemed appropriate or if it is too coupled. (We already have a static class that deals with notifications that I am trying to wrap for now, and maybe remove at a later time?)</p>
<pre><code>INotifier
{
void Notify(Notification notification);
}
ConcreteNotifier()
{
void Notify(Notification notification)
{
Notification.ShowMessage(notification.Title, notification.Message, notification.MessageLevel);
}
}
</code></pre>
<p>Main will create ConcreteNotifier and pass it into each View, which will pass it into each VM</p>
<pre><code>ViewModel(INotifier notifier)
{
_notifier = notifier;
}
DoStuff()
{
try
{
}
catch(Exception ex)
{
_notifier.Notify(new Notification{Title="DoStuff Error", Message=ex.Message, MessageLevel=Error});
}
}
</code></pre>
<p>This seems ok to me, however there is coupling due to the <code>Notification</code> class. This is really just encapsulating parameters, so it is probably ok, but I wanted to run it past some people who are more familiar with MVVM and UI interaction. I only need to talk one way, so the Messenger pattern seems like overkill as I do not need to talk to other VM's, and this seemed like a simplistic way of dealing with this issue. Can anybody verify that this approach is ok, or if it has some issues with it?</p>
|
[] |
[
{
"body": "<p>If you are looking for a general approach for notifications (I imagine something along the lines of a \"notification tray\", so corrent me if I'm wrong), this is, how I do it:</p>\n\n<p>The notification is always realyed through the Messenger class from one ViewModel to another. The ViewModel of the component sending the notification creates the message based on its properties and command executions by the view. The recieving ViewModel then exposes the message properties or the whole message on its properties. Those get propagated via binding into the View.</p>\n\n<p>All notification of UI should be, if possible, done via binding, which will minimize to the amout of codebehind needed. Furthermore, the ViewModel should be the decision maker and \"publisher\" of notifications. This way, you create a derived message class (You didn't which MVVM library you use) which can be recieved at multiple notification targets, which will give you great flexibility in sending and recieving notifications.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T07:59:42.450",
"Id": "14161",
"ParentId": "14147",
"Score": "0"
}
},
{
"body": "<p>Generally speaking, view should bind to viewmodel and viewmodel should notify view through injected adapter. I read about this approach in Mark Seemann's \"Dependency injection in .NET\" book.</p>\n\n<p>You are injecting, to your viewmodels, interface like this:</p>\n\n<pre><code>public interface IWindow\n {\n void Close();\n\n IWindow CreateChild(object viewModel);\n\n void Show();\n\n bool? ShowDialog();\n }\n</code></pre>\n\n<p>Download source code to see usage: <a href=\"http://www.manning.com/seemann/\" rel=\"nofollow\">http://www.manning.com/seemann/</a></p>\n\n<p>Another approach, through static Messager, is proposed by mvvm light framework.\nHere are some tutorials and videos: <a href=\"http://www.galasoft.ch/mvvm/#tutorials\" rel=\"nofollow\">http://www.galasoft.ch/mvvm/#tutorials</a></p>\n\n<p>Personally I prefer injection, because only stateless classes should be considered as static (otherwise there are not testable). Besides, static Messager hides class dependency.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T17:29:13.207",
"Id": "26154",
"Score": "2",
"body": "I am fine with injection, and make heavy use of it. However, my only concern with that would be that should the ViewModel really care about UI concerns, like Show and ShowDialog?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-01T18:35:38.430",
"Id": "26159",
"Score": "0",
"body": "I don't want to misguide you because I'm not an expert. My only advice is to analyze WpfProductManagementClient project from Seemann's book source code.\n\nHowever, I'm using this pattern in my regular project at work and it works fine. I like this IWindow interface even more because I'm hosting WPF in WinForms. Using it I can flexibly switch between WinForms and Wpf implementations."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T18:25:49.263",
"Id": "16037",
"ParentId": "14147",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T14:24:38.283",
"Id": "14147",
"Score": "2",
"Tags": [
"c#",
"wpf",
"mvvm"
],
"Title": "MVVM notification messages"
}
|
14147
|
<p>When I realized that the code below has a major problem in what it'll do (it'll just update the database with information currently in the database), I was told that there are a lot of mistakes.</p>
<p>Please point out the mistakes to me, suggest improvements and how to avoid the mistakes in the future.</p>
<pre><code>public User Get(int UserID)
{
string sql = "select * from users where userid = :id";
List<MySqlParameter> args = new List<MySqlParameter>();
args.Add(new MySqlParameter("id", UserID));
MySqlCommand cmd = new MySqlCommand(sql, db.conn);
cmd.Parameters.AddRange(args.ToArray());
db.createConnection();
MySqlDataReader dr = cmd.ExecuteReader();
db.closeConnection();
User user = new User();
if (dr.HasRows)
{
dr.Read();
user.EmailAddress = (string)dr["email"];
user.Password = (string)dr["passcode"];
}
return user;
}
public void Update(int UserID)
{
User user = Get(UserID);
string sql = "update users set email = :email, passcode = :pass where userid = :id";
List<MySqlParameter> args = new List<MySqlParameter>();
args.Add(new MySqlParameter(":email", user.EmailAddress));
args.Add(new MySqlParameter(":pass", user.Password));
args.Add(new MySqlParameter("id", UserID));
MySqlCommand cmd = new MySqlCommand(sql, db.conn);
cmd.Parameters.AddRange(args.ToArray());
db.createConnection();
cmd.ExecuteNonQuery();
db.closeConnection();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T15:16:46.653",
"Id": "22876",
"Score": "4",
"body": "This code uses .NET 1.0 technology. You can still learn and use that but step quickly into Entity Framework."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T09:02:08.907",
"Id": "22916",
"Score": "0",
"body": "A couple of quick comments. \n1) It's generally a good idea to wrap any object, which can be cast to `IDisposable`, into `using(..){ }` statement. \n2) Your select statement \"select * from users where userid = :id\" is too implicit, I'd recommend to use \"select field1, field2...\" type of statement as a more explicit way. In that case changes to database schema will cause your command to fail after schema changes and it will be easier to catch bugs, related to schema changes."
}
] |
[
{
"body": "<p>I'm not sure why you're using your own built classes to access the database when .net has a very complete set of classes that can be used for data access.</p>\n\n<p>Just looking at your syntax, I see the same functionality, so to me that is a waste of development time.</p>\n\n<p>Also, it seems while I don't have access to your classes locally, I've changed them to use the included .net classes.</p>\n\n<p>EDIT: Changed <code>dr.GetString(\"\")</code> to <code>dr.GetString(dr.GetOrdinal(\"\"))</code></p>\n\n<pre><code>using System.Data.SqlClient;\n\npublic User Get(int userID)\n{\n const string sql = \"select * from users where userid = @id\";\n const string connnectionString = \"<your connection string>\";\n\n // Using will dispose of the connection when the inner statements \n // have completed executing. The dispose actually closes the connection.\n // The class has to implement the IDisposable interface.\n // var is a strongly typed variable, mostly used to keep the code easy to read.\n using(var connection = new SqlConnection(connnectionString))\n {\n connection.Open();\n\n // Make sure the SqlCommand object is disposed\n using (var cmd = new SqlCommand(sql, connection))\n {\n // No need to use a separate list to add parameters, just\n // add them directly to the command.\n cmd.Parameters.Add(new SqlParameter(\"@id\", userID));\n\n var dr = cmd.ExecuteReader();\n var user = new User();\n\n // Read returns a boolean if it reads a record.\n if (dr.Read())\n {\n user.EmailAddress = dr.GetString(dr.GetOrdinal(\"email\"));\n user.Password = dr.GetString(dr.GetOrdinal(\"passcode\"));\n }\n return user;\n }\n }\n}\n\npublic void Update(int userID)\n{\n const string sql = \"update users set email = @email, passcode = @pass where userid = @id\";\n const string connnectionString = \"<your connection string>\";\n\n var user = Get(userID);\n\n using (var connection = new SqlConnection(connnectionString))\n {\n connection.Open();\n\n using (var cmd = new SqlCommand(sql, connection))\n {\n cmd.Parameters.Add(new SqlParameter(\"@email\", user.EmailAddress));\n cmd.Parameters.Add(new SqlParameter(\"@pass\", user.Password));\n cmd.Parameters.Add(new SqlParameter(\"@id\", userID));\n\n cmd.ExecuteNonQuery();\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T17:46:06.317",
"Id": "22892",
"Score": "0",
"body": "`SqlDataReader.GetString` doesn't seem to allow a string to be passed as a parameter... is that an extension method of yours?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T17:50:57.543",
"Id": "22893",
"Score": "0",
"body": "My mistake, it should read:\n\nuser.EmailAddress = dr.GetString(dr.GetOrdinal(\"email\"));\nuser.Password = dr.GetString(dr.GetOrdinal(\"passcode\"));"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T07:08:26.137",
"Id": "22909",
"Score": "0",
"body": "Is there a reason you don't declare your object types? `var dr = cmd.ExecuteReader();` as opposed to `SqlDataReader dr = cmd.ExecuteReader();` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T07:09:28.430",
"Id": "22910",
"Score": "0",
"body": "Other than that, I'm very grateful to see your proposed changes, people (the same that told me my code had mistakes) kept telling \"use usings\" and I could never understand what they meant until now :) thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T08:56:28.377",
"Id": "22915",
"Score": "1",
"body": "@Ortund It's a recommended practice to use var to instantiate a variable when the type is obvious."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T12:44:02.460",
"Id": "22919",
"Score": "1",
"body": "@Louhike recommended practice, by whom? I think those advocates will also frown upon using ultra-shortened variables like `dr`. Eric Lipert advises precisely that: [Use descriptive variable names regardless of whether you use \"var\". Variable names should represent the semantics of the variable, not details of its storage; \"decimalRate\" is bad; \"interestRate\" is good.](http://blogs.msdn.com/b/ericlippert/archive/2011/04/20/uses-and-misuses-of-implicit-typing.aspx)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T13:23:27.543",
"Id": "22921",
"Score": "0",
"body": "@ANeves By Microsoft : http://msdn.microsoft.com/en-us/library/ff926074.aspx (\"Implicitly Typed Local Variables\" paragraph)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-20T23:50:23.490",
"Id": "115930",
"Score": "0",
"body": "`var` or not, I do think it is bad practive to mix the application and database layer like this. Having well-defined, encapsulated DAOs would separate concerns much better than throwing SQL strings into the code whenever you need it. It makes updating the underlying database model very expensive as well."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T16:23:28.817",
"Id": "14151",
"ParentId": "14149",
"Score": "12"
}
},
{
"body": "<p>Besides the suggestions from @JeffVanzela , I would suggest to use object initializer syntax when building lists:</p>\n\n<pre><code>var foo = new List<string>() {\n \"item 1\",\n \"item 2\",\n \"item 3\", // Comma at the end of the last item allows swapping items around easily.\n};\n</code></pre>\n\n<p>This also works for dictionaries:</p>\n\n<pre><code>var bar = new Dictionary<int, string>() {\n {1, \"item 1\"},\n {3, \"item 2\"},\n {5, \"item 3\"},\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T12:51:40.470",
"Id": "14166",
"ParentId": "14149",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T15:08:03.507",
"Id": "14149",
"Score": "11",
"Tags": [
"c#",
"mysql"
],
"Title": "Updating user information"
}
|
14149
|
<p>I'm looking for a better more efficient way to write some code I have where I"m synchronizing two lists. Basically, the first list is a list of devices I need to check. The second list is a list of devices that I have already checked with dates. I need to synchronize the two lists so I only check devices that are new or out of date based on the date. I also need to delete any devices that have been removed.</p>
<p>Here is my current code that works fine, it just looks and feels SO clunky.</p>
<pre><code>public IEnumerable<AssetBlob> Synchronize(IEnumerable<AssetBlob> assets, string id) {
//Get list of devices already checked in lineitemsmap
List<AssetBlob> items = new List<AssetBlob>();
IEnumerable<LineItemsMap> lineItems = auditRepo.GetLineItemsMap(id).DeviceResults;
List<LineItemsMap> deleted = new List<LineItemsMap>();
//put new items into list
items.AddRange((from t0 in assets
join t1 in lineItems on t0.Id equals t1.BlobId into t1_join
from t1 in t1_join.DefaultIfEmpty()
where t1 == null
select t0).ToList());
//list of existing items that need updated
items.AddRange((from t0 in assets
join t1 in lineItems on t0.Id equals t1.BlobId
where t0.Imported > t1.Created
select t0).ToList());
deleted.AddRange((from t0 in assets
join t1 in lineItems on t0.Id equals t1.BlobId
where t0.Imported > t1.Created
select t1).ToList());
//Delete items in lineitems that don't exists in assets list
deleted.AddRange((from t0 in lineItems
join t1 in assets on t0.BlobId equals t1.Id into t1_join
from t1 in t1_join.DefaultIfEmpty()
where t1 == null
select t0).ToList());
if (deleted.Any()) {
auditRepo.RemoveLineItemMaps(deleted);
}
return items;
}
</code></pre>
<p>Any suggestion or improvements would be great. Thank you.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T16:41:35.483",
"Id": "22878",
"Score": "0",
"body": "You're used to writing SQL queries with outer joins, don't you? :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T17:05:08.843",
"Id": "22880",
"Score": "0",
"body": "I have to use outer joins because some of the records won't be in both tables."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T12:30:19.537",
"Id": "22922",
"Score": "0",
"body": "You should look into .Intersect and .Except methods."
}
] |
[
{
"body": "<p>I haven't tested this due to time constraints, and lack of knowledge of the data, but from my understanding of the problem, this should work.</p>\n\n<p>I have taken the linq join queries, two for the insert, two for the delete and created two IEnumerable.Where clauses, one for insert, one for delete. The two sets of criteria are combined in an OR statement within the .Where statement.</p>\n\n<p>The one thing I wasn't sure on is if the original list needed to be returned. That wasn't clear in the original code. If it does need to be returned, that's an easy change to implement.</p>\n\n<p>EDIT: Changed to do work per Kyles suggestion in comments.</p>\n\n<pre><code>public IEnumerable<AssetBlob> Synchronize(IEnumerable<AssetBlob> assets, string id)\n{\n var assetsList = assets.ToList();\n\n //Get list of devices already checked in lineitemsmap\n IEnumerable<LineItemsMap> lineItems = auditRepo.GetLineItemsMap(id).DeviceResults;\n\n var items =\n assetsList.Where(\n existingAsset => \n // ExisingItems that need updating\n // Any returns true if any of the items in a list meet the criteria\n lineItems.Any(lineItem => lineItem.BlobId == existingAsset.Id && existingAsset.Imported > lineItem.Created) ||\n // New items that need inserting.\n // All returns true if all of the items in a list meet the criteria\n // therefore All == !Any\n lineItems.All(lineItem => lineItem.BlobId == existingAsset.Id)).ToList();\n\n\n var deleted =\n lineItems.Where(lineItem =>\n assetsList.Any(existingAsset => existingAsset.Imported > lineItem.Created) ||\n assetsList.All(existingAsset => existingAsset.Id != lineItem.BlobId)).ToList();\n\n // If there is a foreach in RemoveLineItemMaps you can probably remove this check.\n // Just cleans up the code a little, and the foreach will take care of this check.\n if (deleted.Any())\n {\n auditRepo.RemoveLineItemMaps(deleted);\n }\n\n return items;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T17:28:47.263",
"Id": "22886",
"Score": "0",
"body": "Could you explain what did change outside of comments, so that people don't have to go through all the code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T17:35:25.933",
"Id": "22889",
"Score": "0",
"body": "@svick Is that better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T18:36:11.030",
"Id": "22898",
"Score": "0",
"body": "Interesting. All my tests passed for this but the scenario where a device previously existed got removed. So basically when 'assets' = 2 and lineitems = 3. deleted.Count() should be 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T19:07:36.387",
"Id": "22900",
"Score": "0",
"body": "All my tests passed once I switched the boolean on the All() for deleted to !=. Thanks for the suggestion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T22:19:57.313",
"Id": "22905",
"Score": "0",
"body": "Glad you got it working"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T17:25:28.723",
"Id": "14154",
"ParentId": "14150",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "14154",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T16:18:11.583",
"Id": "14150",
"Score": "2",
"Tags": [
"c#",
"linq"
],
"Title": "Synchronization of two lists"
}
|
14150
|
<p><strong>Edit:</strong> I updated the JavaScript modules in <a href="http://enlargeyourpassword.com" rel="nofollow">http://enlargeyourpassword.com</a> to use scope(). You can see the result in the source of the page, and get an idea of the process by looking at the <a href="https://github.com/eric-brechemier/enlargeyourpassword/commits/master" rel="nofollow">commit history on GitHub</a>. </p>
<p>As a JavaScript developer, I want to write modules in a format that is well supported today and that will still work in five years.</p>
<p>I designed an open-source library to this end, <a href="https://github.com/eric-brechemier/scopeornot" rel="nofollow">scope or not</a>, with two goals in mind. It should be:</p>
<ol>
<li>simple to declare JavaScript modules with dependencies</li>
<li>simple to implement your own version of the library to customize its behavior</li>
</ol>
<p>There is a single function named <code>scope()</code>. This is a <a href="https://github.com/eric-brechemier/scopeornot/blob/master/scope-level0-api.js" rel="nofollow">null implementation</a>:</p>
<pre><code>function scope(code, needs, name){
return null;
}
</code></pre>
<p>The parameter <code>code</code> is required. It is a function that defines a module. For example:</p>
<pre><code>scope(function(){
var module = {};
// ...
return module;
});
</code></pre>
<p>The <code>scope()</code> function has different implementations with different behaviors: it may create a module in the global scope, in a private scope, synchronously or asynchronously after loading dependencies.</p>
<p>When the <code>scope()</code> function is synchronous, it returns the module just created, which allows to use <code>scope()</code> as a direct replacement of the <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/" rel="nofollow">Immediately Invoked Function Expression</a> pattern typically used to declare modules in JavaScript:</p>
<pre><code>var myLib = myLib || scope(function(){
return {
// myLib API
};
});
</code></pre>
<p>The last two parameters <code>needs</code> and <code>name</code> are optional. The name of a module is a string which identifies the module and allows to reference it in the list of needs of other modules:</p>
<pre><code>scope(function(){
var moduleA = {};
// ...
return moduleA;
},[],"moduleA");
scope(function(context){
// ...
return moduleB;
},["moduleA"],"moduleB");
</code></pre>
<p>For each dependency in the array of needs, a property of the same name is set on the context object which is provided as argument to the function:</p>
<pre><code>scope(function(context){
var
moduleA = context.moduleA, // a local alias for "moduleA"
moduleB = {};
// ...
return moduleB;
},["moduleA"],"moduleB");
</code></pre>
<p>To use the <code>scope()</code> function, you can write your own or build it from building blocks available in the <a href="https://github.com/eric-brechemier/scopeornot" rel="nofollow">scope or not project</a>. The building blocks are sorted in levels. The level 1 provides the bootstrap, it must be loaded first. One building block may be picked from each level. Building blocks from lower levels are expected to be loaded first, but they are all optional.</p>
<p>Building blocks in higher levels use the <code>scope()</code> function of the bootstrap to define a replacement function "scope", declared as a module. For example:</p>
<pre><code>// from scope-level2-shared.js
scope(function(parentContext){
var
// private field
privateContext = {};
/*
Function: scope(code[,needs[,name]]): any
Run code immediately in a private context, and set the return value,
if any, to a property with given name in the private context
(...)
*/
function scope(code,needs,name){
var result = code(privateContext);
if (typeof name !== "string"){
return result;
}
privateContext[name] = result;
if (name === "scope"){
// replace the current implementation of scope() in parent context
parentContext.scope = result;
}
return result;
}
return scope;
},[],"scope");
</code></pre>
<p>When you implement the <code>scope()</code> API yourself, you may either create a building block on top of the scope bootstrap and other building blocks, or rewrite the <code>scope()</code> function from scratch, replacing the bootstrap and all building blocks altogether.</p>
<p>In a browser, you can load building blocks with script tags, then load your own modules:</p>
<pre><code><script src="scopeornot/scope-level1-global.js"></script>
<script src="scopeornot/scope-level2-shared.js"></script>
<script src="moduleA.js"></script>
<script src="moduleB.js"></script>
...
</code></pre>
<p>You may later change the building blocks to load your modules asynchronously instead:</p>
<pre><code><script src="scopeornot/scope-level1-global.js"></script>
<script src="scopeornot/scope-level2-shared.js"></script>
<script src="requirejs/require.js"></script>
<script src="scopeornot/scope-level3-amd.js"></script>
<script src="setup-and-startup-top-level-module-with-require.js"></script>
</code></pre>
<p>Please review the usability of this API from the point of view of a developer who uses the API and from the point of view of a developer who implements the API.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T17:09:26.507",
"Id": "22882",
"Score": "0",
"body": "If you know about [AMD](http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition) and [RequireJS](http://requirejs.org) etc.. why did you create this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T10:59:53.790",
"Id": "22917",
"Score": "0",
"body": "@Esailija I designed scope() to be 100% compatible with the define() function of AMD, but without all the semantics attached. While you would expect a call to define() to be compliant with the AMD specification, scope() can follow your own conventions, e.g. synchronous definition in the global scope by default."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-04T02:24:15.573",
"Id": "29023",
"Score": "1",
"body": "My only usability concern is a very simple and pragmatic one: Having dependencies and name as the 2nd and 3rd arguments means they end up at the very end of a file. To me, it'd make a lot more sense to have that at the top, simply to keep the code more readable; \"this thing is called 'foo', depends on 'bar' and 'baz', and is defined thusly...\". A little tricky to do with optional args, of course, but well worth the effort in my opinion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T12:43:49.637",
"Id": "29092",
"Score": "0",
"body": "@Flambino Thanks for the feedback. You are right, this is a compromise between ease of use and ease of implementation. Another rationale was to make the signature compatible with AMD but different. I have started to identify other shortcomings, that I will develop as an answer to my own question."
}
] |
[
{
"body": "<p>I could suggest you to have a look at requirejs (http://requirejs.org/) and plugin (https://github.com/tbranyen/use.js) for it for synchronous loading scripts to respect dependencies</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T16:18:29.603",
"Id": "23133",
"Score": "0",
"body": "Please clarify. How do you see this RequireJS plugin as relevant to evaluate the usability of scope()?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T17:55:16.647",
"Id": "23137",
"Score": "0",
"body": "@Eric What I was saying is that your approach does not care about asynchronous loading of the scripts and also seems to be reinventing the wheel. I am not agains `scopes` but from the terms of usability it looks inconsistent with the way requirejs handles dependency declaration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T19:34:30.907",
"Id": "23140",
"Score": "0",
"body": "There is no need to run all scripts asynchronously all the time. For example, scripts are loaded synchronously on node.js. As for use.js, it has different goals than scope(): \"It simply ensures the proper dependencies have loaded and attaches the specified global object to the module definition.\". scope() is not a module loader or a plugin for a module loader. It is a layer of indirection that you can use to define modules in an abstract way, leaving the choice of the module loader open. AMD is a great specification for asynchronous module loading, but it ties you to one kind of loader."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-03T15:07:43.020",
"Id": "14299",
"ParentId": "14153",
"Score": "1"
}
},
{
"body": "<p>Like the <code>define()</code> method in AMD API, which is very similar, the <code>scope()</code> function mixes separate concerns in a single call :</p>\n\n<ul>\n<li>private scope: prevent declarations inside the module from polluting global namespace</li>\n<li>definition of the module dependencies (imports)</li>\n<li>definition of shared symbols (exports)</li>\n<li>resolution of module names to paths of scripts</li>\n<li>deferred loading of scripts</li>\n<li>access to shared symbols (imports)</li>\n</ul>\n\n<p>I am now considering ways to separate these concerns into several functions and even several independent libraries.</p>\n\n<p>For example, <code>scope()</code> could be restricted to a single argument, to cover only the first concern:</p>\n\n<pre><code>scope(function(){\n ... // private scope\n});\n</code></pre>\n\n<p>A separate function/library could be defined to declare dependencies, another for synchronous/asynchronous loading, and yet another to import and export symbols in a shared context.</p>\n\n<p>These separate functions may communicate and interact through a common event system (pub/sub).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-05T13:01:19.490",
"Id": "18244",
"ParentId": "14153",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T17:02:54.817",
"Id": "14153",
"Score": "8",
"Tags": [
"javascript",
"library"
],
"Title": "Usability of API to declare modules in JavaScript"
}
|
14153
|
<p>I'm using the following pattern in my mobile app. The code snippet below manages a stopwatch.</p>
<p>Is there a way to simplify the code for better readability and probably getting away from needing to use <code>MyApp.stopwatch.</code> inside it? Somehow in some cases using <code>this</code> instead works, and in some it doesn't.</p>
<p>And what about getting rid of using repeating <code>var settings = MyApp.stopwatch.settings</code>?</p>
<pre><code>(function (MyApp, $, undefined) {
// Using strict mode to throw exceptions for 'unsafe' actions and coding patterns
'use strict';
// Initializes app
function init() {
MyApp.stopwatch.init('startStopwatch', 'pauseStopwatch', 'resetStopwatch');
}
// Manages the stopwatch
MyApp.stopwatch = {
init: function (startButton, pauseButton, resetButton) {
document.getElementById(startButton).addEventListener('click', MyApp.stopwatch.startTimer, false);
document.getElementById(pauseButton).addEventListener('click', MyApp.stopwatch.pauseTimer, false);
document.getElementById(resetButton).addEventListener('click', MyApp.stopwatch.resetTimer, false);
MyApp.stopwatch.displayTimer();
},
settings: {
timerId: -1,
interval: 100,
millis: 0,
seconds: 0,
minutes: 0
},
displayTimer: function () {
// ARE THESE REPEATING DECLARATIONS REALLY NEEDED?
var settings = MyApp.stopwatch.settings,
millis = Math.round(settings.millis / 100).toFixed(0),
seconds = settings.seconds,
minutes = settings.minutes;
if (seconds < 10) {
seconds = '0' + seconds;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
document.getElementById('stopwatch').innerHTML = minutes + ':' + seconds + ':' + millis;
},
updateTimer: function () {
// ARE THESE REPEATING DECLARATIONS REALLY NEEDED?
var settings = MyApp.stopwatch.settings;
settings.millis += settings.interval;
if (settings.millis >= 1000) {
settings.millis = 0;
settings.seconds += 1;
}
if (settings.seconds >= 60) {
settings.millis = 0;
settings.seconds = 0;
settings.minutes += 1;
}
MyApp.stopwatch.displayTimer();
},
pauseTimer: function () {
// ARE THESE REPEATING DECLARATIONS REALLY NEEDED?
var settings = MyApp.stopwatch.settings;
window.clearInterval(settings.timerId);
settings.timerId = -1;
},
startTimer: function () {
// ARE THESE REPEATING DECLARATIONS REALLY NEEDED?
var settings = MyApp.stopwatch.settings;
if (settings.timerId === -1) {
settings.timerId = window.setInterval(MyApp.stopwatch.updateTimer, settings.interval);
}
},
resetTimer: function () {
// ARE THESE REPEATING DECLARATIONS REALLY NEEDED?
var settings = MyApp.stopwatch.settings;
MyApp.stopwatch.pauseTimer();
settings.millis = 0;
settings.seconds = 0;
settings.minutes = 0;
MyApp.stopwatch.displayTimer();
}
};
// PhoneGap, jQuery & device is ready now -> initialize
$(document).on('deviceready', init);
}(window.MyApp = window.MyApp || {}, jQuery));
</code></pre>
|
[] |
[
{
"body": "<p>This is what I came up with (untested):</p>\n\n<p>I got rid of your settings-stuff, introduced a variable <code>self</code> so there's no interference with <code>this</code>, moved your initialization code to the only place it is (and can ever be) called from, extracted a method for padding and event handler registration and fixed your updateTimer so it works for values > 1000 (it's not fit for negative values, though). I hope you like it...</p>\n\n<pre><code>(function (MyApp, $, undefined) {\n // Using strict mode to throw exceptions for 'unsafe' actions and coding patterns\n 'use strict';\n\n function addClickHandlerToButton(buttonId, handler) {\n document.getElementById(buttonId).addEventListener('click', handler, false);\n }\n\n function padLeft(number) {\n number = +number;\n return (number < 10 ? '0' : '') + Math.floor(number);\n }\n\n // Manages the stopwatch\n var stopwatch = (function(){\n var minutes = 0,\n seconds = 0,\n millis = 0,\n interval = 100,\n timerId = -1,\n displayTimer = function () {\n document.getElementById('stopwatch').innerHTML =\n padLeft(minutes) + ':' +\n padLeft(seconds) + ':' +\n Math.floor(millis);\n },\n\n updateTimer = function () {\n millis += interval;\n if (millis >= 1000) {\n seconds += millis / 1000;\n millis %= 1000;\n }\n if (seconds >= 60) {\n minutes += seconds / 60;\n seconds %= 60;\n }\n displayTimer();\n },\n\n pauseTimer = function () {\n window.clearInterval(timerId);\n timerId = -1;\n },\n\n startTimer = function () {\n if (timerId === -1) {\n timerId = window.setInterval(updateTimer, interval);\n }\n },\n\n resetTimer = function () {\n pauseTimer();\n millis = 0;\n seconds = 0;\n minutes = 0;\n displayTimer();\n };\n\n return function (startButton, pauseButton, resetButton) {\n addClickHandlerToButton(startButton, startTimer)\n addClickHandlerToButton(pauseButton, pauseTimer)\n addClickHandlerToButton(resetButton, stopTimer)\n displayTimer();\n };\n })();\n\n // PhoneGap, jQuery & device is ready now -> initialize\n $(document).on('deviceready', function() {\n stopwatch('startStopwatch', 'pauseStopwatch', 'resetStopwatch');\n });\n\n}(window.MyApp = window.MyApp || {}, jQuery));\n</code></pre>\n\n<p><strong>EDIT 1+2:</strong> updated the code to integrate suggestions from the comments by the OP and fix errors.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-24T20:40:43.323",
"Id": "24410",
"Score": "0",
"body": "Looks good. Especially like the handler function. Never seen `self.self = self;` being used? Is it a good practice? And doesn't `init` and `displayTimer` have a different scope? So when you assign `MyApp.stopwatch.self = MyApp.stopwatch` can you really just call `self.millis`? Because if you can access MyApp.stopwatch with `self` inside any of those functions, why can't you then just call `displayTimer()` instead of `self.displayTimer`, or `millis` instead of `self.millis`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-24T22:14:14.437",
"Id": "24413",
"Score": "0",
"body": "You are right, my changes weren't fully thought through and included redundancies (and a copy paste error, I used the same button for all 3 event handler registrations). Please have another look. I also moved `self` - it's a neat trick, although in this version, it isn't really needed anymore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-24T22:41:42.230",
"Id": "24414",
"Score": "0",
"body": "My questions on last comment were kind of rhetorical. The code won't still work because those functions have different scope and therefore you just can't call `stopTimer` or `millis` inside them. But yeah, I'll implement that handler-function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-25T05:47:44.027",
"Id": "24424",
"Score": "0",
"body": "Hmm... I really need a testbed :-) - just give them scope by making MyApp.stopwatch a function. I'll do another rewrite!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-25T16:04:11.097",
"Id": "24435",
"Score": "0",
"body": "Although you've changed the pattern, i'll accept this as an answer. Good effort. Ty!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-24T17:27:47.900",
"Id": "15042",
"ParentId": "14157",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "15042",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T22:26:34.870",
"Id": "14157",
"Score": "5",
"Tags": [
"javascript",
"optimization",
"design-patterns",
"timer"
],
"Title": "Managing a stopwatch mobile app"
}
|
14157
|
<p>This morning I decided to write this question: <a href="https://stackoverflow.com/questions/11727571/are-there-problems-if-i-have-a-verbose-datatype/11727723#11727723">https://stackoverflow.com/questions/11727571/are-there-problems-if-i-have-a-verbose-datatype/11727723#11727723</a></p>
<p>I don't really explain my scenario about how am I accesing through the nested dictionaries. I decided to have the default alias (<code>IDictionary<string, IDictionary<Levels, IList<Problem>>></code>) but I'm thinking that's not a good option right now.</p>
<p>I'm gonna show some parts of my code:</p>
<p>ProblemBaseFactory</p>
<pre><code>public abstract class ProblemBaseFactory : IProblemFactory
{
private IDictionary<string, IDictionary<Levels, IList<Problem>>> problemDictionaryPackages;
protected ProblemBaseFactory()
{
problemDictionaryPackages = new Dictionary<string, IDictionary<Levels, IList<Problem>>>();
}
protected IDictionary<string, IDictionary<Levels, IList<Problem>>> ProblemDictionaryPackages
{
get { return problemDictionaryPackages; }
}
public abstract IEnumerable<Levels> AvailableLevels(string packageName);
public abstract IEnumerable<Problem> LoadProblems(ProblemFactoryProperties properties);
}
</code></pre>
<p>RuleProblemFactory</p>
<pre><code>public abstract class RuleProblemFactory : ProblemBaseFactory
{
private IDictionary<string, IDictionary<Levels, IList<ProblemRule>>> ruleDictionaryPackages;
private IRuleAlgorithmSelector ruleAlgorithmSelector;
private IList<Problem> temp;
protected RuleProblemFactory()
: this(new Dictionary<string, IDictionary<Levels, IList<ProblemRule>>>(), new SequentialRuleSelector())
{
}
protected RuleProblemFactory(IRuleAlgorithmSelector ruleAlgorithmSelector)
: this(new Dictionary<string, IDictionary<Levels, IList<ProblemRule>>>(), ruleAlgorithmSelector)
{
}
protected RuleProblemFactory(IDictionary<string, IDictionary<Levels, IList<ProblemRule>>> ruleDictionary,
IRuleAlgorithmSelector ruleAlgorithmSelector)
{
this.ruleDictionaryPackages = ruleDictionary;
this.ruleAlgorithmSelector = ruleAlgorithmSelector;
LoadBankOfRules();
}
protected IDictionary<string, IDictionary<Levels, IList<ProblemRule>>> RuleDictionaryPackages
{
get { return ruleDictionaryPackages; }
}
public override IEnumerable<Problem> LoadProblems(ProblemFactoryProperties properties)
{
// does exist the package name?
if (!ProblemDictionaryPackages.ContainsKey(properties.NamePackage))
throw new InvalidOperationException("namePackage");
IDictionary<Levels, IList<Problem>> problemPackage = this.ProblemDictionaryPackages[properties.NamePackage];
// does exist the list
if (!problemPackage.ContainsKey(properties.Difficulty))
problemPackage.Add(properties.Difficulty, new List<Problem>());
temp = problemPackage[properties.Difficulty];
if (temp.Count >= properties.Quantity)
return temp;
else
return GenerateProblems(properties);
}
private IEnumerable<Problem> GenerateProblems(ProblemFactoryProperties properties)
{
ruleAlgorithmSelector.Rules = ruleDictionaryPackages[properties.NamePackage][properties.Difficulty];
...
}
public override IEnumerable<Levels> AvailableLevels(string name)
{
return ruleDictionaryPackages[name].Keys;
}
}
</code></pre>
<p>Sometimes I guess is difficult to readability. What do you recomend me to to mantain a better readability?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T22:56:08.120",
"Id": "22908",
"Score": "1",
"body": "For readabilitiy I prefer the curly brackets in conditions and loops, one place I saw you could use var. I dont mind the `nested IDictionary`'s, if you did wrap them up in another class would that abstraction yield any benefit in your scenario?"
}
] |
[
{
"body": "<p><code>IDictionary<string, IDictionary<Levels, IList<ProblemRule>>></code> is difficult to understand and maintain. I don't know enough about your problem domain to give you reasonably sounding names for classes, but I'll try.</p>\n\n<p>In your <code>LoadProblems</code> method, I see you set the <code>IDictionary<Levels, IList<ProblemRule>></code> to a variable named <code>problemPackage</code>, so I would create a class <code>ProblemPackage</code>, containing a list of ProblemRules per Level (I would drop the 's' in Levels) and move the related logic there.</p>\n\n<p>In <code>ProblemBaseFactory</code> you end up with a <code>IDictionary<string, ProblemPackage></code>. <code>ProblemPackage</code> will have a <code>IDictionary<Level, ProblemRules></code> and the class <code>ProblemRules</code> will be an easy wrapper around a <code>IList<ProblemRule></code>.</p>\n\n<p>If you try to delegate the work to these classes, the readability will almost certainly go up.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T11:41:02.960",
"Id": "14163",
"ParentId": "14158",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-30T22:30:13.627",
"Id": "14158",
"Score": "4",
"Tags": [
"c#",
"algorithm",
"object-oriented"
],
"Title": "How to refactor a verbose datatype?"
}
|
14158
|
<p>I am building a website that uses Amazon S3 to host its image (and other) files.</p>
<p>I require that images displayed on the website look like they come from my site and not from Amazon (so we are talking on the request/response level). What I have done is created a controller which all these files will pass through. The controller should request the file from Amazon and pass it on, as if it's from the local website.</p>
<p>My concern is my usage of the response stream and error-handling. Basically, if anything happens, I want it to simply return a 404.</p>
<pre><code>public class RequestState
{
public RequestState()
{
BufferSize = 1024;
BufferRead = new byte[BufferSize];
Request = null;
ResponseStream = null;
}
public int BufferSize { get; private set; }
public byte[] BufferRead { get; set; }
public HttpWebRequest Request { get; set; }
public HttpWebResponse Response { get; set; }
public Stream ResponseStream { get; set; }
}
public class MediaController : AsyncController
{
public void IndexAsync(string key)
{
if (string.IsNullOrWhiteSpace(key))
throw new HttpException((int)HttpStatusCode.NotFound, "File not found.");
AsyncManager.OutstandingOperations.Increment();
var request = (HttpWebRequest)WebRequest.Create(string.Format(Constants.Urls.AmazonFileGetUrlFormat, AppSettings.AmazonS3BucketName, key));
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
var state = new RequestState { Request = request };
request.BeginGetResponse(ResponseCallback, state);
}
private void ResponseCallback(IAsyncResult result)
{
try
{
var state = (RequestState)result.AsyncState;
HttpWebRequest request = state.Request;
state.Response = (HttpWebResponse)request.EndGetResponse(result);
Stream responseStream = state.Response.GetResponseStream();
state.ResponseStream = responseStream;
AsyncManager.Parameters["imageInBytes"] = ReadFully(responseStream);
AsyncManager.Parameters["contentType"] = state.Response.ContentType;
}
catch (WebException ex)
{
var state = (RequestState)result.AsyncState;
if (state.Response != null)
state.Response.Close();
AsyncManager.Parameters["webException"] = ex;
}
catch (Exception ex)
{
var state = (RequestState)result.AsyncState;
if (state.Response != null)
state.Response.Close();
throw;
}
finally
{
AsyncManager.Parameters["key"] = "key";
AsyncManager.OutstandingOperations.Decrement();
}
}
public static byte[] ReadFully(Stream input)
{
var buffer = new byte[16 * 1024];
using (var stream = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, read);
}
return stream.ToArray();
}
}
[OutputCache(Duration = 600, VaryByParam = "key")]
public FileContentResult IndexCompleted(string key, byte[] imageInBytes, string contentType, WebException webException)
{
if (webException != null && webException.Status == WebExceptionStatus.ProtocolError)
{
var response = webException.Response as HttpWebResponse;
if (response != null)
{
throw new HttpException((int)response.StatusCode, response.StatusDescription);
}
throw new HttpException((int)HttpStatusCode.NotFound, "File not found.");
}
if (imageInBytes == null || imageInBytes.Length == 0)
{
throw new HttpException((int)HttpStatusCode.NotFound, "File not found.");
}
return File(imageInBytes, contentType);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-06T16:54:02.633",
"Id": "126154",
"Score": "0",
"body": "Can't this problem be solved easier by [Customizing Amazon S3 URLs with CNAMEs](http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html#VirtualHostingCustomURLs)?"
}
] |
[
{
"body": "<p>I don't understand the point in using this pattern:</p>\n\n<pre><code> catch (WebException ex)\n {\n var state = (RequestState)result.AsyncState;\n\n if (state.Response != null)\n state.Response.Close();\n\n AsyncManager.Parameters[\"webException\"] = ex;\n }\n catch (Exception ex)\n {\n var state = (RequestState)result.AsyncState;\n\n if (state.Response != null)\n state.Response.Close();\n\n throw;\n }\n finally\n {\n AsyncManager.Parameters[\"key\"] = \"key\";\n AsyncManager.OutstandingOperations.Decrement();\n }\n</code></pre>\n\n<p>When it looks like it could be simplified to this:</p>\n\n<pre><code> catch (WebException ex)\n {\n AsyncManager.Parameters[\"webException\"] = ex;\n }\n finally\n {\n var state = (RequestState)result.AsyncState;\n\n if (state.Response != null)\n state.Response.Close();\n\n AsyncManager.Parameters[\"key\"] = \"key\";\n AsyncManager.OutstandingOperations.Decrement();\n }\n</code></pre>\n\n<p>The following may stem from my lack of familiarity with Amazon S3:</p>\n\n<p>I'm not sure what functionality your <code>ReadFully</code> method offers over <code>Stream.Read(Stream.Length)</code> or, more safely, <code>Stream.Read(Stream.Length - Stream.Position)</code> except potentially causing issues if the stream does not have a length of multiplies of 16x1024.</p>\n\n<p>Speaking of which, you've hard-coded that 16x1024 in a magic number: </p>\n\n<p><code>var buffer = new byte[16 * 1024];</code></p>\n\n<p>I would recommend converting these values to consts so you can change them later with ease.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-06T15:07:34.433",
"Id": "69088",
"ParentId": "14160",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T05:01:28.953",
"Id": "14160",
"Score": "2",
"Tags": [
"c#",
"mvc",
"asynchronous",
"asp.net-mvc-3",
"amazon-s3"
],
"Title": "Amazon S3 pass-through controller"
}
|
14160
|
<p>I'm writing a results wrapper for a <a href="https://github.com/dtuite/dinosaurus" rel="nofollow">gem which wraps a Thesaurus API</a>. Basically, when you lookup a word in the thesaurus, the results come back in approximately this JSON form:</p>
<pre><code>{
'noun' => {
'syn' => ['array', 'of', 'synonyms'],
'rel' => ['array', 'of', 'related terms']
},
'verb' => {
'syn' => ['synonyms', 'of', 'verb', 'word form'],
'ant' => ['antonyms', 'of', 'word']
}
}
</code></pre>
<p>I would like to be able to access the results in the following ways:</p>
<ul>
<li><p>Get an array of synonyms across all parts of speech. eg.</p>
<pre><code>results.synonyms
# => ['array', 'of', 'synonyms', 'synonyms', 'of', 'verb', 'word form']
</code></pre></li>
<li><p>Indifferently (writing <code>results['noun']</code> all the time is a PITA):</p>
<pre><code>results[:noun]
</code></pre></li>
</ul>
<p>Here is my code and questions:</p>
<ol>
<li>Is it acceptable to create a dependance on <code>ActiveSupport</code> just so I can access the results indifferently, or should I just suck it up? THe only other AR method I'm using in the gem is <code>blank?</code>.</li>
<li><p>Is the usage of <code>define_method</code> too magical? Should I just define the convenience methods normally instead?</p>
<pre><code>require "active_support/core_ext/hash/indifferent_access"
module Dinosaurus
class Results < HashWithIndifferentAccess
def initialize(data = {})
super(data)
end
# Define some convenience methods.
{ 'synonyms' => :syn,
'antonyms' => :ant,
'similar_terms' => :sim,
'related_terms' => :rel
}.each do |name, key|
define_method name do
grouped(key)
end
end
private
def grouped(key)
group = []
self.each do |pos, type|
group += type[key] if type[key]
end
group
end
end
end
</code></pre></li>
</ol>
|
[] |
[
{
"body": "<p>1) I believe that depending on popular and stable libraries is not a problem. Though I prefer more opinionated approach: to <code>symbolize_keys!</code>.</p>\n\n<p>2) You <code>define_method</code> looks clear enough, IMHO </p>\n\n<p>3) You may simplify grouped like this:</p>\n\n<pre><code>def grouped_by(key)\n self.values.flat_map { |type| type[key] }.compact!\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-08T09:23:27.027",
"Id": "23397",
"Score": "0",
"body": "Thanks. That `flat_map` trick is a beautiful thing!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-07T20:59:31.203",
"Id": "14421",
"ParentId": "14162",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T10:15:11.653",
"Id": "14162",
"Score": "2",
"Tags": [
"ruby"
],
"Title": "Reasonable ActiveSupport dependency and define_method usage?"
}
|
14162
|
<p>I'm writing am application that I've previously posted questions on here, but I'm looking for similar advice if possible. I am looking for how best to write my code, as I have a working example, but to me it feels long winded.</p>
<p>The application first grabs 3 tables via DataContext:-</p>
<pre><code> var contacts = db.GetTable<Contact>();
var distributionLists = db.GetTable<DistributionList>();
var JunctionTable = db.GetTable<ContactsDistribution>();
</code></pre>
<p>I then get the selected items from my listbox, which are distribution lists. A contact can be in more than one distribution list, so I first get the raw data from my database:</p>
<pre><code>var listBoxItems = listBox1.SelectedItems.Cast<object>().Select(t => t.ToString());
var initialList = (from j in JunctionTable
where listBoxItems.Contains(j.DistributionName)
join c in contacts on j.ContactID equals c.ContactID
select new { c.ContactID,c.Surname,j.DistributionName, j.EmailFlag, j.SMSFlag}).ToList();
</code></pre>
<p>I then need to search the <code>initialList</code> collection for users who require email notifications. I also need to remove duplicate entries, as a Contact can appear multiple times. So the list is made Distinct:-</p>
<pre><code>var email = (from l in initialList
where l.EmailFlag.Equals(true)
select new { l.ContactID }).Distinct().ToList();
</code></pre>
<p>I then do the same search for Contacts that require SMS Notification from the selected lists:</p>
<pre><code>var sms = (from l in initialList
where l.SMSFlag.Equals(true)
select new { l.ContactID }).Distinct().ToList();
</code></pre>
<p>Now that I have lists for both SMS & Email Notifications I need get the required email address or mobile number by doing this:</p>
<pre><code>var smsMobileNumbers = (from s in sms
join c in contacts on s.ContactID equals c.ContactID
select new { c.MobileNumber }).ToList();
var emailAddresses = (from m in email
join c in contacts on m.ContactID equals c.ContactID
elect new { c.EmailAddress }).ToList();
</code></pre>
<p>Is there a cleaner way of writing this code or is there a better, more efficient way of achieving this?</p>
|
[] |
[
{
"body": "<p>The only change I would make would be to remove the two statements where you create the lists <em>sms</em> and <em>email</em>. They are redundant: by adding the EmailAddress and MobileNumber to the query where you are creating the <em>initialList</em>, you can do a select on the <em>initialList</em>.</p>\n\n<pre><code>var initialList = (from j in JunctionTable\n where listBoxItems.Contains(j.DistributionName)\n join c in contacts on j.ContactID equals c.ContactID\n select new { c.ContactID, c.Surname, c.EmailAddress, c.MobileNumber, \n j.DistributionName, j.EmailFlag, j.SMSFlag }).ToList();\n</code></pre>\n\n<p>I changed these more because I like this syntax better than the SQL like Linq.</p>\n\n<pre><code>var emailAddresses = initialList\n .Where(l => l.EmailFlag)\n .Select(l => l.EmailAddress).Distinct().ToList();\n\nvar smsMobileNumbers = initialList\n .Where(l => l.SMSFlag)\n .Select(l => l.MobileNumber).Distinct().ToList();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T16:20:03.477",
"Id": "14169",
"ParentId": "14165",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T12:48:42.360",
"Id": "14165",
"Score": "4",
"Tags": [
"c#",
"beginner",
"linq"
],
"Title": "Parsing notification information from distribution lists"
}
|
14165
|
<p>I need some useful functions that faster than the original. (Original - C++'s functions)</p>
<p>For example:</p>
<pre><code>#include <time.h>
#include <stdio.h>
#include <Windows.h>
struct TestMemory {
double a,b,c;
};
void* __TestMemory__Sample=0;
int WINAPI WinMain(HINSTANCE h1,HINSTANCE h2,LPSTR str,int i) {
AllocConsole();
__TestMemory__Sample=calloc(1,sizeof(TestMemory));
TestMemory* test=(TestMemory*)malloc(sizeof(TestMemory));
clock_t c1=clock(),c2;
for (int i=0;i<100000000;i++)
memcpy(test,__TestMemory__Sample,sizeof(TestMemory));
c1=clock()-c1;
c2=clock();
for (int i=0;i<100000000;i++)
memset(test,0,sizeof(TestMemory));
c2=clock()-c2;
printf("memcpy: %d\nmemset: %d\nradio: %f (set/cpy)",c1,c2,c2/(float)c1);
getchar();
}
</code></pre>
<p>Output:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>memcpy: 1410
memset: 3250
radio: 2.304965 (set/cpy)
</code></pre>
</blockquote>
<p>This function replace the current way to zero memory.</p>
<p>What it does:</p>
<ol>
<li>Create a global pointer, first set with zeroed memory.</li>
<li>When you want to allocate zeroed memory, allocate memory with <code>malloc</code> and then copy the zeroed memory (global variable) to this memory.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T21:20:16.663",
"Id": "22939",
"Score": "1",
"body": "1) Did you turn on the optimizer. 2) Did you check to see if your code has been removed by the optimizer. 3) Check that you are timing what you think you are timming."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T21:23:04.633",
"Id": "22940",
"Score": "0",
"body": "I know about all of those ,but I need more then this. I am programming scripting language. I need to make it fast as native (C++)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T22:28:53.860",
"Id": "22945",
"Score": "1",
"body": "As expected I get the exact opposite: `memcpy: 141861\nmemset: 139421\nradio: 0.982800`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T13:54:22.593",
"Id": "22974",
"Score": "0",
"body": "That's when you enabling optimizations ,it's deleting all the code. Use it in variables that you really use."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-18T22:35:52.280",
"Id": "24093",
"Score": "0",
"body": "Sorry ,but I need this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T12:36:30.913",
"Id": "24714",
"Score": "1",
"body": "Need _what_? You have an idea, which may or may not be faster than just using memset under some circumstances. Is that what you need? Or you need it to actually be faster?"
}
] |
[
{
"body": "<p>Beware of optimising things, trying to get tiny improvements. By running your program with varying optimisation settings, I got the following ratios (memcpy/memset):</p>\n\n<ul>\n<li>1.8</li>\n<li>1.0</li>\n<li>0.8</li>\n<li>5.1</li>\n</ul>\n\n<p>I think you can use these to prove anything you like. If your program is running too slowly, your attention probably should be directed elsewhere.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T13:56:32.967",
"Id": "22975",
"Score": "0",
"body": "That's when you enabling optimizations ,it's deleting all the code. Use it in variables that you really use."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T10:18:12.923",
"Id": "14194",
"ParentId": "14174",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T18:40:22.693",
"Id": "14174",
"Score": "-2",
"Tags": [
"performance",
"c",
"memory-management",
"windows",
"winapi"
],
"Title": "Zeroing memory on Windows"
}
|
14174
|
<p>Techies--
This routine does more once the channels + the subsets of existing batch arrays are re-distributed for processing. However, the success of that will only work as well as the initial splits. The threshold value is dubbed here, but it will come from app.config as configurable setting. Obviously the jagged string array is dubbed for review purposes. The real values will be coming from another routine and will frequently have counts > 100000. The 3 lines of comments where one will do is a product of formatting the code for StackExchange.</p>
<p>Please review what's here.</p>
<pre><code> #region Channel Assignment Testing
static void ChannelAssign()
{
int THRESHOLD = 1;
string[] batch = new string[]
{ "item1", "item2", "item3", "item4","item5","item6","item7" };
int batchcnt = batch.Count();
int subsetqty; // subset batch item quantity
string[][] subsets; // Split extension returns these values
int channelidx; // index for channels back from Split
if (THRESHOLD != 0) //avoid accidental division by 0.
{
float channels = batchcnt/THRESHOLD;
if (channels < 1) // can handle all items in existing batch based on
// threshold setting.
{
channels = 1; // dub as a single channel
subsetqty = batchcnt; // process all batch items in batch
channelidx = 1; // dub index for a single channel
subsets = batch.Split(batchcnt); // ship the batchcount
// to split routine.
}
else // we need at least 2 channels; round up from float
// and decide how many.
{
channels = (int)Math.Round(channels,
MidpointRounding.ToEven); //determines channel# estimate
subsetqty = batchcnt/(int)channels; // estimates # of
// existing batch items to
// place in each subset
subsets = batch.Split(subsetqty); // actual subsets of batches returned
channelidx = subsets.GetLength(0); //gets actual channel# assigned
// by split
}
//distribute contents of batch into subsets for channel consumption
for (int channel = 0; channel < channelidx; channel++)
{
for(int i = 0; i < subsets[channel].Length; i++)
{
Console.WriteLine(" Channel:" + channel.ToString() + " ItemName:
{0} ", subsets[channel][i]);
}
}
}
else
{
Console.WriteLine("Threshold value set to zero. This is an
invalid value. Please set THRESHOLD.");
}
}
#endregion
</code></pre>
<p>Split Extension</p>
<pre><code> public static T[][] Split<T>(this T[] arrayIn, int length)
{
bool even = arrayIn.Length % length == 0;
int totalLength = arrayIn.Length / length;
if (!even)
totalLength++;
T[][] newArray = new T[totalLength][];
for (int i = 0; i < totalLength; ++i)
{
int allocLength = length;
if (!even && i == totalLength - 1)
allocLength = arrayIn.Length % length;
newArray[i] = new T[allocLength];
Array.Copy(arrayIn, i * length, newArray[i], 0, allocLength);
}
return newArray;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T20:20:45.397",
"Id": "22935",
"Score": "2",
"body": "What kind of review are you looking for? Are there performance problems? Are you looking at ways of doing things differently, just looking for code improvements?"
}
] |
[
{
"body": "<p>I like the formatting, use of white space and tabs.</p>\n\n<p>I'm not sure what THRESHOLD is supposed to represent or where its set, but in the example, I'd make it a const.</p>\n\n<p>I would do the check for 0 right below the assignment:</p>\n\n<pre><code>if (THRESHOLD == 0)\n{\n ...\n\n return;\n}\n</code></pre>\n\n<p>This will un-nest the main logic of your function and catch the error before any processing is done.</p>\n\n<p>The logic should be moved out into their own functions:</p>\n\n<pre><code>var subsets = (channels < 1) ? ProcessWholeList(...) : ProcessPartialList(...);\n</code></pre>\n\n<p>This will better portray then intention of the logic and remove most of the unimportant variables out of the function cleaning it up quite a bit.</p>\n\n<p>I like that you have created an extension to do the split, not many people think of that.</p>\n\n<p>I would change the bool even ... into a check for odd numbers. That what you could change the </p>\n\n<pre><code>if (!even)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if (odd)\n{\n ....\n}\n</code></pre>\n\n<p>Again, expresses the intent a little better. I would also either move the assignment to right above the check.</p>\n\n<p>This assignment:</p>\n\n<pre><code>int allocLength = length;\nif (!even && i == totalLength - 1)\n allocLength = arrayIn.Length % length;\n</code></pre>\n\n<p>Should be changed to:</p>\n\n<pre><code>var allocLength = (!even && i == totalLength - 1) ? arrayIn.Length % length : length;\n</code></pre>\n\n<p>There are just a few simple changes that will clean it up quite a bit. I hope this is a good start and gives you some ideas.</p>\n\n<p>I have another question, is there a reason why you are using a 2 dimensional array rather than one of the build in IEnumerables (i.e. HashTable)? I think for performance purposes, the two dimensional array would be the slowest way of doing it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T00:32:57.450",
"Id": "22949",
"Score": "0",
"body": "Jeff, thanks so much for reviewing this! I really appreciate it. I think I was way too influenced by Bruce Eckel in the early \"Thinking in C\" days to have first gone to a Hash Table. Thank you for reminding me that its an option!;-) Again, thanks so much for looking at this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T20:35:09.747",
"Id": "14177",
"ParentId": "14175",
"Score": "5"
}
},
{
"body": "<p>My biggest issue is with ambiguous variable names and excessive comments. The reason why you wrote so many comments is that the variable names and the method names do not speak to you. Here is my first attempt to clean it up:</p>\n\n<pre><code> public static void AssignChannels()\n {\n int threshold = 1;\n\n // What sort of batch? You can find a better variable name here.\n string[] batch = new string[] { \"item1\", \"item2\", \"item3\", \"item4\", \"item5\", \"item6\", \"item7\" };\n\n int subsetQty; // Subset batch item quantity\n string[][] subsets; // Split extension returns these values\n int channelIndex; // Index for channels back from Split\n\n // This is not strictly necessary, a Debug.Assert would d as well and it will compile away in the release mode. \n Contract.Requires(threshold != 0, \"Threshold value set to zero. This is an invalid value. Please set the threshold.\");\n\n float channelsEstimate = batch.Length / threshold;\n if (channelsEstimate < 1) // can handle all items in existing batch based on \n // threshold setting.\n {\n channelsEstimate = 1; // dub as a single channel\n subsetQty = batch.Length; // process all batch items in batch \n channelIndex = 1; // dub index for a single channel\n subsets = batch.Split(batch.Length); // ship the batchcount to split routine.\n }\n else\n {\n // We need at least 2 channels; round up from float and decide how many.\n channelsEstimate = (int) Math.Round(channelsEstimate, MidpointRounding.ToEven);\n subsetQty = batch.Length / (int)channelsEstimate; // Estimates # of existing batch items to place in each subset.\n subsets = batch.Split(subsetQty); // Actual subsets of batches returned\n channelIndex = subsets.GetLength(0); // Gets actual channel# assigned by split\n }\n\n PrintResult(subsets, channelIndex);\n }\n\n private static void PrintResult(string[][] subsets, int channelIndex)\n {\n // Distribute contents of batch into subsets for channel consumption\n for (int channelLoopIndex = 0; channelLoopIndex < channelIndex; channelLoopIndex++)\n {\n for (int i = 0; i < subsets[channelLoopIndex].Length; i++)\n {\n Console.WriteLine(\" Channel:\" + channelLoopIndex.ToString() + \" ItemName: {0} \", subsets[channelLoopIndex][i]);\n }\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T00:48:23.123",
"Id": "22951",
"Score": "0",
"body": "Leonid, thank you for reviewing my work. I've cleaned up the variable names, implemented your print result concept, used Jeff's idea about splitting the whole or partial batch queues into separate functions--I can't believe how much better this code is!:-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T15:41:59.537",
"Id": "22996",
"Score": "1",
"body": "@plditallo, cool, you might want to add an edit to your question and show the final code. Jeff Vanzella's answer is great; it just does not show the final version. This is not as helpful to those who might want to learn from your problem and the solution. Once you share your \"final\" version, people might find additional ways to improve. Sometimes you re-factor in layers."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T22:18:33.823",
"Id": "14180",
"ParentId": "14175",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "14177",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T19:37:10.037",
"Id": "14175",
"Score": "2",
"Tags": [
"c#"
],
"Title": "C#; Working code--needs review"
}
|
14175
|
<p>I'm designing a small intranet-based time-tracking web app that accepts an unknown number of data "rows" which each consist of 7 form fields. Rows can by dynamically added by the browser.</p>
<p><strong>Can I do better?</strong></p>
<p>Given this (partial) example POST data:</p>
<pre><code>$_POST['project'] =>
Array
(
[0] => PROJECT_CODE_1
[1] => PROJECT_CODE_1
)
$_POST['task']
Array
(
[0] => 21
[1] => 4
)
$_POST['date']
Array
(
[0] => 2012-07-31
[1] => 2012-07-31
)
</code></pre>
<p>And this iterator:</p>
<pre><code><?php
$insert_values = array();
for ($i = 0; $i < count($_POST['project']); $i++)
{
$insert_values[] = array(
'entry_id' => null,
'user_id' => $this->session->userdata('user_id'),
'project_id' => $_POST['project'][$i],
'task_id' => $_POST['task'][$i],
'date' => $_POST['date'][$i]
);
}
$this->db->insert_batch('entries', $insert_values);
?>
</code></pre>
<p>In general, is this iteration pattern safe and sensible? <code>POST['project']</code> is a drop-down, is validated and will always be filled.</p>
|
[] |
[
{
"body": "<blockquote>\n <p>is this iteration pattern safe?</p>\n</blockquote>\n\n<p>Safe for what? Safe for a database? We can't tell you that! There's no code for your database entry function. What you have here is perfectly safe, but that's excluding any type of insert into a database. To safely protect yourself from SQL injection and <a href=\"https://www.owasp.org/index.php/Cheat_Sheets\" rel=\"nofollow noreferrer\">other types of security exploits</a>, use <a href=\"http://www.php.net/manual/en/security.database.sql-injection.php\" rel=\"nofollow noreferrer\">prepared queries</a>, <a href=\"https://stackoverflow.com/questions/17473586/input-sanitization-vs-validation\">validate</a> (sanitize only if needed) incoming data (which includes the username and <code>$_POST['project']</code>!), and <a href=\"http://us2.php.net/htmlentities\" rel=\"nofollow noreferrer\">encode any output</a>.</p>\n\n<p>Without your database function, it's difficult to critique your code. There's not too much that be be done wrong in the snippet provided.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T04:08:06.363",
"Id": "42926",
"ParentId": "14179",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "42926",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T21:51:17.750",
"Id": "14179",
"Score": "1",
"Tags": [
"html",
"php5",
"codeigniter",
"form"
],
"Title": "Is this a sensible form iteration pattern for a web form with an unknown number of fields?"
}
|
14179
|
<p>Any comments are welcome. However I'd like to call specific attention to my... interpretation of the N-Tier application architecture and how I'm consuming data. Note that the namespacing and inline comments have been factored out for brevity.</p>
<h3>The Data Tier (DataModel.csproj)</h3>
<pre><code>// Base class for EF4 Entities
public abstract class EntityBase {
public int Id { get; set; }
}
// Entities
public class Account : EntityBase {
public string UserName { get; set; }
public string Password { get; set; }
public byte[] Salt { get; set; }
public string EmailAddress { get; set; }
}
public class Entry : EntityBase {
public string Title { get; set; }
public DateTime Created { get; set; }
public Account Owner { get; set; }
}
// EF4 Code-First Data Context
public class DataContext : DbContext {
public DbSet<Account> Accounts { get; set; }
public DbSet<Entry> Entries { get; set; }
}
// Repository Pattern
public interface IRepository<TEntity>
where TEntity : EntityBase {
TEntity Create();
void Delete(TEntity entity);
TEntity Get(int id);
TEntity Get(Expression<TEntity,bool>> where);
void Insert(TEntity entity);
void Save();
IQueryable<TEntity> Where(Expression<TEntity,bool>> where);
}
public class Repository<T> : IRepository<T>
where T : EntityBase, new() {
private readonly DataContext context;
private readonly DbSet<T> set;
public Repostory(DataContext context) {
// context injected via ioc.
this.context = context;
this.set = this.context.Set<T>();
}
// Implementation of IRepository<T>
}
</code></pre>
<h3>Business Logic Tier (Runtime.csproj)</h3>
<pre><code>// IOC Container
public static class IOC {
public static readonly IWindsorContainer Container = new WindsorContainer();
static IOC() {
InstallAssembly("Presentation");
InstallAssembly("Runtime");
InstallAssembly("DataModel");
}
public static void InstallAssembly(string name) {
Container.Install(FromAssembly.Named(name));
}
}
// Also includes System.Configuration ConfigSections, HttpModules and Provider classes
// which are strongly tied to IRepository<>.
</code></pre>
<h3>Presentation Layer (Mvc App) (Presentation.csproj)</h3>
<pre><code>protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
// Controller Factory instance makes initial reference to IOC class, causing
// the installers to run.
ControllerBuilder.Current.SetControllerFactory(new Runtime.Mvc.WindsorControllerFactory());
}
// Data-Driven Controller
public class DashboardController : SecureController {
private readonly IRepository<Entry> entries;
public DashboardController(IRepository<Entry> entries) {
// entries injected via ioc.
this.entries = entries;
}
[ChildActionOnly, HttpGet]
public ActionResult RecentEntries() {
var viewModel = new RecentEntriesViewModel( entries.Where( stuffHappens ) );
return PartialView(viewModel);
}
}
</code></pre>
<p>I feel like letting IRepository<> reach the presentation layer may be a violation of the pattern. Exposition of an IQueryable<> through IRepository<>.Where seems like a bad idea at the Presentation level. There's no way to moderate the use of IQueryable and could lead to brittle code. Inputs?</p>
|
[] |
[
{
"body": "<p>I agree that exposing <strong>IRepository<></strong> to the presentation layer is bad.</p>\n\n<p>The reason it's bad is that your Business Logic Tier (BLT) might want to enforce business-y rules on the access of data. That's what the business layer is for, after all.</p>\n\n<p>Your heart is in the right place when you restrict use of the repository to <strong>.Where</strong> in the presentation layer. However, you still have that <strong>entries</strong> field exposed for another programmer to come along and abuse later. To prevent this from happening, you could expose only an <strong>Expression</strong> in the presentation layer. Pass that <strong>Expression</strong> to the BLT, which would then instantiate the <strong>IRepository<></strong> and use the <strong>Expression</strong>. That would also provide a hook for the BLT to add additional conditions to the <strong>Expression</strong> for access control, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-21T13:08:51.210",
"Id": "25714",
"Score": "0",
"body": "-1, If exposing a Repository interface in the presentation layer is bad, then exposing its methods would be bad too, right? Assuming that we are using a DDD approach, the \"Save\" method for any entity or list of entities is probably going to be located in the repository, and defined in this interface. Think of how many applications would completely cease to be functional if all \"Save\" buttons were removed from the UI. Repository implementation details should be buried deep in the infrastructure layer, but the interface is pure domain and must be accessible."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-21T16:09:56.943",
"Id": "14904",
"ParentId": "14182",
"Score": "1"
}
},
{
"body": "<p>If you want to read a good discussion about architecture layouts... check out Onion Architecture.</p>\n\n<p><a href=\"http://blog.giatechnology.com/2011/05/24/a-breakdown-of-onion-architecture-use-in-enterprise-applications-part-1/\" rel=\"nofollow\">http://blog.giatechnology.com/2011/05/24/a-breakdown-of-onion-architecture-use-in-enterprise-applications-part-1/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T06:09:02.903",
"Id": "26048",
"Score": "0",
"body": "I'm also a big fan of using PetaPoco as a Data/ORM layer technology. You can use domain POCO objects in your data layer without needing to expose things like IQueryable to the presentation layer. Also I have found that I have written less code and that it runs faster (versus EntityFramework)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-29T06:01:04.693",
"Id": "16020",
"ParentId": "14182",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-31T23:12:39.280",
"Id": "14182",
"Score": "7",
"Tags": [
"c#",
"asp.net-mvc-3",
"mvc"
],
"Title": "ASP.NET MVC using an N-Tier Model and DDD"
}
|
14182
|
<p>I'm using the cosine function in C++ to simulate flashing for a sprite in my game. The method looks like this:</p>
<p>(anything in the <code>sf</code> namespace is part of the SFML graphics library)</p>
<pre><code>void Player::update(const float& deltaTime)
{
mAccumulatedTime += deltaTime;
float opacity = abs(cosf(5*mAccumulatedTime)) * 255;
static int numFlashes = 0;
if (opacity == 255) {
cout << ++numFlashes << endl;
}
mSprite.setFillColor(sf::Color(255, 255, 255, opacity));
}
</code></pre>
<p>So every time <code>opacity</code> is equal to 255 (basically the passing of one full period), <code>numFlashes</code> should be incremented. The problem is, <code>cos()</code> isn't perfect, meaning it doesn't <em>exactly</em> reach 1 and 0, so the <code>if</code> condition is rarely met. If I use rough checking like <code>if (opacity > 255*0.9999)</code>, then <code>numFlashes</code> becomes really high, really fast.</p>
<p>Does anyone know a way to accurately check when a full period has passed? Or is that just not possible?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T03:08:23.530",
"Id": "22954",
"Score": "0",
"body": "Is delta time in seconds or milli seconds?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T03:18:39.463",
"Id": "22955",
"Score": "1",
"body": "@LokiAstari microseconds (SFML supports it)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T03:24:05.167",
"Id": "22956",
"Score": "0",
"body": "@LokiAstari it's actually not supposed to be in microseconds... I just fixed that problem by dividing `deltaTime` by 1,000,000 in the method-call, so NOW it's in seconds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T06:04:16.760",
"Id": "22960",
"Score": "0",
"body": "Note: cosf() parameter is in radians. So it will get back to 1 every 2.pi/5 seconds (apprx 1.25 seconds). But since you are using abs() on it 0.625 seconds."
}
] |
[
{
"body": "<p>Is it critical that you flash on the maximum? You could change it to flash as it crosses a value if not.</p>\n\n<pre><code>double CalcOpacity( const float& accTime )\n{\n return (cosf(PERIOD*mAccumulatedTime)) * AMPLITUDE;\n}\n\nvoid Player::update(const float& deltaTime)\n{\n float old_opacity = CalcOpacity( mAccumulatedTime );\n mAccumulatedTime += deltaTime;\n float opacity = CalcOpacity( mAccumulatedTime );\n static int numFlashes = 0;\n if ( ( old_opacity < 0 ) && ( opacity >= 0 ) ) {// and the other direction\n cout << ++numFlashes << endl;\n }\n mSprite.setFillColor(sf::Color(255, 255, 255, abs(opacity)));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T06:59:21.357",
"Id": "14190",
"ParentId": "14183",
"Score": "1"
}
},
{
"body": "<p>One may use the following closed formula to compute <code>numFlashes</code>:</p>\n\n<pre><code>numFlashes = 5 * mAccumulatedTime / pi.\n</code></pre>\n\n<p>This follows from the fact that the period of the function <code>abs(cos(x))</code> is <code>pi</code> and, if an oscillating function in variable <code>x</code> has a period <code>T</code>, then the number of oscillations, <code>n</code>, is given by the formula:</p>\n\n<pre><code>n = x / T.\n</code></pre>\n\n<p>Thus, your function definition may be corrected, and even simplified, as follows:</p>\n\n<pre><code>const float PI = acosf(-1);\n\nvoid Player::update(const float& deltaTime)\n{\n mAccumulatedTime += deltaTime;\n float opacity = abs(cosf(5*mAccumulatedTime)) * 255;\n int numFlashes = 5 * mAccumulatedTime / PI;\n cout << numFlashes << endl;\n mSprite.setFillColor(sf::Color(255, 255, 255, opacity));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T09:48:42.960",
"Id": "14192",
"ParentId": "14183",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "14192",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T01:36:14.973",
"Id": "14183",
"Score": "7",
"Tags": [
"c++",
"sfml"
],
"Title": "Cosine function period"
}
|
14183
|
<p>Looking for a code review, as working alone on a project and don't have anyone who could possible help me.</p>
<pre><code>if ($('.qp-content-right-scroll-panel').is(':visible')) {
var isLiveData = $("input:radio[name=preview-options]").val();
if (type.indexOf('DASHBOARD_LAYOUT') != -1) {
var base = $('.qp-content-right-scroll-panel .layoutContent');
var flashObj = $($.browser.mozilla ? "[name=layoutExternalflash]" :
'#layoutExternalflash', base).get(0);
if (flashObj != undefined && $.isFunction(flashObj.ext_sendLayoutDefinition)) {
//get data from radio buttons
$("input:radio[name=preview-options]").click(function () {
var isLiveData = $(this).val();
flashObj.ext_sendLayoutDefinition(elementId, state, isLiveData);
});
}
} else {
var base = $('.qp-content-right-scroll-panel .chartContent');
var flashObj = $($.browser.mozilla ? "[name=chartExternalflash]" :
'#chartExternalflash', base).get(0);
if (flashObj != undefined && $.isFunction(flashObj.ext_sendChartDefinition)) {
$("input:radio[name=preview-options]").click(function () {
var isLiveData = $(this).val();
flashObj.ext_sendLayoutDefinition(elementId, state, isLiveData);
});
flashObj.ext_sendChartDefinition(elementId, state, isLiveData);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T03:51:43.147",
"Id": "22957",
"Score": "0",
"body": "Step 1 is running your code through a beautifier. People will put more effort into viewing your code if you present it properly"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T03:53:49.570",
"Id": "22958",
"Score": "1",
"body": "Have you linted it yet? You'll find that linting will find lots of errors for you and make style suggestions as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T04:17:22.230",
"Id": "22959",
"Score": "0",
"body": "More importantly, what are you trying to do? And why are you checking for a browser?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T06:37:47.053",
"Id": "22961",
"Score": "0",
"body": "@Raynos, what do you mean by beautifier? is it sort of online tool or a plugin, thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T09:08:15.537",
"Id": "22968",
"Score": "0",
"body": "What javascript library are you using (jQuery, Prototype or something else)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-04T16:20:22.873",
"Id": "23204",
"Score": "1",
"body": "@DanMyasnikov: http://jsbeautifier.org is really pretty nice."
}
] |
[
{
"body": "<p>From the looks of it, you are using jQuery as your JavaScript library. Here are the improvements that I think will make your code better.</p>\n\n<p>Don't duplicate code. Use functions (objects).</p>\n\n<p>For example:\n<strong>flashObj</strong> must be accessible to this function.</p>\n\n<pre><code> var getDataFromButton = function(elementId, state, isLiveData){\n $(\"input:radio[name=preview-options]\").click(function () {\n var isLiveData = $(this).val();\n flashObj.ext_sendLayoutDefinition(elementId, state, isLiveData);\n });\n }\n</code></pre>\n\n<p>Use local variables were possible.\nInstead of defining the variable 'base' and 'flashObject' twice, define it once outside the if/else statements and modify it inside them.</p>\n\n<p>Or you can redesign the logic by making an object that has properties such as base, isLiveData, and flashObject.</p>\n\n<p>Without knowing the purpose of this code, this is all I can suggest as improvements.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T11:17:49.663",
"Id": "14195",
"ParentId": "14185",
"Score": "1"
}
},
{
"body": "<p>Is that way is better :</p>\n\n<pre><code>var getDataFromButton = function(elementId, state, isLiveData){\n $(\"input:radio[name=preview-options]\").off('click');\n $(\"input:radio[name=preview-options]\").on('click', function () {\n var isLiveData = $(this).val();\n flashObj.ext_sendLayoutDefinition(elementId, state, isLiveData);\n });\n }\n</code></pre>\n\n<p>When you use <code>getDataFromButton</code> several time click function olso executed more time</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-16T15:46:56.870",
"Id": "66885",
"ParentId": "14185",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "14195",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T02:11:40.463",
"Id": "14185",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Radio button selection and flash object initialization"
}
|
14185
|
<p>This Python code parses string representations of Reversi boards and converts them into bit string suitable for use by a bitstring module: <code>b = BitArray('0b110')</code> or bitarray module: <code>a = bitarray('000111')</code> if <code>blackInit</code> and <code>whiteInit</code> are initialized as empty strings.</p>
<p>I am interested in a simpler way to do this in Python. I would like to preserve the idea of having a human readable string representation of the board converted into 2 bitstrings, one for the black pieces and one for the white pieces. It seems like it could be simpler if it was just a split and then a map instead of a loop, but I wanted to be able to see the strings line by line and don't see how to workaround that.</p>
<pre><code>board1 = [
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_']
board2 = [
'B|_|_|_|_|_|_|W',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'W|_|_|_|_|_|_|B']
board3 = [
'W|W|W|W|B|B|B|B',
'W|_|_|_|_|_|_|B',
'W|_|_|_|_|_|_|B',
'W|_|_|_|_|_|_|B',
'B|_|_|_|_|_|_|W',
'B|_|_|_|_|_|_|W',
'B|_|_|_|_|_|_|W',
'B|B|B|B|W|W|W|W']
board4 = [
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|W|B|_|_|_',
'_|_|_|B|W|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_']
board5 = [
'W|_|_|_|_|_|_|B',
'_|W|_|_|_|_|B|_',
'_|_|W|_|_|B|_|_',
'_|_|_|W|B|_|_|_',
'_|_|_|B|W|_|_|_',
'_|_|B|_|_|W|_|_',
'_|B|_|_|_|_|W|_',
'B|_|_|_|_|_|_|W']
def parse_board(board):
def map_black(spot):
return str(int(spot == 'B'))
def map_white(spot):
return str(int(spot == 'W'))
blackInit = '0b'
whiteInit = '0b'
for line in board:
squares = line.split('|')
blackInit = blackInit + ''.join(map(map_black,squares))
whiteInit = whiteInit + ''.join(map(map_white,squares))
return (blackInit,whiteInit)
print(parse_board(board1))
print(parse_board(board2))
print(parse_board(board3))
print(parse_board(board4))
print(parse_board(board5))
</code></pre>
|
[] |
[
{
"body": "<pre><code>def parse_board(board):\n def map_black(spot):\n</code></pre>\n\n<p>This name suggests that the function is a variant on map. Whereas its actually intended to be used as a parameter on map</p>\n\n<pre><code> return str(int(spot == 'B'))\n def map_white(spot):\n return str(int(spot == 'W'))\n</code></pre>\n\n<p>Both functions are very similiar, can you refactor?</p>\n\n<pre><code> blackInit = '0b'\n whiteInit = '0b'\n</code></pre>\n\n<p>The python style guide suggest 'lowercase_with_underscores' for local variable names</p>\n\n<pre><code> for line in board:\n squares = line.split('|')\n blackInit = blackInit + ''.join(map(map_black,squares))\n whiteInit = whiteInit + ''.join(map(map_white,squares))\n</code></pre>\n\n<p>Repeatedly adding strings is not very efficient python.</p>\n\n<pre><code> return (blackInit,whiteInit)\n</code></pre>\n\n<p>Everything in your function is done twice. Once for 'B' and once for 'W'. I'd suggest you should have a function that takes 'B' or 'W' as parameter, and call that twice.</p>\n\n<p>Here's how I'd tackle this:</p>\n\n<pre><code>def bitstring_from_board(board, letter):\n bits = []\n for line in board:\n bits.extend( spot == letter for spot in line.split('|') )\n return '0b' + ''.join(str(int(x)) for x in bits)\n\ndef parse_board(board):\n return bitstring_from_board(board, 'B'), bitstring_from_board(board, 'W')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-02T04:37:35.093",
"Id": "23027",
"Score": "0",
"body": "Thank you for your effort. I will avoid doing things twice in my revision."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T14:10:09.680",
"Id": "14202",
"ParentId": "14187",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "14202",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-01T05:03:43.310",
"Id": "14187",
"Score": "1",
"Tags": [
"python",
"strings",
"parsing"
],
"Title": "Reversi text board parsing to bitfield"
}
|
14187
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.