body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have the following <code>using</code> statement, used specifically for the purpose of archiving content in SharePoint libraries. In this statement my objects are disposed in two places:</p> <pre><code>finally { web.Dispose(); site.Dispose(); } </code></pre> <p>and at the termination of my <code>using</code> statement.</p> <p>The full <code>using</code> statement is:</p> <pre><code>using (var site = new SPSite(connectionString)) { SPWeb web = site.OpenWeb(); // open the site Console.WriteLine("[{0}] Opened site: {1}", DateTime.Now.ToShortTimeString(), web); Console.WriteLine("[{0}] Web Relative URL is: {1}", DateTime.Now.ToShortTimeString(), web.ServerRelativeUrl); try { // Get your source and destination libraries var source = web.GetList(web.ServerRelativeUrl + @"/Approval%20History%20%20Sales1"); var destination = web.GetList(web.ServerRelativeUrl + @"/Approval%20History%20%20Sales"); Console.WriteLine("[{0}] Source set to: {1}", DateTime.Now.ToShortTimeString(), source); Console.WriteLine("[{0}] Destination set to: {1}", DateTime.Now.ToShortTimeString(), destination); // Get the collection of items to move, use source.GetItems(SPQuery) if you want a subset SPListItemCollection items = source.Items; // Get the root folder of the destination we'll use this to add the files SPFolder folder = web.GetFolder(destination.RootFolder.Url); Console.WriteLine("[{0}] Moving {1} files from {2} to {3} - please wait...", DateTime.Now.ToShortTimeString(), items.Count, source, destination); // Now to move the files and the metadata foreach (SPListItem item in items) { //Get the file associated with the item SPFile file = item.File; // Create a new file in the destination library with the same properties SPFile newFile = folder.Files.Add(folder.Url + "/" + file.Name, file.OpenBinary(), file.Properties, true); // Optionally copy across the created/modified metadata SPListItem newItem = newFile.Item; newItem["Editor"] = item["Editor"]; newItem["Modified"] = item["Modified"]; newItem["Modified By"] = item["Modified By"]; newItem["Author"] = item["Author"]; newItem["Created"] = item["Created"]; newItem["Created By"] = item["Created By"]; // UpdateOverwriteVersion() will preserve the metadata added above. newItem.UpdateOverwriteVersion(); // Delete the original version of the file // todo: make local backup before deleting? file.Delete(); fileCount++; } Console.WriteLine("[{0}] Completed moving {1} files to {2}", DateTime.Now.ToShortTimeString(), fileCount, destination); } catch (System.IO.FileNotFoundException) { Console.WriteLine("[{0}] Unable to set a location. Please check that paths for source and destination libraries are correct and relative to the site collection.", DateTime.Now.ToShortTimeString()); } finally { web.Dispose(); site.Dispose(); } } </code></pre> <p>Is my <code>finally</code> statement here redundant? Is there any reason that even if potentially it <em>is</em> redundant that I should retain it anyway?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T02:30:43.373", "Id": "24229", "Score": "0", "body": "I recommend reading this item, even though there is a better construct in c# 4.0 http://my.safaribooksonline.com/book/programming/csharp/9780321659149/dotnet-resource-management/ch02lev1sec4" } ]
[ { "body": "<p>Prefer to use RAII above <code>finally</code>; you are already doing this with <code>site</code>, so disposing of it in the <code>finally</code> doesn't make much sense. On the other hand, you are not disposing of <code>web</code> that way and I would say that this could leak to (extremely unlikely) errors. For example, if <code>web.ServerRelativeUrl</code> was a property and threw, you would now fail to dispose of <code>web</code> correctly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T07:14:11.233", "Id": "24234", "Score": "0", "body": "I think you can't call `using` RAII. It serves a very similar purpose, but it is not the same." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T17:24:50.743", "Id": "24272", "Score": "0", "body": "@svick: Why not? It is definitely SBRM, which is generally considered a synonym for it as far as I know." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T01:18:36.960", "Id": "14927", "ParentId": "14922", "Score": "0" } }, { "body": "<p>It depends on the logic of the <code>Dispose</code> implementation in each class:</p>\n\n<p>If the class can tolerate consequent invocations to its <code>Dispose</code> method, then all is fine and dandy.</p>\n\n<p>If not, then, maybe an exception would be thrown...</p>\n\n<p>In any case, I would avoid invoking a <code>Dispose</code> method more than once - indicates a code smell.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T07:16:10.780", "Id": "24235", "Score": "0", "body": "[“If an object's Dispose method is called more than once, the object must ignore all calls after the first one.”](http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx) So, all `IDisposable` types should work fine with multiple invocations of `Dispose()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T03:07:01.600", "Id": "24599", "Score": "0", "body": "@svick, that's theory. In practice, it's totally up to the developer if to follow this instruction or not..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T01:45:52.297", "Id": "14929", "ParentId": "14922", "Score": "0" } }, { "body": "<p>There is no reason to have to call dispose on site, the using statement takes care of it.</p>\n\n<p>On the same note, the web variable should be wrapped in a using statement too, then the finally block is redundant.</p>\n\n<pre><code>using (var site = new SPSite(connectionString))\n{\n using(var web = site.OpenWeb())\n {\n //...\n }\n}\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.100%29.aspx\">Microsoft Help</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T02:21:01.293", "Id": "14930", "ParentId": "14922", "Score": "5" } }, { "body": "<p>Well, one is redundant, <code>Dispose()</code> on the <code>site</code> object is done for you automatically in the context of <code>using</code>. To be idiomatic in C#, you should do the following:</p>\n\n<pre><code>using (var site = new SPSite(connectionString))\nusing (SPWeb web = site.OpenWeb()) // open the site\n{\n try\n {\n Console.WriteLine(\"[{0}] Opened site: {1}\", DateTime.Now.ToShortTimeString(), web);\n Console.WriteLine(\"[{0}] Web Relative URL is: {1}\", DateTime.Now.ToShortTimeString(), web.ServerRelativeUrl);\n\n // Get your source and destination libraries\n var source = web.GetList(web.ServerRelativeUrl + @\"/Approval%20History%20%20Sales1\");\n var destination = web.GetList(web.ServerRelativeUrl + @\"/Approval%20History%20%20Sales\");\n\n Console.WriteLine(\"[{0}] Source set to: {1}\", DateTime.Now.ToShortTimeString(), source);\n Console.WriteLine(\"[{0}] Destination set to: {1}\", DateTime.Now.ToShortTimeString(), destination);\n\n // Get the collection of items to move, use source.GetItems(SPQuery) if you want a subset\n SPListItemCollection items = source.Items;\n\n // Get the root folder of the destination we'll use this to add the files\n SPFolder folder = web.GetFolder(destination.RootFolder.Url);\n\n Console.WriteLine(\"[{0}] Moving {1} files from {2} to {3} - please wait...\", DateTime.Now.ToShortTimeString(),\n items.Count, source, destination);\n\n // Now to move the files and the metadata\n foreach (SPListItem item in items)\n {\n //Get the file associated with the item\n SPFile file = item.File;\n\n // Create a new file in the destination library with the same properties\n SPFile newFile = folder.Files.Add(folder.Url + \"/\" + file.Name, file.OpenBinary(), file.Properties, true);\n\n // Optionally copy across the created/modified metadata \n SPListItem newItem = newFile.Item;\n newItem[\"Editor\"] = item[\"Editor\"];\n newItem[\"Modified\"] = item[\"Modified\"];\n newItem[\"Modified By\"] = item[\"Modified By\"];\n newItem[\"Author\"] = item[\"Author\"];\n newItem[\"Created\"] = item[\"Created\"];\n newItem[\"Created By\"] = item[\"Created By\"];\n\n // UpdateOverwriteVersion() will preserve the metadata added above. \n newItem.UpdateOverwriteVersion();\n\n // Delete the original version of the file\n // todo: make local backup before deleting?\n file.Delete();\n fileCount++;\n }\n\n Console.WriteLine(\"[{0}] Completed moving {1} files to {2}\", DateTime.Now.ToShortTimeString(), fileCount,\n destination);\n }\n catch (System.IO.FileNotFoundException)\n {\n Console.WriteLine(\"[{0}] Unable to set a location. Please check that paths for source and destination libraries are correct and relative to the site collection.\", DateTime.Now.ToShortTimeString());\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T02:21:03.917", "Id": "14931", "ParentId": "14922", "Score": "10" } } ]
{ "AcceptedAnswerId": "14931", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T23:05:02.307", "Id": "14922", "Score": "5", "Tags": [ "c#" ], "Title": "Archiving content in SharePoint libraries" }
14922
<p>Okay, So I have this method I made that searches a 2d array of user input column length and row length comprised of integers. The method is suppose to find 4 alike numbers in rows, columns, and both major and minor diagonals throughout the entire array. The array can be as large as the user would like. My method works, however it is extremely ugly and feels redundant. I feel like there should be a better way to compact my code that I just am not seeing. Can anyone tell me how I may accomplish this? I am trying to self teach myself so I don't really have any help but my own. Please dont bash my ugly code :) haha. My main issue is the check diagonals part... It seems like it could be shorter. </p> <pre><code>public static boolean isConsecutiveFour(int[][] values) { int count = 0; int currentElement = 0; //count rows for (int x = 0; x &lt; values.length; x++) { count = 0; currentElement = values[x][0]; for (int y = 0; y &lt; values[x].length; y++) { if (currentElement == values[x][y]) count++; currentElement = values[x][y]; } if (count &gt;= 4) return true; } //count columns for (int x = 0; x &lt; values[0].length; x++) { count = 0; currentElement = values[0][x]; for (int y = 0; y &lt; values.length; y++) { if (currentElement == values[y][x]) count++; currentElement = values[y][x]; } if (count &gt;= 4) return true; } //count diagonals for (int x = 0; x &lt; values.length; x++) { int increaseRow = x; for (int y = 0; y &lt; values[x].length; y++) { int currentMajElement = values[x][y], currentSubElement = values[x][y]; int majCount = 0, subCount = 0; int increaseColumn = y, decreaseColumn = y; //Check major diagonals while (increaseRow &lt; values.length &amp;&amp; increaseColumn &lt; values[x].length) { if (currentMajElement == values[increaseRow][increaseColumn]) majCount++; currentMajElement = values[increaseRow][increaseColumn]; increaseColumn++; increaseRow++; } increaseRow = x; //Check minor diagonals while (increaseRow &lt; values.length &amp;&amp; decreaseColumn &gt;= 0) { if (currentSubElement == values[increaseRow][decreaseColumn]) subCount++; currentSubElement = values[increaseRow][decreaseColumn]; increaseRow++; decreaseColumn--; } if (majCount &gt;= 4 || subCount &gt;= 4) return true; } } return false; } </code></pre>
[]
[ { "body": "<p>I think the nicest thing to do is to create a function which separates the counting of the elements of an array from the array itself. For example, right now you have a \"counting procedure\", which basically looks like this:</p>\n\n<pre><code>public static boolean count(int[] values) {\n\n int count = 0;\n int currentElement = values[0];\n for(int i = 0; i &lt; values.length; i++) {\n if (currentElement == values[i])\n count++;\n currentElement = values[i];\n }\n return (count &gt;= 4);\n}\n</code></pre>\n\n<p>Once you've separated this out, counting the rows is as simple as</p>\n\n<pre><code>int rows = values.length\nint cols = values[0].length\nfor (int i = 0;i &lt; rows; i++)\n if (count(values[i]))\n return true;\n</code></pre>\n\n<p>Counting the columns like this is a little trickier. I think the cleanest way to do this is to actually allocate a temporary array and fill it with the correct values. Note that this isn't faster than what you've recommended -- it's only prettier.</p>\n\n<pre><code>int[] tmpArray = new int[rows];\nfor (int j = 0; j &lt; cols; i++) {\n for (int i = 0; i &lt; rows; i++)\n tmpArray[i] = values[i][j];\n if (count(tmpArray))\n return true;\n}\n</code></pre>\n\n<p>It's not actually clear to me at all if your diagonal counting code works, but now we have a nice tool to write it intuitively. What's tricky is I cannot see the four distinct diagonals you're counting, and what parts of the code handle each one. With the following approach, we do each one individually: </p>\n\n<pre><code>int diagonal_length = min(rows, cols)\ntmpArray = new int[diagonal_length];\n\n//first major diagonal\nfor(int i = 0; i &lt; diagonal_length;i++)\n tmpArray[i] = values[i][i];\nif (count(tmpArray))\n return true;\n\n//second major diagonal\nfor(int i = 0; i &lt; diagonal_length;i++)\n tmpArray[i] = values[i][cols - 1 - i];\nif (count(tmpArray))\n return true;\n\n//first minor diagonal\nfor(int i = 0; i &lt; diagonal_length;i++)\n tmpArray[i] = values[rows - 1 - i][i];\nif (count(tmpArray))\n return true;\n\n//second minor diagonal\nfor(int i = 0; i &lt; diagonal_length;i++)\n tmpArray[i] = values[rows - 1 - i][cols - 1 - i];\nif (count(tmpArray))\n return true;\n\nreturn false;\n</code></pre>\n\n<p>The big advantage of this proposed rewrite is <em>not</em> in speed or algorithms, simply a matter of code clarity. It's easier to test and examine this code; e.g. the count function can be tested separately. You can also easily print out the tmpArray variable to check that the right thing is being counted at the beginning of count(), and this is a must if you want to be sure this code is working properly.</p>\n\n<p>Important note:: I haven't tested any of this code yet!! Errors are fairly likely, but the idea should work either way.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T07:44:29.050", "Id": "14933", "ParentId": "14928", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T01:20:27.437", "Id": "14928", "Score": "6", "Tags": [ "java", "array", "search" ], "Title": "Java 2d array nested loops" }
14928
<p>While preparing an automated process to manipulate files, I've made the following function to check for the base directory and sub-directories presence, as to allow or deny the remaining code to be executed:</p> <pre><code>/* Check Directories * * Confirm that the necessary directories exist, and if not, * tries to create them. * * @_param string $whereAmI -&gt; Script location * @_param string $backup_path -&gt; target directory relative path * @_param array $subDirArr -&gt; sub-directories array * * @return * success -&gt; Boolean * failure -&gt; string with failure path */ function check_directories($whereAmI, $backup_path, $subDirArr) { // initialize return variable $status = FALSE; // check for the merchant base directory if (!is_dir($whereAmI."/".$backup_path)) { // trying to create the directory with permissions exec("mkdir ".$backup_path." -m 777 2&gt;&amp;1", $output, $return_value); // error returned, stop and return status $status = (is_array($output) &amp;&amp; count($output)&gt;=1) ? $backup_path : TRUE; } else { $status = TRUE; } // base directory exists, continue if ($status===TRUE) { // run by each sub-directory foreach ($subDirArr as $subDir) { /* keep checking for status value, if changed, * one directory has failed and we can't proceed */ if ($status===TRUE) { // check for the sub-directory presence if (!is_dir($whereAmI."/".$subDir)) { // trying to create the directory with permissions exec("mkdir ".$subDir." -m 777 2&gt;&amp;1", $output, $return_value); // error returned, stop and update status $status = (is_array($output) &amp;&amp; count($output)&gt;=1) ? $subDir : TRUE; } } else { return $status; } } } return $status; } </code></pre> <p><strong>Considerations:</strong></p> <ul> <li>Directory permissions when in production aren't <code>777</code>.</li> <li>Server is running PHP Version 5.3.10.</li> </ul> <p>Can this be simplified, thus reducing the amount of code, and perhaps in such reduction, have it improved?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T13:38:34.707", "Id": "24245", "Score": "1", "body": "why not just use mkdir() from PHP?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T20:09:55.637", "Id": "24286", "Score": "0", "body": "I'm quite curious too. The `exec` stuff seems very excessive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T17:05:04.530", "Id": "24346", "Score": "0", "body": "Essentially, I was working on a stand-alone server that was giving me a hard time with the folder permissions. I couldn't workaround this with the very limited time that I had to build the solution, and so, since security wasn't a concern, I used `exec()` to create and set the folder permissions. Now I'm in the process of improving the entire solution, being this code a tiny part of the big picture. Hence why I came here to ask for advice on stuff that I may have overlooked. I'll be dealing with the `exec()` issue, as to make this a more \"recyclable\" function to use on other projects." } ]
[ { "body": "<p>Quite a few things wrong with your PHPDoc. I'm actually learning quite a bit myself. Doccomments require two asterisks to begin, not one, no matter what language you are using. One asterisk just defines a multi-line comment. Your IDE will skip over this, essentially making these useless as doccomments. The underscore before param, the \"yields\" operator <code>-&gt;</code>, and your return syntax all cause my IDE to ignore this comment because it is in the wrong syntax. The multi-return sequences are best done using the bitwise OR operator separating the types, but you can also use a \"mixed\" type to accomplish the same thing.</p>\n\n<pre><code>/** Check Directories\n * etc...\n * @param string $whereAmI Script location\n * @return bool|string String on success, FALSE on failure\n//OR\n * @return mixed String on success, FALSE on failure\n */\n</code></pre>\n\n<p>Be careful with \"clever\" variables. For a few seconds there I was quite confused about your <code>$whereAmI</code> variable, thinking that last letter was an \"L\" and not an \"I\". I'm a bit slow sometimes and I was sitting there scratching my head trying to figure out what an \"aml\" was (in case you're curious, my best guess was animal). I would stick with simple variable names, such as <code>$location</code> or <code>$position</code>. Additionally, pick a style and be consistent. I see both camelCase AND under_score variables. One or the other, not both. You can do one for functions and the other for variables, if you wish. I've seen that done frequently enough that I wouldn't comment on it, but switching between the styles on the same datatype is just confusing.</p>\n\n<p>Internal comments, especially ones that explain what is already in the doccomments, are just noise. Anyone reading this function will know that <code>$status</code> is important, and once they reach the end of the function they will know its also returned. If, like me, you skip to the bottom of the function to see what it returns and then work backwards from there, then you will already know that it is returned. Same for the rest of these comments. The only time I use internal comments is for explaining confusing lines, such as REGEX, <code>compact()</code>, <code>extract()</code>, or, in your case, that <code>exec()</code>.</p>\n\n<p>Alright, lets move on to actual code.</p>\n\n<p>Why did you bother setting an initial value to <code>$status</code>, your very next line of code overwrites that value no matter what. Let the if/else statements assign it for you. Or lose the else and use that as the default value.</p>\n\n<p>Avoid using \"not\" <code>!</code> unless you have to. In this instance you have an if/else statement. Switch them around and remove the \"not\". In the above scenario you would keep the \"not\".</p>\n\n<pre><code>if( is_dir( $whereAmI . '/' . $backup_path ) ) {\n $status TRUE;\n} else {\n</code></pre>\n\n<p><strong>Explaining Not:</strong></p>\n\n<p>If you are doing a single if statement, then the not is fine and necessary. Though this could be argued that the <code>empty()</code> function should be used, either is fine, but I find the \"not\" syntax preferrable in this case.</p>\n\n<pre><code>if( ! $var ) {//fine\n//OR\nif( empty( $var ) ) {//also fine, though less preferrable IMO\n</code></pre>\n\n<p>If you are using an if/else statement, as I demonstrated in initial answer, the not is implied by else and should be removed for clarity as well as efficiency.</p>\n\n<pre><code>if( $var ) {\n} else {//not implied here\n}\n</code></pre>\n\n<p>This helps with clarity because the \"not\" operator <code>!</code> is not always immediately noticeable, depending on how you space your statements (which is one of the reasons my statements are so spacious). This helps with efficiency because typically your \"not\" clause holds the least amount of coding and might even contain an early escape, resulting in the else syntax not even being necessary which meaning less indentation and increased clarity.</p>\n\n<pre><code>if( $var ) {\n return FALSE;\n}\n//contents of else\n</code></pre>\n\n<p>The only time to compare a value explicitly to a boolean is when doing a type comparison. Such as an integer \"0\" to a boolean \"FALSE\", or string \"FALSE\" to FALSE. And the above rules hold true for this as well.</p>\n\n<pre><code>if( $var !== FALSE ) {\n//OR\nif( $var === FALSE ) {\n} else {\n}\n//OR\nif( $var === FALSE ) {\n return FALSE;\n}\n//contents of else\n</code></pre>\n\n<p><strong>End of Explanation</strong></p>\n\n<p>You mentioned security; You should be careful of functions such as <code>exec()</code>. Functions, by definition, are public. So, this script is public, therefore you can not guarantee the validity of those parameters being passed to it, or rather, you aren't validating them. This is a potential security issue, but only if you plan on using this in a public domain (internet). That and the \"777\" permissions. Directories should not be executable. I can't remember off the top of my head what the proper permissions to use are, but I DO know that \"777\" will get you in trouble. Though, admittedly I do this in my server as well, but mine is a small intranet and security isn't one of the things I'm particularly worried about.</p>\n\n<p>Split up your function. It is concerned with entirely too much. <code>check_directories()</code> should only be concerned with checking the directories, but then you start adding on subdirectories. This is a different concern altogether. Take a look at the Single Responsibility Principle. Additionally, look at \"Don't Repeat Yourself\" (DRY) Principle. Your if/else statement that I mentioned above is repeated, therefore it can be made into a function to avoid this. This will be the biggest contributor to reducing the size of this program. That and removing those unnecessary comments. Besides that, I don't think there are any other ways to do this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:08:22.577", "Id": "24262", "Score": "0", "body": "You've mentioned some issues that despite the fact I've wrote the function in the rush, I shouldn't have overlooked, thanks! Regarding avoid using \"not\", can you elaborate? And if I go from `!$check` to `$check === FALSE`, will the recommendation continue to be \"avoid it!\" ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T17:03:59.543", "Id": "24271", "Score": "0", "body": "@Zuul: Added explanation in answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T17:08:58.690", "Id": "24347", "Score": "0", "body": "Thank you for the extra insight. I already applied your suggestions, that leaded to a code reduction, more compatible with other projects and with a proper Doccomment." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T15:18:48.860", "Id": "14946", "ParentId": "14936", "Score": "2" } }, { "body": "<p>Maybe something like this, adjust the path to mkdir() as necessary</p>\n\n<pre><code>function check_directories($whereAmI, $backup_path, $subDirArr) {\n foreach ($subDirArr as $subDir) {\n mkdir( $subDir, 0777, true ) or return false;\n }\n return true;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T04:53:38.723", "Id": "15015", "ParentId": "14936", "Score": "1" } } ]
{ "AcceptedAnswerId": "14946", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T13:20:44.767", "Id": "14936", "Score": "1", "Tags": [ "php", "performance", "security" ], "Title": "Confirming the presence/create directories" }
14936
<p>I have been trying to get the problem <a href="https://www.interviewstreet.com/challenges/dashboard/#problem/4e48b9cb8917f" rel="nofollow">Quadrant Queries</a> correct for a while now. Although my approach is an optimal one, I am getting a TLE on 3 test cases. Please help me optimize my approach so that I can pass all test cases for the problem.</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; #include &lt;cstring&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;utility&gt; using namespace std; typedef pair &lt;int,int&gt; pii; void performCquery(int i,int j, const vector&lt; pii &gt; &amp;pointList) { i = i-1; j = j-1; int q1 = 0; int q2 = 0; int q3 = 0; int q4 = 0; for (int k = i; k &lt;=j ; k++) { if ( (pointList[k].first &gt; 0 ) &amp;&amp; ( pointList[k].second &gt; 0) ) { q1++; } else if ( (pointList[k].first &lt; 0) &amp;&amp; ( pointList[k].second &gt; 0) ) { q2++; } else if ( ( pointList[k].first &lt; 0) &amp;&amp; (pointList[k].second &lt; 0 ) ) { q3++; } else if ( ( pointList[k].first &gt; 0) &amp;&amp; (pointList[k].second &lt; 0 ) ) { q4++; } } cout &lt;&lt; q1 &lt;&lt; " " &lt;&lt; q2 &lt;&lt; " " &lt;&lt; q3 &lt;&lt; " " &lt;&lt; q4 &lt;&lt; endl; } void performXYquery(char qType, int i, int j, vector&lt; pii &gt; &amp;pointList) { i = i-1; j = j-1; for ( int k = i; k &lt;= j ;k++) { pii pnt = pointList[k]; if ( qType == 'X') { pointList[k].second = -pointList[k].second; } else if (qType == 'Y') { pointList[k].first = -pointList[k].first; } } } int main(int argc, char* argv[]) { int numOfPoints; cin &gt;&gt; numOfPoints; vector &lt; pii &gt; pointList; for (int i = 0; i &lt; numOfPoints ; i++) { int x,y; cin &gt;&gt; x &gt;&gt; y; pii temp(x,y); pointList.push_back(temp); } int numOfQueries; cin &gt;&gt; numOfQueries; for (int i = 0; i &lt; numOfQueries; i++) { char qName; int startIndex; int endIndex; cin &gt;&gt; qName &gt;&gt; startIndex &gt;&gt; endIndex; if (qName == 'C') { performCquery(startIndex,endIndex, pointList); } else if (qName == 'X' || qName == 'Y') { performXYquery(qName, startIndex,endIndex, pointList); } else { cerr &lt;&lt; "Error: This line should not be printed" &lt;&lt;endl; } } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:35:00.493", "Id": "24266", "Score": "0", "body": "The point of this test is to test YOUR current ability to code, not your ability to solicit help on the internet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T03:15:03.850", "Id": "24313", "Score": "0", "body": "Thanks, but IMO I never asked for code or solution to my problem. Instead, my code was able to pass 8/10 test case and had a timeout on the remaining 2, therefore I wanted to know if I could optimize my code or my algorithm. Now I do know that my algorithm was pretty naive one.\nTherefore, inseatead of posting a rude comment, please provide some help." } ]
[ { "body": "<h3>Algorithmic optimizations.</h3>\n<p>As you read the values in work out what quadrant the point belongs to and keep a running total for each quadrant (not adjustment needed on X/Y query). Then you do not need to re-calculate everything every time there is a 'C' request.</p>\n<p>As it stands complexity for each C request of O(n). If you keep a running total then it is merely o(1). Think of the situation where you have a 1,000,000 points and you do a 1,000,000 C requests. The code would basically do 1,000,000 * 1,000,000 operations rather than just 1,000,000.</p>\n<h3>Style</h3>\n<p>Please stop using this:</p>\n<pre><code>using namespace std;\n</code></pre>\n<p>For simple ten line programs it makes things simpler. But once you get past that stage it makes things exceedingly more complex. By causing name clashing problems. It is preferable to prefix stuff in the standard namespace with <code>std::</code> (why do you think they kept it so short).</p>\n<p>A personal opinion. So feel free to ignore. But to distinguish types and objects. I nae types with a leading capitol letter. A lower case indicates an object (or reference).</p>\n<pre><code>typedef pair &lt;int,int&gt; pii;\n</code></pre>\n<p>What happens below if any point is on the line (first or second == 0)?</p>\n<pre><code> if ( (pointList[k].first &gt; 0 ) &amp;&amp; ( pointList[k].second &gt; 0) ) {\n q1++;\n }\n else if ( (pointList[k].first &lt; 0) &amp;&amp; ( pointList[k].second &gt; 0) ) {\n q2++;\n }\n else if ( ( pointList[k].first &lt; 0) &amp;&amp; (pointList[k].second &lt; 0 ) ) {\n q3++;\n }\n else if ( ( pointList[k].first &gt; 0) &amp;&amp; (pointList[k].second &lt; 0 ) ) {\n q4++;\n }\n}\n</code></pre>\n<p>Here:</p>\n<pre><code>void performXYquery(char qType, int i, int j, vector&lt; pii &gt; &amp;pointList)\n</code></pre>\n<p>For readability I would just make this two separate functions <code>performXquery()</code> and <code>performYquery()</code>. It make the code more readable and removes the need for an if statement in the middle of a tight loop.</p>\n<p>There is a standard utility function for creating std::pair&lt;&gt; called make_pair.</p>\n<pre><code> pii temp(x,y);\n pointList.push_back(temp);\n\n // can be written as:\n pointList.push_back(std::make_pair(x, y));\n</code></pre>\n<p>Since qName is a char you can use a switch statement here:</p>\n<pre><code> if (qName == 'C') {\n performCquery(startIndex,endIndex, pointList);\n }\n else if (qName == 'X' || qName == 'Y') {\n performXYquery(qName, startIndex,endIndex, pointList);\n }\n\n // can be written as:\n switch(qName)\n {\n case 'C': performCquery(startIndex,endIndex, pointList);break;\n case 'X': performXquery(startIndex,endIndex, pointList);break;\n case 'Y': performYquery(startIndex,endIndex, pointList);break;\n default: /* Error Msg */\n }\n</code></pre>\n<p>No need to return 0 from main() in C++. If no explicit return is placed then an automatic return 0 is planted.</p>\n<h3>Algorithmic optimizations.</h3>\n<p>As you read the values in work out what quadrant the point belongs to and keep a running total for each quadrant (not adjustment needed on X/Y query). Then you do not need to re-calculate everything every time there is a 'C' request.</p>\n<p>As it stands complexity for each C request of O(n). If you keep a running total then it is merely o(1). Think of the situation where you have a 1,000,000 points and you do a 1,000,000 C requests. The code would basically do 1,000,000 * 1,000,000 operations rather than just 1,000,000.</p>\n<h3>Macro optimizations</h3>\n<p>Only do these to make the code more readable. Usually the compiler already handles this kind of optimization.\nAssume we have an average distribution of points in 4 quadrants:</p>\n<pre><code>100 pts // cmp == conditional test like &gt; or &lt; \n25 in q1 use 2 cmp // must pass both to enter\n25 in q2 use 3.5 cmp // Note: average (12.5 will do 3 cmp 12.5 will do 4 cmp)\n25 in q3 use 5 cmp // to enter the code section that will do q2++\n25 in q4 use 6.5 cmp\n\nTotal: 425 cmp\n</code></pre>\n<p>If we change the code so you include values on the line (ie first or second == 0) in an appropriate quadrant. You don't need the last if statement which reduces the number of comparisons so that:</p>\n<pre><code>100 pts // cmp == conditional test like &gt; or &lt; \n25 in q1 use 2 cmp // must pass both to enter\n25 in q2 use 3.5 cmp \n25 in q3 use 5 cmp\n25 in q4 use 4.5 cmp\n\nTotal: 375 cmp\n</code></pre>\n<p>If we re-range the tests:</p>\n<pre><code>if (first &gt;= 0)\n{\n if (second &gt;= 0) ++q1;\n else ++q4;\n}\nelse // first = 0\n{\n if (second &gt;= 0) ++q2;\n else ++q3;\n}\n</code></pre>\n<p>In this case there are always 2 cmp:</p>\n<pre><code>100 nodes * 2 cmp = 200 cmp\nApproximately a 100% reduction in the number of cmp.\nNote: this does not mean a doubling of speed (maybe a slight improvement on average).\n Assuming the compiler has not already worked this out.\n</code></pre>\n<p>But in my opinion makes the code more readable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T15:48:07.493", "Id": "14947", "ParentId": "14937", "Score": "3" } }, { "body": "<p>Your approach is <strong>not</strong> an optimal one.</p>\n\n<p>What you need to do is store the points in a data structure that allows you to flip and count the points without looking at each points independently. Otherwise, it will simply take too long.</p>\n\n<p>I used a tree for each quadrant for this problem, the rest I leave up to you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T15:59:07.060", "Id": "14949", "ParentId": "14937", "Score": "3" } } ]
{ "AcceptedAnswerId": "14947", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T13:36:57.190", "Id": "14937", "Score": "2", "Tags": [ "c++", "interview-questions", "time-limit-exceeded" ], "Title": "Optimization in overcoming TLE in interviewStreet problem" }
14937
<p>I was looking into removing multiple inputs and selects at once using jQuery, but I couldn't find a solution, so I ended up with the following code:</p> <pre><code>$(function() { $('a.add').click(function(evt) { //clone lists //is there any way to simplify this part --begin-- $('#s0 option').clone().appendTo('#s'+obj); $('#i0 option').clone().appendTo('#i'+obj); $('#r0 option').clone().appendTo('#r'+obj); $('#ieu0 option').clone().appendTo('#ieu'+obj); $('#ied0 option').clone().appendTo('#ied'+obj); //--end-- evt.preventDefault(); //prevents scrolling }); //remove inputs/selects $('a.remove').click(function(evt) { //animation is not necessary. How can I simplify this code? --begin-- $('#comp'+x).animate({opacity:"hide"}, "slow").remove(); $('#ppt'+x).animate({opacity:"hide"}, "slow").remove(); $('#ct'+x).animate({opacity:"hide"}, "slow").remove(); $('#p'+x).animate({opacity:"hide"}, "slow").remove(); $('#ipvs'+x).animate({opacity:"hide"}, "slow").remove(); $('#s'+x).remove(); $('#i'+x).remove(); $('#r'+x).remove(); $('#ipvs'+x).remove(); $('#other'+x).remove(); //--end-- } evt.preventDefault(); }); }); </code></pre> <p>How can the sections marked between <code>--begin--</code> and <code>--end--</code> be simplified/improved?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T18:10:37.453", "Id": "24246", "Score": "0", "body": "[`.each()`](http://api.jquery.com/each)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T18:12:35.613", "Id": "24247", "Score": "1", "body": "It would be hard to know how to best do this without seeing the HTML structure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T18:12:44.803", "Id": "24248", "Score": "2", "body": "Just a hint, you can select elements using `,` to separate them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T19:50:39.813", "Id": "24249", "Score": "0", "body": "Check [this fiddle](http://jsfiddle.net/LJTjw/12/), it might help you." } ]
[ { "body": "<p>for the top part you might be able to add some logic to your html.\nit looks when something is clicked you move the options to another element.\nif you just specified in the HTML the source and target elements through a class name like:\n<code>&lt;select class=\"source\" target=\"targetSelector\"...</code>\nand \n<code>&lt;select class=\"target\"...</code></p>\n\n<p>you could use a script like </p>\n\n<pre><code>$('a.add').click(function(){\n $('.source').each(function(){\n var source = $(this);\n var target = $(source.attr('target'));\n target.append(source.find('option'))\n })\n})\n</code></pre>\n\n<p>Not really more simplified but a way to abstract your logic a bit.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T18:27:41.080", "Id": "14939", "ParentId": "14938", "Score": "0" } }, { "body": "<p>I would go with ChrisThompson's method of adding classes and referring to them. \nBut to answer your question straight and simple </p>\n\n<p>the first block can look like </p>\n\n<pre><code>$.each( ['s','i','r','ieu','ied'], function(index,item){\n $('#' + item + '0 option').clone().appendTo('#' + item + obj );\n });\n</code></pre>\n\n<p>However, you did not specify what <code>obj</code> is</p>\n\n<p>The second block can use the same technic to be simplified. </p>\n\n<p>The entire code would look something like this</p>\n\n<pre><code>$(function() {\n $('a.add').click(function(evt) {\n //clone lists\n //is there any way to simplify this part --begin--\n $.each( ['s','i','r','ieu','ied'], function(index,item){\n $('#' + item + '0 option').clons().appendTo('#' + item + obj );\n });\n //--end--\n evt.preventDefault(); //prevents scrolling\n });\n\n //remove inputs/selects\n $('a.remove').click(function(evt) {\n //animation is not necessary. How can I simplify this code? --begin--\n $.each( ['comp','ppt','ct','p','ipvs'], function(index,item){ $('#' + item + x).animate({opacity:\"hide\"} ,\"slow\").remove();});\n $.each(['s','i','r','other'], function(index,item){ $('#'+item+x).remove()});\n //--end--\n evt.preventDefault();\n } \n });\n});\n</code></pre>\n\n<p>However, it seems to me you are using too complex HTML structure. \nyou need to </p>\n\n<ol>\n<li><p>Stop using IDs, and start using classes for elements that have things in common\nFor example : </p>\n\n<p></p></li>\n<li><p>Instead of cloning each item, you can wrap all of the in a DIV and simple use <code>html()</code> to clone the entire HTML. When you inject the HTML to some other div, give the new wrapper div an ID. </p></li>\n</ol>\n\n<p>For example </p>\n\n<pre><code>$(\".my-form\").append($(\"&lt;div/&gt;\").addClass(\".object-item\").attr(\"id\",\"newObject\" + $(\".my-form .object-item\").length ).html( $(\".items-to-clone-wrapper\").html() );\n</code></pre>\n\n<p>You then have a unique identifier for every element on the page. for example <code>$(\"#newObject1 .s\")</code> instead of <code>$(\"#s1\")</code>. </p>\n\n<p>Here is a <a href=\"http://jsfiddle.net/LJTjw/12/\" rel=\"nofollow\">fiddle I made</a> on the assumptions I made about your code. I hope it will be of use to you. please let me know if there's something I can do. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T14:02:39.630", "Id": "24257", "Score": "0", "body": "one though - I wouldn't necessarily use jQuery's each() function, as it tends to be slower (sometimes much slower) than JavaScript's native for statement" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T15:08:30.667", "Id": "24259", "Score": "0", "body": "ok. then simply replace the each with a native for loop. - the answer still stands, it will still make the code simpler." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T20:44:07.043", "Id": "24290", "Score": "0", "body": "yes, I agree... I've also removed my answer, seeing you already have it in yours now :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T16:49:46.340", "Id": "24583", "Score": "0", "body": "Exactly what I was looking for, thank you so much to everyone!\nI did put the cloned items inside a div tag as suggested, and to remove the whole thing I just used: \n<code>\n $('a.remove').click(function(evt) {\n if(i > 0) { \n $('#clonedItems'+i).remove();\n i-- ;\n }\n evt.preventDefault();\n });\n</code>\n\nNot sure how to use the code block... I'm a noob here. Anyways, thank you all!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T18:30:06.790", "Id": "14940", "ParentId": "14938", "Score": "3" } } ]
{ "AcceptedAnswerId": "14940", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-21T18:09:15.130", "Id": "14938", "Score": "2", "Tags": [ "javascript", "jquery", "html", "animation", "dom" ], "Title": "An \"Add\" button that clones an item, and a \"Remove\" button that fades and removes an item" }
14938
<p>I have a little chain of JQuery promises. My problem is at each stage I want to notify my progress to the user, keep them in the loop (Perhaps using .notify somehow?)</p> <p>What I've eneded up with is this bizarre mess of callbacks and promises. It works but I'm quite certain there is a neater, more logical way to do this.</p> <p>both <code>fetchSomeData()</code> and <code>Parser()</code> return a promise</p> <pre><code> var parseData = function(json) { showMessage("Updating your data..."); return new Parser(json); }; var onParseDone = function() { hideMessage(); updateView(); }; showMessage("Fetching a bit of data..."); fetchSomeData().pipe(parseData).done(onParseDone); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T13:23:39.647", "Id": "24251", "Score": "2", "body": "Am curious, why do you feel the code you posted is a mess? As in, what sort of pseudo code would look pretty? Maybe once I can see where the mess is, I can attempt to clean it up :) If possible, update the question and post a comment stating the same." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T13:25:38.577", "Id": "24252", "Score": "0", "body": "I agree with @AmithGeorge, the code above doesnt look that messy to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T13:28:14.980", "Id": "24253", "Score": "0", "body": "@AmithGeorge it feels like its a bit of strange combination of promises and functions. Don't get me wrong, if general consensus is its good than I'm happy with that! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T13:31:13.943", "Id": "24255", "Score": "1", "body": "@ChrimsonChin: You don't need to re-post, moderators can move questions - just flag it for mod attention" } ]
[ { "body": "<p>Surely this is possible. Only the <code>fetch</code> and <code>parse</code> functions would need to call <a href=\"http://api.jquery.com/deferred.notify/\" rel=\"nofollow\"><code>notify</code></a> with the respective message on the Deferreds they return. The code then could look like this:</p>\n\n<pre><code>fetchSomeData().pipe(parser).progress(showMessage).done(hideMessage, updateView);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T13:29:43.100", "Id": "14943", "ParentId": "14942", "Score": "2" } } ]
{ "AcceptedAnswerId": "14943", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T13:16:27.740", "Id": "14942", "Score": "2", "Tags": [ "javascript", "jquery", "promise" ], "Title": "Improving a JQuery Promise \"Chain\"" }
14942
<p>I have seven checkboxes on a data maintenance WinForm, which indicate the days of the week that are "valid" for a particular operation to be performed. These "map" to a list of DayOfWeek enum values on the backing domain object; if the value is present in the list, the box should be checked, otherwise not. Any combination of boxes can be checked. In the "bind" method that sets the UI controls to the proper values of the domain object, here's how those checkboxes are set:</p> <pre><code>chkValidDayMon.Checked = myModel.ValidDaysOfWeek.Contains(DayOfWeek.Monday); chkValidDayTue.Checked = myModel.ValidDaysOfWeek.Contains(DayOfWeek.Tuesday); chkValidDayWed.Checked = myModel.ValidDaysOfWeek.Contains(DayOfWeek.Wednesday); chkValidDayThu.Checked = myModel.ValidDaysOfWeek.Contains(DayOfWeek.Thursday); chkValidDayFri.Checked = myModel.ValidDaysOfWeek.Contains(DayOfWeek.Friday); chkValidDaySat.Checked = myModel.ValidDaysOfWeek.Contains(DayOfWeek.Saturday); chkValidDaySun.Checked = myModel.ValidDaysOfWeek.Contains(DayOfWeek.Sunday); </code></pre> <p>The code to read the UI controls' state back out to the domain object is similar; if the box is checked, add the corresponding value to a "clean" (initially empty) list and assign it to the object. </p> <p>This smells. I was thinking of adding a Dictionary containing the checkboxes and keyed to their corresponding DayOfWeek. But, that sounds like a bit much as well (it certainly wouldn't save many LoC). Any other suggestions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:37:29.290", "Id": "24267", "Score": "0", "body": "@Leonid - While in general I agree with you, there are exactly seven days in a Gregorian week (and in most other Abrahamic culture calendars), so until the entire world adopts the Javanese five-day week I don't foresee this code having to change (not in a way that having a Dictionary would make more difficult, anyway). I could use Linq to create the Dictionary based on the controls, maybe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T18:03:23.257", "Id": "24277", "Score": "0", "body": "If you do not want to hide information, then you should go with one of the two approaches that you suggested yourself. Either way you will have to write about 7 lines of code. The dictionary approach is probably better for it cannot be re-factored further. Once the code works, you pretty much know that it will not break. So what that it smells a bit? Seven controls do not justify going overboard, so KISS. The only danger really is programmers who will want to re-factor the working code and may introduce bugs. This is why dictionary is a decent solution. Speed is not an issue at all here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T19:13:05.470", "Id": "24280", "Score": "0", "body": "Well, if you make your comment an answer I'll accept it, because the solution I arrived at was to give the checkboxes Tag values for the integer representations of each DayOfWeek, then slurp the Controls (which were already in a GroupBox) into a Dictionary keyed by the Tag." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T20:03:33.670", "Id": "24284", "Score": "0", "body": "the `Tag` is of the type `object`. Why not stick an enum value rather than an integer in there?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T20:27:58.330", "Id": "24287", "Score": "0", "body": "Because the designer assumes anything you enter into the Tag field is a string, so it actually doesn't really matter either way; I still have to parse it. I could use \"Sunday\", \"Monday\" etc as well, it works either way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T01:13:33.893", "Id": "24299", "Score": "0", "body": "If your constructor calls `this.InitializeComponent` followed by your own `this.InitializeComponentCustom`, then you could set the tags right in that method. It is more typing, but it is more explicit - less surprising." } ]
[ { "body": "<p>I'd create an extension method that calculates the day by the name of the checkbox.</p>\n\n<p>I'm using dynamic because I don't know the name of your domain class, just replace it with your name.</p>\n\n<p>Also note, I'm using the web version of CheckBox, substitute ID with whatever version you are using.</p>\n\n<p>Here is the class for the extension:</p>\n\n<pre><code>public static class CheckboxExtensions\n{\n public static void DetermineStateFromModel(this CheckBox me, dynamic myModel)\n {\n if (!me.ID.Contains(\"chkValidDay\"))\n {\n // Could throw an exception if required.\n return;\n }\n\n var dayOfWeek = DayOfWeekFromString(me.ID.Replace(\"chkValidDay\", string.Empty));\n\n me.Checked = myModel.ValidDaysOfWeek.Contains(dayOfWeek);\n }\n\n private static DayOfWeek DayOfWeekFromString(string dayOfWeek)\n {\n switch (dayOfWeek)\n {\n case \"Mon\":\n return DayOfWeek.Monday;\n case \"Tue\":\n return DayOfWeek.Tuesday;\n // ...\n default:\n throw new ApplicationException(\"Invalid dayOfWeek specified.\");\n\n }\n }\n}\n</code></pre>\n\n<p>Then your calls would be</p>\n\n<pre><code>chkValidDayMon.DetermineStateFromModel(myModel);\nchkValidDayTues.DetermineStateFromModel(myModel);\n...\n</code></pre>\n\n<p>Another thing you might look into is to put the CheckBox objects into a list, then you could just iterate it:</p>\n\n<pre><code>dayCheckBoxList.ForEach(checkBox =&gt; checkBox.DetermineStateFromModel(myModel));\n</code></pre>\n\n<p>Another note, Hungarian casing on variables is not really accepted anymore. It clutters up the code, and there are too many variable types to abbreviate them all to 3 letters. <a href=\"https://stackoverflow.com/questions/309205/are-variable-prefixes-hungarian-notation-really-necessary-anymore\">Read this</a>. A better naming convention would be mondayIsValidCheckBox. You would have to modify my extension method to use this new convention.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:20:45.213", "Id": "24263", "Score": "0", "body": "String parsing on the name of a control? That smells worse than individual binding/unbinding." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:27:30.680", "Id": "24265", "Score": "0", "body": "I agree that Hungarian casing is bad. I do it on UI controls only, mainly out of old habit (and because changing the type of a control laid out in the Designer requires either ripping it out and replacing it, or touching so much code that changing its name becomes rather trivial)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T17:47:12.323", "Id": "24274", "Score": "1", "body": "String parsing on the name of a control falls into a paradigm call Convention over Configuration: http://en.wikipedia.org/wiki/Convention_over_configuration which I have been using more and more." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T17:51:39.210", "Id": "24275", "Score": "0", "body": "... which I generally criticize as information-hiding; you're basically \"tightly coupling\" conventions to behavior, creating a hidden reason why things need to be exactly the way they are, setting yourself up for failure when someone decides that the convention should change. It has value, but I generally prefer that the convention be used to generate initial configuration of behavior rather than define behavior directly and dynamically." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T17:58:57.780", "Id": "24276", "Score": "1", "body": "Its not hiding as long as it is documented and followed. You also have checks in the methods to make sure the convention is being followed, so if somebody doesn't follow it, an exception is thrown." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T17:32:06.523", "Id": "25738", "Score": "2", "body": "I think it would be better to use Dictionary<string, DayOfWeek> rather than that big case tree. I have not used C# for some time so I am not sure if the hashmap is called Dictionary in .NET :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-21T18:23:53.367", "Id": "25742", "Score": "0", "body": "I agree @Aleksandar" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:18:41.427", "Id": "14950", "ParentId": "14948", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T15:55:50.310", "Id": "14948", "Score": "5", "Tags": [ "c#", "winforms", "gui" ], "Title": "Ideas for reducing repetition in control binding" }
14948
<p>This is a pet project :)</p> <p>I have hundreds of playlist files .m3u whose many entries have a wrong path. I'd like to fix them programmatically. Suppose one of my .m3U contains the following entry:</p> <pre><code>z:\wrong-folder\Michael Jackson - Thriller.mp3 </code></pre> <p>The file is stored in:</p> <pre><code>G:\my-collection-of-mp3\any-folder\Michael Jackson - Thriller.mp3 </code></pre> <p>The goal is to update the wrong path with the right one :)</p> <p>I have to create a collection of all my mp3 (around 6000 files) and their path. As I said, I have hundreds of .mu3 ; each .m3u has 15-20 entries. I have to check each entry against my 6000-entries-collection until the name matches. Well it is a plethora of loops :)</p> <p>To ease the process I would create an ordered dictionary of dictionary whose the key would be the first letter of the name i.e. "M" (for Michael Jackson - Thriller.mp3) and the sub dictionary would be:</p> <pre><code>- key: Michael Jackson - Thriller.mp3 - value: G:\my-collection-of-mp3\any-folder\Michael Jackson - Thriller.mp3 </code></pre> <p>Doing so I would only to iterate over a subset of the collection (looking up for the first letter of the name) instead of iterating over the whole non ordered collection.</p> <pre><code>A / Albert Jones - Song 1.mp3 -&gt; G:\my-collection-of-mp3\any-folder\Albert Jones - Song 1.mp3 M / Madonna - Song 1.mp3 -&gt; D:\somewhere-else\Madonna - Song 1.mp3 M / Michael Jackson - Thriller -&gt; G:\my-collection-of-mp3\any-folder\Michael Jackson - Thriller.mp3 </code></pre> <p>Do you think it is ok? What else would you recommend?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:27:17.843", "Id": "24386", "Score": "0", "body": "Why do you think you need to break up a dictionary of just 6000 files? What makes you think you can repeat a key (e.g. M) in a dictionary? What have you tried? SO is for specific programming questions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:28:53.963", "Id": "24387", "Score": "0", "body": "It is a dictionary of dictionary" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:31:32.223", "Id": "24388", "Score": "0", "body": "Still why do you think you need to break up 6000? Hash is Int32. Did you try a straight single dictionary?" } ]
[ { "body": "<p>If you are particularly interested in doing substring look-ups, you could look into the <a href=\"http://en.wikipedia.org/wiki/Trie\" rel=\"nofollow\">Trie</a> data structure. You will be stuck writing your own, however, as there is no implementation I know of in the BCL.</p>\n\n<p>Alternatively, if you just want to put something together quick, you could just use a normal, single-level-deep dictionary keyed by file name. If you build your dictionary for existing MP3s first using an actual System.Collections.Hashtable or (preferably) <a href=\"http://msdn.microsoft.com/en-us/library/xfhwa508.aspx\" rel=\"nofollow\">System.Collections.Generic.Dictionary&lt;TKey,TValue&gt;</a>, the key lookups will be constant-time.</p>\n\n<p>The only loops you will need are the initial loop to build the correct file path dictionary, then the loops over .m3u files with sub-loops over their referenced files. Retrieving the correct mp3 reference for each file in a m3u is just <code>value = dictionary [key]</code> or <code>dictionary.TryGetValue (key, out value)</code>. The lookups themselves are not loops - rather, they generate hash codes for the keys which ultimately translate to array indexes in the underlying data structure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T18:30:04.203", "Id": "24279", "Score": "0", "body": "By the way, List<T> has a BinarySearch() ; do you think it is worth taking a look at it based on my situation?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T17:54:18.557", "Id": "24350", "Score": "1", "body": "The BinarySearch function would work as well if you make sure the list is kept sorted. Assuming the function to retrieve your list of correct file paths is already sorted, it is possible that this ends up performing better. I couldn't tell you for sure if the overhead of hash generation would out-weigh the logarithmic-time binary search for 6000 elements, though. Since this is a personal project, it may be interesting to do it both ways and compare, since neither should take all that much time to implement." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T17:43:50.923", "Id": "14953", "ParentId": "14951", "Score": "4" } }, { "body": "<p>If I were you I'd do two passes (error checking, case-invariance and recursion omitted for clarity).</p>\n\n<p>Pass1:</p>\n\n<pre><code> Dictionary&lt;string, string&gt; paths = new Dictionary...\n foreach(var filepath in files(recursively))\n paths.Add(new System.IO.FileInfo(file).FileName, filepath);\n</code></pre>\n\n<p>Pass2:</p>\n\n<pre><code> foreach(string path in m3ulist)\n if(!System.IO.File.Exists(path))\n {\n string key = new System.IO.FileInfo(path);\n if(paths.ContainsKey(key))\n MessageBox.Show(string.Format(\"replacing path {0} with {1}\", key, paths[key]));\n else\n MessageBox.Show(string.Format(\"could not find mp3 path\", key));\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:22:14.960", "Id": "24391", "Score": "1", "body": "I guess the line in the second pass should be `string key = new System.IO.FileInfo(path).FileName;`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:33:02.193", "Id": "24392", "Score": "0", "body": "The potential problem here is duplicate FileName. But still +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:51:04.123", "Id": "24393", "Score": "0", "body": "This is what I first came up with. Isn't it possible to improve performance?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T17:31:41.010", "Id": "24394", "Score": "0", "body": "@roland So you had the same code and came to the conclusion paths.ContainsKey(key) was the bottle neck? How did you determine that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T18:19:33.623", "Id": "24395", "Score": "0", "body": "No particular assumption. Only thought that other solutions would have brought other benefits" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T18:39:07.453", "Id": "24396", "Score": "0", "body": "Since I posted my question, I reading a lot about hash (see your previous comment) and list. It seems lookup are not loops, as they are has based and built to be performant." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:16:06.280", "Id": "15031", "ParentId": "14951", "Score": "2" } } ]
{ "AcceptedAnswerId": "14953", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T16:19:17.943", "Id": "14951", "Score": "3", "Tags": [ "c#", ".net", "collections", "hash-map" ], "Title": "Iterating thousands of times over large collections: advices" }
14951
<p>So I had this idea; what if I could decorate my Enum values with an attribute that cross-references a "default" value of another Enum that should be used when a variable of the current Enum type has this value?</p> <p>The desired usage would look like:</p> <pre><code>public enum MyEnum { Value1, Value2, Value3, } public enum ControllingEnum { [LinkedValue(MyEnum.Value1)] ControllingValue1, [LinkedValue(MyEnum.Value2)] ControllingValue2, [LinkedValue(MyEnum.Value1)] ControllingValue3, [LinkedValue(MyEnum.Value3)] ControllingValue4, } ... var relatedValue = ControllingEnum.ControllingValue4.GetLinkedValue&lt;MyEnum&gt;(); </code></pre> <p>I came up with the following:</p> <pre><code>public class LinkedValueAttribute:Attribute { public LinkedValueAttribute(object value) { TypeOfValue = value.GetType(); Value = (Enum)value; } public Type TypeOfValue { get; private set; } public Enum Value { get; private set; } } public static class AttributeHelper { public static T GetLinkedValue&lt;T&gt;(this Enum enumValue) where T:struct { if (!typeof(Enum).IsAssignableFrom(typeof(T))) throw new InvalidOperationException("Generic type must be a System.Enum"); //Look for LinkedValueAttributes on the enum value LinkedValueAttribute[] attr = enumValue.GetType().GetField(enumValue.ToString()) .GetCustomAttributes(typeof(LinkedValueAttribute), false) .OfType&lt;LinkedValueAttribute&gt;() .Where(a=&gt;a.TypeOfValue == typeof(T)) .ToArray(); if (attr.Length &gt; 0) // a DescriptionAttribute exists; use it return (T)(object)attr[0].Value; } } </code></pre> <p>It does the job, but the boxing and unboxing are generally to be avoided. The question is, how?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T19:35:49.797", "Id": "24281", "Score": "0", "body": "Your `GetLinkedValue` method can't compile - not all code paths return a value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T19:43:38.520", "Id": "24282", "Score": "0", "body": "My guess is a last line needs to be added to the method of the nature of `throw new InvalidOperationException(\"No cross-reference LinkedValueAttribute was found for the given value\");` or even `return (T)(object)enumValue;` (which won't be all that useful)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T20:29:26.287", "Id": "24288", "Score": "0", "body": "@JesseC.Slicer - You are correct; I caught that after posting this, and I just throw an exception." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T21:31:56.290", "Id": "24295", "Score": "0", "body": "Oh, hey! I just remembered this and it could be helpful with what your enum work. Jon Skeet has a nifty gizmo that can constrain generics to specific enums: http://msmvps.com/blogs/jon_skeet/archive/2009/09/10/generic-constraints-for-enums-and-delegates.aspx" } ]
[ { "body": "<p>I would personally write the attribute class as such:</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.Field)]\npublic sealed class LinkedValueAttribute : Attribute\n{\n private readonly Type typeOfValue;\n\n private readonly Enum value;\n\n public LinkedValueAttribute(object value)\n {\n this.typeOfValue = value.GetType();\n this.value = (Enum)value;\n }\n\n public Type TypeOfValue\n {\n get\n {\n return this.typeOfValue;\n }\n }\n\n public Enum Value\n {\n get\n {\n return this.value;\n }\n }\n}\n</code></pre>\n\n<p>Reasons:</p>\n\n<p>1: the <code>AttributeUsage</code> attribute limits it to going on fields, which, in this case, is the same as an <code>enum</code> member. Without it, the attribute can go onto anything anywhere, and while harmless from the point of the extension method, it is just a bit weird. Signify intent and don't let your users shoot themselves in the foot if you have the means.</p>\n\n<p>2: <code>sealed</code> class. If you see no more functionality being added by subclasses in the future, seal it up. Compiler and JIT can do some optimizations knowing there are no descendants.</p>\n\n<p>3: <code>readonly</code> fields instead of automatically implemented properties. First, signifies intent. Those fields will not be modified after the constructor assigns them. Don't let any future methods in that class noodle them unknowingly. Second, the compiler and JIT may do some optimizations based on knowing the fields will be unmolested after construction.</p>\n\n<p>Now, in your extension method, since you already use LINQ, there's a couple more extensions you can use:</p>\n\n<pre><code>public static class AttributeHelper\n{\n public static T GetLinkedValue&lt;T&gt;(this Enum enumValue) where T : struct\n {\n if (!typeof(Enum).IsAssignableFrom(typeof(T)))\n {\n throw new InvalidOperationException(\"Generic type must be a System.Enum\");\n }\n\n // Look for LinkedValueAttributes on the enum value.\n var attributes = enumValue.GetType()\n .GetField(enumValue.ToString())\n .GetCustomAttributes(typeof(LinkedValueAttribute), false)\n .OfType&lt;LinkedValueAttribute&gt;()\n .Where(a =&gt; a.TypeOfValue == typeof(T));\n\n // A DescriptionAttribute exists; use it.\n if (attributes.Any())\n {\n return (T)(object)attributes.Single().Value;\n }\n\n throw new InvalidOperationException(\"No cross-reference LinkedValueAttribute was found for the given value\");\n }\n}\n</code></pre>\n\n<p>1: Removed <code>.ToArray()</code> since the LINQ extensions I use don't need an array to work on.</p>\n\n<p>2: Changed <code>attributes.Length &gt; 0</code> to <code>attributes.Any()</code>. This is primarily to signify intent. You want to know if there are any attributes returned, not particularly interested in the length of the array (that's no longer needed).</p>\n\n<p>3: Changed <code>attributes[0].Value</code> to <code>attributes.Single().Value</code>. Because the default for <code>AttributeUsage</code> is <code>Multiple = false</code> and that's a good thing for the semantics of how it's used - we'll only get either zero or one back.</p>\n\n<p>4: Added the exception throw I mentioned in my comment.</p>\n\n<p>Now, as for the box/unbox... I'm still noodling on that one. I'll update this if/when I get something.</p>\n\n<p><strong>UPDATE</strong> I'm still not finding any way around the box/unbox issue. Reflection tricks and casting sorcery is still requiring the <code>object</code> bit.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T20:30:52.737", "Id": "24289", "Score": "0", "body": "I will make the suggested improvements to the extension method. I'm not a huge proponent of using readonly behind a get-only property (especially if all data members are readonly; why not just expose the fields?), but it's definitely something that could be done. One thing: if there's more than one attribute for a type, Single will panic and throw out, but I can handle that situation easily by just returning the first one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T21:06:41.470", "Id": "24291", "Score": "0", "body": "But there won't be more than just one attribute for the *individual field*. Zero or one only. So `Single()` will have no opportunity to panic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T21:07:44.650", "Id": "24292", "Score": "0", "body": "... Unless I *want* more than one attribute for the individual field and set the AllowMultiple property to True on the AttributeUsage tag. I want to be able to specify multiple links to enum values of other types; unfortunately it's impossible at present to limit those to one per other linked type (generic attributes FTW)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T21:14:52.390", "Id": "24293", "Score": "0", "body": "I see your point. But that would require a pretty big breaking change in the extension method as it is (i.e. returning `IEnumerable<T>` instead of `T`) and you could make the move away from `Single()` at that point. **Scratch the above. Not sure how the extension method would work for multiple**" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T21:27:20.170", "Id": "24294", "Score": "0", "body": "We're searching for an attribute with a given TypeOfValue. There should be a maximum of one of these on any given enum value; however I can't enforce that. What I can do is ignore additional attributes with a value of the same type by using First(). That was my point, way back when." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T19:58:37.660", "Id": "14955", "ParentId": "14954", "Score": "2" } } ]
{ "AcceptedAnswerId": "14955", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T19:11:06.910", "Id": "14954", "Score": "2", "Tags": [ "c#", "optimization" ], "Title": "\"Linked\" Enum value attribute" }
14954
<p>I have a simple class inheritance in JS:</p> <pre><code>var Class = function(){}; Class.extend = function(){ var Extended = function(constructor){ function extend_obj(destination, source) { for(var property in source){ if(typeof source[property] === "object" &amp;&amp; source[property] !== null &amp;&amp; destination[property]){ extend_obj(destination[property], source[property]); }else{ destination[property] = source[property]; } } }; extend_obj(Extended.prototype, constructor); this.constructor.init(); }; Extended.init = function(){}; for(var key in this.prototype){ Extended.prototype[key] = this.prototype[key]; } Extended.prototype.constructor = Extended; for (var key in this) { Extended[key] = this[key]; }; return Extended; }; </code></pre> <p>Which allow me to do so:</p> <pre><code>var SubClass = Class.extend(); SubClass.static_property = "a static property"; SubClass.static_method = function(){ return "a static method"; }; SubClass.prototype.a_new_property = "something new"; //instance method var instance = new SubClass({ name: "custom name" }); SubClass.init = function(){ //custom constructor }; this.constructor.static_method_or_property //call instance method </code></pre> <p>I need:</p> <ul> <li>multiple inheritance</li> <li>the possibility to use module pattern</li> </ul> <p>There's a cleaner/better/faster way to do that?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T18:43:57.157", "Id": "24728", "Score": "0", "body": "Try http://hay.github.com/stapes/" } ]
[ { "body": "<p>First of all, it seems like you're reinventing the wheel here. You didn't provide any context for what this is for so I'll try to cover all bases.</p>\n\n<p>If you are using this as part of a bigger project, I'd recommend abandoning this approach and picking up something like <a href=\"http://prototypejs.org/learn/class-inheritance\" rel=\"nofollow\">Prototype.js</a> or maybe Ember.js if you're ambitious. Alternatively, take a look at how <a href=\"http://coffeescript.org/#classes\" rel=\"nofollow\">CoffeeScript does it</a>. CoffeeScript's underlying JS is pretty messy but it's significantly simpler than yours AND supports inheritance.</p>\n\n<p>If this is just an educational exercise, I can point out a few problems with your code that I see.</p>\n\n<ol>\n<li><code>extend_obj(Extended.prototype, constructor);</code>\n<ul>\n<li>This seems to be copying the instance's properties onto the class prototype. This doesn't make much sense as the instance's properties should be separate.</li>\n</ul></li>\n<li><code>var instance = new SubClass({ name: \"custom name\" })</code>\n<ul>\n<li>This actually instantiates an <code>Extended</code> (aka <code>SubClass</code>) object with no instance properties and modifies the <code>Extended</code> prototype to have a <code>name</code> property of \"custom name\". This is very strange behavior.</li>\n</ul></li>\n</ol>\n\n<p>In general, when trying to emulate Classes in JS, the prototype is where instance methods go or, possibly, default values for properties. However, an instance (created with <code>new</code>) should have no effect on it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T09:06:11.850", "Id": "24662", "Score": "0", "body": "I'd also think you shouldn't force classical OOP theme's and instead use a more functional programming approach." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T07:23:00.743", "Id": "15205", "ParentId": "14956", "Score": "4" } }, { "body": "<p>JavaScript's prototypal inheritance has some advantages over classical inheritance. As mentioned above, if you really need to use classical inheritance, its far better to go with the libraries as suggested, or even change language (such as to coffeescript or even Dart). </p>\n\n<p>I would highly recommend you read up a little on prototypal inheritance, it may well be that you can solve your needs with it. </p>\n\n<p>Try here: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain\" rel=\"nofollow\">Mozilla Developer Network - Prototypal Inheritance</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-11T07:59:07.443", "Id": "73302", "ParentId": "14956", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T20:21:21.333", "Id": "14956", "Score": "5", "Tags": [ "javascript", "classes", "prototypal-class-design" ], "Title": "Javascript inheritance" }
14956
<p>Below is the code for a compiler I created for a language called Jack. This compiler is one of the projects for the book "The Elements of Computing Systems" (http://www1.idc.ac.il/tecs/plan.html) where you build an entire computing system from the ground up. Anyway, what this compiler does is translate code from a high level language (called Jack, it looks similar to Java) and then translates it to intermediate code while also creating a parse tree from it. It takes in a list of tokens (the tokenizing is handled by another component whose code I haven't included) as input. </p> <p>Can someone take a look at this code and help me improve it? I'm done with the project but I want to make a similar compiler for another language I'm gonna make for this Hack platform. </p> <p>(Note: I took out some code because it went over the character limit)</p> <pre><code>class CompilationEngine { private $tokens; // Token list to operate on private $symbol_table; // Symbol table that stores all identifiers private $registry; // Hash table to store any additional information private $xml; // Contains the XML code in a SimpleXMLElement object private $vm; // Contains the VM code in a VMWriter object private $write_xml; // Boolean flag that determines whether to output XML code private $write_vm; // Boolean flag that determines whether to output VM code private $current_xml; // Points to the current XML child object private $parent_xml; // Array of parent XML objects // Initializes the CompilationEngine object with a list of tokens public function __construct($tokens) { $this-&gt;tokens = $tokens; $this-&gt;symbol_table = new SymbolTable(); $this-&gt;registry = array(); $this-&gt;xml = new SimpleXMLElement('&lt;class&gt;&lt;/class&gt;'); $this-&gt;vm = new VMWriter(); $this-&gt;current_xml = $this-&gt;xml[0]; $this-&gt;parent_xml = array(); $this-&gt;write_xml = false; $this-&gt;write_vm = false; // This is gonna be really hackish, but it's the only way I could think // of to implement proper method calling within the same class $this-&gt;registry['methods'] = array(); $length = count($this-&gt;tokens); for ($c = 0; $c &lt; $length; $c++) { if ($this-&gt;tokens[$c][TOKEN_TEXT] == 'method' &amp;&amp; ($c + 2) &lt; $length) $this-&gt;registry['methods'][] = $this-&gt;tokens[$c+2][TOKEN_TEXT]; } } // Turns XML code writing on and off public function setWriteXML($flag) { $this-&gt;write_xml = $flag; } // Turns VM code writing on and off public function setWriteVM($flag) { $this-&gt;write_vm = $flag; } // Creates a child XML node of the current node and shifts focus to it public function XML_enterChildNode($child_node_name) { if (!$this-&gt;write_xml) return; $this-&gt;parent_xml[] = $this-&gt;current_xml; $this-&gt;current_xml = $this-&gt;current_xml-&gt;addChild($child_node_name); } // Shifts focus back to the parent node of the current node public function XML_returnToParent() { if (!$this-&gt;write_xml) return; if (empty($this-&gt;parent_xml)) return; $this-&gt;current_xml = array_pop($this-&gt;parent_xml); } // Checks a condition and triggers a warning if it's false private function check($condition, $message) { if (!$condition) trigger_error(sprintf('CompilationEngine: %s', $message), E_USER_WARNING); } // Writes primitive token data to the XML output private function writeTokenData($tokens) { if (!$this-&gt;write_xml) return; if (!is_object($this-&gt;current_xml)) return; $tokentype_to_string = array( TOKENTYPE_KEYWORD =&gt; 'keyword', TOKENTYPE_SYMBOL =&gt; 'symbol', TOKENTYPE_IDENTIFIER =&gt; 'identifier', TOKENTYPE_INT_CONST =&gt; 'integerConstant', TOKENTYPE_STRING_CONST =&gt; 'stringConstant' ); foreach ($tokens as $token) { if (!array_key_exists($token[TOKEN_TYPE], $tokentype_to_string)) trigger_error(sprintf('Unknown token type %d for token text "%s"', $token[TOKEN_TYPE], $token[TOKEN_TEXT]), E_USER_WARNING); $this-&gt;current_xml-&gt;addChild($tokentype_to_string[$token[TOKEN_TYPE]], htmlentities(htmlentities($token[TOKEN_TEXT], ENT_QUOTES))); } } // This function will write the function declaration private function VM_writeFunctionDeclaration($name, $type) { $this-&gt;vm-&gt;writeFunction($name, $this-&gt;symbol_table-&gt;getIndex(KIND_VAR)); // If function type is constructor, then allocate memory for it and set "this" to assigned address if ($type == 'constructor') { $this-&gt;vm-&gt;writePush(SEGMENT_CONSTANT, $this-&gt;symbol_table-&gt;getIndex(KIND_FIELD)); $this-&gt;vm-&gt;writeCall('Memory.alloc', 1); $this-&gt;vm-&gt;writePop(SEGMENT_POINTER, 0); } // If function type is method, then set "this" to value of first argument else if ($type == 'method') { $this-&gt;vm-&gt;writePush(SEGMENT_ARG, 0); $this-&gt;vm-&gt;writePop(SEGMENT_POINTER, 0); } } // Outputs the resulting XML or VM code, or both if specified public function compile() { $this-&gt;compileClass($this-&gt;tokens); if ($this-&gt;write_xml &amp;&amp; !$this-&gt;write_vm) return $this-&gt;xml-&gt;asXML(); else if ($this-&gt;write_vm &amp;&amp; !$this-&gt;write_xml) return implode("\n", $this-&gt;vm-&gt;getCode()); else if ($this-&gt;write_xml &amp;&amp; $this-&gt;write_vm) return array( 'xml' =&gt; $this-&gt;xml-&gt;asXML(), 'vm' =&gt; implode("\n", $this-&gt;vm_-&gt;getCode()) ); return null; } // Compiles a complete class -- this method should be called first private function compileClass($tokens) { $this-&gt;check(JackTokenizer::isKeyword($tokens[0], 'class'), 'class (keyword) is incorrect'); $this-&gt;check(JackTokenizer::isIdentifier($tokens[1]), sprintf('className "%s" is not a valid identifier', $tokens[1][TOKEN_TEXT])); $this-&gt;check(JackTokenizer::isSymbol($tokens[2], '{'), 'missing { symbol for class declaration'); $this-&gt;writeTokenData(array_slice($tokens, 0, 3)); $this-&gt;registry['className'] = $tokens[1][TOKEN_TEXT]; $position = 3; $length = count($tokens); while ($position &lt; $length) { $token_args = array_slice($tokens, $position); if (JackTokenizer::isKeyword($tokens[$position], array('field', 'static'))) { $vardec_length = $this-&gt;compileClassVarDec($token_args); $position += $vardec_length; } else if (JackTokenizer::isKeyword($tokens[$position], array('constructor', 'function', 'method'))) { $subroutine_length = $this-&gt;compileSubroutine($token_args); $position += $subroutine_length; } else { break; } } $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], '}'), 'missing } symbol for class declaration'); $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; return $position; } // Compiles a class static/field variable declaration private function compileClassVarDec($tokens) { $this-&gt;check(JackTokenizer::isKeyword($tokens[0], array('static', 'field')), 'Class variable declarations must use static or field keyword'); $this-&gt;check(JackTokenizer::isType($tokens[1]), 'Type in class variable declaration is not a valid type'); $this-&gt;XML_enterChildNode('classVarDec'); $length = count($tokens); $position = 2; $comma_needed = false; for ($c = $position; $c &lt; $length &amp;&amp; $tokens[$c][TOKEN_TEXT] != ';'; $c++) { if ($comma_needed &amp;&amp; JackTokenizer::isSymbol($tokens[$c], ',')) { $comma_needed = false; $position++; } else if (!$comma_needed &amp;&amp; JackTokenizer::isIdentifier($tokens[$c])) { $comma_needed = true; $position++; // Add class variables (static and field) to the symbol table $this-&gt;symbol_table-&gt;define($tokens[$c][TOKEN_TEXT], $tokens[1][TOKEN_TEXT], $tokens[0][TOKEN_TEXT] == 'static' ? KIND_STATIC : KIND_FIELD); } else { break; } } $this-&gt;check($comma_needed, 'Trailing comma after class variable declaration'); $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], ';'), 'Class variable declaration must end with a semicolon'); $position += 1; $this-&gt;writeTokenData(array_slice($tokens, 0, $position)); $this-&gt;XML_returnToParent(); return $position; } // Compiles a complete method private function compileSubroutine($tokens) { $this-&gt;check(JackTokenizer::isKeyword($tokens[0], array('constructor', 'function', 'method')), sprintf('Subroutine declaration "%s" is incorrect, must be either constructor, function or method', $tokens[0][TOKEN_TEXT])); $this-&gt;check(JackTokenizer::isTypeOrVoid($tokens[1]), 'Class variable type must be a valid primitive type, void or identifier of a class'); $this-&gt;check(JackTokenizer::isIdentifier($tokens[2]), sprintf('%s is not a valid identifier for subroutine method', $tokens[2][TOKEN_TYPE])); $this-&gt;check(JackTokenizer::isSymbol($tokens[3], '('), 'Missing ( symbol for subroutine declaration'); // $this-&gt;XML_enterChildNode('subroutineDec'); $this-&gt;writeTokenData(array_slice($tokens, 0, 4)); $position = 4; $this-&gt;symbol_table-&gt;resetSubroutineTable(); // Because this = arg[0], then arg[1] = arg[0], arg[2] = arg[1], ... (for methods) // So all indexes for arguments now need to be shifted up by one if ($tokens[0][TOKEN_TEXT] == 'method') $this-&gt;symbol_table-&gt;incrementIndex(KIND_ARG); // Compile parameter list $paramlist_length = $this-&gt;compileParameterList(array_slice($tokens, $position)); $position += $paramlist_length; $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], ')'), 'Missing ) symbol for subroutine declaration'); $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; // Compile subroutine body $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], '{'), 'Subroutine body is missing { symbol'); $position += 1; $this-&gt;XML_enterChildNode('subroutineBody'); $this-&gt;writeTokenData(array($tokens[$position - 1])); $length = count($tokens); $function_declaration_written = false; $vm_function_name = $this-&gt;registry['className'] . '.' . $tokens[2][TOKEN_TEXT]; // Check for local variable declarations and statements while ($position &lt; $length) { $token_args = array_slice($tokens, $position); if (JackTokenizer::isKeyword($tokens[$position], 'var')) { $var_length = $this-&gt;compileVarDec($token_args); $position += $var_length; } else if (JackTokenizer::isKeyword($tokens[$position], array('do', 'if', 'while', 'return', 'let'))) { // If we detect an expression, that signals the end of local variable declarations // in the current function. If the VM function declaration has not been written yet, // then declare the function. if (!$function_declaration_written) { $function_declaration_written = true; $this-&gt;VM_writeFunctionDeclaration($vm_function_name, $tokens[0][TOKEN_TEXT]); } $statements_length = $this-&gt;compileStatements($token_args); $position += $statements_length; } else { break; } } // If there are no statements in the function, then the function declaration will not have been written // So check again after the subroutine body has been processed if (!$function_declaration_written) { $function_declaration_written = true; $this-&gt;VM_writeFunctionDeclaration($vm_function_name, $tokens[0][TOKEN_TEXT]); } $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], '}'), 'Subroutine body is missing } symbol'); $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; $this-&gt;XML_returnToParent(); $this-&gt;XML_returnToParent(); return $position; } // Compiles a parameter list for a method private function compileParameterList($tokens) { $this-&gt;XML_enterChildNode('parameterList'); $length = count($tokens); $position = 0; $comma_needed = false; $type_on = false; for ($c = 0; $c &lt; $length; $c++) { if ($comma_needed &amp;&amp; JackTokenizer::isSymbol($tokens[$c], ',')) { $comma_needed = false; $position++; } else if (!$comma_needed &amp;&amp; !$type_on &amp;&amp; JackTokenizer::isTypeOrVoid($tokens[$c])) { $type_on = true; $position++; } else if (!$comma_needed &amp;&amp; $type_on &amp;&amp; JackTokenizer::isIdentifier($tokens[$c])) { $comma_needed = true; $type_on = false; $position++; // Add variable to symbol table $this-&gt;symbol_table-&gt;define($tokens[$c][TOKEN_TEXT], $tokens[$c-1][TOKEN_TEXT], KIND_ARG); } else { break; } } $this-&gt;check(!$type_on, 'Trailing comma or type expression at end of parameter list'); $this-&gt;writeTokenData(array_slice($tokens, 0, $position)); $this-&gt;XML_returnToParent(); return $position; } // Compiles a variable declaration private function compileVarDec($tokens) { $this-&gt;check(JackTokenizer::isKeyword($tokens[0], 'var'), 'Variable declarations must start with "var" keyword'); $this-&gt;check(JackTokenizer::isType($tokens[1]), 'Type in variable declaration is not a valid type'); $this-&gt;check(JackTokenizer::isIdentifier($tokens[2]), 'First variable in var declaration is not a valid identifier'); $this-&gt;XML_enterChildNode('varDec'); $length = count($tokens); $position = 2; $comma_needed = false; for ($c = $position; $c &lt; $length &amp;&amp; $tokens[$c][TOKEN_TEXT] != ';'; $c++) { if (!$comma_needed &amp;&amp; JackTokenizer::isIdentifier($tokens[$c])) { $comma_needed = true; $position++; // Add variable to symbol table $this-&gt;symbol_table-&gt;define($tokens[$c][TOKEN_TEXT], $tokens[1][TOKEN_TEXT], KIND_VAR); } else if ($comma_needed &amp;&amp; JackTokenizer::isSymbol($tokens[$c], ',')) { $comma_needed = false; $position++; } else { break; } } $this-&gt;check($comma_needed, 'Trailing comma at end of variable declaration'); $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], ';'), 'Variable declaration must end with a semicolon'); $position += 1; $this-&gt;writeTokenData(array_slice($tokens, 0, $position)); $this-&gt;XML_returnToParent(); return $position; } // Compiles a sequence of statements private function compileStatements($tokens) { $this-&gt;XML_enterChildNode('statements'); $length = count($tokens); $position = 0; while ($position &lt; $length) { // If a statement keyword is detected, then process that statement and update the position pointer to the next statement if (JackTokenizer::isKeyword($tokens[$position], array('let', 'if', 'while', 'do', 'return'))) { $function_name = 'compile' . ucwords($tokens[$position][TOKEN_TEXT]); $statement_length = call_user_func_array(array($this, $function_name), array(array_slice($tokens, $position))); $position += $statement_length; } // If the entry is not a valid statement keyword, then there are no more statements to compile else { break; } } $this-&gt;XML_returnToParent(); return $position; } // Compiles a let statement private function compileLet($tokens) { $this-&gt;check(JackTokenizer::isKeyword($tokens[0], 'let'), 'Let statement must begin with keyword let'); $this-&gt;check(JackTokenizer::isIdentifier($tokens[1]), 'Invalid identifier for variable name in let statement'); $this-&gt;XML_enterChildNode('letStatement'); $this-&gt;writeTokenData(array_slice($tokens, 0, 2)); $position = 2; $has_index = false; $text = $tokens[1][TOKEN_TEXT]; $kind_to_segment = array( KIND_STATIC =&gt; SEGMENT_STATIC, KIND_FIELD =&gt; SEGMENT_THIS, KIND_VAR =&gt; SEGMENT_LCL, KIND_ARG =&gt; SEGMENT_ARG ); // Check for indexing if (JackTokenizer::isSymbol($tokens[$position], '[')) { $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; $has_index = true; $this-&gt;vm-&gt;writePush($kind_to_segment[$this-&gt;symbol_table-&gt;kindOf($text)], $this-&gt;symbol_table-&gt;indexOf($text)); $position += $this-&gt;compileExpression(array_slice($tokens, $position)); $this-&gt;vm-&gt;writeArithmetic(COMMAND_ADD); $this-&gt;vm-&gt;writePop(SEGMENT_TEMP, 1); $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], ']'), 'Let statement is missing ] symbol after index expression'); $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; } $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], '='), 'Missing or misplaced = symbol in let statement'); $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; $position += $this-&gt;compileExpression(array_slice($tokens, $position)); $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], ';'), 'Missing semicolon at end of let statement'); $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; // Store the result in the variable (VM) if ($has_index) { $this-&gt;vm-&gt;writePush(SEGMENT_TEMP, 1); $this-&gt;vm-&gt;writePop(SEGMENT_POINTER, 1); $this-&gt;vm-&gt;writePop(SEGMENT_THAT, 0); } else { $this-&gt;vm-&gt;writePop($kind_to_segment[$this-&gt;symbol_table-&gt;kindOf($text)], $this-&gt;symbol_table-&gt;indexOf($text)); } $this-&gt;XML_returnToParent(); return $position; } // Compiles a while statement private function compileWhile($tokens) { $this-&gt;check(JackTokenizer::isKeyword($tokens[0], 'while'), 'While statement must begin with keyword while'); $this-&gt;check(JackTokenizer::isSymbol($tokens[1], '('), 'Missing ( symbol for start of expression in while statement'); $this-&gt;XML_enterChildNode('whileStatement'); $this-&gt;writeTokenData(array_slice($tokens, 0, 2)); $id = uniqid(); $loop_id = sprintf('WHILE_LOOP_%s', $id); $end_id = sprintf('WHILE_END_%s', $id); $this-&gt;vm-&gt;writeLabel($loop_id); // Compile while expression $position = 2; $position += $this-&gt;compileExpression(array_slice($tokens, $position)); $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], ')'), 'Missing ) symbol for end of expression in while statement'); $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; $this-&gt;vm-&gt;writeArithmetic(COMMAND_NOT); $this-&gt;vm-&gt;writeIfGoto($end_id); // Compile while statements $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], '{'), 'Missing { symbol for start of statements in while statement'); $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; $position += $this-&gt;compileStatements(array_slice($tokens, $position)); $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], '}'), 'Missing } symbol for end of statements in while statement'); $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; $this-&gt;vm-&gt;writeGoto($loop_id); $this-&gt;vm-&gt;writeLabel($end_id); $this-&gt;XML_returnToParent(); return $position; } // Compiles a return statement private function compileReturn($tokens) { $this-&gt;check(JackTokenizer::isKeyword($tokens[0], 'return'), 'Return statement must begin with keyword return'); $this-&gt;XML_enterChildNode('returnStatement'); $this-&gt;writeTokenData(array($tokens[0])); $position = 1; // If next token is a semicolon, then there is no expression to parse if (JackTokenizer::isSymbol($tokens[$position], ';')) { $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; // If return statement has no arguments, then it is returning from a void function // In this case, we must manually push a constant zero onto the stack to be returned by the VM $this-&gt;vm-&gt;writePush(SEGMENT_CONSTANT, 0); $this-&gt;vm-&gt;writeReturn(); } // Otherwise, parse the expression and check for a semicolon at the end else { $position += $this-&gt;compileExpression(array_slice($tokens, $position)); $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], ';'), 'Return statement is missing semicolon ending symbol'); $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; // Write return statement (VM) $this-&gt;vm-&gt;writeReturn(); } $this-&gt;XML_returnToParent(); return $position; } // Compiles an if statement private function compileIf($tokens) { $this-&gt;check(JackTokenizer::isKeyword($tokens[0], 'if'), 'If statement must begin with if keyword'); $this-&gt;check(JackTokenizer::isSymbol($tokens[1], '('), 'If statement missing ( for start of expression in if clause'); $this-&gt;XML_enterChildNode('ifStatement'); $this-&gt;writeTokenData(array_slice($tokens, 0, 2)); $id = uniqid(); $else_id = sprintf('IF_ELSE_%s', $id); $end_id = sprintf('IF_END_%s', $id); // Compile the "if" clause $position = 2; $position += $this-&gt;compileExpression(array_slice($tokens, $position)); $this-&gt;vm-&gt;writeArithmetic(COMMAND_NOT); $this-&gt;vm-&gt;writeIfGoto($else_id); $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], ')'), 'If statement missing ) for end of expression in if clause'); $this-&gt;check(JackTokenizer::isSymbol($tokens[$position+1], '{'), 'If statement missing { for start of statements in if clause'); $this-&gt;writeTokenData(array_slice($tokens, $position, 2)); $position += 2; $position += $this-&gt;compileStatements(array_slice($tokens, $position)); $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], '}'), 'If statement missing } for end of statements in if clause'); $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; $this-&gt;vm-&gt;writeGoto($end_id); // Check for an "else" clause, and compile it if it exists $this-&gt;vm-&gt;writeLabel($else_id); if ($position &lt; count($tokens) &amp;&amp; JackTokenizer::isKeyword($tokens[$position], 'else')) { $this-&gt;check(JackTokenizer::isSymbol($tokens[$position+1], '{'), 'If statement missing { for start of statements in else clause'); $this-&gt;writeTokenData(array($tokens[$position], $tokens[$position+1])); $position += 2; $position += $this-&gt;compileStatements(array_slice($tokens, $position)); $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], '}'), 'If statement missing } for end of statements in else clause'); $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; } $this-&gt;vm-&gt;writeLabel($end_id); $this-&gt;XML_returnToParent(); return $position; } // Compiles an expression private function compileExpression($tokens, $return_on_no_terms = false) { $this-&gt;XML_enterChildNode('expression'); // Check if first term exists and compile it if it does $term_length = $this-&gt;compileTerm($tokens); if ($term_length == 0 &amp;&amp; $return_on_no_terms) { $this-&gt;XML_returnToParent(); $this-&gt;XML_returnToParent(); // For some reason you need a second return-to-parent, not sure why return 0; } $this-&gt;check($term_length &gt; 0, 'Expression missing first term'); $position = $term_length; // If there are more entries in the form (op term), then compile them as well $length = count($tokens); $op_used = false; $last_op = ''; $op_to_command = array( '+' =&gt; COMMAND_ADD, '-' =&gt; COMMAND_SUB, '*' =&gt; COMMAND_MUL, '/' =&gt; COMMAND_DIV, '=' =&gt; COMMAND_EQ, '&gt;' =&gt; COMMAND_GT, '&lt;' =&gt; COMMAND_LT, '&amp;' =&gt; COMMAND_AND, '|' =&gt; COMMAND_OR, ); for (; $position &lt; $length; $position++) { $token_args = array_slice($tokens, $position); // If an operator was found and there is no previous un-used operator, then compile it if (JackTokenizer::isOp($tokens[$position]) &amp;&amp; !$op_used) { $this-&gt;writeTokenData(array($tokens[$position])); $op_used = true; $last_op = $tokens[$position][TOKEN_TEXT]; } // If there is a previous un-used operator and a term is found, then compile the term else if ($op_used) { $term_length = $this-&gt;compileTerm($token_args); $this-&gt;check($term_length &gt; 0, 'Invalid additional term in expression'); $position += $term_length - 1; $op_used = false; // Write arithmetic operation (VM) $this-&gt;vm-&gt;writeArithmetic($op_to_command[$last_op]); $last_op = ''; } // If there is no operator and no term, then that signals the end of the expression else { break; } } // If an operator was the last entry in the expression and it wasn't used, then that is a syntax error if ($this-&gt;write_xml) $this-&gt;check(!$op_used, 'Syntax error in expression, operator cannot be the last entry'); $this-&gt;XML_returnToParent(); return $position; } // Compiles a term for an expression private function compileTerm($tokens) { $this-&gt;XML_enterChildNode('term'); $length = count($tokens); $position = 0; // Integer constants, string constants and keyword constants if ($tokens[0][TOKEN_TYPE] == TOKENTYPE_INT_CONST || $tokens[0][TOKEN_TYPE] == TOKENTYPE_STRING_CONST || JackTokenizer::isKeywordConstant($tokens[0])) { $this-&gt;writeTokenData(array($tokens[0])); $position += 1; // Write constant (VM) if ($tokens[0][TOKEN_TYPE] == TOKENTYPE_INT_CONST) { $this-&gt;vm-&gt;writePush(SEGMENT_CONSTANT, $tokens[0][TOKEN_TEXT]); } else if ($tokens[0][TOKEN_TYPE] == TOKENTYPE_STRING_CONST) { $text = $tokens[0][TOKEN_TEXT]; $length = strlen($text); $this-&gt;vm-&gt;writePush(SEGMENT_CONSTANT, $length); $this-&gt;vm-&gt;writeCall('String.new', 1); $this-&gt;vm-&gt;writePop(SEGMENT_TEMP, 1); for ($c = 0; $c &lt; $length; $c++) { $this-&gt;vm-&gt;writePush(SEGMENT_TEMP, 1); $this-&gt;vm-&gt;writePush(SEGMENT_CONSTANT, ord($text[$c])); $this-&gt;vm-&gt;writeCall('String.appendChar', 2); $this-&gt;vm-&gt;writePop(SEGMENT_TEMP, 1); } $this-&gt;vm-&gt;writePush(SEGMENT_TEMP, 1); } else { $text = $tokens[0][TOKEN_TEXT]; if ($text == 'null' || $text == 'false') { $this-&gt;vm-&gt;writePush(SEGMENT_CONSTANT, 0); } else if ($text == 'true') { $this-&gt;vm-&gt;writePush(SEGMENT_CONSTANT, 1); $this-&gt;vm-&gt;writeArithmetic(COMMAND_NEG); } else if ($text == 'this') { $this-&gt;vm-&gt;writePush(SEGMENT_POINTER, 0); } } } // varName, varName[expr], subroutineCall else if (JackTokenizer::isIdentifier($tokens[0])) { $kind_to_segment = array( KIND_STATIC =&gt; SEGMENT_STATIC, KIND_FIELD =&gt; SEGMENT_THIS, KIND_VAR =&gt; SEGMENT_LCL, KIND_ARG =&gt; SEGMENT_ARG ); // If next token is [ symbol, then it's a varName with an index if (JackTokenizer::isSymbol($tokens[1], '[') &amp;&amp; $length &gt;= 3) { $this-&gt;writeTokenData(array($tokens[0], $tokens[1])); $position += 2; $text = $tokens[0][TOKEN_TEXT]; $this-&gt;vm-&gt;writePush($kind_to_segment[$this-&gt;symbol_table-&gt;kindOf($text)], $this-&gt;symbol_table-&gt;indexOf($text)); $position += $this-&gt;compileExpression(array_slice($tokens, $position)); $this-&gt;vm-&gt;writeArithmetic(COMMAND_ADD); $this-&gt;vm-&gt;writePop(SEGMENT_POINTER, 1); $this-&gt;vm-&gt;writePush(SEGMENT_THAT, 0); $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], ']'), 'End of index expression in term missing ] symbol'); $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; } // If next token is ( or . symbol, then it's a subroutine call else if (JackTokenizer::isSymbol($tokens[1], array('(', '.')) &amp;&amp; $length &gt;= 3) { $position += $this-&gt;compileSubroutineCall($tokens); } // Otherwise, it's just a regular varName else { $this-&gt;writeTokenData(array($tokens[0])); $position += 1; // Write varName (VM) $text = $tokens[0][TOKEN_TEXT]; if (!$this-&gt;symbol_table-&gt;exists($text)) trigger_error(sprintf('Variable "%s" used in expression does not exist', $text), E_USER_WARNING); $this-&gt;vm-&gt;writePush($kind_to_segment[$this-&gt;symbol_table-&gt;kindOf($text)], $this-&gt;symbol_table-&gt;indexOf($text)); } } // (expr) else if (JackTokenizer::isSymbol($tokens[0], '(') &amp;&amp; $length &gt;= 2) { $this-&gt;writeTokenData(array($tokens[0])); $position += 1; $position += $this-&gt;compileExpression(array_slice($tokens, 1)); $this-&gt;check(JackTokenizer::isSymbol($tokens[$position], ')'), 'End of expression in term missing ) symbol'); $this-&gt;writeTokenData(array($tokens[$position])); $position += 1; } // Term with a preceding unary operator else if (JackTokenizer::isUnaryOp($tokens[0]) &amp;&amp; $length &gt;= 2) { $this-&gt;writeTokenData(array($tokens[0])); $token_args = array_slice($tokens, 1); $term_length = $this-&gt;compileTerm($token_args); $this-&gt;check($term_length &gt; 0, 'Invalid sub-term after unary operator in term'); $position += 1 + $term_length; // Write term (VM) $this-&gt;vm-&gt;writeArithmetic($tokens[0][TOKEN_TEXT] == '-' ? COMMAND_NEG : COMMAND_NOT); } $this-&gt;XML_returnToParent(); return $position; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T14:37:30.430", "Id": "24339", "Score": "0", "body": "\"I took out some code because it went over the character limit\" - You beat me to it, I thought one of my answers would have done that first :) Anyways, this is usually a sign that A) your class is too big or B) you should separate these into multiple posts. We'll see once I actually start looking through it." } ]
[ { "body": "<p>Needs more classes, this one class does too many different things. </p>\n\n<p>Firstly, I'd suggest a Scanner class. This class will hold the array of tokens and the current position. It will then also have a number of methods to operate on it. It'll also keep track of errors during the parsing process. Here is one of your functions as I'd rewrite it, (skipping XML for now)</p>\n\n<pre><code>private function compileClassVarDec($scanner)\n{\n\n $field_scope = $scanner-&gt;matchKeyword( array('static','field') );\n $field_scope = $field_scope == 'static' ? KIND_STATIC : KIND_FIELD;\n $field_type = $scanner-&gt;matchType();\n // the match* functions increment the position, and record errors\n // if the provided tokens did not actually match\n\n while(true)\n {\n $identifier = $scanner-&gt;matchIdentifier();\n $this-&gt;symbol_table-&gt;define($identifier, $field_type, $field_scope);\n\n if( $scanner-&gt;isSymbol(\",\") )\n {\n $scanner-&gt;matchSymbol(\",\");\n }else{\n break;\n }\n }\n\n $scanner-&gt;matchSymbol(\";\");\n}\n</code></pre>\n\n<p>I think a scanner class would really help clean up the parsing code.</p>\n\n<p>Next, I'd have this class solely worry about parsing, not generating the code or the xml. I'd have it generate an AST, which you could then pass either to a XML dumper or a code generator class. I'd have a seperate AST class to handle the generation logic, and do something like this:</p>\n\n<pre><code>private function compileSubroutine($scanner)\n{\n\n $this-&gt;ast-&gt;pushScope('subroutineDec', $scanner);\n // pushScope records the current position for later\n\n $this-&gt;ast-&gt;attribute('category', $scanner-&gt;matchKeyword( array('constructor', 'function', 'method') ));\n $this-&gt;ast-&gt;attribute('type', $scanner-&gt;matchType());\n $this-&gt;ast-&gt;attribute('name' $scanner-&gt;matchIdentifier());\n $scanner-&gt;matchSymbol('(');\n $this-&gt;ast-&gt;attribut('parameterlist', $this-&gt;parseParameterList($scanner)); \n $scanner-&gt;matchSymbol(')');\n $scanner-&gt;matchSymbol('{');\n $this-&gt;parseBody($scanner);\n $scanner-&gt;matchSymbol('}');\n\n $this-&gt;ast-&gt;popScope($scanner); // records ending position\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T14:51:09.163", "Id": "14991", "ParentId": "14957", "Score": "2" } }, { "body": "<p>Alright, I'm not going to pretend I understand what's going on here. First, there's just too much. Second, I don't know Jack about Jack, all puns intended. I'm only going to do a once over on this. Usually I'm a bit more thorough, but you have entirely too much here. And by that I mean you really need to break this up into tinier, more efficient, classes.</p>\n\n<p>First thing, since this is something that is going to be shared (you mentioned a book), then you should use proper PHPDoc as if this were a traditional API. Will make importing this into an IDE much easier and make documentation easier too. I'll demonstrate with your properties and constructor.</p>\n\n<pre><code>private\n /** Token list to operate on */\n $tokens,\n /** Symbol table that stores all identifiers */\n $symbol_table,\n //etc...\n /** Array of parent XML objects */\n $parent_xml\n;\n\n/** Initializes the CompilationEngine object with a list of tokens\n *\n * @param array Token list to operate on\n */\npublic function __construct($tokens)\n</code></pre>\n\n<p>You can assign default property values when initially declaring the property, no need to clutter the constructor. For instance, <code>$write_xml</code> and <code>$write_vm</code> are both statically set to FALSE, so they could easily be moved into the initial declaration. There are more, these are just two.</p>\n\n<p>This for loop looks like the <code>$token</code> array should have been a multidimensional associative array. Some things I'm seeing later on seem to confirm this suspicion. This would make needing to check for every two elements unnecessary, I'm assuming these are parameters or something? Ideally, you would want to look at changing this, if possible. I'm not sure of the source, so maybe not.</p>\n\n<p>If <code>setWriteXML()</code> is just a toggle, why accept a flag? Same for vm. Just toggle it.</p>\n\n<pre><code>public function setWriteXML() {\n $this-&gt;write_xml = ! $this-&gt;write_xml;\n}\n</code></pre>\n\n<p>I would try to avoid braceless statements. They can cause confusion and can lead to mistakes. This isn't Python so the syntax is inherently necessary. Maybe, as people are starting to point out to me, this is a stylistic choice, but I believe its one PHP should not have introduced, at least not halfheartedly as they have.</p>\n\n<p>You should remain consistent in your style. CamelCase or Under_Score, at least for the same data type. You can switch between them for methods and variables if you want, but methods should be identical in style to other methods, as should variables. For instance, you have combined camelcase and underscore with your XML prefixed methods, all other methods are camelcase only. Also, because of the wide usage of this prefix, and other prefixes, I think this is pretty indicative of a need for a new class. You are essentially namespacing your methods.</p>\n\n<p>Why are you using <code>sprintf</code>? Yes, its fine and dandy for templating larger strings, but for simpler strings you can just concatenate. Much quicker, and cleaner, and less overhead.</p>\n\n<pre><code>trigger_error( \"CompilationEngine: $message\", E_USER_WARNING );\n</code></pre>\n\n<p>I can't decide if these all caps words are constants, or just WANT to be constants. They aren't defined here, so I can't be sure. If you have them defined as constants somewhere you can skip over this section. If these aren't constants, PHP is throwing silent warnings every time this comes up saying that these are \"Undefined, assuming 'TOKENTYPE_KEYWORD'\". Meaning its using these as strings. If you want to use them as strings, make them strings, if you want to use them as constants, make them constants. Unless these are PHP constants, then continue.</p>\n\n<p>\"Don't Repeat Yourself\" (DRY) Principle. Your <code>compile()</code> method is repeating itself, moving the xml and vm out of this class and into their own will help, but you will still need to avoid calling the functions more than once.</p>\n\n<pre><code>$xml = $this-&gt;write_xml ? $this-&gt;xml-&gt;asXML() : '';\n$vm = $this-&gt;write_vm ? implode( \"\\n\", $this-&gt;vm-&gt;getCode() ) : '';\n\nif( $xml &amp;&amp; $vm ) {\n return compact( 'xml', 'vm' );\n} else if( $xml || $vm ) {\n return $xml . $vm;//one's empty, so concatenating won't hurt\n}\n</code></pre>\n\n<p>Another DRY violation. You have at least two methods that have <code>$isCommaNeeded</code> routines that appear to be almost identical. Try combining these into a new method where you can.</p>\n\n<p>And another. You use a similar routine each time you iterate over the tokens. Make this a method.</p>\n\n<pre><code>$this-&gt;check(JackTokenizer::isSymbol($tokens[$position], '}'), 'Missing } symbol for end of statements in while statement');\n$this-&gt;writeTokenData(array($tokens[$position]));\n$position += 1; \n</code></pre>\n\n<p>I stopped about here, I'm starting to get lost in your code. I would suggest, if you take nothing else from this review, that you split this class up into more logical subclasses. Your \"namespacing\" should help you get started. Another suggestion, put this on github or something. You are liable to get a lot of help there. And let me know if you do, I might just stop by, been trying to convince myself to get into that side of things anyways.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T16:08:03.447", "Id": "14994", "ParentId": "14957", "Score": "3" } } ]
{ "AcceptedAnswerId": "14994", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T21:58:22.740", "Id": "14957", "Score": "3", "Tags": [ "php", "parsing" ], "Title": "A simple compiler for a language called Jack" }
14957
<p>I created the following code to solve a simple ODE. It is clear enough? Is it efficient code? I really want to read opinions because I want to make all my exercise solutions the same way (same structure of the program), so I need to make sure that this code is really clear and efficient.</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;vector&gt; class step { public: step() : time(0.), velocity(0.) {} step(const double&amp; t, const double&amp; v) : time(t), velocity(v) {} double time; double velocity; }; void calculate( std::vector&lt;step&gt;&amp; steps, double g, double t_max, double dt) { int iterations(t_max / dt + 1); steps.resize(iterations); for(int i(0); i &lt;= iterations; i++) { steps[i+1].time = steps[i].time + dt; steps[i+1].velocity = steps[i].velocity - g * dt; } } void save( const std::vector&lt;step&gt;&amp; steps, const std::string&amp; filename) { std::ofstream out(filename); for(int i(0); i &lt; steps.size(); i++) { out &lt;&lt; steps[i].time &lt;&lt; ' ' &lt;&lt; steps[i].velocity &lt;&lt; std::endl; } } int main() { double g(9.81); double t_max(10.); double dt(0.01); step initial_conditions(0.,0.); std::vector&lt; step &gt; steps({initial_conditions}); calculate(steps, g, t_max, dt); save(steps, "ex_1.1.dat"); return 0; } </code></pre>
[]
[ { "body": "<p>Although I'm not a C++ programmer I once held a course in computations with Matlab for physicists. So I can only give hints and thoughts on your code but I won't answer your question on efficiency.</p>\n\n<p>As you mentioned that this code will be the basic of following exercises, I'm missing all sorts of documentation. If you are planning to teach someone (solving) ODEs with this code, you should at least refer to a physical or mathematical problem, which will be solved by your code and you should comment every function and what it does. However, if you want to teach writing clean code, you should separate your definitions from the implementation.\nI'm the opinion that variables should have meaningful names even if you are referring to the standard variable names in physics (like g for gravity). This will ease the burden of understanding the code if you are not familiar with standard variable names.</p>\n\n<p>Lastly, there is the call to the resize method of the vector. As I am no C++ programmer, so I can't say for sure, but I feel uncomfortable with this function. I searched in a C++ reference and found out about the method reserve which might be more appropriate in a safer way.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-06T14:32:00.650", "Id": "15384", "ParentId": "14959", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T22:34:20.177", "Id": "14959", "Score": "1", "Tags": [ "c++", "optimization", "physics" ], "Title": "Simple Open Dynamics Engine (ODE)" }
14959
<p>In the code below, does not clearing or setting the local variable <code>completed</code> to null create the potential for a memory leak?</p> <pre><code>private Vector&lt;Element&gt; elements; private void update() { Vector&lt;Element&gt; completed = new Vector&lt;Element&gt;(); for( Element e : elements ) { if( e.isComplete() ) { completed.add( e ); } else { e.update(); } } elements.removeAll( complete ); } </code></pre> <p>Should I add <code>complete.clear()</code> before the <code>update()</code> method exits? </p> <p>The <code>elements</code> Vector is an instance variable on a class that is populated with Element objects elsewhere in the program.</p>
[]
[ { "body": "<p>Because <code>complete</code> is used and is referenced entirely within the context of the method <code>update()</code>, it will become unreferenced after the method returns.</p>\n\n<p>This will eventually cause it to be garbage collected.</p>\n\n<p>After it has been garbage collected, some or all of the elements that belong to it will also become unreferenced and then garbage collected.</p>\n\n<p>So technically, no, it is not necessary to call <code>complete.clear()</code>.</p>\n\n<p>On the other hand, getting into the habit of insuring that things are properly cleaned up can be important in other circumstances. As such, it would not be wrong to add the <code>clear()</code> call to the end of the method. To do so, or not do so could be either a stylistic choice, or something to consider addressing in a coding standards document. I would probably add it myself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T02:57:04.060", "Id": "24310", "Score": "0", "body": "Thanks for the info. I was pretty sure that this was the case, however Java is not my native language so it seemed wise to get a second opinion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T06:24:13.527", "Id": "24318", "Score": "0", "body": "Actually it would be more efficient to just let the garbage collector claim the entire list rather than manually clearing it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T02:18:02.010", "Id": "14970", "ParentId": "14963", "Score": "3" } }, { "body": "<p>Two things. First, you really shouldn't be using Vector. See <a href=\"https://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete-or-deprecated\">https://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete-or-deprecated</a></p>\n\n<p>Second, I would not clear the list. The garbage collector will handle it for you and unless you have a very specific reason to not rely on the GC to do its job, there is no reason to clear it. Clearing it may not seem to have any downsides, however, you are adding code that is not needed. Although it may seem trivial, having these calls all over a program will only serve to decrease the readability of the code. When the code is revisited later, it may be confusing as to why the collections are being cleared when they are going out of scope anyway.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T15:00:15.523", "Id": "24343", "Score": "0", "body": "Good to know! Looks like ArrayList is the way to go." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T14:34:50.593", "Id": "14989", "ParentId": "14963", "Score": "3" } } ]
{ "AcceptedAnswerId": "14970", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T00:18:08.860", "Id": "14963", "Score": "4", "Tags": [ "java", "memory-management" ], "Title": "Can not clearing a local java.util.Vector cause a memory leak?" }
14963
<p>I have a helper method to clean up a string and remove pieces that I will be generating again. (defined by the "SpecialKey" Constants) but I've never been real happy with the code. Although <strong>I</strong> find it easy to read adding more keys doesn't always seem so clean.</p> <pre><code> protected static System.String[] GetStringParts(System.String stringValue) { System.String[] stringParts = stringValue.Split('!'); System.Func&lt;System.String, System.Boolean&gt; isConstKey = (System.String key) =&gt; { return !System.String.IsNullOrWhiteSpace(key) &amp;&amp; ( key.StartsWith(MyUtility.SpecialStringKey1) || key.StartsWith(MyUtility.SpecialStringKey2) || key.StartsWith(MyUtility.SpecialStringKey3) || key.StartsWith(MyUtility.SpecialStringKey4) ); }; return stringParts.Where(key =&gt; !isConstKey(key)).ToArray(); } </code></pre> <p><em>I have removed specific names and such. I don't usually go by the convention SpecialKey1/2 etc</em></p> <p>I'd like any pointers on performance or readability. This code gets hit often but in the last two years has only been changed once (maybe twice).</p>
[]
[ { "body": "<p>I assume that the part that you want to improve is the key.StartsWith....</p>\n\n<p>I would replace the anonymous function with an Extension method String.StartsWith(IEnumerable&lt;string&gt;) -- then create a list of special keys (perhaps even load them from persisted storage, depending upon your usage), to be used in the extension method.</p>\n\n<p>Basically you add the over head of list creation, but your code now more precisely reflects the INTENT, making it easier to understand and modify. As middle ground between using persisted storage and creating the list in the middle of the your function, you could create a static function that returns your specialKeysList.</p>\n\n<p>As for performance, you should always keep performance in mind, but don't worry about it unless you have to -- you should only worry about performance when you <strong>have</strong> to ask \"how can I improve the performance when doing this\". At that point you have an identified problem, and you need a solution. If you don't have a problem, then don't do things that you <strong>know</strong> will cause a problem, but don't spend time trying to make it faster, that time is better spent either writing more code or making it more readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T02:35:16.413", "Id": "24302", "Score": "0", "body": "The Keys are `static const string` so they can be used elsewhere. Is creating a list really worth it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T02:45:03.153", "Id": "24305", "Score": "1", "body": "Absolutely. What you now have is a random number of strings, defined by unrelated const values, with at best a shared naming convention. Their relationship in this function is defined by their usage. Imagine that you have a new hire, and he's told to work on this on the first day. Are those all of the special keys? Are there more special keys that exist but aren't relvant to this process? Does the naming convention define what should be checked, or is that just a concidence. Looking at this line of code in isolation, you can't know any of that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T02:57:16.843", "Id": "24311", "Score": "0", "body": "Do you have special keys in there that shouldn't be? You really don't know what those strings represent when looking at this code. If OTOH, if you split out the strings into a function that returns a private static list, when you look at *this* code, it will be quite clear what is happening. Your performance isn't impacted, because the list is, only created once, and then returned, but when used, it is clear that it is \"the list of strings that are to be used for X\"" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T01:46:46.430", "Id": "14967", "ParentId": "14964", "Score": "2" } }, { "body": "<p>I have a couple of suggestions and observations I'd like to point out:</p>\n<ul>\n<li><p>Fully qualified <code>System</code> types <strong>reduce readability</strong> without adding information.<br />\nSo: use <code>string[]</code> instead of <code>System.String[]</code>, <code>bool</code> instead of <code>System.Boolean</code> and so on.</p>\n</li>\n<li><p>Defining a lambda statement and storing it in a variable overcomplicates the code. <strong>Use query expression syntax instead.</strong></p>\n</li>\n<li><p>Are you actually using the return value as a <code>string[]</code> (accessing by index, etc.) or could you get away with returning <code>IEnumerable&lt;string&gt;</code>? <em>(<a href=\"https://docs.microsoft.com/en-us/archive/blogs/ericlippert/arrays-considered-somewhat-harmful\" rel=\"nofollow noreferrer\">Eric Lippert explains</a> why you should.)</em></p>\n</li>\n<li><p>Your <code>isConstKey</code> looks wrong, but it's hard to tell because of the double negative. Are you trying to remove empty strings? Currently, you're leaving the white space in the result, not removing it. In below code sample, I've corrected the problem.</p>\n</li>\n<li><p>Instead of comparing all the SpecialKeyStrings seperately, put them into a sequence exposed as a property of <code>MyUtility</code> and use LINQ to validate against that:</p>\n<pre><code> public static IEnumerable&lt;string&gt; SpecialStringKeys\n {\n get\n {\n return new[] { SpecialStringKey1, SpecialStringKey2, SpecialStringKey3, \n SpecialStringKey4, };\n }\n }\n</code></pre>\n</li>\n</ul>\n<p><em>Edit:</em> other possibilities would be to avoid creating a new array every time; you could create a <code>private static readonly</code> <a href=\"https://stackoverflow.com/questions/2649626/c-immutable-view-of-a-lists-objects/2649711#2649711\"><code>ReadOnlyCollection&lt;string&gt;</code></a> field or just a <code>private static readonly string[]</code>.</p>\n<p>All that would allow your <code>GetStringParts</code> method to be changed to the following:</p>\n<pre><code>protected static IEnumerable&lt;string&gt; GetStringParts(string stringValue)\n{\n return from part in stringValue.Split('!')\n where !string.IsNullOrWhiteSpace(part) &amp;&amp; \n !MyUtility.SpecialStringKeys.Any(part.StartsWith)\n select part;\n}\n</code></pre>\n<p>(If you really need an array, add the <code>ToArray</code> call and change the return type back).</p>\n<p>If you want to go one step further in readability, you could extract the condition to an extension method:</p>\n<pre><code>public static bool IsNeitherKeyNorWhiteSpace(this string source)\n{\n return !string.IsNullOrWhiteSpace(source) &amp;&amp; \n !MyUtility.SpecialStringKeys.Any(source.StartsWith);\n}\n</code></pre>\n<p>Changing your original method thus:</p>\n<pre><code>protected static IEnumerable&lt;string&gt; GetStringParts(string stringValue)\n{\n return from part in stringValue.Split('!')\n where part.IsNeitherKeyNorWhiteSpace()\n select part;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T02:32:54.047", "Id": "24301", "Score": "0", "body": "+1 `System.String` vs `string` is for some of our \"legacy\" developers... unfortunately I can't change that. Other code Relies on it being a `String[]`. These are both things I'd normally do in personal projects. The double negative I believe was due to some re-factoring earlier but I see what you mean now. The only bit I disagree with is the lambda, as having it in the one statement previously seemed like the `return ....` was too long to read. `.Any(source.StartsWith)` is not something I knew was even ossible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T03:31:39.503", "Id": "24314", "Score": "1", "body": "thanks for the explanation (I had a feeling that `System.String` was probably not your choice). `.Any(source.StartsWith)` is called a [method group](http://stackoverflow.com/a/2914951/1106367), being equivalent to `.Any(key => source.StartsWith(key))`. As for the lambda, I wasn't suggesting you should have *inlined* it; my point was that [using query syntax instead of method syntax](http://msdn.microsoft.com/en-us/library/bb397947.aspx) would make your code more readable (regardless of whether you check the special keys seperately or as an array)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T04:29:38.240", "Id": "24315", "Score": "0", "body": "Thanks that makes more sense now. I should point out a minor detail is that I don't actually care here if it is null. It was there just as defensive code and in its current form would have allowed null/whitespace through. But that is a tiny detail." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-08-23T01:48:09.657", "Id": "14968", "ParentId": "14964", "Score": "4" } } ]
{ "AcceptedAnswerId": "14968", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T00:23:17.940", "Id": "14964", "Score": "2", "Tags": [ "c#", "linq" ], "Title": "Filter out string sections" }
14964
<p>I've got a <code>NumericUpDown</code> control for each denomination of money and all of the events run the exact same code save for a single line so I'm trying to condense them into 1 event. I was originally going to use a <code>switch</code> but you can't switch on a non-value object so I just did an <code>if</code> tree. Is there a better way to do this?</p> <pre><code>private void BankInChanged(object sender, EventArgs e) { var objSender = (NumericUpDown) sender; if(objSender == bkI_Ls_Quarters) { currBoat.inBank.setQuarters(Convert.ToInt32(bkI_Ls_Quarters.Value)); } else if(objSender == bkI_Rl_Quarters) { currBoat.inBank.setQuarterRolls(Convert.ToInt32(bkI_Rl_Quarters.Value)); } else if(objSender == bkI_Ls_Nickels) { currBoat.inBank.setNickels(Convert.ToInt32(bkI_Ls_Nickels.Value)); } else if(objSender == bkI_Rl_Nickels) { currBoat.inBank.setNickelRolls(Convert.ToInt32(bkI_Rl_Nickels.Value)); } else if(objSender == bkI_Ls_Dimes) { currBoat.inBank.setDimes(Convert.ToInt32(bkI_Ls_Dimes.Value)); } else if(objSender == bkI_Rl_Dimes) { currBoat.inBank.setDimeRolls(Convert.ToInt32(bkI_Rl_Dimes.Value)); } else if(objSender == bkI_Ls_Pennies) { currBoat.inBank.setPennies(Convert.ToInt32(bkI_Ls_Pennies.Value)); } else if(objSender == bkI_Rl_Pennies) { currBoat.inBank.setPennyRolls(Convert.ToInt32(bkI_Rl_Pennies.Value)); } else if(objSender == bkI_Ones) { currBoat.inBank.setOnes(Convert.ToInt32(bkI_Ones.Value)); } else if(objSender == bkI_Fives) { currBoat.inBank.setFives(Convert.ToInt32(bkI_Fives.Value)); } else if(objSender == bkI_Tens) { currBoat.inBank.setTens(Convert.ToInt32(bkI_Tens.Value)); } else if(objSender == bkI_Twenties) { currBoat.inBank.setTwenties(Convert.ToInt32(bkI_Twenties.Value)); } else if(objSender == bkI_Fifties) { currBoat.inBank.setFifties(Convert.ToInt32(bkI_Fifties.Value)); } else if(objSender == bkI_Hundreds) { currBoat.inBank.setHundreds(Convert.ToInt32(bkI_Hundreds.Value)); } currBoat.updateTotals(); updateStatDisplay(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T01:47:56.880", "Id": "24300", "Score": "2", "body": "Upon loading and just briefly seeing your code, NO." } ]
[ { "body": "<p>The problem is not in switching between senders but the fact that each branch calls a different method on <code>inBank</code>. I would suggest creating an enum for the denominations:</p>\n\n<pre><code>enum Denomination {\n Quarters,\n QuarterRolls,\n Nickels,\n NickelRolls,\n ...\n}\n</code></pre>\n\n<p>and having a single setter in <code>inBank</code>:</p>\n\n<pre><code>void set(Denomination denomination, int value);\n</code></pre>\n\n<p>Then you can create a dictionary of controls to denominations:</p>\n\n<pre><code>IDictionary&lt;NumericUpDown, Denomination&gt; dict = new Dictionary&lt;NumericUpDown, Denomination&gt;();\ndict[bkI_Ls_Quarters] = Denomination.Quarters;\ndict[bkI_Rl_Quarters] = Denomination.QuarterRolls;\n...\n</code></pre>\n\n<p>and your event handler would simply be:</p>\n\n<pre><code>private void BankInChanged(object sender, EventArgs e)\n{\n var objSender = (NumericUpDown) sender;\n Denomination denomination = dict[objSender];\n\n currBoat.inBank.set(denomination, Convert.ToInt32(objSender.Value));\n currBoat.updateTotals();\n updateStatDisplay();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T12:37:21.433", "Id": "24333", "Score": "0", "body": "That's awesome, thanks! I'm still pretty new and I've never used a Dictionary before. Will definitely be making use of this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T14:42:54.527", "Id": "24340", "Score": "0", "body": "I think using collection initializer for your dictionary would make the code even better. Something like `new Dictionary<NumericUpDown, Denomination> { { bkI_Ls_Quarters, Denomination.Quarters }, … };`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T06:15:22.170", "Id": "14976", "ParentId": "14965", "Score": "5" } } ]
{ "AcceptedAnswerId": "14976", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T00:53:01.493", "Id": "14965", "Score": "2", "Tags": [ "c#" ], "Title": "Is this an efficient way to use one event for multiple controls?" }
14965
<p>I have two methods here that does the same thing: get the user input and validate them.</p> <p>If they enter a letter, the program will prompt them again to enter a number. |After that, if it's a number it will compare it to the bound given by the program or the user. It is working fine, but can anybody help me refactor this code? It would be really helpful if I could dissect the validations into smaller pieces of code or methods.</p> <pre><code>public void addToQuestionToQbank(){ this.askForCategory(); System.out.println("Add Questions[1]Multiple Choice[2] Identification: "); int choice; boolean notValid = true; do{ while(!input.hasNextInt()){ System.out.println("Numbers Only!"); System.out.print("Try again: "); input.nextLine(); } notValid = false; choice = input.nextInt(); }while(notValid); while(choice &gt; 2){ System.out.println("Out of bounds"); choice = input.nextInt(); input.nextLine(); } } public Difficulty askForDifficulty(){ System.out.println("Difficulty For This Question:\n1)Easy\n2)Medium\n3)Hard\nChoice: "); int choice = 0; boolean notValid = true; do{ while(!input.hasNextInt()){ System.out.println("Numbers Only!"); System.out.print("Try again: "); input.nextLine(); } notValid = false; choice = input.nextInt(); }while(notValid); while(choice &gt; diff.length){ System.out.println("Out of bounds"); choice = input.nextInt(); input.nextLine(); } System.out.println(diff[choice -1]); return diff[choice -1]; } </code></pre>
[]
[ { "body": "<p>There are 2 problems that must be addressed first. Where did <code>diff.choice</code> come from, what is that? Second. What is the <code>this.askForCategory()</code> call? It <em>sounds like</em> exactly what <code>addToQuestionToQbank()</code> is doing. <code>addToQuestionToQbank()</code> does not do what it says, so I wonder what the real adding method looks like ....</p>\n\n<p>Anyway, I would expect the calling code to look something like this:</p>\n\n<pre><code>public void newQuestion () {\n Question myQuestion = new Question();\n\n myQuestion.Question = this.askForQuestion();\n myQuestion.Answer = this.askForAnswer ();\n\n // here is where we call your code, refactored.\n myQuestion.category = this.multiChoicePrompt(\"Add Questions[1]Multiple Choice[2] Identification: \", 2);\n myQuestion.Difficulty = this.multiChoicePrompt(\"Difficulty For This Question:\\n1)Easy\\n2)Medium\\n3)Hard\\nChoice: \" ,3);\n\n this.addQuestionToQbank(myQuestion);\n}\n</code></pre>\n\n<p>By passing the prompt as a parameter we can now refactor as you asked:</p>\n\n<pre><code>// this prompt designed specifically to pick from multiple choices\n// note how the method name makes that comment irrelevant.\npublic int multiChoicePrompt(String askUser, int responseMaxValue) {\n System.out.println(askUser);\n\n int choice;\n boolean notValid = true;\n do{\n while(!input.hasNextInt()){\n System.out.println(\"Numbers Only!\");\n System.out.print(\"Try again: \");\n input.nextLine();\n }\n notValid = false;\n choice = input.nextInt();\n }while(notValid);\n\n // assume numbered choices always start with \"1\"\n while(choice &gt; responseMaxValue || choice &lt; 1){\n System.out.println(\"Out of bounds\");\n choice = input.nextInt();\n input.nextLine();\n }\n return choice;\n} \n</code></pre>\n\n<p>The easiest way to \"<a href=\"http://sourcemaking.com/refactoring/extract-method\" rel=\"nofollow\">extract method</a>\" might be to physically move all that code to the new method and then recompile and let the compiler errors tell you what variables it doesn't \"know\" - these are what you pass in as parameters.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T16:55:41.480", "Id": "14996", "ParentId": "14966", "Score": "4" } }, { "body": "<blockquote>\n <p>it is working fine. </p>\n</blockquote>\n\n<p>Are you sure about that?</p>\n\n<p>Your validation will fail miserably in the following scenario:</p>\n\n<blockquote>\n <p><code>Add Questions[1]Multiple Choice[2] Identification:</code><br>\n <code>10</code><br>\n <code>Out of bounds</code><br>\n <code>asdf</code> </p>\n\n<pre><code>Exception in thread \"main\" java.util.InputMismatchException\n</code></pre>\n</blockquote>\n\n<p>You need to check if the input is a number <em>every time you process it; not just the first time.</em> Note that your do-while loop will run for a single iteration every single time, so it is completely redundant and can be deleted (keeping the loop body). </p>\n\n<p>Take a look at this:</p>\n\n<h1>Improved Version</h1>\n\n<h2>Usage</h2>\n\n<p><code>askQuestion</code> is called with a question and a valid range of answers (refactored from your two similar methods). Note that this flexible scheme allows for arbitrary ranges to be passed in.</p>\n\n<pre><code>String categoryQuestion = \"Add Questions[1] Multiple Choice[2] Identification: \";\nString difficultyQuestion = \"Difficulty For This Question:\\n1)Easy\\n2)Medium\\n3)Hard\\nChoice: \";\nint category = askQuestion(categoryQuestion, Range.between(1, 2));\nint difficulty = askQuestion(difficultyQuestion, Range.between(1, 3));\n// it's not clear what you are actually doing with category and difficulty, \n// so I left that up to you\n</code></pre>\n\n<h2>Input Processing</h2>\n\n<p>This will properly validate the input, and I made it a bit more readable by extracting a method for getting the next integer. I have to admit I'm not a big fan of <code>while (true)</code> but it was the simplest and most readable thing I could come up with. Note that each method has its own, clearly defined task: the <code>askQuestion</code> method is all about validating the correct bounds (and doesn't know anything about your <code>Scanner input</code>) while the <code>getNextInt</code> method is all about retrieving the next integer from <code>input</code>.</p>\n\n<pre><code>public int askQuestion(String question, Range&lt;Integer&gt; responseRange) {\n System.out.println(question);\n while (true) {\n int choice = getNextInt();\n if (responseRange.contains(choice)){\n return choice;\n }\n System.out.println(\"Out of bounds\");\n }\n}\n\nprivate int getNextInt(){\n while (!input.hasNextInt()) {\n System.out.println(\"Numbers Only!\");\n System.out.println(\"Try again: \");\n input.nextLine();\n }\n int nextInt = input.nextInt();\n input.nextLine();\n return nextInt;\n}\n</code></pre>\n\n<h2>Range Helper Class</h2>\n\n<p>This class makes heavy use of generics to allow for flexible ranges to be defined (ranges are always inclusive in this implementation, i.e. <code>from</code> and <code>to</code> are included in the range). You might want to extend this class later on, but currently all we need is the convenient factory method <em><code>Range.between</code></em> and the check for <em><code>Range.contains</code></em>.</p>\n\n<pre><code>public class Range&lt;T extends Comparable&lt;? super T&gt;&gt; {\n private final T from;\n private final T to;\n\n public static &lt;T extends Comparable&lt;? super T&gt;&gt; Range&lt;T&gt; between(T start, T end){\n return new Range&lt;T&gt;(start, end);\n }\n\n private Range(T start, T end) {\n from = start;\n to = end;\n }\n\n public boolean contains(T value) {\n return from.compareTo(value) &lt;= 0 &amp;&amp; to.compareTo(value) &gt;= 0;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>It's important to study your code carefully and step through it in the debugger to verify that your validation is actually working <em>(it was not).</em> This is a lot easier if you have written readable, clean code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T02:18:42.670", "Id": "24536", "Score": "0", "body": "what if I wanted to validate String inputs? let's say the string input shouldn't have a ? @ etc etc" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T03:53:06.123", "Id": "15014", "ParentId": "14966", "Score": "3" } } ]
{ "AcceptedAnswerId": "14996", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T01:10:26.380", "Id": "14966", "Score": "1", "Tags": [ "java", "validation", "io" ], "Title": "User prompts for entering quiz questions" }
14966
<p>I am writing a script to count the number of rows in a textarea, and as it will be called on every keypress I want to make sure it runs as fast as possible. I'm not aiming for a general solution: we can assume that the textarea has a monospace font and enough horizontal space for exactly 80 characters.</p> <p>I've probably solved this problem in 20 different ways, and this is by far the fastest solution I've come up with:</p> <pre><code>function countRows1(txt) { var i, len, rows = 0; txt = txt.split('\n'); len = txt.length; for (i = 0; i &lt; len; i++) { rows += Math.ceil(txt[i].length / 80) || 1; } return rows; } </code></pre> <p>Here's a second solution, which is slightly faster in Firefox, but otherwise between a little and 5x slower:</p> <pre><code>function countRows2(txt) { var i = 0, nextBreak, rows = 0; while ((nextBreak = txt.indexOf('\n', i)) !== -1) { rows += Math.ceil((nextBreak - i) / 80) || 1; i = nextBreak + 1; } return rows + (Math.ceil((txt.length - i) / 80) || 1); } </code></pre> <p>The performance doesn't make any sense to me - <code>countRows2</code> does the same thing as <code>countRows1</code>, except it doesn't create any unnecessary strings or arrays. Is <code>indexOf</code> with a start position just really slow, or is there some optimization only the first method is picking up on?</p> <p>Finally, here's one more method, which is much slower in every browser I've tested, but beautifully concise:</p> <pre><code>function countRows3(txt) { return txt.match(/\n?[^\n]{1,80}|\n/g).length; } </code></pre> <p><a href="http://jsperf.com/countrows/2" rel="nofollow">Here's the jsPerf I'm using to compare the three.</a></p> <p>So I've really got three questions:</p> <ol> <li>Why is <code>countRows2</code> slower than <code>countRows1</code>?</li> <li>Is there any way to optimize the regex in <code>countRows3</code> so the performance is comparable to the first two?</li> <li>Is there any other way to speed up this code?</li> </ol> <p>ps: I can't just do something like <code>el.scrollHeight</code>, because I need it to shrink as text is deleted. Also, I don't want to remember the previous count and just calculate the difference, because some changes will inevitably be missed and a differential script will never right itself.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T02:41:42.597", "Id": "24303", "Score": "0", "body": "Not that the performance difference will be noticable - but do you really need to do this on every keypress event? If not consider throttling the calls to maybe one call every (half) second." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T02:52:48.287", "Id": "24309", "Score": "0", "body": "@ThiefMaster well it's for a personal page, so I can do whatever I want. On every keypress would make it more responsive though, and I'm not really seeing performance issues as-is. I guess I'm more curious to see where this can go, than to solve a pressing problem." } ]
[ { "body": "<p>What kind of performance are you getting? Is it acceptable. If it's not, then I'd look for changing your algorithm, and not minor tweaks. In particular, I'd look into NOT splitting the string and recalclating each time. Instead keep track of the state (what line and the number of characters on that line, whether it's a paste or a delete), and do the right thing based upon that. Adding an additional character at the end of a 5k block of text, adds one more line at most, if the last line was 1 character long, then unless the key being pressed is the enter key, it doesn't even do that. </p>\n\n<p>But before doing anything, sit down and see how well your existing function works, for your typcial data, and then for some extreme data.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T02:46:46.473", "Id": "24307", "Score": "0", "body": "As I said in the question, I'd rather not take a differential approach, as it reacts very poorly to common failures like missing a single edit. You're 100% right about the testing though - I did test it, and performance has never faltered. So I guess this isn't a pressing problem, but I still want to see if I can speed it up, for slower machines, even extremer cases, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T02:49:30.773", "Id": "24308", "Score": "0", "body": "Also, really good point about the algorithm. This was actually one of the clearest times I've been able to see my code improve with a better algorithm - first I tried looping over each character, then each line, then this approach, and each time I saw an order of magnitude improvement. I'm not sure where I can go from here though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T02:39:40.883", "Id": "14971", "ParentId": "14969", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T02:07:20.297", "Id": "14969", "Score": "1", "Tags": [ "javascript", "google-chrome" ], "Title": "Help optimizing a function to count the rows in a textarea" }
14969
<p>I'm writing a simulator for Conway's Game of Life (<a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow">http://en.wikipedia.org/wiki/Conway's_Game_of_Life</a>) in C++ and I'm trying to make the code as idiomatic as possible. </p> <p>The central object is a double array to represent the board:</p> <pre><code>typedef vector&lt;vector&lt;bool&gt; &gt; Board; </code></pre> <p>My <code>main</code> method has a <code>Board b</code> as a local variable, and I'm passing the board to several methods that update the board, draw the board, and so on. Is it better (that is, more efficient and/or idiomatic) to use methods like</p> <pre><code>void update(Board *board); int main() { Board b; //... update(&amp;b); //... } </code></pre> <p>or in this way:</p> <pre><code>void update(Board &amp; board); int main() { Board b; //... update(b); //... } </code></pre> <p>Which is the proper choice for idiomatic C++?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T05:45:08.583", "Id": "24316", "Score": "0", "body": "I don't know C++ but I think its the game of life thing is pretty cool just downloaded [this](http://www.macupdate.com/app/mac/26608/my-game-of-life)." } ]
[ { "body": "<p>Second one is better. Do not use pointers if it is possible to avoid them.\nFor example, in the beggining of the function update(Board *board) you have to check that board!=0 (to be sure, that your program will not crash). But in the function update(Board &amp; board) you are sure, that board exists. So second function is better.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T08:27:13.573", "Id": "14977", "ParentId": "14972", "Score": "8" } }, { "body": "<p>One rules of thumb to write idiomatic C++ is:</p>\n\n<blockquote>\n <p>Use references where you can and pointers where you have to.</p>\n</blockquote>\n\n<p>It's especially true for argument passing to a variable.\nIn your case, you have the choice, so use references, for all the reasons cited by Ilya and also just because you won't have any * to put everywhere in your function. Your code might be clearer that way.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T08:37:14.167", "Id": "14978", "ParentId": "14972", "Score": "11" } } ]
{ "AcceptedAnswerId": "14978", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T05:19:21.480", "Id": "14972", "Score": "4", "Tags": [ "c++", "memory-management", "game-of-life" ], "Title": "C++ Vector memory management in Game of Life" }
14972
<p>This is my first implementation of MongoDB, much much more to come. This sheds light on some things like how I've structured my collection. I hope to gain feedback and insight from the community on best practices as well as do's and don'ts.</p> <p><strong>Givens</strong></p> <ul> <li>I have a website with multiple apps.</li> <li>Each user can at one point signup / login for an app.</li> <li>There is one MongoDB collection called <code>users</code> that will store all the information.</li> <li>I want a log for each app that tracks users actions (signup, login, logout).</li> </ul> <p><strong>Example User Document</strong></p> <pre><code>{ "_id": ObjectId("5035b9fc0000005eed000002"), "apps": { "app0": { "log": [ { "status": "signup", "created_at": ISODate("2012-08-23T05:05:00.872Z") }, { "status": "login", "created_at": ISODate("2012-08-23T05:05:04.012Z") }, { "status": "login", "created_at": ISODate("2012-08-23T05:05:06.236Z") } ] } }, "user": "reggi" } </code></pre> <p>This code is the first interaction with the user they put a small piece of information in and I have to determine whether they are already in the database or not. They can initiate the signup process more than once, so both the initial and update need to write the same log.</p> <pre><code>users.findOne({"username":req.query.user},function(err, post){ if(typeof(post) == "undefined"){ //username does not exist in users create it with this app instance users.save((function(){ var object = { "username":req.query.user, "apps":{}, }; object.apps[appAlias] = {}; object.apps[appAlias].log = []; object.apps[appAlias].log.push({ status: "initiated-signup", created_at: new Date(), }); return object; }())); }else{ //username does exist in users create new apps object users.update({"_id":post._id},(function(){ var object = {}; object.$push = {}; object.$push["apps."+appAlias+".log"] = { status: "initiated-signup", created_at: new Date() }; return object; })()) } }); </code></pre> <p>This is my first dabble with MongoDB. I'm using <a href="https://github.com/marcello3d/node-mongolian" rel="nofollow">Mongolian</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T09:30:30.230", "Id": "25535", "Score": "0", "body": "Welcome to Code Review! Since you were wondering: the question is great, perfectly in the scope of Code Review. It's actually sad to see you didn't get an answer." } ]
[ { "body": "<p>While I cannot comment on your Node.js code, I can tell you that we're doing something very similar on a project that uses Mongo to store every bit of information for around 200 social profiles. In our case, we're doing something like:</p>\n\n<pre><code>foreach ($videos as $video) {\n $payload = ['$set' =&gt; $defaults + $meta + $this-&gt;interjectTimestamps((array)$video)];\n\n if (isset($video['statistics'])) {\n // Maintain a log of statistics for each video\n $payload['$push'] = ['statistics_log' =&gt; ['execute_at_ts' =&gt; $meta['execute_at_ts'], 'statistics' =&gt; $video['statistics']]];\n }\n $coll-&gt;update(['_type' =&gt; 'video', 'id' =&gt; $video['id']], $payload, ['upsert' =&gt; true]);\n}\n</code></pre>\n\n<p>From my research, this is fine. Mongo's $push works great for logs like this, but be wary, it can be difficult to query data in array's like this. If you plan on doing a lot of querying against a user's app's, it may be better to store this information in a separate collection.</p>\n\n<p>On the flip side, this design can be crucial if you ever need to perform any calculations with data from both your User document and the nested log. In our case, we're doing MapReduce on data from the entire document, log and all.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T16:22:27.353", "Id": "26158", "ParentId": "14973", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T05:21:05.923", "Id": "14973", "Score": "4", "Tags": [ "javascript", "node.js", "mongodb" ], "Title": "User-like MongoDB implementation" }
14973
<p>SQL:</p> <pre class="lang-sql prettyprint-override"><code>CREATE FUNCTION dbo.fnRandomForeNames () RETURNS VARCHAR(50) AS BEGIN RETURN ( SELECT TOP 1 [FirstName] FROM [tmp_ForeNames] ORDER BY (SELECT new_id from GetNewID) ) END GO </code></pre> <p>Similar functions for dbo.fnRandomSurNames() etc.</p> <pre class="lang-sql prettyprint-override"><code>UPDATE Table1 SET firstname = dbo.fnRandomForeNames(), lastname = dbo.fnRandomSurNames(), address1 = dbo.fnRandomAddress1(), address2 = dbo.fnRandomAddress2(), address3 = dbo.fnRandomAddress3(), birthdate = DATEADD(DAY, ABS(CHECKSUM(NEWID()) % 3650), '1990-01-01') </code></pre> <p>My C# Code: </p> <pre><code> private void RunThis(string connString, StreamReader sr) { sr.BaseStream.Position = 0; string sqlQuery = sr.ReadToEnd(); using (SqlConnection connection = new SqlConnection(connString)) { Server server = new Server(new ServerConnection(connection)); server.ConnectionContext.StatementTimeout = 4200; server.ConnectionContext.ExecuteNonQuery(sqlQuery); } sr.Close(); } </code></pre> <p>........ </p> <pre><code> RunThis(e.Argument.ToString(), _updateClaim); </code></pre> <p>Where <code>e.Argument.ToString()</code> is the connection string.</p> <p>The <code>CREATE FUNCTION</code> scripts are run earlier, take very little time to run. Also, names are stored in tmp databases, these are entered in C# via arrays. These also take very little time to run.</p> <p>Table1 contains approx 140,000 rows and takes approx. 14 mins to complete.</p> <p>I have also tried using parameterised SQL queries, skipping the tmp tables and SQL functions and instead creating the SQL query and executing it from the code, such as the following:</p> <pre class="lang-sql prettyprint-override"><code>UPDATE Table1 SET lastname = '{0}', firstname = '{1}', birthdate = DATEADD(DAY, ABS(CHECKSUM(NEWID()) % 3650), '1990-01-01'), address1 = '{2}', address2 = '{3}', address3 = '{4}' WHERE u_id = '{6}' </code></pre> <p>And some C#: </p> <pre><code> using (SqlConnection connection = new SqlConnection(connString)) { connection.Open(); for (int i = 0; i &lt; arraySize; ++i) { string updateString = string.Format(updateString2, GetRandomSurname(), GetRandomForeName(), GetRandomAddress1(), GetRandomAddress2(), GetRandomAddress3(), "", ids[i]); SqlCommand cmd = new SqlCommand(updateString, connection); cmd.CommandType = CommandType.Text; cmd.ExecuteNonQuery(); } } </code></pre> <p>The latter method also taking upwards of 14 minutes.</p> <p>Any ideas on how to cut down the time it takes to update the table?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T14:22:12.843", "Id": "24337", "Score": "3", "body": "Just a note:\nwhat you call a \"parametrised query\" is not actually it. In parametrised query you refer to parameters like @id, and add SqlParameter objects when running, not use string.Format." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T14:46:00.213", "Id": "24341", "Score": "1", "body": "To add to @ElDog's comment, using actual parametrized queries is a good idea, using `string.Format()` this way is not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T18:08:19.630", "Id": "24351", "Score": "1", "body": "Additionally, using a real parameterized query is likely to cause a significant speed-up, because SQL will only have to calculate the execution plan the first time it is run. With string.Format building, it has to re-calculate every time the values change. Parsing the query in this case is likely to be the most expensive step of executing the query." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T10:39:12.453", "Id": "24508", "Score": "0", "body": "Just as an update to this, I have tried using parameterised queries(correctly) but have come into the issue of only being allowed a max of 2100 queries per execution, I have tried to get around this by breaking it up into seperate queries but I couldn't get it to work. Will post code later. Thanks for replies." } ]
[ { "body": "<p>indexes! Index on new_id. </p>\n\n<p>You say you're using temp tables, so I assume you're populating them all at once. Do a update statistics after you fill them.</p>\n\n<p>Finally, why cant you say something like this?</p>\n\n<pre><code> select firstName from tmp_ForeNames where new_id = getNewId()\n</code></pre>\n\n<p>order by takes time so you should avoid it if possible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T14:37:43.293", "Id": "14990", "ParentId": "14980", "Score": "2" } }, { "body": "<p>Not sure what that <code>ORDER BY (SELECT new_id from GetNewID)</code>, but comparing the following approaches, second is much faster and spends most of the time in COUNT(*), which could be pre-calculated.</p>\n\n<pre><code>SELECT TOP 1 name FROM master.sys.all_objects ORDER BY NEWID()\n\nDECLARE @n int\nSELECT @n = RAND() * (SELECT COUNT(*) FROM master.sys.all_objects)\n\nSELECT name FROM (\n SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as n, name\n FROM master.sys.all_objects\n) AS names\nWHERE n = @n\n</code></pre>\n\n<p>I guess you could make it even faster by materializing integer sequential <code>id</code> inside your names tables and making a clustered index on that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T09:22:34.363", "Id": "15761", "ParentId": "14980", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T09:43:41.497", "Id": "14980", "Score": "3", "Tags": [ "c#", "sql", "sql-server", "winforms" ], "Title": "Any way to speed up this UPDATE?" }
14980
<p>I'm starting Rails and Ruby for a short time. But I try to make it the cleanest way I can. So, in an attempt to clean my view, I try to custom my <code>FormBuilder</code>:</p> <pre><code># /config/initializers/custom_form_builder.rb class ActionView::Helpers::FormBuilder # My test form function def test label return "Whatever I want to do ..." end end </code></pre> <p>And then I can use it like this:</p> <pre><code># /app/views/test/test.html.erb ... &lt;%= form_for test, :html =&gt; {:multipart =&gt; true} do |f| %&gt; ... &lt;%= f.test(":-)") %&gt; ... &lt;% end %&gt; ... </code></pre> <p>This part works perfectly fine. However, what I want to do know is how to create form views containing the HTML code that I want to use in my forms. This way, I can store the HTML of all my form in a pseudo-HTML way, and structured within my directories.</p> <p>So, I've created a template:</p> <pre><code># /app/views/forms/test.html.erb &lt;input type="text" value="test" /&gt; </code></pre> <p>And I've tried to render it from my <code>FormBuilder</code>:</p> <pre><code># /config/initializers/custom_form_builder.rb def test label render "forms/test" end </code></pre> <p>And I added it to my routes:</p> <pre><code># /config/routes.rb match "/forms/test" =&gt; "forms#test" </code></pre> <p>My questions:</p> <ol> <li>Do I try to make it work the wrong way?</li> <li>Is it possible to render from my <code>FormBuilder</code> class?</li> <li>Is there some useless code in there?</li> </ol>
[]
[ { "body": "<p>I made it a different way. But, the answer was quite simple.</p>\n\n<p>The class ActionView::Helpers::FormBuilder inherit of the @template attribute.</p>\n\n<p>And to render my partials, I just need to call it this way :</p>\n\n<pre><code>def test label\n @template.render \"/forms/test\"\nend\n</code></pre>\n\n<p>Then you can use the partial as specified on <a href=\"http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials\" rel=\"nofollow\">RoR Guides</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T11:29:09.023", "Id": "15098", "ParentId": "14981", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T09:59:06.013", "Id": "14981", "Score": "2", "Tags": [ "ruby", "ruby-on-rails", "erb" ], "Title": "Custom FormBuilder" }
14981
<p>I am using the following code to compare 2 images:</p> <p>HTML (for example use only):</p> <pre><code>&lt;canvas id="gViewCanvas"&gt;&lt;/canvas&gt; &lt;img id="image1" src="image1.png" /&gt; &lt;img id="image2" src="image2.png" /&gt; </code></pre> <p>Javascript:</p> <pre><code>var gOldImage = document.getElementById("image1"); var gScreenImage = document.getElementById("image2"); var gViewCanvas = document.getElementById("gViewCanvas"); var gViewContext = gViewCanvas.getContext('2d'); var gGridSizeX = 1920; var gGridSizeY = 32; var nrX = Math.round(1920 / gGridSizeX); var nrY = Math.round(955 / gGridSizeY); gPixelCount = (gGridSizeX * gGridSizeY) * 4; function compareImages(img1, img2, pixelCount) { for (var i = 0; i &lt; pixelCount; ++i) { if (img1.data[i] !== img2.data[i]) { return false; } } return true; } var data, data2, BMPData, xpos, ypos, encoded, y, x; //Iterate through lines of the image (width x 32) for (y = 0; y &lt; nrY; y++) { for (x = 0; x &lt; nrX; x++) { xpos = x * gGridSizeX; ypos = y * gGridSizeY; //draw both sextions of images to the canvas and store pixel data in variables: data and data2 gViewContext.drawImage(gOldImage, xpos, ypos, gGridSizeX, gGridSizeY, 0, 0, gGridSizeX, gGridSizeY); data = gViewContext.getImageData(0, 0, gGridSizeX, gGridSizeY); gViewContext.drawImage(gScreenImage, xpos, ypos, gGridSizeX, gGridSizeY, 0, 0, gGridSizeX, gGridSizeY); data2 = gViewContext.getImageData(0, 0, gGridSizeX, gGridSizeY); if (!compareImages(data, data2, gPixelCount)) { console.log("images are different"); }else{ console.log("same"); } } } </code></pre> <p>​ I am looking for any speed increases possible please.</p> <p>I have already tested things such as:</p> <ul> <li>Methods of getting data from the canvas (toDataURL etc) </li> <li>different grid sizes (width * X is the faster than 32x32 etc) </li> <li>Drawing each image onto the canvas only once rather that inside the for loop (takes longer as canvas is bigger)</li> </ul> <p>Any obvious things i've missed?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T14:31:16.763", "Id": "24338", "Score": "1", "body": "FYI, If you draw an image on a canvas from a different domain than your own, you can't use `getImageData`. In short, this code will not work if you change `image1.png` to `http://www.google.com/logo.png` (unless this script were to be run from `www.google.com`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T14:54:49.343", "Id": "24342", "Score": "0", "body": "Yep thanks. In reality, I am actually getting a DataURL from a chrome extension, but the principal is the same :)" } ]
[ { "body": "<p>Instead of redrawing and getting new data for every pixel, just draw once and get both data arrays. Next loop through them and check their values:</p>\n\n<pre><code>var c1 = document.getElementById('c1');\nvar c2 = document.getElementById('c2');\nctx1 = c1.getContext('2d');\nctx2 = c2.getContext('2d');\n\nctx1.fillRect(10, 10, 280, 280);\nctx2.fillRect(10, 10, 280, 280);\n\nvar data1 = ctx1.getImageData(0, 0, c1.width, c1.height).data;\nvar data2 = ctx2.getImageData(0, 0, c2.width, c2.height).data;\n\nvar same = true;\n\nfor (var i = 0; i &lt; data1.length; i++) {\n if (data1[i] !== data2[i]) {\n same = false;\n break;\n }\n}\n</code></pre>\n\n<p>Fiddle here: <a href=\"http://jsfiddle.net/SBDfz/1/\">http://jsfiddle.net/SBDfz/1/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T18:58:42.577", "Id": "15001", "ParentId": "14984", "Score": "5" } } ]
{ "AcceptedAnswerId": "15001", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T12:41:25.643", "Id": "14984", "Score": "3", "Tags": [ "javascript", "optimization" ], "Title": "Compare 2 Images" }
14984
<p>I have a List of a custom structure (myStruct) which has two ranges stored in it. I'm trying to write a function where I can figure out if a range is completely enclosed in any of the ranges. Is this optimal and if not how can I improve it in terms of speed and memory efficiency?</p> <pre><code>class myStruct { private int start_one; private int stop_one; private int start_two; private int stop_two; public myStruct(int input_start_one, int input_stop_one, int input_start_two, int input_stop_two) { start_one = input_start_one; stop_one = input_stop_one; start_two = input_start_two; stop_two = input_stop_two; } } public void run() { List&lt;Struct&gt; myStructs = new List&lt;Struct&gt;(); myStructs.Add(new myStruct(86,724,725,1364)); myStructs.Add(new myStruct(86,724,2068,2707)); myStructs.Add(new myStruct(725,1364,2068,2707)); if(is_in_range(88,100)) { // in range } } public bool is_in_range(int in_start, int in_stop, BindingList&lt;myStruct&gt; input_list) { myStruct current_item; for (int i = 0; i &lt; input_list.Count; i++) { current_item = input_list[i]; if ( (in_start &gt;= current_item.start_one &amp;&amp; in_stop &lt;= current_item.stop_one) || (in_start &gt;= current_item.start_two &amp;&amp; in_stop &lt;= current_item.stop_two)) return true; } return false; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T20:58:40.153", "Id": "24334", "Score": "1", "body": "You could improve the *design* by introducing a `Range` type, and following .NET naming conventions." } ]
[ { "body": "<p>Just an idea</p>\n\n<pre><code>public struct Range\n{\n public readonly int From;\n public readonly int To;\n\n public Range(int from, int to)\n {\n From = from;\n To = to;\n }\n\n public bool Contains(Range other)\n {\n return Contains(other.From, other.To);\n }\n\n public bool Contains(int from, int to)\n {\n return From &lt;= from &amp;&amp; To &gt;= to;\n }\n}\n\n\npublic class MyStruct\n{\n public readonly Range Range1;\n public readonly Range Range2;\n\n public MyStruct(Range range1, Range range2)\n {\n Range1 = range1;\n Range2 = range2;\n }\n\n public MyStruct(int from1, int to1, int from2, int to2)\n {\n Range1 = new Range(from1, to1);\n Range2 = new Range(from2, to2);\n }\n\n public bool Contains(Range r)\n {\n return Range1.Contains(r) || Range2.Contains(r);\n }\n\n public bool Contains(int from, int to)\n {\n return Range1.Contains(from, to) || Range2.Contains(from, to);\n }\n}\n</code></pre>\n\n<p>-</p>\n\n<pre><code>List&lt;MyStruct&gt; myStructs = new List&lt;MyStruct&gt;()\n {\n new MyStruct(86, 724, 725, 1364),\n new MyStruct(86, 724, 2068, 2707),\n new MyStruct(725, 1364, 2068, 2707)\n };\n\nbool b = myStructs.Any(r =&gt; r.Contains(88, 100));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T21:18:58.300", "Id": "14986", "ParentId": "14985", "Score": "4" } }, { "body": "<p>Apart from some typos (f.e. <code>List&lt;Struct&gt;</code> instead of <code>List&lt;myStruct&gt;</code>), the conditions in <code>is_in_range</code> are wrong. You want to return <code>false</code> if any of the items are not in the range and not <code>true</code>.</p>\n\n<p>But instead of this method you can also use <a href=\"http://msdn.microsoft.com/en-us/library/bb548541.aspx\" rel=\"nofollow\"><code>Enumerable.All</code></a>:</p>\n\n<pre><code>if (myStructs.All(s =&gt; 88 &gt;= s.start_one &amp;&amp; 88 &gt;= s.start_two \n &amp;&amp; 100 &lt;= s.stop_one &amp;&amp; 100 &lt;= s.stop_two))\n{\n // all in range\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T21:19:30.583", "Id": "14987", "ParentId": "14985", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T20:51:55.173", "Id": "14985", "Score": "2", "Tags": [ "c#", "algorithm" ], "Title": "determining if a range is within array of ranges" }
14985
<p>When <code>git</code> runs my <code>post-receive</code> hook, I'd like it to run all the scripts in the subdirectory <code>post-receive.d</code>.</p> <p>My script is as follows</p> <pre><code>#!/bin/bash SOURCE="${BASH_SOURCE[0]}" DIR="$( dirname "$SOURCE" )" for SCRIPT in $DIR/post-receive.d/* do if [ -f "$SCRIPT" -a -x "$SCRIPT" ] then "$SCRIPT" fi done </code></pre> <p>Source: <a href="https://github.com/alexchamberlain/githooks/blob/master/post-receive" rel="nofollow">https://github.com/alexchamberlain/githooks/blob/master/post-receive</a></p> <p>Is this secure? Reliable?</p> <p>I can foresee one problem. The hook supplies data using <code>stdin</code>, which should be copied to each subscript. I'm pretty sure this isn't happening at the moment. Any ideas?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T19:49:24.860", "Id": "74343", "Score": "0", "body": "`test -x \"$file\"` or `[[ -x \"$file\" ]]` is the only test you need; a file doesn't need to be readable to be executable." } ]
[ { "body": "<pre><code>for SCRIPT in $DIR/post-receive.d/*\n</code></pre>\n\n<p>You might want to limit that to only <code>*.sh</code> pattern, just for clarity.</p>\n\n<p>Personally I'm a fan of the one-line-style, but that's personal preference:</p>\n\n<pre><code>for ITEM in SET; do\nif [ CONDITION ]; then\n</code></pre>\n\n<p>And yes, input from <code>stdin</code> is at the moment ignored completely by your script. Reading from <code>stdin</code> can be done via the <code>read</code> command, like this.</p>\n\n<pre><code>#!/bin/sh\n\n# This whill be our input variable\ninput=\"\"\n\n# Read the first line without adding\n# a new line to the start.\nread input\n\n# Start reading from stdin\nwhile read line; do\n # Concate the input into our variable\n input=$input\"\\n\"$line\ndone\n\n# Echo it...what else?\necho $input\n</code></pre>\n\n<p>After doing that you can pipe the variable into the scripts like this:</p>\n\n<pre><code>echo $INPUT | \"$SCRIPT\"\n</code></pre>\n\n<p><em>One word of warning</em>: I'm not sure if this is BASH only or cross-shell compatible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T11:34:57.207", "Id": "25169", "Score": "3", "body": "Use More Quotes™ and watch out for newlines - `printf %s \"$input\" | \"$SCRIPT\"`. Your `while` loop will drop the last line of input if it's not followed by a newline and treats backslashes specially - `while IFS=$'\\n' read -r line || [[ -n \"$line\" ]]; do`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-08T20:33:57.133", "Id": "15440", "ParentId": "14988", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T13:24:56.053", "Id": "14988", "Score": "2", "Tags": [ "security", "bash", "shell", "git" ], "Title": "Run all scripts in a sub-directory" }
14988
<p>The domain model of my application revolves around movies.</p> <p>Use case:</p> <p>We have a movie for which only one title (in one country) is known and we want to know titles of this movie in other countries. To get that information, we call external movie repositories.</p> <p>The <code>Movie</code> class has a map of titles in countries. It also has a list of external IDs. For example, we might know that IMDB's ID for the movie <em>Breakfast at Tiffany's</em> is <em>tt0054698</em>.</p> <pre><code>class Movie { private Map&lt;Country, String&gt; titles; private Year yearOfRelease; private Map&lt;ExternalMovieRepository, String&gt; externalIds; public Map&lt;Country, String&gt; titles() { return titles; } public Year yearOfRelease() { return yearOfRelease; } public Map&lt;ExternalMovieRepository, String&gt; externalIds() { return externalIds; } } </code></pre> <p>The <code>ExternalMovieRepository</code> <code>enum</code> is used as a key to which external ID value is mapped.</p> <pre><code>enum ExternalMovieRepository { IMDB, ROTTEN_TOMATOES; } </code></pre> <p>The classes representing the external movie repositories will be able to find additional information only for <code>Movie</code> instances carrying some information the repository requires.</p> <p>For example, <code>RottenTomatoesMovieRepository</code> requires the Movie instance either to have a US movie title (<code>&lt;Country, String&gt;</code> map entry) or the Rotten Tomatoes' external ID in its <code>externalId</code>s map.</p> <p>Here is a draft for an interface that could represent the external repositories:</p> <pre><code>/** * Finds movie title for other countries using information from Movie. * */ interface MovieTitleFinder { boolean accepts( Movie m ); Map&lt;Country, String&gt; findTitles( Movie m ); } </code></pre> <p>An implementation could look like this:</p> <pre><code>class RottenTomatoesTitleFinder implements MovieTitleFinder { private final String US_ISO = "us"; private CountryRepository countryRepository; RottenTomatoesTitleFinder( CountryRepository countryRepository ) { this.countryRepository = countryRepository; } @Override public boolean accepts( Movie m ) { return ( getUSTitle( m ) != null || getRTId( m ) != null ); } @Override public Map&lt;Country, String&gt; findTitles( Movie m ) { String rtId = getRTId( m ); if ( rtId != null ) { return findByRTid( rtId ); } String usTitle = getUSTitle( m ); if ( usTitle != null ) { return findByUSTitle( usTitle ); } return Collections.emptyMap(); } private String getUSTitle( Movie m ) { Country us = countryRepository.findByIso( US_ISO ); return ( m.titles().get( us ) ); } private String getRTId( Movie m ) { return ( m.externalIds().get( ExternalMovieRepository.ROTTEN_TOMATOES ) ); } private Map&lt;Country, String&gt; findByUSTitle( String usTitle ) { // call some collaborating object } private Map&lt;Country, String&gt; findByRTid( String rtId ) { // call some collaborating object } } </code></pre> <p>Could this design be improved?</p>
[]
[ { "body": "<p>One thing - this design is based on a false premise - that there is only ever a single title within a given country. See for example <a href=\"http://www.imdb.com/title/tt0216216/releaseinfo\">this movie</a> which has 3 USA titles (albeit only one, final, official title). This can be fixed by changing the <code>Country</code> key of the hash map to a <code>TitleType</code> (which will often be just a country).</p>\n\n<p>Another problem is that <code>Movie</code> isn't really an object - it doesn't implement any member functions. In fact, your <code>RottenTomatoesTitleFinder</code> works by directly manipulating <code>Movie</code> properties rather than calling <code>Movie</code> member functions. This is a violation of basic <a href=\"http://codebetter.com/raymondlewallen/2005/07/19/4-major-principles-of-object-oriented-programming/\">OO principles</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T18:46:40.830", "Id": "24353", "Score": "0", "body": "Good point abouth the non-uniqueness of titles. I have added the accessors. Since I don't use the getX convention, I should have typed them out before. But I suppose that encapsulation is still breached the same as the Movie class just hands over its internals (the two maps)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T19:55:35.883", "Id": "24357", "Score": "1", "body": "@stoupa - Instead of returning the maps, provide accessors such as `Movie.getTitle(Country)`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T16:28:38.100", "Id": "14995", "ParentId": "14993", "Score": "7" } } ]
{ "AcceptedAnswerId": "14995", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T16:06:26.893", "Id": "14993", "Score": "8", "Tags": [ "java", "object-oriented" ], "Title": "Movie repository for storing movies based on country" }
14993
<pre><code>String fileId = "CPP420.A2_2012072416244467745"; String reg1 = "CPP350"; String reg2 = "CPP420.A1"; String reg3 = "CPP420.A2"; String country = ""; if(fileId.startsWith(reg1)) { country = "CA"; } else if(fileId.startsWith(reg2)) { country = "US"; } else if(fileId.startsWith(reg3)) { country = "FR"; } else { System.out.println("Error invalid file"); } </code></pre> <p>OR</p> <pre><code>String country = fileId.startsWith(reg1) ? "CA" : ""; country = fileId.startsWith(reg2) ? "US" : ""; country = fileId.startsWith(reg3) ? "FR" : ""; if("".equals(country)) { System.out.println("No country found"); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T23:16:36.533", "Id": "24416", "Score": "1", "body": "If \"CA\" is 'California' (the US State), you have a bigger problem - you're mixing your domains." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-20T21:25:08.217", "Id": "25664", "Score": "1", "body": "Country CA = Canada" } ]
[ { "body": "<p>Neither. Note: haven't tried this in and IDE, but you should be able to get the idea.</p>\n\n<pre><code>interface RegionID {\n boolean isRegionMatch(String fileID);\n String getRegionCode();\n}\n\nclass SimpleMatchRegionID implements RegionID {\n private String regionPrefix;\n private String regionCode;\n\n public SimpleMatchRegionID(String regionPrefix, String regionCode) {\n this.regionPrefix = regionPrefix;\n this.regionCode = regionCode;\n }\n\n public boolean isRegionMatch(String fileID) {\n return fileID.startsWith(regeionPrefix);\n }\n\n public String getRegionCode() {\n return regionCode;\n }\n}\n\nRegionID us = new SimpleMatchRegionID(\"CPP420.A1\", \"US\");\nRegionID ca = new SimpleMatchRegionID(\"CPP350\", \"CA\");\nRegionID fr = new SimpleMatchRegionID(\"CPP350\", \"FR\");\nRegionID[] regions = {us, ca, fr};\n\npublic String findRegionCode(String fileID) {\n for (i = 0; i &lt; regions.length; i++) {\n if (regions[i].isRegionMatch(fileID)) {\n return regions[i].getRegionCode();\n }\n }\n\n return \"\";\n}\n</code></pre>\n\n<p>An implementation like this would allow you to load the <code>regions</code> array from a data file, or with some other run-time mechanism. It would also allow you to implement other strategies for recognizing a region that doesn't follow the same basic pattern.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T18:28:25.073", "Id": "15000", "ParentId": "14997", "Score": "18" } }, { "body": "<p>You can improve the code even without a separate class in the case that you don't need other detection mechanisms. The following will allow you to easily add new prefixes but nothing more.</p>\n\n<pre><code>String fileId = \"CPP420.A2_2012072416244467745\"; \nMap&lt;String,String&gt; countriesByPrefix = new HashMap&lt;&gt;() {{\n put(\"CPP350\", \"CA\");\n put(\"CPP420.A1\", \"US\");\n put(\"CPP420.A2\", \"FR\");\n}};\nString country = null;\nfor (Map.Entry&lt;String,String&gt; entry : countriesByPrefix.entrySet()) {\n if (fileId.startsWith(entry.getKey()) {\n country = entry.getValue();\n break;\n }\n}\nif (country == null) {\n System.out.println(\"Error invalid file\");\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T20:04:25.213", "Id": "15007", "ParentId": "14997", "Score": "13" } }, { "body": "<p>If you can use Java 7, you can put Strings in switch statements (this came with JSR334):</p>\n\n<pre><code>String fileId = \"CPP420.A2_2012072416244467745\"; \nString country = \"\"; \nString fileReg = fileId.split(\"_\")[0]; \nswitch(fileReg) {\n case \"CPP350\" : country = \"CA\"; break; \n case \"CPP420.A1\" : country = \"US\"; break;\n case \"CPP420.A2\" : country = \"FR\"; break;\n default : System.out.println(\"Error invalid file\"); \n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T20:51:04.437", "Id": "24361", "Score": "0", "body": "Actually, that's kind of cool. Although it still has all of the disadvantages that prompted http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T20:42:59.067", "Id": "15010", "ParentId": "14997", "Score": "11" } }, { "body": "<p>I already see some good/better solutions here but what I am missing is an example which uses the famous(?) java <strong>ENUM</strong>'s</p>\n\n<pre><code>public enum Country {\n CA, US, FR;\n}\n\npublic enum FileType {\n CPP350(\"CPP350\", Country.CA),\n CPP420_A1(\"CPP420.A1\", Country.US),\n CPP420_A2(\"CPP420.A2\", Country.FR);\n\n private final String fileId;\n private final Country country;\n\n private FileType(final String fileId , final Country country) {\n this.fileId = fileId;\n this.country = country;\n }\n\n public Country getCountry() {\n return country;\n }\n\n public static FileType match( final String fileId ) {\n for ( final FileType fileType : values() ) {\n if ( fileId.startsWith( fileType.fileId ) ) {\n return fileType;\n }\n }\n return null;\n }\n}\n</code></pre>\n\n<p>And the below code should help you to get your desired country for the given fileId.</p>\n\n<pre><code>final Country country = FileType.match( fileId ).getCountry();\n</code></pre>\n\n<p><strong>Note:</strong> As you can see that there is a possibility for NullPointerException if no match found. But I believe it should be handled as part of the implementation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T09:30:09.570", "Id": "24506", "Score": "0", "body": "+1 The more secure way if you add : `XX` as \"unkoown contry\" and `return Contry.XX` instead of `null` - Implementation can test `if((Contry) return == Contry.XX) {..` - - - change also your enum in an Enum Class http://docs.oracle.com/javase/6/docs/api/java/lang/Enum.html ; see also samples in /Effective%20Java%20-%20Programming%20Language%20Guide.pdf)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T06:15:16.000", "Id": "15057", "ParentId": "14997", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T17:26:00.760", "Id": "14997", "Score": "14", "Tags": [ "java" ], "Title": "Country selector: if or ternary?" }
14997
<p>I have recently started a project of SIMD libraries development for C++ on FASM for x86-64 Linux. I would be glad to hear any opinion or feedback about the project, cleanness of the code and documentation. Here is the project's <a href="http://linasm.sourceforge.net/docs/index.php" rel="nofollow">web site</a> on SourceForge.</p> <p>This is just a fragment of code (addition of two vectors) and some kind of comments next to asm directives.</p> <pre><code>;==============================================================================; ; Binary operations ; ;==============================================================================; macro SCALAR op, x { ;---[Parameters]--------------------------- array equ rdi ; pointer to array size equ rsi ; array size (count of elements) value equ xmm0 ; value to process with ;---[Internal variables]------------------- temp equ xmm1 ; temp value if x eq s bytes = 4 ; array element size (bytes) else bytes = 8 ; array element size (bytes) end if step = 16 / bytes ; step size (in bytes) ;------------------------------------------ sub size, step ; size -= step jb .sclr ; if (size &amp;lt step) then skip vector code clone_flt value, x ; Duplicating value through the entire register ;---[Vector loop]-------------------------- @@: movup#x temp, [array] ; temp = array[0] op#p#x temp, value ; do operation to temp value movup#x [array], temp ; array[0] = temp add array, 16 ; array++ sub size, step ; size -= step jae @b ; do while (size &amp;gt;= step) ;------------------------------------------ .sclr: add size, step ; size += step jz .exit ; If no scalar code is required, then exit ;---[Scalar loop]-------------------------- @@: movs#x temp, [array] ; temp = array[0] op#s#x temp, value ; do operation to temp value movs#x [array], temp ; array[0] = temp add array, bytes ; array++ dec size ; size-- jnz @b ; do while (size != 0) 1 ;------------------------------------------ .exit: ret } ;::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: macro VECTOR op, x { ;---[Parameters]--------------------------- target equ rdi ; pointer to target array source equ rsi ; pointer to source array size equ rdx ; array size (count of elements) ;---[Internal variables]------------------- value equ xmm0 ; value to process with temp equ xmm1 ; temp value if x eq s bytes = 4 ; array element size (bytes) else bytes = 8 ; array element size (bytes) end if step = 16 / bytes ; step size (in bytes) ;------------------------------------------ sub size, step ; size -= step jb .sclr ; if (size &amp;lt step) then skip vector code ;---[Vector loop]-------------------------- @@: movup#x value, [source] ; value = source[0] movup#x temp, [target] ; temp = target[0] op#p#x temp, value ; do operation to temp value movup#x [target], temp ; target[0] = temp add source, 16 ; source++ add target, 16 ; target++ sub size, step ; size -= step jae @b ; do while (size &amp;gt;= step) ;------------------------------------------ .sclr: add size, step ; size += step jz .exit ; If no scalar code is required, then exit ;---[Scalar loop]-------------------------- @@: movs#x temp, [target] ; temp = target[0] op#s#x temp, [source] ; do operation to temp value movs#x [target], temp ; target[0] = temp add source, bytes ; source++ add target, bytes ; target++ dec size ; size-- jnz @b ; do while (size != 0) ;------------------------------------------ .exit: ret } ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~; ; Addition ; ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~; ; Scalar addition AddS_flt32: SCALAR add, s AddS_flt64: SCALAR add, d ; Vector addition AddV_flt32: VECTOR add, s AddV_flt64: VECTOR add, d </code></pre> <p>I need feedback on style of code writing and readability of comments for most programmers. Or I need cleaner style for code and its description.</p> <p>Because this is a piece of program from big open source project, it should be human-readable. And I just need some kind of critique and proposition from other programmers.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T20:52:04.007", "Id": "24634", "Score": "0", "body": "For people, who would like to see the library speed, I made a simple performance testing page with graphics. I compare LinAsm algorithms with their GNU libc analogs. \nHere is the [link](http://linasm.sourceforge.net/about/performance.php) to LinAsm performance tests." } ]
[ { "body": "<pre><code>array equ rdi ; pointer to array\nsize equ rsi ; array size (count of elements)\nvalue equ xmm0 ; value to process with\n</code></pre>\n\n<p>I don't particularly care for these. It seems like you're trying to make the code look more like a high-level language, <em>but</em> it seems to me that it ends up neither fish no fowl; it loses readability for those accustomed to assembly language without seeming to really gain much (if anything) for those accustomed to higher level languages.</p>\n\n<pre><code>temp equ xmm1 ; temp value\nif x eq s\nbytes = 4 ; array element size (bytes)\nelse\nbytes = 8 ; array element size (bytes)\nend if\nstep = 16 / bytes ; step size (in bytes)\n</code></pre>\n\n<p>I think I'd write this something more like:</p>\n\n<pre><code>chunk_size = 16\nif x eq s\nelement_size = 4\nelse\nelement_size = 8\nend if\nstep_size = chunk_size / element_size\n</code></pre>\n\n<hr>\n\n<pre><code>;---[Vector loop]--------------------------\n</code></pre>\n\n<p>At least in my opinion, <code>@@</code> labels should be reserved for times when the meaning is exceptionally obvious. Preceding an <code>@@:</code> with a comment describing its meaning indicates that you'd probably be better off with a normal label in this case.</p>\n\n<p>With those, your code would come out closer to:</p>\n\n<pre><code> sub rsi, step_size ; size -= step\n jb .sclr ; if (size &amp;lt step) then skip vector code\n clone_flt xmm0, x ; Duplicate value through entire register\n\nvector_loop:\n movup#x xmm1, [rdi] ; temp = array[0]\n op#p#x xmm1, xmm0 ; do operation to temp value\n movup#x [rdi], xmm0 ; array[0] = temp\n add rdi, chunk_size ; array++\n sub rsi, step_size ; size -= step\n jae vector_loop ; do while (size &amp;gt;= step)\n;------------------------------------------\n.sclr: add size, step ; size += step\n jz .exit ; If no scalar code is required, then exit\nscalar_loop:\n movs#x xmm1, [rdi] ; temp = array[0]\n op#s#x xmm1, xmm0 ; do operation to temp value\n movs#x [rdi], temp ; array[0] = temp\n add rdi, element_size ; array++\n dec rsi ; size--\n jnz scalar_loop ; do while (size != 0)\n</code></pre>\n\n<p>The code itself is <em>quite</em> nicely done, especially doing subtraction before the main loop to avoid a <code>cmp</code> before the <code>jmp</code> in the main loop. Kudos!</p>\n\n<p>I can only make a couple of possible suggestions about the code itself:</p>\n\n<ol>\n<li><p>issuing some prefetch instructions if/when rsi is greater than a few hundred or so (but maybe it never is for your uses). Prefetching can be a little difficult to get right, and this is a simple linear pattern, so the prefetch hardware may well be perfectly adequate to the job.</p></li>\n<li><p>unrolling a few iterations of the loop--but then again, especially for simple instructions, it may be memory bound already and unrolling would just make the code bigger (and pollute more code cache) with little or no speed gain to compensate.</p></li>\n</ol>\n\n<p>Neither of these has any real certainty of improvement, but if you're feeling adventurous some day, they might be worthy of a little experimentation (if you haven't already).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-11T20:52:44.953", "Id": "44102", "ParentId": "14998", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T17:56:33.030", "Id": "14998", "Score": "7", "Tags": [ "linux", "library", "assembly", "sse", "simd" ], "Title": "Writing SIMD libraries for C++ on FASM in x86-64 Linux" }
14998
<p>I neglected <code>java.nio</code> package in the past and now I am wondering if this is the best way to copy everything from a <code>Readable</code> to an <code>OutputStream</code>:</p> <pre><code>public static void copy(@Nonnull Readable src, @WillNotClose @Nonnull OutputStream dest, @Nullable Charset targetCharset) throws IOException { targetCharset = safeCharset(targetCharset); CharBuffer buf = CharBuffer.allocate(CHAR_BUF_SIZE); ByteBuffer byteBuffer = null; WritableByteChannel outChannel = Channels.newChannel(dest); while (src.read(buf) != -1) { buf.flip(); byteBuffer = targetCharset.encode(buf); outChannel.write(byteBuffer); buf.clear(); } } </code></pre> <h2>General</h2> <p>Is this the best way to do it? Am I missing something? What should I do to improve this code?</p> <h2>Closing the channel or not</h2> <p>I wonder if I must/should close the channel created by <code>Channels.newChannel(dest)</code>? From the general contract of my class the caller of this method here is responsible for closing the provided OutputStream, because every resource should be closed where it was created. It's bad that closing the channel also closes the underlying stream, too. </p> <p>On the other hand not closing the channel relies on undocumented implementation details of <code>Channels$WritableByteChannelImpl</code> where calling <code>close()</code> is just a delegate to the underlying stream and setting a close flag.</p> <p>I do not want to break my general contract and I do not want to rely on undocumented implementation details.</p> <p>The third option is most probably the best and addressing the source of the problem: Write the content directly to the OutputStream without using a channel or any other wrapper around it which must be closed then. But I could not figure out how to achieve this.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T07:53:09.053", "Id": "24371", "Score": "0", "body": "It seems you forgot `.flush()` - have a look in new Java7 package nio.2 : http://docs.oracle.com/javase/tutorial/essential/io/fileio.html, very useful when Java7 will be in production state" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T08:44:57.407", "Id": "24373", "Score": "0", "body": "Thanks for the link. I'll look into it right now. I do not forgot flush - it's not my job to flush here. I should have mentioned that this is a utility method like the ones you find in Apache `IOUtils` or Google Guava `Files`, `CharStreams` and `ByteStreams` classes. Callers of these methods expect the provided streams to be not flushed and not closed. It's caller's responsibility." } ]
[ { "body": "<p>Well, last night I came up with that. I am pretty satisfied with it right now but would be happy to see if I am still missing something.</p>\n\n<p>This solution does not rely on implementation details any more and provided streams are left open as the general contract demands it. </p>\n\n<pre><code>public static void copy(@Nonnull Readable src, @Nonnull @WillNotClose OutputStream dest, @Nullable Charset destCharset) throws IOException {\n CharBuffer charBuf = CharBuffer.allocate(CHAR_BUF_SIZE);\n\n while (src.read(charBuf) != -1) {\n charBuf.flip();\n copy(charBuf, dest, destCharset);\n charBuf.clear();\n }\n}\n\n\npublic static void copy(@Nonnull CharBuffer src, @Nonnull @WillNotClose OutputStream dest, @Nullable Charset destCharset) throws IOException {\n copy(safeCharset(destCharset).encode(src), dest);\n}\n\n\npublic static void copy(@Nonnull ByteBuffer src, @Nonnull @WillNotClose OutputStream dest) throws IOException {\n int len = src.remaining();\n int totalWritten = 0;\n byte[] buf = new byte[0];\n\n while (totalWritten &lt; len) {\n int bytesToWrite = Math.min((len - totalWritten), BYTE_BUF_SIZE);\n\n if (buf.length &lt; bytesToWrite) {\n buf = new byte[bytesToWrite];\n }\n\n src.get(buf, 0, bytesToWrite);\n dest.write(buf, 0, bytesToWrite);\n totalWritten += bytesToWrite;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T08:57:39.320", "Id": "15021", "ParentId": "15002", "Score": "1" } } ]
{ "AcceptedAnswerId": "15021", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T19:16:54.467", "Id": "15002", "Score": "5", "Tags": [ "java" ], "Title": "Any better way to copy from Readable to OutputStream?" }
15002
<p>I'm looking for code correctness and improvements for the following code. It's my first step into class based programing.</p> <p>What the class does, is simply to read a directory (path is passed as constructor argument) and find all sub directories matched by the search pattern. Then it returns a random directory (strimg) based on the result set.</p> <p>I assuming this directory structure:</p> <h2>Directory structure</h2> <pre><code>backend img kombi-1 kombi-2 kombi-3 </code></pre> <h2>PHP</h2> <pre><code>/** * RandomImages * * This class reads based on the passed argument, all directories * matched by the pattern ($pattern) and returns a random path * from the result. */ class RandomImages { private $array; private $path; private $pattern = "/kombis/*"; /** * __construct function. * * @access public * @param mixed $path */ public function __construct($location) { $this-&gt;location = $this-&gt;cleanLocation($location); } /** * getDirectories function. * * Return an array of directories matched by $pattern * * @access private * @return array */ private function getDirectories(){ return glob( $this-&gt;location . $this-&gt;pattern , GLOB_ONLYDIR ); } /** * getRandomKey function. * * @access private * @return int */ private function getRandomKey() { $array = $this-&gt;getDirectories(); return array_rand($array, 1); } /** * cleanLocation function. * * Remove safely the last / * * @access private * @param mixed $string * @return string */ private function cleanLocation($string) { return rtrim($string, '/'); } /** * getRandomPath function. * * @access public * @return string */ public function getRandomPath() { $array = $this-&gt;getDirectories(); return $array[$this-&gt;getRandomKey()]; } } // Init $path = new RandomImages('./backend/img'); // Save path to prevent false combinations $randomPath = $path-&gt;getRandomPath(); // Build link and store string $pattern = $randomPath . '/pattern.png'; $curtain = $randomPath . '/curtain.png'; </code></pre> <h1>UPDATED CLASS</h1> <pre><code>&lt;?php /** * RandomImages * * This class reads based on the passed argument, all directories * matched by the pattern ($pattern) and returns a random path * from the result. */ class RandomImages { /** * Basepath * * @var string Trailing slash is stripped */ private $location; /** * __construct * * @param string $path */ public function __construct($location) { $this-&gt;location = $this-&gt;stripTrailingSlash($location); } /** * setPattern * * @return void */ public function setPattern($pattern) { $this-&gt;pattern = $pattern; } /** * getPattern. * * @return string */ public function getPattern() { return $this-&gt;pattern; } /** * getDirectories * * Returns an array of directories matched by setPattern() * * @return array */ private function getDirectories(){ return glob( $this-&gt;location . $this-&gt;pattern , GLOB_ONLYDIR ); } /** * stripTrailingSlash * * Remove safely the last / * * @param mixed $string * @return string */ private function stripTrailingSlash($string) { return rtrim($string, '/'); } /** * getRandomPath * * @return string */ public function getRandomPath() { $array = $this-&gt;getDirectories(); return $array[array_rand($array, 1)]; } } // Init $path = new RandomImages('./backend/img/kombis'); $path-&gt;setPattern('/kombi*'); </code></pre>
[]
[ { "body": "<p>While not a problem, you aren't using the <code>$path</code> and <code>$array</code> properties and should remove them. You must call <code>getRandomPath</code> to get the actual path from the object.</p>\n\n<pre><code>$randomImages = new RandomImages('./backend/img');\n$path = $randomImages-&gt;getRandomPath();\n</code></pre>\n\n<p>Also, you load the list of directories twice--once to get a random key and again to pull its value. Since you don't expose <code>getRandomKey</code> you may as well move it inside <code>getRandomPath</code>.</p>\n\n<pre><code>public function getRandomPath() {\n $array = $this-&gt;getDirectories();\n return $array[array_rand($array, 1)];\n}\n</code></pre>\n\n<p>Here are a few stylistic pointers as well.</p>\n\n<ul>\n<li>Declare all properties. You are missing a declaration for <code>$location</code> at the top of the class.</li>\n<li>Add PHPDoc comments to properties--even the private ones.\n<br/></li>\n</ul>\n\n<pre>\n/**\n * Base path that must contain the \"kombis\" directory.\n *\n * @var string Trailing slash is stripped\n */\nprivate $location;\n</pre>\n\n<ul>\n<li>Don't bother writing \"&lt;function-name&gt; function.\" as the first line of each function's documentation. It adds nothing, takes up visual space, and will be obvious in the generated documentation.</li>\n<li>Drop the <code>@access</code> attributes as they're inferred from the method declarations.</li>\n</ul>\n\n<p><strong>Update</strong></p>\n\n<ul>\n<li>You're still missing the declaration of <code>$pattern</code>.</li>\n<li>You're not initializing <code>$pattern</code> in the class. What happens if you forget to call <code>setPattern</code>? You could add it as another constructor parameter or assign a default value in the declaration--or both using a parameter default.\n<br/></li>\n</ul>\n\n<pre>\npublic function __construct($location, $pattern = '/kombi*') {\n</pre>\n\n<ul>\n<li>Every method that doesn't return a value can be assumed to return void, however not that assigning that return value to a function will actually assign <code>null</code>. You can omit the <code>@return void</code> unless you want to be really pedantic. :)</li>\n<li><code>setPattern</code> is missing its <code>@param</code> for <code>$pattern</code>.</li>\n<li>If you still wanted to have <code>getRandomKey</code> or you want to call <code>getRandomPath</code> multiple times, you can cache the array of directories in an instance property and reuse it. Just make sure to clear it when the pattern or base path are changed.\n<br/></li>\n</ul>\n\n<pre>\n/**\n * List of directories that match the pattern.\n *\n * @var array null until initialized\n */\nprivate $directories = null;\n\n/**\n * Sets the pattern for loading and clears the cached directories.\n *\n * @param string $pattern appended to $location and passed to glob()\n */\npublic function setPattern($pattern) {\n $this->pattern = $pattern;\n $this->directories = null;\n}\n\n/**\n * Loads the matching directories and caches them for reuse.\n *\n * @return array list of directories that match $pattern\n */\nprivate function getDirectories() {\n if ($this->directories === null) { // make sure to use triple-equals here\n $this->directories = glob( $this->location . $this->pattern , GLOB_ONLYDIR );\n }\n return $this->directories;\n}\n</pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T20:25:21.080", "Id": "24358", "Score": "0", "body": "Thank you for your suggestions. I'm calling getRandomPath() as you can see in my update above. I thought it was not necessary..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T20:39:04.287", "Id": "24360", "Score": "0", "body": "Do you think it's better to exclude the `private $pattern = \"/kombis/*\";` part and inject it somehow in the constructor? It feels wrong to write hardcoded stuff within the class.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T21:58:08.027", "Id": "24364", "Score": "0", "body": "@gearsdigital - Either inject it, add a setter, or make it a constant (`const GLOB_PATTERN = '/kombis/*')." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T18:11:37.817", "Id": "24407", "Score": "0", "body": "Could you please take a look at my updated class above? What are you saying?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T21:14:40.547", "Id": "24412", "Score": "1", "body": "@gearsdigital - Did mseancole's answer address your question? You can read up on [class constants in PHP](http://php.net/manual/en/language.oop5.constants.php). As you have it now you wouldn't need a constant (maybe for the default) since the client can change the pattern." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T09:18:42.897", "Id": "24471", "Score": "0", "body": "Some points of my code are not as elegant as i want. For example the `getRandomPath()`-Method feels somehow dirty, but I think it's fine now. Thanks again for your qualified feedback." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T19:48:14.040", "Id": "24490", "Score": "1", "body": "@gearsdigital - I added a few more items based on your updated code." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T20:22:04.827", "Id": "15009", "ParentId": "15004", "Score": "7" } }, { "body": "<p>A couple of things to add to David's post. Nothing major, he did an excellent job +1</p>\n\n<p>You removed the reference to your <code>$pattern</code> property, but you are still using it. Any properties you are using in a class should ALWAYS be declared. This makes it easier to determine if a property actually belongs to a specific class, or if there were typos. It also ensures that the property is in the right scope. For instance, you wouldn't want a password in the public scope. And eventually this will be required, as I have heard that PHP is decrementing \"default\" scopes. A step forward in my opinion. Also, when initially declaring class properties, you can combine similarly scoped properties. Some people don't like using this method because they think that you can't add doc comments to them, but you can. For example:</p>\n\n<pre><code>private\n /**@var string Trailing slash is stripped*/\n $location,\n\n /**@var string Pattern to file*/\n $pattern = '/kombis/*'\n;\n</code></pre>\n\n<p>Your PHPDoc comments should specify proper parameter types, instead of just using \"mixed\" for everything. I'm assuming these are IDE generated? Mine does the same thing for anything its unsure of, which seems to be everything. Just make sure everything looks right when using any auto generated data. If you have a variable that could be a couple of different things, you can do something along the lines of the following.</p>\n\n<pre><code>* @param string|array $path\n</code></pre>\n\n<p>Now, about those doc comments. This is something I have been noticing more and more people arguing about recently. Some are of the opinion EVERYTHING needs to be documented, and maybe for public API's this is the case, but I think I'm starting to lean more towards the camp that believes only the unobvious should be documented. For instance, I know, or can guess, what <code>getDirectories()</code> does. However, if there is something unobvious about it, say you decide to start using <code>readdir()</code> instead because <code>glob()</code> uses too much memory (which can be a problem), then you should say so in the doc comments. If your code is self documenting, then there really is no need to redundantly document your code. They are a good thing to have, but sometimes they are unnecessary.</p>\n\n<p>This is more a choice of preference, but you don't have to declare a method's return value to a variable if all you are going to be doing is passing it on to something else. Some people find your way better because it makes it easier to read, some the following way because its smaller, honestly, I have no preference, its just whatever mood I'm in at the time, or whatever looks better :)</p>\n\n<pre><code>private function getRandomKey() {\n return array_rand( $this-&gt;getDirectories(), 1 );\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T21:13:11.183", "Id": "24411", "Score": "1", "body": "More great points. For the last point you make about assigning to a local variable, I agree in general. However, in this case the array needs to be used twice to return a random *value* instead of its *key*." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T20:52:28.720", "Id": "15050", "ParentId": "15004", "Score": "4" } } ]
{ "AcceptedAnswerId": "15009", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T19:55:19.270", "Id": "15004", "Score": "5", "Tags": [ "php", "object-oriented", "random", "file-system" ], "Title": "Selecting a random image from a subdirectory" }
15004
<p>I have the following code to split an address string in T-SQL. Excepting the unit number, which is already in its own field, it would affect too much of the application to split the address into different database fields. It's a bit of a long story, but it's also not possible to make it a parameterized query, or to write the equivalent application code in C#. Still, I'm curious if anyone can think of any edge case that would put things into the wrong fields.</p> <p>The only case I've come across is "East End Ave", but even the US Postal Service suggests incorrectly parsing 'East' as a directional (for consistency) (reference: <a href="http://pe.usps.gov/cpim/ftp/pubs/Pub28/pub28.pdf" rel="nofollow noreferrer">very long pdf</a>, search for 'directional', or go to page 233).</p> <p>I'm only worried about Canadian and American addresses, but in Canada, French-style street types before the street name are fair game (e.g. 'Rue Montreal'). For a tie-breaker, I default to the English style (e.g. <a href="https://www.google.com/maps/preview#!q=rue+street" rel="nofollow noreferrer">'Rue Street'</a> is parsed with the name 'Rue' and type 'Street').</p> <p><code>StreetType</code> and <code>StreetDirection</code> are tables which contain street types and street directions, as <code>TypeName</code>/<code>TypeAbbr</code> and <code>DirectionName</code>/<code>DirectionType</code> pairs respectively - I can post the values I've been using there if anyone's curious, but the <code>StreetType</code> is <em>quite</em> long. <code>StreetDirection</code> also includes French directions ('ouest', 'nord', 'sud', 'est', etc.), as well as their equivalents of 'northeast', 'northwest', etc.</p> <pre><code>DECLARE @CivicNum AS NVARCHAR(10) = '' DECLARE @Predir AS NVARCHAR(10) = '' DECLARE @Name AS NVARCHAR(100) = '' DECLARE @Type AS NVARCHAR(15) = '' DECLARE @FrenchType AS NVARCHAR(15) = '' DECLARE @Postdir AS NVARCHAR(10) = '' SET @Name = '123 E Fake St. S' SET @CivicNum = SUBSTRING(@Name, 1, 1) IF ISNUMERIC(@CivicNum) = 1 BEGIN -- will assume an initial integer is a civic number DECLARE @LastSpace AS INTEGER DECLARE @NextSpace AS INTEGER DECLARE @Temp as VARCHAR(15) -- get the first token, and push it into @CivicNum SET @LastSpace = 1 SET @NextSpace = CHARINDEX(' ', @Name) SET @CivicNum = SUBSTRING(@Name, 1, @NextSpace) -- get the next token, to check for a fractional @CivicNum SET @LastSpace = @NextSpace + 1 SET @NextSpace = CHARINDEX(' ', @Name, @LastSpace) SET @Temp = SUBSTRING(@Name, @LastSpace, @NextSpace - @LastSpace) -- assumption: if the token contains a slash, it is a fraction -- for @CivicNum IF CHARINDEX('\\', @Temp) &gt; 0 OR CHARINDEX ('/', @Temp) &gt; 0 SET @CivicNum = @CivicNum + ' ' + @Temp ELSE SET @NextSpace = @LastSpace -- reverse the string to extract type, direction from right SET @Name = REVERSE(SUBSTRING(@Name, @NextSpace, LEN(@Name))) -- get the final token, check if it is a post directional (N, S, E, W) SET @LastSpace = 1 SET @NextSpace = CHARINDEX(' ', @Name) SET @Temp = RTRIM(LTRIM(REVERSE(SUBSTRING(@Name, 1, @NextSpace)))) -- strip period, if one exists IF SUBSTRING(@Temp, LEN(@Temp), 1) = '.' SET @Temp = SUBSTRING(@Temp, 1, LEN(@Temp) - 1) -- check if it exists in the StreetDirection table SELECT @PostDir=DirectionAbbr FROM StreetDirection WHERE UPPER(DirectionName) LIKE UPPER(@Temp) IF NOT (@PostDir LIKE @Temp) -- try abbreviation SELECT @PostDir=DirectionAbbr FROM StreetDirection WHERE UPPER(DirectionAbbr) LIKE UPPER(@Temp) -- if @PostDir was found, get the next token IF NOT (@PostDir LIKE '') BEGIN SET @LastSpace = @NextSpace + 1 SET @NextSpace = CHARINDEX(' ', @Name, @LastSpace + 1) SET @Temp = RTRIM(LTRIM(REVERSE(SUBSTRING(@Name, @LastSpace, @NextSpace - @LastSpace)))) IF SUBSTRING(@Temp, LEN(@Temp), 1) = '.' -- strip period SET @Temp = SUBSTRING(@Temp, 1, LEN(@Temp) - 1) END -- check if the current token is a StreetType SELECT @Type=TypeName FROM StreetType WHERE UPPER(TypeName) LIKE UPPER(@Temp) IF NOT (@Type LIKE @Temp) -- try abbreviation SELECT @Type=TypeName FROM StreetType WHERE UPPER(TypeAbbr) LIKE UPPER(@Temp) -- reverse address again to check for pre-directional and french street type IF NOT (@Type LIKE '') SET @LastSpace = @NextSpace + 1 SET @Name = RTRIM(LTRIM(REVERSE(SUBSTRING(@Name, @LastSpace, LEN(@Name))))) -- get the next token, and check for a pre-directional SET @LastSpace = 1 SET @NextSpace = CHARINDEX(' ', @Name) SET @Temp = RTRIM(LTRIM(SUBSTRING(@Name, 1, @NextSpace))) IF SUBSTRING(@Temp, LEN(@Temp), 1) = '.' -- strip period SET @Temp = SUBSTRING(@Temp, 1, LEN(@Temp) - 1) SELECT @PreDir=DirectionAbbr FROM StreetDirection WHERE UPPER(DirectionName) LIKE UPPER(@Temp) IF NOT (@PreDir LIKE @Temp) -- try abbreviation SELECT @PreDir=DirectionAbbr FROM StreetDirection WHERE UPPER(DirectionAbbr) LIKE UPPER(@Temp) -- if a pre-directional was found, get the next token IF NOT (@PreDir LIKE '') BEGIN SET @LastSpace = @NextSpace + 1 SET @NextSpace = CHARINDEX(' ', @Name, @LastSpace + 1) SET @Temp = RTRIM(LTRIM(SUBSTRING(@Name, @LastSpace, LEN(@Name)))) IF SUBSTRING(@Temp, LEN(@Temp), 1) = '.' -- strip period SET @Temp = SUBSTRING(@Temp, 1, LEN(@Temp) - 1) END -- check for French street type before address, if an -- English street type has not already been found IF (@Type LIKE '') -- only if not already found (prefer English type) BEGIN SELECT @FrenchType=TypeName FROM StreetType WHERE UPPER(TypeName) LIKE UPPER(@Temp) IF NOT (@FrenchType LIKE @Temp) -- try abbreviation SELECT @FrenchType=TypeName FROM StreetType WHERE UPPER(TypeAbbr) LIKE UPPER(@Temp) END -- if @FrenchType was found, get the final remaining token IF NOT (@FrenchType Like '') BEGIN SET @LastSpace = @NextSpace SET @Type = @FrenchType END -- assume it is the street name SET @Name = SUBSTRING(@Name, @LastSpace, LEN(@Name)) SELECT @CivicNum AS CivicNum, @Name AS Address, @Type AS StreetType, @PostDir + @PreDir AS Direction END ELSE SELECT @CivicNum AS CivicNum, @Name AS Address, @Type AS StreetType, @PostDir + @PreDir AS Direction </code></pre> <p>If nothing else, I hope this is a snippet of code someone finds handy! Although they don't particularly apply in my case, <a href="http://www.mjt.me.uk/posts/falsehoods-programmers-believe-about-addresses/" rel="nofollow noreferrer">here is a handy list of address edge cases</a> from <a href="https://codereview.stackexchange.com/users/9357/200-success">@200_success</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T21:32:25.710", "Id": "24362", "Score": "2", "body": "This is probably covered by your French cases but I wanted to point out that in some American cities (San Diego) Spanish names are numerous. Avenida Montuosa, Via San Marco, Caminito Suenos, etc. And you may have spanish directionals as well. \"Paseo del Pueblo Sur\". So it is not just French names that you need to account for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T13:03:41.463", "Id": "24375", "Score": "0", "body": "Interesting! We may not actually be required to fill out American addresses in this same way, but even so it should be fairly simple to add the Spanish types and directionals." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T04:30:50.257", "Id": "24654", "Score": "0", "body": "I can't follow the code, but just wanted to point out that not all US addresses have a \"street type\". My parents once had an address that was something like 20 Fairbanks. That's it, no street, no ave, no blvd, nothing, just Fairbanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T17:12:33.227", "Id": "24681", "Score": "0", "body": "@Donald.McLean Perhaps the most confusing aspect is that I couldn't find a way to find the last occurrence of a character, nor is there a way to split a string into tokens by delimiter. So, I was left to keeping track of the last space, and reversing the whole string to take tokens from the right hand side. Thanks for the comment, though! I think this should still work without a street type." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T12:22:58.900", "Id": "43769", "Score": "0", "body": "I would love to see the reference tables you mention." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-22T15:04:54.267", "Id": "52932", "Score": "1", "body": "@dnix Sorry for the late reply! In case it's still useful: US [Street Types](http://pe.usps.com/text/pub28/28apc_002.htm), [Street Directionals](http://pe.usps.com/text/pub28/28c2_014.htm) Canada [Street Types](http://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp#1423617), [Street Directionals](http://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp#1403220)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-15T20:46:13.793", "Id": "57451", "Score": "3", "body": "I'm curious what the motivation is for trying to decompose an address. [In general](http://www.mjt.me.uk/posts/falsehoods-programmers-believe-about-addresses/), it's an impossible task, though the situation is slightly more sane in the US and Canada." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-15T20:49:17.730", "Id": "57452", "Score": "1", "body": "@200_success One particular government form has split fields, while literally every other situation in our application does not. So, the requirement is currently very specific to not even just Canadian, but to _Ontario_ customers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-15T21:02:25.897", "Id": "57454", "Score": "2", "body": "@200_success That's a great link for edge cases! I doubt most of them will apply in my case, but thanks." } ]
[ { "body": "<p>Reviewing this code is essentially meaningless without a ream of test data to compare against.... and it would be really nice to have a debugger!</p>\n\n<p>The REVERSE operations make keeping track of the data state quite complicated.</p>\n\n<p>In general though, the code is formatted well, though there are a couple of issues:</p>\n\n<ul>\n<li><p>Your first if block <code>IF ISNUMERIC(@CivicNum) = 1</code> has a <code>BEGIN</code>, but I can't see the closing <code>END</code>, which I would have expected to find before the indent-matching <code>ELSE</code> in the second-to-last line. I would assume this is a typo?</p></li>\n<li><p>you have a number of <code>DECLARE</code> instances that are issued inside various other blocks. It is traditional to move all your declare blocks to be the initial part of your t-sql source... I am not certain whether this code-style is relevant though, but <code>DECLARE @LastSpace AS INTEGER</code> and others should be declared at the top.</p></li>\n<li><p>The code is just too much for this area. You need to break it down some more, or find a better algorithm. Tracking the string manipulations is a nightmare, and, frankly, I gave up... which means the code is not well documented, or simply too cumbersome.</p></li>\n</ul>\n\n<p>My recommendations to you (in a priority of sorts):</p>\n\n<ul>\n<li>replace the 1-column system with a pre-parsed data system</li>\n<li>create a separate table with the data columns split, and have a join that your can access to see the fields.</li>\n<li>change the user requirmenets to not need this breakdown.</li>\n<li>Create a CDL User-Defined-Function (C# or something) that does the parse using a more friendly format, perhaps returning the data in tab-separated values.... and then splitting them in the calling SQL.</li>\n<li>go with what you have, it basically works.</li>\n</ul>\n\n<p>Conclusion:</p>\n\n<p>I figure your code is close to right, It may not be worth breaking it. Adding a CDL would be a pain to do, but the code for the parse would be much easier to manage.</p>\n\n<p>My money is on the system-change to store the parsed fields.... ;-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-10T13:07:49.807", "Id": "70938", "Score": "0", "body": "You can do debugging in Microsoft SQL Management Studio - it's really the only reason I was able to keep track of anything. Putting the data into columns instead was considered, it's just that it was a very hard requirement for a very small percentage of customers. Fixed the missing `END`, thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-10T06:00:25.160", "Id": "41311", "ParentId": "15012", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T21:20:45.183", "Id": "15012", "Score": "7", "Tags": [ "sql", "parsing", "sql-server", "t-sql" ], "Title": "Splitting an address into fields in SQL" }
15012
<p>I've seen few ways of processing forms with PHP. Whenever I am working with a form, I typically have two files: one for displaying the information (e.g. form.php) and the other for processing information (e.g. process_form.php). The latter uses sessions and simply redirects to the appropriate page depending on if the information submitted has been validated correctly or not. Below is a simple example of how I normally do things.</p> <p><strong>Form.php</strong></p> <pre><code>&lt;form name="form" action="process_form.php" method="POST"&gt; &lt;? $field = 'name'; ?&gt; &lt;label for="&lt;?= $field ?&gt;"&gt;What is your name?&lt;/label&gt; &lt;input type="text" id="&lt;?= $field ?&gt;" name="&lt;?= $field ?&gt;" value="&lt;?= !isset($_SESSION['form'][$field]) ? $_SESSION['form'][$field] : '' ?&gt;" maxlength="60" /&gt; &lt;? if (!isset($_SESSION['errors'][$field])) { ?&gt; &lt;label class="error" for="&lt;?= $field ?&gt;"&gt;&lt;?= $_SESSION['errors'][$field] ?&gt;&lt;/label&gt; &lt;? } ?&gt; &lt;? $field = 'age'; ?&gt; &lt;label for="&lt;?= $field ?&gt;"&gt;What is your age?&lt;/label&gt; &lt;input type="text" id="&lt;?= $field ?&gt;" name="&lt;?= $field ?&gt;" value="&lt;?= isset($_SESSION['form'][$field]) ? $_SESSION['form'][$field] : '' ?&gt;" maxlength="2" /&gt; &lt;? if (isset($_SESSION['errors'][$field])) { ?&gt; &lt;label class="error" for="&lt;?= $field ?&gt;"&gt;&lt;?= $_SESSION['errors'][$field] ?&gt;&lt;/label&gt; &lt;? } ?&gt; &lt;? $field = 'email'; ?&gt; &lt;label for="&lt;?= $field ?&gt;"&gt;What is your email?&lt;/label&gt; &lt;input type="text" id="&lt;?= $field ?&gt;" name="&lt;?= $field ?&gt;" value="&lt;?= isset($_SESSION['form'][$field]) ? $_SESSION['form'][$field] : '' ?&gt;" maxlength="100" /&gt; &lt;? if (isset($_SESSION['errors'][$field])) { ?&gt; &lt;label class="error" for="&lt;?= $field ?&gt;"&gt;&lt;?= $_SESSION['errors'][$field] ?&gt;&lt;/label&gt; &lt;? } ?&gt; &lt;input type="submit" value="Submit Your Information" /&gt; &lt;input type="hidden" name="hid_submit" value="1" /&gt; &lt;/form&gt; &lt;? if (isset($_SESSION['form'])) unset($_SESSION['form']); if (isset($_SESSION['errors'])) unset($_SESSION['errors']); ?&gt; </code></pre> <p><strong>Process_form.php</strong></p> <pre><code>$redirect_page = 'form.php'; $form = array(); $errors = array(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { $hid_submit = isset($_POST['hid_submit']) ? $_POST['hid_submit'] : NULL; if ($hid_submit) { $form['name'] = isset($_POST['name']) ? trim($_POST['name']) : ''; $form['age'] = isset($_POST['age']) ? trim($_POST['age']) : ''; $form['email'] = isset($_POST['email']) ? trim($_POST['email']) : ''; // validate fields if (!valid($form['name'], 'name')) $errors['name'] = 'Please enter a valid name.'; if (!valid($form['age'], 'age')) $errors['age'] = 'Please enter a valid age.'; if (!valid($form['email'], 'email')) $errors['email'] = 'Please enter a valid email.'; if (count($errors)) { $_SESSION['form'] = $form; $_SESSION['errors'] = $errors; } else { $redirect_page = 'another_page.php'; } } } redirect($redirect_page); </code></pre> <p>I find the following approach has worked well in most situations, however I am always looking for better ways to improve.</p>
[]
[ { "body": "<p>That method is fine, and is the one I use. As for a better way? I don't know, seems just fine to me. However, there are some other things that could be improved with this script, and that may be why you feel there might be a better way.</p>\n\n<p>For one, that's some really messy HTML... I would try and separate your PHP from your HTML as much as possible. This is a little harder to do when not using MVC, but can still be accomplished by abstracting your larger bits of code. Also, you are using PHP short tags, but then not using PHP template syntax, this seems counter productive. The purpose of the short tags is to make your code cleaner and make it non-PHP user friendly. Of course, I'm not endorsing PHP short tags, I think you should avoid them, as you are not always guaranteed to have a server that will support them. Lastly, your code is pretty repetitive, the best thing for repetitive stuff like this is loops. For example, here's a sample of how my version of this form would look.</p>\n\n<pre><code>&lt;?php\n$fields = array(\n 'name',\n 'age',\n //etc...\n);\n?&gt;\n\n&lt;?php foreach( $fields AS $field ) : ?&gt;\n\n&lt;?php $value = isset( $_SESSION[ 'form' ] [ $field ] ) ? $_SESSION[ 'form' ] [ $field ] : ''; ?&gt;\n\n&lt;label for=\"&lt;?php echo $field; ?&gt;\"&gt;What is your &lt;?php echo $field; ?&gt;?&lt;/label&gt;\n&lt;input type=\"text\" name=\"&lt;?php echo $field; ?&gt;\" value=\"&lt;?php echo $value; ?&gt;\" maxlength=\"60\" /&gt;\n\n&lt;?php if( ! isset( $_SESSION[ 'errors' ] [ $field ] ) ) : ?&gt;\n\n&lt;label class=\"error\" for=\"&lt;?php echo $field; ?&gt;\"&gt;&lt;?php echo $_SESSION[ 'errors' ] [ $field ]; ?&gt;&lt;/label&gt;\n\n&lt;?php endif; ?&gt;\n\n&lt;?php endforeach; ?&gt;\n</code></pre>\n\n<p>Of course, even this seems really messy to me, though I can't think of much more, besides using MVC, to do to this to make it cleaner. Also, notice I removed the \"id\" attribute from your input tag. When your tag has a name, it doesn't need an id, you can just call it with the name. Example:</p>\n\n<pre><code>alert( document.form.name.value );//may not work, dont think \"form\" is valid name\n</code></pre>\n\n<p>Take a look at PHP's <code>filter_input()</code> function. Its available as long as your PHP version is >= 5.2. It also has some validation flags if you're interested.</p>\n\n<pre><code>$form[ 'name' ] = filter_input( INPUT_POST, 'name', FILTER_SANITIZE_STRING );\n</code></pre>\n\n<p>Keep in mind the \"Don't Repeat Yourself\" (DRY) principle. There are a lot of violations of it here. I demonstrated how to avoid it with your form above, you can do something similar for the processing script.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T20:07:42.210", "Id": "15047", "ParentId": "15013", "Score": "3" } } ]
{ "AcceptedAnswerId": "15047", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-23T21:26:22.117", "Id": "15013", "Score": "4", "Tags": [ "php", "form" ], "Title": "Processing a form with PHP" }
15013
<p> As an exercise on GADTs I wrote a type-safe implementation of <a href="https://en.wikipedia.org/wiki/AA_tree" rel="nofollow">AA trees</a>. I'm quite happy that the <code>AANode</code> data type correctly grasps the properties of the tree. Just from the type it can be concluded that the trees has the balancing property. But there I things I'd like to improve, but I didn't find a nice solution for it:</p> <ol> <li>I need separate data type for the result of <code>insert'</code>. I'm afraid nothing can be done about that, as the algorithm really needs to finely distinguish the possible outcomes.</li> <li>For inserting a new value into subtrees with a black root, I need a separate function <code>insertBlack</code>. The reason is that in this case, the tree level cannot rise, and it is necessary to capture this property. I'd be nicer to have it all in <code>insert'</code>, but I'm afraid this would require dependent types (as the result type would depend on the color of the input).</li> <li>I need a separate data type for the result of <code>insertBlack</code>. A solution would be to write the type of the result as an existential, like <code>... -&gt; (exists c . AANode c (Succ n) a)</code>, but AFAIK GHC doesn't support that.</li> <li>Even though the AA trees are quite simple, I feel that I have a lot of pattern matching for all the different case. At the end, I have 8 possibilities. Maybe they really need to be there, as for each node, we have to distinguish if we insert into the left or the right subtree, we need to distinguish its color, and also we need to match on the recursive result to correctly update the tree.</li> <li>Perhaps, there is a better way how to capture the required properties of the trees? To construct the type of <code>AANode</code> differently?</li> </ol> <p>Any other comments on how to make the code shorter, more readable or more beautiful are welcomed.</p> <p>The code is below:</p> <pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE GADTs #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} -- Based on https://en.wikipedia.org/wiki/AA_tree -- If it happens that anyone ever wants to use this code for something, -- it's licensed under The BSD 3-Clause License. import qualified Data.Foldable as F -- Types representing natural numbers: data Zero data Succ a -- Phantom types for possible colors of nodes. data Red data Black {- | Every child node has a level -1 its parent node, except the right node of a red node. Nodes have 3 type parameters: Color (phantom), level (phantom), values. -} data AANode c n a where -- Leaf nodes are black and have no value (their color isn't really important). Leaf :: AANode Black Zero a -- Red nodes can have the right child with the same level, but then -- the child must be black. The left child must have -1 of its level. Red :: !(AANode c n a) -&gt; a -&gt; !(AANode Black (Succ n) a) -&gt; AANode Red (Succ n) a -- Both children of a black node must have -1 of its level. -- They can have arbitrary colors. Black :: !(AANode c1 n a) -&gt; a -&gt; !(AANode c2 n a) -&gt; AANode Black (Succ n) a -- Two operations to fix improper tree shapes (see the Wikipedia article). skew :: AANode Black (Succ n) a -&gt; a -&gt; AANode c n a -&gt; AANode Red (Succ n) a skew (Black a x b) y r = Red a x (Black b y r) split :: AANode c n a -&gt; a -&gt; AANode Red (Succ n) a -&gt; AANode Black (Succ (Succ n)) a split a t (Red b r x) = Black (Black a t b) r x -- Insert operation .................................................. -- A possible outcome of an insert operation: Either the level -- remains unchanged, or it's increased and the resulting node is black. data Outcome n a where Inc :: !(AANode Black (Succ n) a) -&gt; Outcome n a Same :: !(AANode c n a) -&gt; Outcome n a insert' :: (Ord a) =&gt; a -&gt; AANode c n a -&gt; Outcome n a insert' x Leaf = Inc $ Black Leaf x Leaf insert' x (Red l y r) | x &lt; y = case insert' x l of Same l' -&gt; Same $ Red l' y r Inc l' -&gt; Inc $ Black l' y r | otherwise = case insertBlack x r of AnyColor r'@(Black _ _ _) -&gt; Same $ Red l y r' AnyColor r'@(Red _ _ _) -&gt; Inc $ split l y r' insert' x t@(Black _ _ _) = case insertBlack x t of AnyColor t -&gt; Same t -- Inserting a node into a black subtree never increases height. -- To capture this, we have a separate function for inserting into -- black nodes. We need this property in insert` when we're inserting -- into a red node's right subtree. data AnyColor n a where AnyColor :: !(AANode c n a) -&gt; AnyColor n a insertBlack :: (Ord a) =&gt; a -&gt; AANode Black (Succ n) a -&gt; AnyColor (Succ n) a insertBlack x (Black l y r) | x &lt; y = case insert' x l of Same l' -&gt; AnyColor $ Black l' y r Inc l' -&gt; AnyColor $ skew l' y r | otherwise = case insert' x r of Same r' -&gt; AnyColor $ Black l y r' Inc r' -&gt; AnyColor $ Red l y r' -- --------------------------------------------------------------------- -- | The actual tree type hiding colors/levels. data AATree a where AATree :: !(AANode c n a) -&gt; AATree a instance F.Foldable (AANode c n) where foldr _ x Leaf = x foldr f x (Red l y r) = F.foldr f (f y (F.foldr f x r)) l foldr f x (Black l y r) = F.foldr f (f y (F.foldr f x r)) l instance F.Foldable AATree where foldr f x (AATree t) = F.foldr f x t insert :: (Ord a) =&gt; a -&gt; AATree a -&gt; AATree a insert x (AATree t) = case insert' x t of Same t -&gt; AATree t Inc t -&gt; AATree t empty :: AATree a empty = AATree Leaf -- TESTING CODE -------------------------------------------------- main :: IO () main = do let fromList :: Ord a =&gt; [a] -&gt; AATree a fromList = foldr insert empty print $ F.foldr (:) [] $ fromList "ABCD Kocka prede." </code></pre>
[]
[ { "body": "<p>As suggested, I'm doing a review myself after a few years.</p>\n\n<p>First, let's use GHC's extensions to derive the phantom types from data definitions.\nThis also has the advantage of having proper kinds for each of these types.</p>\n\n<pre><code>{-# LANGUAGE GADTs, DataKinds, KindSignatures, TypeFamilies #-}\n{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}\n\n-- |\n-- Module: AATree\n-- Copyright: Petr Pudlak\n-- License: BSD-3\n--\n-- Based on https://en.wikipedia.org/wiki/AA_tree\nmodule AATree where\n\nimport qualified Data.Foldable as F\nimport Data.Monoid\n\n-- * Internals of the tree with type-level colors and depths.\n\n-- | Types representing natural numbers:\ndata Nat = Zero | Succ Nat\n\n-- | Phantom types for possible colors of nodes.\ndata Color = Red | Black\n</code></pre>\n\n<p>The definition of the main data type is basically unchanged.\nOne important change here is the color of <code>Leaf</code>. Originally it was <em>black</em>, but actually it needs to be <em>red</em> in order to have consistent color change in the <code>insert</code> operation, see <code>SomeOrNext</code> below.</p>\n\n<pre><code>-- | Every child node has a level -1 its parent node, except\n-- the right node of a red node. Nodes have 3 type parameters:\n-- Color (phantom), level (phantom), values.\ndata AANode (c :: Color) (n :: Nat) a where\n Leaf :: AANode 'Red 'Zero a\n -- | Red nodes can have the right child with the same level, but then\n -- the child must be black. The left child must have -1 of its level.\n BlackNode :: !(AANode c1 n a) -&gt; a -&gt; !(AANode c2 n a) -&gt; AANode 'Black ('Succ n) a\n -- | Both children of a black node must have -1 of its level.\n -- They can have arbitrary colors.\n RedNode :: !(AANode c1 n a) -&gt; a -&gt; !(AANode Black ('Succ n) a) -&gt; AANode 'Red ('Succ n) a\n\n-- ** Two operations to fix improper tree shapes (see the Wikipedia article).\n\n-- | Left node grows too large.\nskew :: AANode 'Black ('Succ n) a -&gt; a -&gt; AANode c n a -&gt; AANode 'Red ('Succ n) a\nskew (BlackNode a x b) y r = RedNode a x (BlackNode b y r)\n\n-- | Right node grows too large.\nsplit :: AANode c n a -&gt; a -&gt; AANode 'Red (Succ n) a -&gt; AANode 'Black (Succ (Succ n)) a\nsplit a t (RedNode b r x) = BlackNode (BlackNode a t b) r x\n\n-- ** Insert operation\n</code></pre>\n\n<p>Instead of two types, <code>Outcome</code> and <code>AnyColor</code>, which were holding outputs of the different insert operations, let's have just one, parametrized by <code>Color</code>.</p>\n\n<pre><code>-- | Holds the outcome of an insert operation on a node of color 'c'.\n-- Inserting into a black node retains its depth and possibly chcanges it\n-- to red ('Same'). Inserting into a red one either keeps it the same\n-- ('Same') or changes it to a black node of increased depth ('Next').\ndata SameOrNext (c :: Color) (n :: Nat) a where\n Same :: AANode c_any n a -&gt; SameOrNext c n a\n Next :: AANode 'Black ('Succ n) a -&gt; SameOrNext 'Red n a\n</code></pre>\n\n<p>This allows us to have just a single insert function with a simple recursive definition.\nThere are still 8 cases to cover, but it seems this can't be simplified, at least not without a considerable sacrifice of code readability. In particular, we need to branch whether we move to the left or right, distinguish inserting into a red/black node, and act depending on the outcome of a recursive insert.</p>\n\n<pre><code>insert' :: (Ord a) =&gt; a -&gt; AANode c n a -&gt; SameOrNext c n a\ninsert' x Leaf = Next (BlackNode Leaf x Leaf)\ninsert' x (BlackNode l y r)\n | x &lt; y = case insert' x l of\n Same l' -&gt; Same (BlackNode l' y r)\n Next l' -&gt; Same (skew l' y r)\n | otherwise = case insert' x r of\n Same r' -&gt; Same (BlackNode l y r')\n Next r' -&gt; Same (RedNode l y r')\ninsert' x (RedNode l y r)\n | x &lt; y = case insert' x l of\n Same l' -&gt; Same (RedNode l' y r)\n Next l' -&gt; Next (BlackNode l' y r)\n | otherwise = case insert' x r of\n Same r'@(BlackNode _ _ _) -&gt; Same (RedNode l y r')\n Same r'@(RedNode _ _ _) -&gt; Next (split l y r')\n\n-- * Public interface.\n\n-- | The actual tree type hiding colors/levels.\ndata AATree a where\n AATree :: !(AANode c n a) -&gt; AATree a\n</code></pre>\n\n<p>Minor change in the <code>Foldable</code> definition: Instead of using <code>foldr</code>, it's more natural to define it using <code>foldMap</code>, especially for trees. This can also have significant performance benefits in certain cases, like when using the <code>Last</code> monoid (untested).</p>\n\n<pre><code>instance F.Foldable (AANode c n) where\n foldMap f Leaf = mempty\n foldMap f (RedNode l y r) = F.foldMap f l &lt;&gt; f y &lt;&gt; F.foldMap f r\n foldMap f (BlackNode l y r) = F.foldMap f l &lt;&gt; f y &lt;&gt; F.foldMap f r\n\ninstance F.Foldable AATree where\n foldMap f (AATree t) = F.foldMap f t\n\ninsert :: (Ord a) =&gt; a -&gt; AATree a -&gt; AATree a\ninsert x (AATree t) = case insert' x t of\n Same t -&gt; AATree t\n Next t -&gt; AATree t\n\nempty :: AATree a\nempty = AATree Leaf\n\n\n-- * Very simple test.\n\nmain :: IO ()\nmain = do\n let fromList :: Ord a =&gt; [a] -&gt; AATree a\n fromList = foldr insert empty\n\n print . F.toList . fromList $ \"ABCD Kocka prede.\"\n</code></pre>\n\n<p>I also changed comments to conform to proper the Haddock documenation format.</p>\n\n<hr>\n\n<p><strong>Further ideas:</strong> In addition to insertion and deletion, there are two other fundamental operations on search trees:</p>\n\n<ul>\n<li>Split a tree into two, one with elements less and other with elements greater than a given key.</li>\n<li>Merge two trees for which we know that all elements in one are greater than all elements in another one.</li>\n</ul>\n\n<p>Not only they are very useful on their own, but they can be also used to easily implement other operations such as <em>insert</em>, <em>delete</em>, <em>merge</em> and <em>intersect</em>. The general idea is that when we want to do an operation on two trees, we can split the first one using the root key of the second one and perform the operation recursively on the subtrees of the second one.</p>\n\n<p>Splitting two <code>AATree</code>s is more-or-less straightforward, but merging them is more problematic, as for merging we need to start from the bottom, not from the top, and we don't have information about heights of trees. We could traverse both trees until the bottom layer, unwinding the visited nodes into a heterogeneous lists that holds trees of increasing heights and then merge them backwards up. Or we could embrace this idea into the data structure itself and implement <a href=\"https://en.wikipedia.org/wiki/Finger_tree\" rel=\"nofollow noreferrer\">finger trees</a> based on <code>AANode</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-29T07:38:42.113", "Id": "190745", "ParentId": "15017", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T07:52:02.630", "Id": "15017", "Score": "5", "Tags": [ "haskell", "tree", "type-safety", "gadt" ], "Title": "Improving General Algebraic DataType type-safe code for AA trees" }
15017
<p>I have a jQuery script that checks for the strength of a password. The code looks like this (with more more of those "blocks"):</p> <pre><code>if(passwordLC &amp;&amp; lessThan12Password) { $('.passwordStrenght').animate({width:'75px',height:'5px'},200).show(); $('.passwordStrenght').css('background-color',red); $('#password').css('border-color',green); $('.passwordStrenghtInfo').text(weak).show(); passwordErrors = true; }else if(passwordUC &amp;&amp; lessThan12Password) { $('.passwordStrenght').animate({width:'75px',height:'5px'},200).show(); $('.passwordStrenght').css('background-color',red); $('#password').css('border-color',green); $('.passwordStrenghtInfo').text(weak).show(); passwordErrors = true; }else if(passwordN &amp;&amp; lessThan12Password) { $('.passwordStrenght').animate({width:'75px',height:'5px'},200).show(); $('.passwordStrenght').css('background-color',red); $('#password').css('border-color',green); $('.passwordStrenghtInfo').text(weak).show(); passwordErrors = true; }else </code></pre> <p>And it goes on and on...</p> <p>Is there a way to reduce all that code to something simpler and efficient, or am I stuck with those horrible "blocks" of repeated code?</p>
[]
[ { "body": "<p>The solution depends on your exact requirements and the context.\nIn your case, you could simplify the <code>if</code>-condition like below. If all fit into one <code>if</code>, you can write your code block there only once. If you need it and can't unify your condition, make it a function.</p>\n\n<p>Here, I'm using a combined approach. I put the code from your <code>if</code> into a function, jQuery objects are cached and don't have to be recreated (but are still protected from outside modification because they only exist inside the scope of that function). And I combined all the conditions I could see in your example.</p>\n\n<pre><code>var indicateBadPassword = (function() {\n var $passwordStrength = $('.passwordStrength'),\n $password = $('#password'),\n $passwordStrengthInfo = $('.passwordStrenghtInfo');\n return function() {\n $passwordStrength.\n animate({width:'75px',height:'5px'},200).\n show().\n css('background-color',red);\n $password.css('border-color',green);\n $passwordStrengthInfo.text(weak).show();\n passwordErrors = true;\n\n }\n })();\nif (lessThan12Password &amp;&amp; (passwordLC || passwordUC || passwordN)) {\n indicateBadPassword();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T08:30:01.737", "Id": "15020", "ParentId": "15018", "Score": "2" } } ]
{ "AcceptedAnswerId": "15020", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T08:06:20.433", "Id": "15018", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "Script for checking password strength" }
15018
<p>Can anyone review this?</p> <pre><code>setInterval(function() { var days_array = [31,29,31,30,31,30,31,31,30,31,30,31]; var m = randNum(12); var m_limit = days_array[m-1]; var d = randNum(m_limit); $("code").html("day = "+d+"&lt;br&gt;month = "+m); },1000); function randNum(limit){var r=Math.floor(Math.random()*limit)+1;return r;} </code></pre> <p><a href="http://jsfiddle.net/QERu2/" rel="nofollow">jsFiddle</a></p>
[]
[ { "body": "<pre><code>function randNum(limit){var r=Math.floor(Math.random()*limit)+1;return r;}\n</code></pre>\n\n<p>Can be shortened to:</p>\n\n<pre><code>function randNum(limit){return Math.floor(Math.random()*limit)+1;}\n</code></pre>\n\n<p>You should also declare your variables outside of the setInterval and then set them inside only if you need to (for example, the days_array never changes so only needs to be decalared once and not every second.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T10:00:57.183", "Id": "15023", "ParentId": "15022", "Score": "3" } }, { "body": "<p>I would reduce the visibility of the variables so they won't get overwritten by accident and I'd separate the date creation from displaying them. Like this, for example:</p>\n\n<pre><code>var datePasser = function(callback) {\n var randNum = function(max) {\n return Math.floor(1 + Math.random() * max);\n },\n daysInMonth = [31,29,31,30,31,30,31,31,30,31,30,31];\n return function() {\n var month = randNum(12),\n date = randNum(daysInMonth[month - 1]);\n callback(month, date);\n }\n },\n printRandomDate = datePasser(function(month, date) {\n $('code').html(\"day = \"+date+\"&lt;br&gt;month = \"+month);\n });\nsetInterval(printRandomDate, 1000);​\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T16:07:29.600", "Id": "15040", "ParentId": "15022", "Score": "0" } }, { "body": "<p>This is biased towards days in shorter months. If you want every day to be equally likely you should choose a random number from 1 to 365 (366 for leap years) and calculate the day and month from that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T18:17:42.057", "Id": "15045", "ParentId": "15022", "Score": "3" } }, { "body": "<pre><code>function randomMillisecond()\n{\n return Math.floor(Math.random() * 1000 * 60 * 60 * 24 * 365.25);\n}\n\nsetInterval(function() {\n var date = new Date(randomMillisecond());\n\n $(\"code\").html(\"day = \" + date.getDate() + \"&lt;br&gt;month = \" + date.getMonth());\n}, 1000);\n</code></pre>\n\n<p>If you don't need 02/29.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T20:59:52.023", "Id": "15051", "ParentId": "15022", "Score": "3" } } ]
{ "AcceptedAnswerId": "15051", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T09:01:01.173", "Id": "15022", "Score": "0", "Tags": [ "javascript", "jquery", "datetime", "random" ], "Title": "Random \"month & day\" with JS" }
15022
<p>I know this code is pretty awful, but, by any chance, could someone point out all the flaws you can find and tell me them? It's Python 3.2.3, by the way.</p> <pre><code># Alien Assualt # A bullet hell alien invasion game. # Bobby Clarke #Imports import pygame, sys, os, random, math, easygui from pygame.locals import * pygame.init() screen = pygame.display.set_mode((600, 450)) pygame.display.set_caption("Alien Assualt") clock = pygame.time.Clock() # Glitchy Lazer Mode #pygame.key.set_repeat(1, 1) def adv_range(limit1, limit2 = None, increment = 1.): """ Range function that accepts floats (and integers). Usage: adv_range(-2, 2, 0.1) adv_range(10) adv_range(10, increment = 0.5) The returned value is an iterator. Use list(adv_range) for a list. """ if limit2 is None: limit2, limit1 = limit1, 0. else: limit1 = float(limit1) count = int(math.ceil(limit2 - limit1)/increment) return (limit1 + n*increment for n in range(count)) def setup(num_of_enemies, enemyclass): enemies = [] for i in range(0, num_of_enemies): distance = i * round(400 / num_of_enemies) direction = random.choice((True, False)) #True is right, left is false enemies.append(enemyclass(x = random.randint(100, 440), y = distance , right = direction)) return enemies class player(): """The player""" def __init__(self, x = screen.get_width() / 2 - 35, y = screen.get_height() - 45, img = "Images/player.png", speed = 3): self.x = x self.y = y self.img = pygame.image.load(img) self.rightkeys = (K_RIGHT, K_d, K_KP6) #Keys making it move left self.leftkeys = (K_LEFT, K_a, K_KP4) #Keys making it move right self.left = False self.right = False self.speed = speed def move(self): if self.right and self.x &lt;= screen.get_width() - 60: self.x += self.speed # Move right if self.left and self.x &gt;= 0: self.x -= self.speed # Move left def fire(self, shot, shots): shots.append(shot(self)) return shots class shot(): def __init__(self, player, enemy = False): self.x = player.x + 25 self.y = player.y if enemy: img = "Images/enemyshot.png" else: img = "Images/shot.png" self.img = pygame.image.load(img) self.enemy = enemy self.delete = False def move(self, speed = 5): if self.enemy: self.y += speed else: self.y -= speed if self.y &lt;= 0 or self.y &gt; screen.get_height(): self.delete = True class enemy(): def __init__(self, x = random.randint(0, screen.get_width() - 30), y = 0, img = "Images/enemy.png", left = True, right = False, speed = random.randint(4, 7)): self.x = x self.y = y self.img = pygame.image.load(img) self.speed = speed if right: left = False self.left = left self.right = right def move(self): if self.left: self.x -= self.speed elif self.right: self.x += self.speed if self.x &lt; 0: self.right = True self.left = False elif self.x &gt; screen.get_width() - 60: self.right = False self.left = True def fire(self, shot, shots): shots.append(shot(self, enemy = True)) return shots def play(player, enemies, shotclass, secs): shots = [] key = None playing = True while playing: clock.tick(60) screen.fill((0, 0, 0)) # Black player.move() for shot1 in shots: shot1.move() for shot2 in shots: if shot1.x in adv_range(shot2.x, shot2.x + 10) and shot1.y in adv_range(shot2.y, shot2.y + 10) or shot2.x in adv_range(shot1.x, shot1.x + 10) and shot2.y in adv_range(shot1.y, shot1.y + 10): if not shot1 == shot2 and(shot1.enemy == True and shot2.enemy == False) or (shot1.enemy == False and shot2.enemy == True): shot1.delete = True shot2.delete = True #Blits screen.blit(player.img, (player.x, player.y)) for shot in shots: for enemy in enemies: if shot.x in adv_range(enemy.x, enemy.x + 60) and shot.y in adv_range(enemy.y, enemy.y + 20) and not shot.enemy: enemies.remove(enemy) try: shots.remove(shot) except: pass if shot.enemy and shot.x in adv_range(player.x, player.x + 60) and shot.y in adv_range(player.y, player.y + 45): return False, secs if shot.delete: try: shots.remove(shot) except: pass screen.blit(shot.img, (shot.x, shot.y)) for enemy in enemies: screen.blit(enemy.img, (enemy.x, enemy.y)) enemy.move() if random.randint(1, 10 * len(enemies)) == 1: shots = enemy.fire(shotclass, shots) # # # # # pygame.display.update() if not enemies: return True, secs for event in pygame.event.get(): if event.type == pygame.QUIT: playing = False elif event.type == KEYDOWN: if event.key in player.rightkeys: player.right = True elif event.key in player.leftkeys: player.left = True elif event.key == K_SPACE: shots = player.fire(shotclass, shots) elif event.type == KEYUP: if event.key in player.rightkeys: player.right = False elif event.key in player.leftkeys: player.left = False elif event.type == USEREVENT: secs += 1 def main(playerclass, enemyclass, shotclass): win = False enemynum = 0 deaths = 0 secs = 0 while enemynum not in range(5, 21): enemynum = easygui.enterbox("How many enemies do you want? (5 - 20)", "Alien Assualt") try: enemynum = int(enemynum) except ValueError: enemynum = 0 except TypeError: sys.exit() pygame.time.set_timer(USEREVENT, 1000) #Fire a user event every second, for the timer while not win: win, secs = play(playerclass(), setup(enemynum, enemyclass), shotclass, secs) deaths += 1 if secs &lt; 60: time = "{0} seconds".format(secs) else: time = "{0} minute(s) and {1} second(s)".format(math.floor(secs / 60), secs % 60) easygui.msgbox("You won in {0} and died {1} times.".format(time, deaths)) if __name__ == "__main__": main(player, enemy, shot) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:21:48.883", "Id": "24398", "Score": "2", "body": "I'm pretty sure I mentioned that using a pastebin here is a bad practice by itself :P." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T17:44:46.803", "Id": "24588", "Score": "1", "body": "A tiny note, you can drop empty brackets when defining a class `class player:`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-21T18:16:06.317", "Id": "73045", "Score": "0", "body": "I'm locking this as the OP never included the code, but appears to gave been acceptable at the time." } ]
[ { "body": "<p>Some problems:</p>\n\n<ul>\n<li>Classes uncapitalised</li>\n<li>Default parameter equal signs <strong>without</strong> space (<em>def foo(a=0)</em>)</li>\n<li>Too long lines (you can break them!)</li>\n<li>Built-in paths (\"Images/player.png\")</li>\n<li>Use of too many arguments (use **kwargs instead)</li>\n<li><p>Return value instead of in-place operations on lists</p>\n\n<pre><code>def fire(self, shot, shots):\n #You are performing this operation on the mutable object you get\n shots.append(shot(self, enemy = True))\n #Therefore the next line is unnecessary\n return shots\n</code></pre></li>\n</ul>\n\n<p>You code is actually not that bad, you just have to read <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a> and use pylint or something :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T17:31:29.710", "Id": "24405", "Score": "0", "body": "What should I use as an alternative to built-in paths?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T16:11:13.477", "Id": "24482", "Score": "1", "body": "os.path.join('Images', 'player.png') is cross-platform :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T13:06:21.097", "Id": "15028", "ParentId": "15025", "Score": "7" } }, { "body": "<p>I'm not sure the logic of <code>adv_range</code> is doing what you intended:</p>\n\n<pre><code>&gt;&gt;&gt; list(adv_range(4.0, 5.0, 0.3))\n[4.0, 4.3, 4.6]\n&gt;&gt;&gt; list(adv_range(4.0, 5.1, 0.3))\n[4.0, 4.3, 4.6, 4.9, 5.2, 5.5]\n</code></pre>\n\n<p>Normally you would expect a function like this to consistently stop one step before it reaches <code>limit2</code>, or one step after. You should specify in the function's documentation exactly which numbers you expect it to return and test that it does this (you could even throw in some doctests). Note that the line <code>limit1 = float(limit1)</code> won't have any effect unless <code>float1</code> was some unusual type like <code>Decimal</code>.</p>\n\n<p>You could also look at <a href=\"http://numpy.scipy.org/\" rel=\"nofollow\">numpy</a> if you are going to do a lot of numerical work - it has functions like <code>numpy.arange</code> and <code>numpy.linspace</code> that do essentially what <code>adv_range</code> does.</p>\n\n<p>I haven't looked at this in detail but the way you keep storing directions as a pair of bools (left and right) looks a bit awkward. If you just store the direction as an integer, e.g., +1 for right, -1 for left, 0 for stationary, it could simplify things - you could do <code>self.x += self.speed * self.direction</code> instead of testing both <code>self.left</code> and <code>self.right</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-10T13:11:13.127", "Id": "15478", "ParentId": "15025", "Score": "1" } } ]
{ "AcceptedAnswerId": "15028", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T12:17:48.100", "Id": "15025", "Score": "3", "Tags": [ "python", "game", "python-3.x" ], "Title": "Alien Assault game" }
15025
<p>I got a file with lots of ASCII characters. No extension, and has the Type Of file attribute 190000 File.</p> <p>I have many characters like L¿ö in the file however I required to remove lines from a word PYGR to another word MCG. It has several lines in between.</p> <p>I tried the following code. And got everything working. Indexes are 3 and 19001 respectively, </p> <p>VB: </p> <pre><code>Dim Load_File = System.IO.File.ReadAllText("C:\Documents and Settings\Fousu.s\Desktop\Files\SYSI091512.190000") Dim EditedString = "" Dim IndexofPYGR = Load_File.IndexOf("PYGR") Dim indexOfMCG = Load_File.LastIndexOf("MCG") Dim LengthMCG = "MCG" 'System.Console.ReadKey() If ((IndexofPYGR &gt; -1) And (indexOfMCG &gt; -1)) Then EditedString = Load_File.Remove(IndexofPYGR, (indexOfMCG - (LengthMCG.Length + 1))) System.IO.File.WriteAllText("C:\Documents and Settings\Fousu.s\Desktop\Files\SYSI091512.190000V1", EditedString) End If </code></pre> <p>c#</p> <pre><code>//Getting the file as a string. string Load_File = System.IO.File.ReadAllText(@"C:\Documents and Settings\Fousu.s\Desktop\Files\SYSI091512.190000"); string EditedString; int IndexofPYGR = Load_File.IndexOf("PYGR"); int indexOfMCG = Load_File.IndexOf("MCG"); string LengthMCG = "MCG"; //Console.WriteLine("Index of PYGR is : {0}", IndexofPYGR); //Console.WriteLine("Index of MCG is : {0}", indexOfMCG); //System.Console.ReadKey(); if ((IndexofPYGR != -1) &amp;&amp; (indexOfMCG != -1)) { EditedString = Load_File.Remove(IndexofPYGR, (indexOfMCG - (LengthMCG.Length + 1))); System.IO.File.WriteAllText(@"C:\Documents and Settings\Fousu.s\Desktop\Files\SYSI091512.190000V1", EditedString); </code></pre> <p>Would like to request a review of the above code, or is there a better way to achieve this? and also would like to know how to get the Type Of File attribute to 190000.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T13:10:44.230", "Id": "24378", "Score": "5", "body": "Those *aren't* ASCII characters..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T13:24:41.770", "Id": "24380", "Score": "2", "body": "Yes. This isn't an ASCII file, like you say in the question title. It does have a file extension (of \".190000\"). Your approach seems fine for the task in hand, but the inconsistencies in the question are worrying." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T05:46:07.860", "Id": "24494", "Score": "0", "body": "Thanks jon Skeet and Jon Hanna, Actually I have been told that it is an ASCII file. But however I believe its rather an encrypted file. Thanks for pointing that out!!" } ]
[ { "body": "<h1>Some clarifications</h1>\n<blockquote>\n<p>I got a file with lots of ASCII characters. [...] I have many characters like L¿ö in the file [...]</p>\n</blockquote>\n<p>As others have pointed out, these are <em>not</em> ASCII characters.</p>\n<blockquote>\n<p>No extension, and has the Type Of file attribute 190000 File.</p>\n</blockquote>\n<p>Configure Windows Explorer to show file extensions.</p>\n<blockquote>\n<p>I required to remove lines from a word PYGR to another word MCG. It has several lines in between.</p>\n</blockquote>\n<p>Your code tells us otherwise. You are not removing the <em>lines</em> from PYGR to MCG; your code removes the word PYGR and every character that follows <strong>up to one character <em>before</em></strong> <code>MCG</code>. I assume that is not quite what you were trying to achieve?</p>\n<p><del>If you update your question to explain if you are trying to remove everything <strong>between (excluding)</strong> <code>PYGR</code> and <code>MCG</code>, <strong>including one of them</strong> or <strong>including both of them</strong>, I'll gladly adapt my answer. For now, I will assume the latter.</del></p>\n<p><em>Edit:</em> All right, in accordance with your comment I have changed my answer to replace all text from <code>PYGR</code> (inclusive) to <code>MCG</code> (exclusive).</p>\n<h1>Reviewing your code</h1>\n<h2>Readability</h2>\n<ul>\n<li>Please use the well-established C# naming conventions: local variables are <code>camelCase</code></li>\n<li>Format your code with the correct indentation to make it more readable</li>\n<li>Start your file with <code>using System.IO</code> to avoid repeating yourself</li>\n<li>Get rid of unnecessary parenthesis</li>\n<li>Choose proper names</li>\n<li>Join declaration and usage of variables where possible</li>\n</ul>\n<p>For example:</p>\n<pre><code>string EditedString;\n// ...\nEditedString = Load_File.Remove(IndexofPYGR, (indexOfMCG - (LengthMCG.Length + 1))); \n</code></pre>\n<p>should be more like</p>\n<pre><code>string editedContent = fileContent.Remove(startIndex, endIndex - end.Length); \n</code></pre>\n<h2>Maintainability</h2>\n<p>Hard-coding the paths is something that should be avoided even during development. You can use <code>Environment.GetFolderPath</code> with <code>Environment.SpecialFolder.Desktop</code> to retrieve the path to the current user's desktop and add the file name with <code>Path.Combine</code>.</p>\n<h2>Regex</h2>\n<p>I really don't like the heave use of <code>indexOf</code>: your code seems to be all about <em>how</em> the replacement is done, instead of <em>what</em> is going on (i.e. it is imperative, not declarative).</p>\n<p>Using a Regex, we can arrive at a more declarative style. You may need to adjust this to suit your needs (your question is ambiguous).</p>\n<hr />\n<h1>Refactored</h1>\n<pre><code>string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);\nstring inFilePath = Path.Combine(desktop, &quot;SYSI091512.190000&quot;);\nstring outFilePath = Path.Combine(desktop, &quot;SYSI091512.190000V1&quot;); \n\n// you would probably pass the paths into your method as parameters\n\nvar fileContent = File.ReadAllText(inFilePath);\nvar result = Regex.Replace(fileContent, &quot;PYGR.*MCG&quot;, &quot;MCG&quot;, RegexOptions.Singleline);\nFile.WriteAllText(outFilePath, result);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T05:54:01.517", "Id": "24495", "Score": "0", "body": "First of all thanks a lot for this great suggestions, and it will really help beginners like me. Initially I have been told that it is an ASCII file, however I doubt it is just an encrypted file. No extension for the file, however when I right click the file and have 190000 in the file type field. Yes I would like to remove the all characters or lines including the word PYGR to word MCg (Exclude). However a little doubt how to specify the folder name in the desktop where the file is residing? Thanks for this answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T14:35:53.963", "Id": "15032", "ParentId": "15027", "Score": "8" } }, { "body": "<p>For your VB code specifically: </p>\n\n<p>In general, though some might disagree, I would much prefer to see type specification when I see <code>Dim</code>.</p>\n\n<p>i.e.</p>\n\n<pre><code>Dim EditedString As String = \"\"\nDim IndexofPYGR As Long = Load_File.IndexOf(\"PYGR\")\nDim indexOfMCG As Long = Load_File.LastIndexOf(\"MCG\")\nDim LengthMCG As String = \"MCG\"\n</code></pre>\n\n<p>I don't see anything <em>very</em> wrong with this block, and it actually leaves you open for future expansion (with regard to the <code>EditedString</code> variable), but if you wanted to simplify, you could...</p>\n\n<p>Change this:</p>\n\n<pre><code>If ((IndexofPYGR &gt; -1) And (indexOfMCG &gt; -1)) Then\n EditedString = Load_File.Remove(IndexofPYGR, (indexOfMCG - (LengthMCG.Length + 1)))\n System.IO.File.WriteAllText(\"C:\\Documents and Settings\\Fousu.s\\Desktop\\Files\\SYSI091512.190000V1\", EditedString)\nEnd If\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>If ((IndexofPYGR &gt; -1) And (indexOfMCG &gt; -1)) Then\n System.IO.File.WriteAllText(\"C:\\Documents and Settings\\Fousu.s\\Desktop\\Files\\SYSI091512.190000V1\", Load_File.Remove(IndexofPYGR, (indexOfMCG - (LengthMCG.Length + 1))))\nEnd If\n</code></pre>\n\n<p>However, I would consider converting the path string to a variable and place it elsewhere earlier in your code. This allows you to use it in more than one place while requiring you to make only one change in your code later if that path changes.</p>\n\n<p>Taking my last suggestion, I would even break that down more to allow for more possible file names (if that would be useful for your case specifically or not is up to you to decide). I did not make this change in the code below.</p>\n\n<p>My final result, based on these suggestions would be the following:</p>\n\n<pre><code>Dim PathAndFilename As String = \"C:\\Documents and Settings\\Fousu.s\\Desktop\\Files\\SYSI091512.190000\"\nDim Load_File = System.IO.File.ReadAllText(PathAndFilename)\nDim IndexofPYGR As String = Load_File.IndexOf(\"PYGR\")\nDim indexOfMCG As Long = Load_File.LastIndexOf(\"MCG\")\nDim LengthMCG As String = \"MCG\"\n\n'System.Console.ReadKey()\nIf ((IndexofPYGR &gt; -1) And (indexOfMCG &gt; -1)) Then\n System.IO.File.WriteAllText(PathAndFilename &amp; \"V1\", Load_File.Remove(IndexofPYGR, (indexOfMCG - (LengthMCG.Length + 1))))\nEnd If\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T05:56:50.563", "Id": "24496", "Score": "1", "body": "Thanks for this valuable suggestions, will try my best to follow this standards better in my future codes. I am unable to vote up any answers or comments as I don't have enough reputations !!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T11:18:45.250", "Id": "24510", "Score": "2", "body": "No worries; you can always come back and up-vote later if you wish. Glad I could help!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T22:19:10.407", "Id": "15052", "ParentId": "15027", "Score": "2" } } ]
{ "AcceptedAnswerId": "15032", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T13:02:17.023", "Id": "15027", "Score": "4", "Tags": [ "c#", "vb.net" ], "Title": "I have an encrypted file, how to remove a specific string from that file" }
15027
<p>I'm writing a program in wxpython, and to make GUI parts that are built in different modules I made a module called <code>runtime</code>, where all the GUI parts get stored on runtime. This is how it looks: </p> <pre><code>mainFrame = anotherGUIPart = InputDialog = SomethingElse = None </code></pre> <p>For example, when I need to make a ListControl to update itself, I use</p> <pre><code>#anotherGUIPart.py class AnotherGUIPart(wx.Panel): def __init__(self, *args, **kwargs): wx.Panel.__init__(self, *args, **kwargs) self.listCtrl = wx.ListCtrl(self, style=wx.LC_REPORT | wx.LC_SINGLE_SEL) ... def UpdateList(self): self.listCtrl.DeleteAllItems() ... #Somewhere where I need to update the list import runtime runtime.anotherGUIPart.UpdateList() </code></pre> <p>Is this a good practice?<br> If not, what are alternatives?</p>
[]
[ { "body": "<p>This is fine, as long as you're not bleeding too much across the module boundaries. Ideally you would have a structure somewhat akin to MVC, where you have all of your UI logic in one module, all your business logic in another, and a controller module which links the two together. However, if you find that this improves your ability to understand the code then that's just fine. If you post a link to more of your code it'll be easier to review the design as this is quite macro-scale.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-01T02:38:03.637", "Id": "15258", "ParentId": "15029", "Score": "2" } } ]
{ "AcceptedAnswerId": "15258", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T13:07:13.780", "Id": "15029", "Score": "-1", "Tags": [ "python" ], "Title": "Is it a good idea to store GUI elements in a module on runtime?" }
15029
<p>Is this return style acceptable? Would the code be more readable if I assigned the <code>MonthDay.parse()</code> return value to a variable and returned that variable on the last line?</p> <p>Also, is it a bad idea to both log and rethrow inside a catch block?</p> <pre><code>/** * Parses showing date from the header text. * * @throws PageStructureException if the date string does not conform to the expected format */ public MonthDay parseShowingDate( String date ) throws PageStructureException { Preconditions.checkNotNull( date ); DateTimeFormatter matDTF = DateTimeFormat.forPattern( DATE_FORMAT ); String dayAndMonth = removeDayOfWeek( date ); try { return MonthDay.parse( dayAndMonth, matDTF ); } catch ( IllegalArgumentException iae ) { logger.error( "Could not parse MAT date {}, expected format [{}].", date, DATE_FORMAT ); throw new PageStructureException( iae ); } } </code></pre>
[]
[ { "body": "<p>It is a very good understandable write.</p>\n\n<p>You can also write the return method in a parameters, it is optimal (look in <a href=\"http://www.pascal-man.com/navigation/faq-java-browser/java-concurrent/Effective%20Java%20-%20Programming%20Language%20Guide.pdf\" rel=\"nofollow\">Effective Java</a> all subtle reasons):</p>\n\n<pre><code>try {\n return MonthDay.parse( removeDayOfWeek(date), DateTimeFormat.forPattern(DATE_FORMAT));\n} catch ( IllegalArgumentException iae ) {\n logger.error( \"Could not parse MAT date {}, expected format [{}].\", date, DATE_FORMAT );\n throw new PageStructureException( iae );\n}\n</code></pre>\n\n<p>I've not included here <code>Preconditions.checkNotNull( date )</code>, because it is not really a parameters, but I'll do it if it was my job, </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:32:23.403", "Id": "15036", "ParentId": "15034", "Score": "4" } }, { "body": "<p>I believe it's OK. This way, it is immediately clear from the code that the method returns a value only when no exception is thrown during parsing. If you used a variable to store the result, it becomes less clear. And, the reader has to track where the variable is initialized/modified/returned.</p>\n\n<p>Logging an exception when it's rethrown is a bit confusing, because it is possible the caller expect the possibility of receiving an exception and deals with it. But sometimes a programmer needs it so that it's possible to examine what's happening even if the caller catches the exception. In such a case, I'd suggest using only <em>debug</em> or <em>trace</em> logging levels.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:37:40.387", "Id": "15037", "ParentId": "15034", "Score": "6" } } ]
{ "AcceptedAnswerId": "15037", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:19:42.303", "Id": "15034", "Score": "5", "Tags": [ "java", "error-handling" ], "Title": "Error handling for parsing a date" }
15034
<p>Here is my code;</p> <pre><code>import socket def read_line(sock): "read a line from a socket" chars = [] while True: a = sock.recv(1) chars.append(a) if a == "\n" or a == "": return "".join(chars) def read_headers(sock): "read HTTP headers from an internet socket" lines = [] while True: line = read_line(sock) if line == "\n" or line == "\r\n" or line == "": return "".join(lines) lines.append(line) def parse_headers(headerstr): "Return a dict, corresponding each HTTP header" headers = {} for line in headerstr.splitlines(): k, _, v = line.partition(":") headers[k] = v.strip() return headers http_request = """GET / HTTP/1.1 Host: {} """ site = "www.google.com.tr" conn = socket.create_connection((site,80)) conn.sendall(http_request.format(site)) headersstr = read_headers(conn) headersdict = parse_headers(headersstr) if "Transfer-Encoding" in headersdict and headersdict["Transfer-Encoding"] == "chunked": content = "" else: content = conn.recv(headersdict["Content-Length"]) print content conn.close() </code></pre> <p>Can you please comment on how I am using sockets. Is it correct practive to read characters one by one from socket as I did in read_line function? Are there any other mistakes I am doing?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T15:50:00.620", "Id": "24434", "Score": "0", "body": "Code Review strictly improves working code, we aren't here to help debug your code.You can ask on Stackoverflow, but you should narrow down your question first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T17:50:54.513", "Id": "24437", "Score": "0", "body": "@WinstonEwert I edited my question and stripped buggy part. Is it ok now? If so, can you reopen?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T19:35:41.310", "Id": "24456", "Score": "0", "body": "reopened your question" } ]
[ { "body": "<p>Reading one byte at a time is bad idea, because it won't buffer the input. Instead, you'll probably get a system call for each byte which will be really inefficient.</p>\n\n<p>Easiest solution is to use <code>makefile</code></p>\n\n<pre><code>myfile = sock.makefile('r') \n</code></pre>\n\n<p>Then you can treat myfile like a file, including using methods like readline. That'll be more efficient then your version.</p>\n\n<p>It seems a bit of waste to have readheaders() convert all the headers into one long string, only to have parseheaders() split it apart again.</p>\n\n<pre><code>if \"Transfer-Encoding\" in headersdict and headersdict[\"Transfer-Encoding\"] == \"chunked\":\n</code></pre>\n\n<p>I'd use <code>if headersdict.get('Transfer-Encoding') == 'chunked':</code>, if the key is not present, <code>get</code> will return None, and you'll have the same effect as before.</p>\n\n<p>Of course, for serious stuff, you'd want to use the builtin python libraries for this sort of thing. But as long as you are doing it to learn, all well and good.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T21:01:06.777", "Id": "24459", "Score": "0", "body": "Thanks for the answer. Does it matter when I use makefile. Should I use it after or before I make HTTP request?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T21:30:49.520", "Id": "24460", "Score": "0", "body": "@yasar11732, shouldn't matter." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T20:07:45.003", "Id": "15074", "ParentId": "15038", "Score": "3" } } ]
{ "AcceptedAnswerId": "15074", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:45:14.523", "Id": "15038", "Score": "2", "Tags": [ "python" ], "Title": "Working with sockets" }
15038
<p>For educational purposes I've tried to implement a simple algebraic OOP example using CLOS. The functionality is as far as I can say as it is supposed to be. The intended approach was to implement a simple example of ideomatic OOP polymorphism. For a greater learning experience I've wanted to show the code to get suggestions, critic and so on.</p> <pre><code>;; main node class, most general (defclass node () ;; abstract class for nodes ((value :initarg :value :reader value))) (defgeneric evaluate (node) (:documentation "the standard evaluation")) ;; node containing an operation, more specific (defclass op-node (node) ;; abstract class for a node containing an operation ((left-node :initform nil :initarg :left-node :reader left-node) (right-node :initform nil :initarg :right-node :reader right-node))) (defmethod evaluate ((node op-node)) (apply (value node) (list (evaluate (left-node node)) (evaluate (right-node node))))) ;; concrete nodes (defclass add-node (op-node) ;; class for addition ((value :initform #'+ :reader value))) (defclass minus-node (op-node) ;; class for subtraction ((value :initform #'- :reader value))) (defclass multi-node (op-node) ;; class for multiplication ((value :initform #'* :reader value))) (defclass value-node (node) ;; class for a node containing a numerical value ((value :initarg :value :reader value))) (defmethod evaluate (value-node) (value value-node)) ;; 1 + 3 (setf *simple-add* (make-instance 'add-node :left-node (make-instance 'value-node :value 1) :right-node (make-instance 'value-node :value 3))) ;; 1 * 10 (setf *simple-multi* (make-instance 'multi-node :left-node (make-instance 'value-node :value 1) :right-node (make-instance 'value-node :value 10))) ;; (1 + 3) + (1 * 10) (setf *advanced-add* (make-instance 'add-node :left-node *simple-add* :right-node *simple-multi*)) (evaluate *simple-add*) ;; =&gt; 4 (evaluate *simple-multi* ;; =&gt; 10 (evaluate *advanced-add*) ;; =&gt; 14 </code></pre>
[]
[ { "body": "<pre><code>(defmethod evaluate ((node op-node))\n (apply (value node) \n (list (evaluate (left-node node))\n (evaluate (right-node node)))))\n</code></pre>\n\n<p>can be written:</p>\n\n<pre><code>(defmethod evaluate ((node op-node))\n (funcall (value node) \n (evaluate (left-node node))\n (evaluate (right-node node))))\n</code></pre>\n\n<p>For this example, instead of different subclasses for every binary operation, you could just use a <code>binop</code> class and instantiate it with the respective functions, since they share the same <code>evaluate</code> method, but that depends on what else you want do do with the nodes. (Maybe, for example, you want to have different <code>print-object</code> methods for each of them.)</p>\n\n<p>(Also, using toplevel <code>setf</code>s on unestablished symbols is considered bad style, but I suppose this was just for testing and demonstration purposes. In real code, <code>defparameter</code> or <code>defvar</code> should be used.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T07:47:45.070", "Id": "24426", "Score": "0", "body": "Is there any difference between using `apply` and `funcall` in this case? Are there cases where one is better usage instead of the other? The `binop` class hint is very good! I thought of abstracting it more but I wasn't sure how to do it without getting the code too confusing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T09:38:46.993", "Id": "24427", "Score": "0", "body": "http://www.lispworks.com/documentation/HyperSpec/Body/f_funcal.htm: `(funcall function arg1 arg2 ...) == (apply function arg1 arg2 ... nil) == (apply function (list arg1 arg2 ...))`. So no, there is no difference in this case. Just use whatever is less convoluted." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T19:14:06.883", "Id": "15046", "ParentId": "15039", "Score": "2" } }, { "body": "<pre><code>(defmethod evaluate (value-node)\n (value value-node))\n</code></pre>\n\n<p>try calling (evaluate 't). Why did that method get called?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T20:30:08.007", "Id": "15049", "ParentId": "15039", "Score": "0" } } ]
{ "AcceptedAnswerId": "15046", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:55:40.587", "Id": "15039", "Score": "3", "Tags": [ "object-oriented", "lisp" ], "Title": "simple \"if\"-less algebraic computation using CLOS" }
15039
<p>This is for an instrumentation tool using the ASM tree api. This method assigns a <code>handler</code> to a field, which is used in instrumented methods. As a result of my instrumentation, the instrumented class implements an interface and is a handler itself, so a value of <code>this</code> behaves like a NullObject concerning handled methods - it doesn't do anything different but never throws an Exception (when the handled method in the instrumented class is invoked, it will cause a <code>NullPointerException</code> if the handler is <code>null</code> because methods are called on it).</p> <p>Now, there's 3 different ways to avoid <code>NullPointerException</code>s (my enum):</p> <ul> <li><code>checkBeforeCall</code>: on every call of the handled method, <code>this</code> is used as the handler if it is not set to anything else but <code>null</code>. That's a "slow" approach if the handled method is called very often, as an <code>if</code> is required per call. Pretty please avoid telling me that that's ok and I shouldn't use the other two enum values - that's beside the point :-)</li> <li><code>assignAfterSuper</code>: after the super constructor is called, the handler field is initialized. This causes little to no overhead at runtime, but it causes problems if the handled method was overridden and is called in the super constructor, because it will throw the NPE.</li> <li><code>assignBeforeSuper</code>: The handler is set to <code>this</code> <strong>before</strong> the super constructor is called. No Java compiler will ever produce this bytecode, but it's valid and the scala guys do it as well. The handler field is then fully initialized after the super constructor was called.</li> </ul> <p>I provide all three methods as the first one is fail-safe, the second is valid and you should be ok in most scenarios and the third is best but could potentially cause trouble in tools.</p> <p>Now, for each of these initializations, there are two ways to set the handler. One - if you <strong>have</strong> the instrumented instance - is to call a "setHandler" method. That's ok if you have full access to the object, but you're helpless if you don't. The other is to provide a static method, which is called to create a handler. The instrumented instance is passed (so it can be returned itself if no handler is needed) and the result is then used to initialize the field.</p> <p>Passing <code>this</code> to a static method before the super constructor was called is invalid bytecode. So I use this "spawner" method (if it was specified) after <code>super(...)</code> was called.</p> <p>So the gory situation: I have an instruction list which I modify. In the relevant two enum-cases I need to consider for constructor instrumentation, I also execute the code for <code>assignAfterSuper</code> on <code>assignBeforeSuper</code>, but only if a static initializer is used (otherwise, it's already set to <code>this</code>). I'm modifiying an instruction list and use a little more state information and factoring any methods out doesn't really make sense, as the parameter list would be longer than the method itself and readability would be diminished. Factoring it out into different classes would also be problematic, as it hurts readability and I have to switch open files when I want to understand the methods behavior or I have to duplicate all code further up or I have to factor it out but can't see what else happens to my InsnList (which is dangerous, because it could mess up the result. I'd like to keep the <code>InsnList</code> for one <code>MethodNode</code> inside of the method so I can see at first glance which changes occur).</p> <pre><code>private void assignHandler(MethodNode method, String handleeInternalName, String handlerField) { if (this.guard == NullPointerGuard.checkBeforeCall) { return; } InsnList instructions = method.instructions; final boolean usesLabels = instructions.getFirst() instanceof LabelNode; // search for call of constructor super(...) or this(...) AbstractInsnNode constructorCall = instructions.getFirst(); while (!(constructorCall.getOpcode() == INVOKESPECIAL &amp;&amp; constructorCall instanceof MethodInsnNode &amp;&amp; "&lt;init&gt;".equals(((MethodInsnNode) constructorCall).name))) { constructorCall = constructorCall.getNext(); } // skip modification on delegation to this(...) if (handleeInternalName.equals(((MethodInsnNode) constructorCall).owner)) { return; } // not delegating to this(...), inject initialization of Handler field AbstractInsnNode node = instructions.getFirst(); InsnList storeHandler = null; switch (this.guard) { case assignBeforeSuper: storeHandler = storeHandlerInField(handleeInternalName, handlerField, false); if (usesLabels) { storeHandler.add(new LabelNode()); instructions.insert(node, storeHandler); } else { instructions.insertBefore(node, storeHandler); } if (!usesSpawner()) { break; } // else fallthrough case assignAfterSuper: storeHandler = storeHandlerInField(handleeInternalName, handlerField, true); if (usesLabels) { storeHandler.insertBefore(storeHandler.getFirst(), new LabelNode()); } instructions.insert(constructorCall, storeHandler); break; default: throw new InstrumentationException(this.guard + " is not implemented yet"); } method.maxStack += usesSpawner() ? 2 : 1; } </code></pre> <p>I am concerned about the fall-through inside the <code>switch</code>, but before I restructured it this way, I had either duplicated code for the actions or duplicated checks for the conditions. Unfortunately, each case cannot easily be extracted into a method.</p> <p>Now, the structure is transparent, can easily be read and understood (as long as one knows how <code>switch</code> works) and there is no more redundancy. Still, this feels weird. Though I'm really proud I have found this solution, I wonder if there's a better way.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T19:42:00.957", "Id": "24409", "Score": "9", "body": "Without really seeing more of the code a common suggestion is to use inheritance and polymorphism. A first step would be to more common code to code to methods then once that is done decide if a seperate class will encapsulate the functionality you are seeing and the variables used." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T13:21:50.437", "Id": "24432", "Score": "0", "body": "is it possible that only code for e2 should be executed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T17:53:54.237", "Id": "24438", "Score": "0", "body": "Intended and possible. Yes" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T17:57:12.453", "Id": "24439", "Score": "2", "body": "Should be a good starting point if you decide to go the route dreza stated (which I believe is the correct route): http://www.youtube.com/watch?v=4F72VULWFvc" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T19:43:29.837", "Id": "24489", "Score": "2", "body": "« The // do stuff part uses too many variables to extract it into a method. » is the first code smell. Try to refactor it in several independant methods, or group the parameters into a dedicated class. After that you can have e1 and e2 each in its own method, and decide to call one, the other, or both." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T06:29:54.620", "Id": "24499", "Score": "0", "body": "@[Corbin](http://codereview.stackexchange.com/users/7308/corbin): I watched the video, thanks. I kind of disagree with the presenter, though. Not in principle - but I prefer simple type systems and fewer code I have to read and understand to simple methods - as long as I can still understand what the method does and it's well named and documented. I also think abstract classes are a (strong) code smell and I vastly prefer interfaces and flat type hierarchies." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T06:35:47.760", "Id": "24500", "Score": "1", "body": "@[Joan Charmant](http://codereview.stackexchange.com/users/7126/joan-charmant) I do agree with you, but there's some kinds of problems where it's not that easy. For me, there's a threshold for how long a class and a method may get before I am willing to split them. And there's another one for when I'm willing to split a method into sub methods: Each one has to be easily understood and has to do something a human deems sensible. So a matrix multiply is fine, but when will I need some of LU factorization stuff with the relevant state information in another context? And how should I name that?" } ]
[ { "body": "<p>You use of switch is unconventional and in consequence hard to follow. I'd avoid it for that reason. What I see is that that both case are very similar, and so I'd try to refactor them into a function.</p>\n\n<p>Here's my approach:</p>\n\n<pre><code>private void assignHandler(MethodNode method,\n String handleeInternalName, String handlerField) {\n if (this.guard == NullPointerGuard.checkBeforeCall) {\n return;\n }\n MethodInsNode constructorCall = findConstructorCall(method);\n\n // skip modification on delegation to this(...)\n if (handleeInternalName.equals(constructorCall.owner)) {\n return;\n }\n switch (this.guard) {\n case assignBeforeSuper:\n insertHandler(method, handleeInternalName, handlerField, null);\n if( usesSpawner() )\n {\n insertHandler(method, handleeInternalName, handlerField, constructorCall);\n }\n break;\n case assignAfterSuper:\n insertHandler(method, handleeInternalName, handlerField, constructorCall);\n break;\n default:\n throw new InstrumentationException(this.guard + \" is not implemented yet\");\n } \n}\n\nvoid insertHandler(MethodNode method, String handleeInternalName, String handlerField, AbstractInsnNode node) // node specified node\n // to insert before, or null for beginning of method\n{\n InsnList instructions = method.instructions;\n final boolean usesLabels = instructions.getFirst() instanceof LabelNode;\n InsnList storeHandler = storeHandlerInField(handleeInternalName, handlerField, node != null);\n\n\n // the rest of this function probably belongs in a InstructionInserter class \n if(useLabels)\n {\n if(node == null)\n {\n storeHandler.add( new LabelNode() );\n node = instructions.getFirst(); // insert after existing label node\n }\n else\n {\n storeHandler.insert( new LabelNode() );\n }\n }\n\n\n if(node == null)\n {\n instructions.insert(storeHandler);\n }\n else\n {\n instructions.insert(node, storeHandler);\n }\n\n method.maxStack++;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T16:00:52.017", "Id": "24520", "Score": "0", "body": "I think you could be right, but I'm not sure yet. And that's exactly why I posted this. If I use this style, I'd probably also change the `switch` to an `if ... else if ... else ...`. But I have strong aversions to pass control of something changing the state of the MethodNode outside of the function, I think it may hurt maintainability because the control flow is easier and better understood if the corresponding code is in close proximity (and the method length doesn't exceed my tolerance threshold yet). And I still think the `switch` hurts less than having to skip through the file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T16:04:10.000", "Id": "24521", "Score": "0", "body": "... continued: What I love is `findConstructorCall` (but I think I'll pass InsnList instead of MethodNode, so it's a little more generic). I thought of it myself but discarded it, but then I reorganized my method to its current version and now it would probably fit. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T17:18:24.227", "Id": "24527", "Score": "0", "body": "@Arne, I think the control flow is easier to follow if you break it up into functions. That way its easier to grasp the high level logic of function. I think its easier to see in my version the logic about where the extra instructions get inserted because its not tangled with the low level details regarding label nodes and such." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T17:19:04.803", "Id": "24528", "Score": "0", "body": "@Arne, as for findConstructorCall, does it actually make sense for lists of instructions that aren't methods? It seems to me that the method only makes sense in that context so MethodNode is the appropriate parameter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T17:43:30.647", "Id": "24530", "Score": "0", "body": "it doesn't even really make sense for MethodNode - as it's not necessarily a constructor, could also be a regular method. Still, if I want to use it to construct something else, I can use fragments of InsnList to construct a new MethodNode." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T15:48:26.920", "Id": "15102", "ParentId": "15043", "Score": "1" } } ]
{ "AcceptedAnswerId": "15102", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T17:47:53.467", "Id": "15043", "Score": "3", "Tags": [ "java" ], "Title": "Instrumentation tool using the ASM tree API" }
15043
<blockquote> <p>Assume a 2D [n][n] matrix of 1's and 0's. All the 1's in any row should come before 0's. The number of 1's in any row I should be at least the number of 1's row (i+1). Find a method and write a C program to count the number of 1's in a 2D matrix. The complexity of the algorithm should be order <em>n</em>.</p> </blockquote> <p>The question is from Cormen's Algorithm Book. Kindly point out the mistakes in my algorithm and hopefully suggest a better way.</p> <pre><code> #include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; int **map; int getMatrix(); main() { int n,i,j,t; j=0; n=getMatrix(); i=n-1; int sum[n]; for(t=0;t&lt;n;t++) sum[t]=0; int count=0; while ( (i&gt;=0) &amp;&amp; (j&lt;n) ) { if ( map[i][j] == 1 ) { j++; count=count+1; } else { if (i==(n-1)) { sum[i]==count; count=0; } else { sum[i]=sum[i+1]+count; count=0; i--; } } } for (t=0;t&lt;n;t++) { if ((t==(n-1)) &amp;&amp; (sum[t]==0)) sum[t]=0; else if ((sum[t]==0) &amp;&amp; (sum[t+1]&gt;0)) sum[t]=sum[t+1]; } int s=0; for (t=0;t&lt;n;t++) s=s+sum[t]; printf("\nThe No of 1's in the given matrix is %d \n" ,s); } int getMatrix() { FILE *input=fopen("matrix.txt","r"); char c; int nVer=0,i,j; while((c=getc(input))!='\n') if(c&gt;='0' &amp;&amp; c&lt;='9') nVer++; map=malloc(nVer*sizeof(int*)); rewind(input); for(i=0;i&lt;nVer;i++) { map[i]=malloc(nVer*sizeof(int)); for(j=0;j&lt;nVer;j++) { do { c=getc(input); }while(!(c&gt;='0' &amp;&amp; c&lt;='9')); map[i][j]=c-'0'; } } fclose(input); return nVer; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T08:47:28.643", "Id": "24468", "Score": "1", "body": "Please format your code nicely to make it easier for everyone else to read. You only need to format it once, but you'll save a lot of people time and increase your chances of getting feedback. Also, you typically post here when the code is already working to get a review. SO is where you take it when it doesn't work yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-26T01:18:35.150", "Id": "142361", "Score": "0", "body": "`sum[i]==count;`? This is not a working program, and that isn't the only mistake." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-26T01:46:36.057", "Id": "142364", "Score": "0", "body": "I think you are missing a word in the third sentence of the problem description." } ]
[ { "body": "<p>I think your main loop should be something more along the lines of</p>\n\n<pre><code>row = n-1; // start at bottom row \nfor (col=0; col&lt;n; col++) { // read columns from left to right\n while ((row &gt;= 0) &amp;&amp; (map[row,col] == 0)) { // while not out of rows, and on a 0\n sum += col; //add count of 1s to total\n row--; //move to next row up\n }\n // do nothing if we're on a 1, just move to next column.\n}\nif (row &gt;= 0) sum += (row+1)*col; // add in any leftover rows of all 1s\nprintf(\"sum is %d\\n\",sum);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T03:27:32.317", "Id": "24420", "Score": "0", "body": "But this raises the complexity to O(n^2) in the worst case and wont be valid answer to the problem right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T03:28:00.943", "Id": "24421", "Score": "0", "body": "I will think along your lines and come up with a suggestion maybe :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T04:04:59.217", "Id": "24422", "Score": "1", "body": "No, it's O(n); it's got a single loop, col = 0 to n-1. (while the column value goes from 0 to n, the row value goes from n-1 to 0 at the same time; it's not a nested loop but a linked value.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T04:07:25.420", "Id": "24423", "Score": "0", "body": "In fact I believe it'll take n operations in the best case, and 2n operations in the worst case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T09:41:21.370", "Id": "24428", "Score": "0", "body": "But The code gives the wrong result, so maybe the algorithm needs some tuning - \nI implemented for this matrix \n1111\n1111\n1100\n1000\n\nhere is the code I used -" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T08:51:11.370", "Id": "24469", "Score": "0", "body": "You're counting the zeros instead of the ones, and your while loop is advancing as long as it sees a zero. Instead you must advance once you find a one." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T20:21:47.927", "Id": "15048", "ParentId": "15044", "Score": "2" } }, { "body": "<p>Sorry, but <a href=\"https://codereview.stackexchange.com/a/15080/8186\">your solution</a> is still \\$O(N^2)\\$. Say the number of 1s is its minimum. Consider the minimum number of 1s, i.e. each row <code>i</code> has <code>i+1</code> ones. You will have to scan \\$N-i\\$ positions in each row, for a total of \\$N^2/2\\$ actions, i.e. \\$O(N^2)\\$. visually:</p>\n\n<pre><code>1* 0* 0* 0* 0*\n1 1* 0* 0* 0*\n1 1 1* 0* 0*\n1 1 1 1* 0*\n1 1 1 1 1*\n</code></pre>\n\n<p>Where the <code>*</code>s indicate you looked at that position.\nWith smart enough code, you could actually infer the 1s, but that's still \\$O(N^2)\\$ and probably more overhead than it's worth.</p>\n\n<p>A faster solution is to find the border between 0 and 1 by binary search. </p>\n\n<pre><code>int findFirstZero(int *row, int left, int right) \n{\n if(row[right]) return right;\n int lastOne = left;\n int firstZero = right;\n int pos;\n while(firstZero - lastOne &gt; 1) {\n pos = (lastOne + firstZero) / 2;\n if(pos) {\n lastOne = pos;\n } else {\n firstZero = pos;\n }\n }\n return firstZero;\n}\n\nint sumOnes(int **map) {\n int sum = 0;\n for(int i = 0; i &lt; N; i++) {\n sum += findFirstZero(map[i], i, N-i-1);\n }\n return sum;\n}\n</code></pre>\n\n<p>Now, this is actually \\$O(NlogN)\\$, but given the constraints of the problem as I understand them, I'm quite certain that's the best possible; either you or Cormen left something out of the problem or Cormen made a mistake in his big-O analysis. I'd love to see a proof to the contrary, though. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-21T13:38:54.083", "Id": "316614", "Score": "0", "body": "This is in fact not best possible. Binary search is actually wasteful here because it spends time on each row seeking to the left when the actual sequence of indices is increasing." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-04T15:33:37.200", "Id": "18216", "ParentId": "15044", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T18:11:27.740", "Id": "15044", "Score": "4", "Tags": [ "algorithm", "c", "programming-challenge", "matrix" ], "Title": "Devise an algorithm of complexity O(N) finding No of 1's from a 2 dimensional matrix[N][N] containing 1's and 0's" }
15044
<p>I have 16 permutations each with 104 variables using the standard alphabet. The 104 variable permutation is selected based off of compression complexity. This is one example of the pattern I am able to generate it has a low compression ratio of 1.3 with overhead:</p> <blockquote> <p>HHHFHHFFHHFHHFFHHFHHHFHAAAAHHHFHHFFHHFHHFFHHFHHHFHAAAAHHHFHHFFHHFHHFFHHFHHHFHAAAAHHHFHHFFHHFHHFFHHFHHHFH</p> </blockquote> <p>This is a goal pattern I would like to generate it has a better compression ratio of 1.5 </p> <blockquote> <p>mlcllltlgvalvcgvpamdipqtkqdlelpklagtwhsmamatnnislmatlkaplrvhitsllptpednleivlhrwennscvekkvlgektenpkkfkinytvaneatlldtdydnflflclqdtttpiqsmmcqylarvlveddeimqgfirafrplprhlwylldlkqmeepcrf</p> </blockquote> <p>This is one set of permutation code generation:</p> <pre><code>static double GetCompressionRatio(string input) { if (string.IsNullOrEmpty(input)) throw new ArgumentNullException(); MemoryStream ms = new MemoryStream(); GZipStream gzip2 = new GZipStream(ms, CompressionMode.Compress, true); byte[] raw = Encoding.UTF8.GetBytes(input); gzip2.Write(raw, 0, raw.Length); gzip2.Close(); byte[] zipped = ms.ToArray(); // as a BLOB int startsize = raw.Length; double percent = Convert.ToDouble(zipped.Length) / Convert.ToDouble(startsize); return percent; } var query = from sp1 in polar ... //22 lines ... from vp15 in polar where GetCompressionRatio(sp1+...+vp15)&gt;1.5 select sp1+...+vp15; foreach (var element in query) { //output } string[] polar = new string[6]; polar[0]="H"; polar[1]="Q"; polar[2]="N"; polar[3]="K"; polar[4]="D"; polar[5]="E"; string[] nonpolar = new string[5]; nonpolar[0]="F"; nonpolar[1]="L"; nonpolar[2]="I"; nonpolar[3]="M"; nonpolar[4]="V"; string[] all = new string[24]; all[0]="A"; all[1]="B"; all[2]="C"; all[3]="D"; all[4]="E"; all[5]="F"; all[6]="G"; all[7]="H"; all[8]="I"; all[9]="J"; all[10]="K"; all[11]="L"; all[12]="M"; all[13]="N"; all[14]="O"; all[15]="P"; all[16]="Q"; all[17]="R"; all[18]="S"; all[19]="T"; all[20]="U"; all[21]="V"; all[22]="W"; all[23]="Y"; </code></pre> <p>I need it to go much faster like 1000x if possible.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T02:12:54.173", "Id": "24418", "Score": "3", "body": "Could you write this up better? I am forced to read the code since I do not understand the description, but the code is not complete either." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T18:14:15.813", "Id": "24443", "Score": "0", "body": "Are you using the badness of compression to evaluate randomness? If so, there's better ways to evaluate randomness." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T19:05:27.070", "Id": "24452", "Score": "0", "body": "@Corbin yes i am" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T19:06:41.030", "Id": "24476", "Score": "0", "body": "i directly called random for each variable in the proper order and it gave sufficiently random and complex results very quickly" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T04:52:34.807", "Id": "24492", "Score": "0", "body": "To improve performance this code needs to be more complete, the single method is rather simplistic though doesn't appear to serve a known useful purpose? The performance loss is likely in the iterations you're executing against that method, there may be a way to complete their goal with less iterations if you would show those parts of the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T08:39:31.343", "Id": "24661", "Score": "0", "body": "I'd suggest using a dedicated library like https://www.nuget.org/packages/Combinatorics to generate your permutations. (disclaimer: blatant self promotion... I just deployed this to Nuget yesterday) though I've a feeling your perf. bottle neck is not the generation of the permutations but the actual GetCompressionRatio method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T16:59:14.973", "Id": "24677", "Score": "0", "body": "@JimmyHoffa which single method are you referring too? the sheer volume of iterations is impossible for a normal computer to process in a reasonable time i believe. i showed all the code that did anything.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T17:00:07.533", "Id": "24678", "Score": "0", "body": "@EoinCampbell the compression does slow the algorthim down some but the sheer volume of data and number of iterations is so many i dont think any library is going to help processes it all atm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T17:59:52.560", "Id": "24684", "Score": "0", "body": "Edit your question and add your sample data what is the value of polar. Where does the \"16 Permutations\" come into it. (i only count 15 if you go from sp1 -> vp15). you're first example is 105 characters long. Youre second example is 181 characters long. what are these. where do they come from. Post your entire code if you want it reviewed/improved." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T01:24:42.937", "Id": "24700", "Score": "0", "body": "@EoinCampbell i added the contents of polar nonpolar and all but i dont think a non random sample solution will work i also tried to explain in the code that there are more beptween sp1 and vp15 than you can see but thats not really important" } ]
[ { "body": "<p>Ok.</p>\n\n<p>Lots of stuff going on here and I'm writing this as I work your example so bear with me...</p>\n\n<p>In you code, polar contains six letters. And you don't care about letter repetition in your top examples so what you are calculating here are not permutations but variations. Secondly, you're example shows 22 ommitted lines so you have 24 <code>from</code> statements in your LINQ query... that's going to generate 6^24 variations (4738381338321616896)</p>\n\n<p>That's a very large number. Even if you could paralelize this across 1000 servers, they would still need to be calculating 150million compressions ratios per second for this to complete in a year. (((6^24)/1000)/365)/86400) = ~150,253,000</p>\n\n<p>As soon as you call <code>foreach (var element in query)</code> that query is going to execute and it's going to try and create a list of 4.7 Quintillion strings in memory. This is BAD. You're attempting a brute force calculation on an impossibly large problem set so you need to go back and rethink your approach to whatever it is you are trying to solve/accomplish</p>\n\n<p>But again... lets just assume that you have enough power &amp; bandwidth &amp; compute resource (GPUs are shiny) And lets bring it back to more manageable numbers. lets says 6^10 = </p>\n\n<ol>\n<li>Strings in General</li>\n</ol>\n\n<p>Strings are immutable in .NET. Everytime you alter a string, you throw away the old one, and make a new one and the garbage collector has to come along and clean up after you. so this part here will be very expensive where you concat all those strings together, twice.</p>\n\n<pre><code>where GetCompressionRatio(sp1+...+vp15)&gt;1.5 \nselect sp1+...+vp15;\n</code></pre>\n\n<p>at the very least you would want to change this to </p>\n\n<pre><code>let concatval = sp1+...+vp15\nwhere GetCompressionRation(concatVal) &gt; 1.5\nselect concatVal\n</code></pre>\n\n<ol>\n<li>Big Numbers are Big.</li>\n</ol>\n\n<p>Using LINQ like that to generate your variations is not optimal. As I suggested in the comments... use a library. The following code snippet.</p>\n\n<pre><code>var polar = new[] { \"H\", \"Q\", \"N\", \"K\", \"D\", \"E\" };\n\nvar sw = new Stopwatch();\nsw.Start();\nvar results1 = from a1 in polar from a2 in polar\n from a3 in polar from a4 in polar\n from a5 in polar from a6 in polar\n from a7 in polar from a8 in polar\n from a9 in polar from a10 in polar\n select a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10;\nvar l1 = results1.Count();\nsw.Stop();\nConsole.WriteLine(\"{0} variations in {1}ms\", l1, sw.ElapsedMilliseconds);\n\nsw = new Stopwatch();\nsw.Start();\nvar results2 = new Variations&lt;string&gt;(polar, 10, GenerateOption.WithRepetition);\nvar l2 = results2.Count();\nsw.Stop();\nConsole.WriteLine(\"{0} variations in {1}ms\", l2, sw.ElapsedMilliseconds);\n\nConsole.ReadLine();\n</code></pre>\n\n<p>RESULTS</p>\n\n<pre><code>60466176 variations in 54161ms\n60466176 variations in 4624ms\n</code></pre>\n\n<ol>\n<li>The Compression Method.</li>\n</ol>\n\n<p>On my machine this is repeatedly capable of performing 100,000 compressions on a 10 character string in 2200-2300ms. With the following modifications, that comes down to 1800-1900ms. Small improvement that's possibly related to what else my machine was doing but still.</p>\n\n<ul>\n<li><code>MemoryStream</code> &amp; <code>GZipStream</code> are <code>IDisposable</code> &amp; should be wrapped in <code>using()</code> statements</li>\n<li>removed unnecessary int assignments</li>\n<li>removed unnecessary if(check) at top... you know this to be impossible based on your input set. </li>\n</ul>\n\n<p>Code</p>\n\n<pre><code>static float GetCompressionRatio2(string input)\n{\n using(var ms = new MemoryStream())\n using (var gzip2 = new GZipStream(ms, CompressionMode.Compress, true))\n {\n var raw = Encoding.UTF8.GetBytes(input);\n gzip2.Write(raw, 0, raw.Length);\n var percent = ((float)ms.ToArray().Length) / raw.Length;\n return percent;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T15:25:55.957", "Id": "24722", "Score": "0", "body": "btw the Variations class comes from this Library.\nhttps://www.nuget.org/packages/Combinatorics" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T23:40:21.077", "Id": "24744", "Score": "0", "body": "btw, why `float` and not `double`?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T09:41:28.877", "Id": "15232", "ParentId": "15053", "Score": "4" } } ]
{ "AcceptedAnswerId": "15232", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T23:17:03.130", "Id": "15053", "Score": "4", "Tags": [ "c#", "performance", "combinatorics" ], "Title": "compression condition permutation" }
15053
<p>I started learning <code>C</code> a week ago, and here is my implementation for the <code>split</code> function:</p> <pre><code>char** my_split(const char* str, char delim, int* size) { int index = 0, start; char** results = NULL; *size = 0; do { if ((*size) % 10 == 0) //top floor reached { results = realloc(results, ((*size) + 10) * sizeof(char*)); //extend the space for another 10 pointers if (results == NULL) //if failed, return NULL return NULL; } start = index; while (str[index] != delim &amp;&amp; str[index]) //find the delimeter or end of string { index++; } int length = index - start; //length of matching string results[*size] = malloc((length + 1) * sizeof(char)); //allocate memory in the size of the string, and another char for '\0' if (results[*size] == NULL) //if failed, return NULL return NULL; strncpy(results[*size], &amp;str[start], length); //copy the matching string to the array results[*size][length] = 0; //end the string (*size)++; //add 1 to the total size } while (str[index++]); results = realloc(results, (*size) * sizeof(char*)); //trim unused bytes return results; } </code></pre> <p>Is there anything I could do better (memory, performance and error handling)? Maybe in the logic of the function?</p> <p>Also, feel free to criticize my writing style, as I want it to be more readable and "correct".</p>
[]
[ { "body": "<p><strong>Note:</strong> I would take everything I say with a grain of salt. It's been a few years since I used C on a regular basis, and even at my peak with C, I was never very familiar with the standard or certain best practices.</p>\n\n<p>Your function is responsible for cleaning up memory, yet when you bail in your NULL returns, you don't do that. </p>\n\n<p>In particular, if a realloc fails, the memory already allocated stays, and if allocating the second dimension-ed array fails, you still need to free what you have already allocated before returning.</p>\n\n<hr>\n\n<p>A review of a few code points:</p>\n\n<ul>\n<li>I would highly consider abstracting away the memory stuff, but if you don't, I would consider doubling the array size instead of adding ten.\n<ul>\n<li>Consider a fairly long string being split on space. Assume it ends up being 1000 split strings. This means 100 allocations, and allocating is fairly slow. If you were to double, it would be 10 allocations.\n<ul>\n<li>Doubling wastes, at most, <code>sizeof(type) * n/2</code> bytes, but has at most, <code>lg n</code> allocations (note: very rough math)</li>\n<li>Doubling using more memory but is typically faster</li>\n</ul></li>\n</ul></li>\n<li><code>size</code> should be an unsigned type (I would use size_t)</li>\n<li>As previously mentioned, you have potential memory leaks</li>\n<li>As your code exists, there's really no advantage over strtok\n<ul>\n<li>strtok doesn't very well allow storing into an array, but your function requires fairly manual memory management anyway</li>\n</ul></li>\n<li>The malloc/strncpy combination could be changed to use strndup and be a lot simpler (I think strndup is standard?)</li>\n<li>You could actually use strtok inside of your function to avoid doing the index calculations\n<ul>\n<li>Part of your code is recreating strtok</li>\n<li>The other part of your code is taking that strtok functionality and using it to push things into an array</li>\n<li>What you have now will (probably) perform better than strtok</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>I'm not familiar enough with standard practices of C to know what the expected way would be, but something about the the memory handling feels odd to me:</p>\n\n<pre><code>const char[] str = \"Hello World\";\nint size = 0;\nchar** str_parts = my_split(str, ' ', &amp;size);\nif (str_parts != NULL) {\n //Let's do something with the parts\n for (int i = 0; i &lt; size; ++i) {\n printf(\"Part %d: '%s'\\n\", size, str_parts[i]);\n }\n //Now we have to clean up (could technically be in the printing loop)\n for (int i = 0; i &lt; size; ++i) {\n free(str_parts[i]);\n }\n free(str_parts);\n}\n</code></pre>\n\n<p>I might consider abstracting the memory away to a generalized vector or a specialized string vector.</p>\n\n<p>That could bring your API to something like:</p>\n\n<pre><code>const char[] str = \"Hello World\";\ncvector parts;\n//A vector of char*'s that will call free() on each element before destructing\ncvector_init(&amp;parts, sizeof(char*), free);\nif (my_split(&amp;parts, ' ')) {\n for (size_t i = 0; i &lt; parts.size; ++i) {\n //I'm a bit rusty on C, so I'm not sure if the char* cast is needed or not\n printf(\"Part %d: '%s'\\n\", size, (char*) cvector_get(&amp;parts, i));\n }\n}\ncvector_destory(&amp;parts);\n</code></pre>\n\n<p>The downside to this would be that you'd be tying your other code to a specific API (though bastardizing the vector into a <code>char**</code> would actually be <em>fairly</em> easy if you wrote the cvector API in a particular way -- though then you'd be depending on implementation details, which is usually a bad idea), and this vector would perform worse than a plain 2d array. (Though if you wrote a string specialized vector, the performance could be very similar and, depending on design, you could even use it as a <code>char**</code> without worrying much about the implications.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T07:08:45.720", "Id": "24425", "Score": "0", "body": "That's something I haven't noticed. Thanks for the tip!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T17:10:33.653", "Id": "24436", "Score": "0", "body": "@GuyDavid No problem :). Also, I've edited the post to add a few more suggestions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T19:01:00.027", "Id": "24450", "Score": "0", "body": "Wow, words can not express the gratitude which I owe you, thanks for taking your time for writing this down. I'm now reviewing and applying each one of your points." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T19:27:44.370", "Id": "24455", "Score": "0", "body": "What is the condition that should tell that I should increase the size? (using `realloc`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T19:44:06.990", "Id": "24457", "Score": "0", "body": "@GuyDavid You will need to keep track of how many elements have been used. (The only other option would be to calculate if the number is a power of two, but that presents performance problems.) Basically if you go the doubling route, you'll need to keep track of the size of the array and how many elements you have. Every time numElems == size, double the array." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T06:59:51.340", "Id": "15058", "ParentId": "15055", "Score": "5" } }, { "body": "<p>For only 1-week experience I'd say you are top of the class. However, I do have some notes on your function (to add to those of Corbin):</p>\n\n<ul>\n<li><p>if the delimiter character is repeated you output empty strings. Is that desirable?</p></li>\n<li><p>calls to <code>realloc</code> usually assign the result to a temporary variable so that if NULL is returned the original pointer is not lost (if it is lost, it cannot be freed).</p></li>\n<li><p>nested loops usually indicate a lazy or inexperienced programmer. Your nested while() is just a strchr() - check what functions are available in the standard library. If you are on linux/Unix/MacOS, do 'man strchr' and look down the bottom of the manual page for 'See Also'. Browse around.</p></li>\n<li><p>sizeof(char) is 1 by definition. Use 1.</p></li>\n<li><p>in your use of strncpy, where the length is guaranteed to be enough, strncpy guarantees to terminate the new string for you; you need not do it yourself. However...</p></li>\n<li><p>as you already know the length of the string to be copied, strncpy is inefficient. strncpy has to check each character against \\0 to know when to stop copying. Where you know the length, memcpy is preferable (followed by manual termination, as you have it).</p></li>\n<li><p>some of your comments are just 'noise'</p></li>\n<li><p>be nice to readers, stick to 80 character width. This applies to readers of your code in general, not just for readers of Stack Exchange.</p></li>\n<li><p>consider whether it would be better to copy the entire input string once at the top and then create a list of pointers into that copy, rather than allocating each sub-string.</p></li>\n<li><p>consider whether the interface is good. This was just an exercise, so maybe the interface was specified for you. If you were designing it yourself, would you use this interface? Maybe so - I'm not saying it is wrong. But there are alternatives that would avoid the memory allocation. For example, consider passing in a writable string, an array of char* and its length and returning the number of strings. etc.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T14:57:00.680", "Id": "15101", "ParentId": "15055", "Score": "3" } }, { "body": "<p>If you don't mind modifying the caller's input buffer, there's another style of doing this in C that results in fewer allocations.</p>\n\n<p>Let's look at <code>strsep</code>, present in some C libraries as a less ugly version of the older <code>strtok</code>:</p>\n\n<pre><code> char *\n strsep(char **stringp, const char *delim);\n</code></pre>\n\n<p><code>*stringp</code> starts out as the beginning of the string, the function searches for chars in <code>delim</code>, replaces the delimiter with a <code>NUL</code> character and updates <code>*stringp</code>. So the caller would look like:</p>\n\n<pre><code> char buf[] = \"The quick brown fox ...\";\n char *string = buf;\n char *r;\n\n while ((r = strsep(&amp;string, \" \")))\n puts(r);\n</code></pre>\n\n<p>Here's what the function might look like:</p>\n\n<pre><code>char *\nstrsep(char **stringp, const char *delim)\n{\n char *ret = *stringp;\n if (ret)\n {\n char *next = strpbrk(ret, delim);\n\n if (next)\n *next++ = 0;\n\n *stringp = next;\n }\n return ret;\n}\n</code></pre>\n\n<p>As you can see, shorter, simpler code and no allocations. It's also not so hard to implement your more allocation-heavy approach in terms of this, either: start out by duping the caller's buffer, then iterate through this function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-23T20:31:54.403", "Id": "15857", "ParentId": "15055", "Score": "1" } } ]
{ "AcceptedAnswerId": "15058", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T01:33:24.953", "Id": "15055", "Score": "5", "Tags": [ "c" ], "Title": "C Split function review" }
15055
<p><code>playerObject</code> is an <code>NSDictionary</code> from <code>JSONObjectWithData:options:error</code>.</p> <p>I'm trying to update a <code>CoreData</code> entity.</p> <pre><code>if ([results count] &gt; 0) { newPlayer = (Player *)[results objectAtIndex:0]; } else { //Add a new player newPlayer = [NSEntityDescription insertNewObjectForEntityForName:@"Player" inManagedObjectContext:temporaryContext]; } //Assume these exist and are not null newPlayer.email = [playerObject objectForKey:@"email"]; newPlayer.username = [playerObject objectForKey:@"username"]; newPlayer.continent = [playerObject objectForKey:@"continent"]; //Dates NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; newPlayer.created = [df dateFromString: [playerObject objectForKey:@"created"]]; //Optional properties if ([[playerObject objectForKey:@"title"] isKindOfClass:[NSNull class]]) { newPlayer.title = nil; } else { newPlayer.title = [[playerObject objectForKey:@"title"] stringValue]; } </code></pre> <p>Is there any way to make it less verbose? Have I left myself open to any issues?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-05T15:53:02.570", "Id": "24872", "Score": "1", "body": "Take a look at JSRestNetworkKit and stop parsing the JSON yourself :) https://github.com/JaviSoto/JSRestNetworkKit" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T09:10:25.403", "Id": "25498", "Score": "0", "body": "Looks interesting but I'd just want to use the mapping from a dictionary to CoreData entity. Would this be possible?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T18:37:15.530", "Id": "25521", "Score": "1", "body": "You mean without making requests to an API? Yes, absolutely, you would just have to make your CoreData entities inherit from JSBaseCoreDataBackedEntity and use + (id)updateOrInsertIntoManagedObjectContext:(NSManagedObjectContext *)managedObjectContext withDictionary:(NSDictionary *)dictionary;" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T11:08:17.870", "Id": "25540", "Score": "1", "body": "Excellent. I'll take a look into that then, since I'm using JSON-RPC for the web service." } ]
[ { "body": "<pre><code>if ([results count] &gt; 0)\n{\n newPlayer = (Player *)[results objectAtIndex:0];\n} else {\n //Add a new player\n newPlayer = [NSEntityDescription insertNewObjectForEntityForName:@\"Player\" inManagedObjectContext:temporaryContext];\n}\n</code></pre>\n\n<p>This chunk of code could be replaced with:</p>\n\n<pre><code>newPlayer = (Player *)([results firstObject] ?: [NSEntityDescription insertNewObjectForEntityForName:@\"Player\" inManagedObjectContext:temporaryContext]);\n</code></pre>\n\n<hr>\n\n<pre><code>if ([[playerObject objectForKey:@\"title\"] isKindOfClass:[NSNull class]])\n{\n newPlayer.title = nil;\n} else {\n newPlayer.title = [[playerObject objectForKey:@\"title\"] stringValue];\n}\n</code></pre>\n\n<p>This chunk of code could also be slightly better.</p>\n\n<pre><code>NSString *newTitle = playerObject[@\"title\"];\nnewPlayer.title = [newTitle isEqual:[NSNull null]] ? nil : [newTitle stringValue];\n</code></pre>\n\n<hr>\n\n<p>The last comment that I'll make is a strong recommendation that you use constants for your keys rather than literal strings. Defined constants will auto-complete for you, which is nice, but more importantly, it will eliminate misspellings entirely.</p>\n\n<pre><code>static NSString * const kKey_Player = @\"Player\";\nstatic NSString * const kKey_Title = @\"title\";\n// etc.\n</code></pre>\n\n<p>Then use it as such:</p>\n\n<pre><code>NSString *newTitle = playerObject[kKey_Title];\n</code></pre>\n\n<p>Under the covers, this actually doesn't change in the slightest what the code does. Even when you use string literals, a memory location is still allocated for them. The advantage here is that you eliminate programmer mistakes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-05T18:34:13.233", "Id": "56215", "ParentId": "15059", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T13:05:25.767", "Id": "15059", "Score": "5", "Tags": [ "objective-c", "json", "ios" ], "Title": "Parsing NSDictionary from NSJSONSerialization" }
15059
<pre><code>import java.util.ArrayList; public class SumsOfPerfectPowers { ArrayList&lt;Long&gt; numList = new ArrayList&lt;Long&gt;(5000001); // status of whether a number is power number boolean[] result = new boolean[5000001]; public SumsOfPerfectPowers() { numList.add((long) 0); numList.add((long) 1); for (int i = 2; i &lt;= 2237; i++) { int j = 2; double value; while ((value = Math.pow(i, j)) &lt;= 5000000) { numList.add((long) value); j++; } } int len = numList.size(); // System.out.println(len); int value; for (int i = 0; i &lt; len; i++) { for (int j = 0; j &lt; len; j++) { value = (int) (numList.get(i) + numList.get(j)); if (value &lt;= 5000001) { result[value] = true; } } } } static { } public int howMany(int a, int b) { int sum = 0; for(int i=a;i&lt;=b;i++) { if(result[i]) { sum ++; } } return sum; } public static void main(String[] args) { SumsOfPerfectPowers test = new SumsOfPerfectPowers(); System.out.println(test.howMany(0, 1)); System.out.println(test.howMany(5, 6)); System.out.println(test.howMany(25, 30)); System.out.println(test.howMany(103, 103)); System.out.println(test.howMany(1, 100000)); } } </code></pre> <ol> <li>Is this piece of code well-coded?</li> <li>Are there any bad habits here?</li> <li>What can be improved?</li> </ol>
[]
[ { "body": "<p>A couple of comments:</p>\n\n<ol>\n<li>Generally, it is recommended to declare variables as interface types for extensibility and implementation-neutral as much as possible. You would realize this when writing large programs. Based on this, numList would be of type List or Collection.</li>\n<li>Instead of typecasting to (long), you can simply suffix the values with 'L' to make them long.</li>\n<li>It is recommended to declare the member variables as private. The default scope is package private.</li>\n<li>Didn't understand the purpose of empty static block!</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T22:34:32.397", "Id": "24461", "Score": "0", "body": "About 1, it's a constructor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T02:59:53.000", "Id": "24465", "Score": "0", "body": "Ah! My bad! I copied the body of the class for review. Updated by comments." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T15:26:19.143", "Id": "15061", "ParentId": "15060", "Score": "10" } }, { "body": "<ol>\n<li><p><code>(long) 0</code> scructures should be written as <code>0L</code>.</p></li>\n<li><p>Access modifiers of <code>numList</code> and <code>result</code> should be <code>private</code>:</p>\n\n<pre><code>private ArrayList&lt;Long&gt; numList = new ArrayList&lt;Long&gt;(5000001);\n// status of whether a number is power number\nprivate boolean[] result = new boolean[5000001];\n</code></pre></li>\n<li><p><code>ArrayList&lt;...&gt;</code> reference types should be simply <code>List&lt;...&gt;</code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p>\n\n<pre><code>private List&lt;Long&gt; numList = new ArrayList&lt;Long&gt;(5000001);\n</code></pre></li>\n<li><p><code>5000000</code> is a magic number. Using named constants instead of numbers would make the code more readable and less fragile. If you have to modify it's value it's easy to forget to do it everywhere. <code>2237</code> is also a magic number and a computed value. I'd create a MAX constant:</p>\n\n<pre><code>private static final int MAX = 5000000;\n</code></pre>\n\n<p>and use it everywhere, for example:</p>\n\n<pre><code>private boolean[] result = new boolean[MAX + 1];\n</code></pre>\n\n<p>then change <code>2237</code> to the following:</p>\n\n<pre><code>final int maxSquare = (int) Math.ceil(Math.sqrt(MAX));\nfor (int i = 2; i &lt;= maxSquare; i++) { ... }\n</code></pre></li>\n<li><p><code>numList</code> only used in the constructor, so it could be a local variable there instead of a field. Try to minimize the scope of variables. See <em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>.</p></li>\n<li><p>Actually, I'd rename <code>numList</code> to <code>perfectPowers</code> since it stores perfect powers. I'd make the code more readable and easier to maintain.</p></li>\n<li><p>You set the initial capacity of the list to <code>5000000</code> while it contains only about 2500 elements. It's a huge memory wasting. I'd use the default constructor of the <code>ArrayList</code> which use less memory.</p>\n\n<pre><code>final List&lt;Long&gt; perfectPowers = new ArrayList&lt;Long&gt;();\n</code></pre></li>\n<li><p><code>Math.pow</code> uses floating point numbers which are not always precise. For small numbers it's correct, but for big numbers it not:</p>\n\n<pre><code>final long a = 97761243;\nfinal long aa = a * a;\nSystem.out.println(\"long \" + aa);\nSystem.out.println(\"Math.pow \" + ((long) Math.pow(a, 2)));\nSystem.out.println(\"BigInteger.pow: \" + BigInteger.valueOf(a).pow(2).longValue());\n</code></pre>\n\n<p>It prints:</p>\n\n<pre><code>long 9557260632905049\nMath.pow 9557260632905048\nBigInteger.pow: 9557260632905049\n</code></pre>\n\n<p>So, I'd change the <code>while</code> loop to the following:</p>\n\n<pre><code>long value;\nwhile ((value = BigInteger.valueOf(i).pow(j).longValue()) &lt;= MAX) {\n perfectPowers.add(value);\n j++;\n}\n</code></pre></li>\n<li><p>Some additional changes on the same loop would result the following:</p>\n\n<pre><code>while (true) {\n final long value = BigInteger.valueOf(i).pow(j).longValue();\n if (value &gt; MAX) {\n break;\n }\n perfectPowers.add(value);\n j++;\n}\n</code></pre>\n\n<p>It does the same but I think it's easier to read.</p></li>\n<li><p>In the first for loop I'd rename <code>i</code> to <code>base</code> and <code>j</code> to <code>exponent</code>, and the parameters of the <code>howMany</code> method to <code>lowerBound</code> and <code>upperBound</code>.</p></li>\n<li><p>The empty <code>static</code> block is unnecessary:</p>\n\n<pre><code>static {\n}\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T20:38:28.240", "Id": "15075", "ParentId": "15060", "Score": "36" } }, { "body": "<p>In addition to the other answers' points which don't need reiterating,</p>\n\n<p>In almost all cases, a <code>boolean[]</code> can be replaced with a <code>BitSet</code>. It takes a significant (and deterministic) amount of space, and provides you with logical operations that, if you tried to do manually on a <code>boolean[]</code> you likely introduce subtle bugs into at worst, and would reinvent the wheel at best. :-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T15:53:33.173", "Id": "24478", "Score": "0", "body": "lol, will BitSet be more efficient than boolean arrarys?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T01:09:09.000", "Id": "15078", "ParentId": "15060", "Score": "10" } }, { "body": "<p>That's how I would write it:</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.List;\n\npublic class SumsOfPerfectPowers {\n\n private final static int SIZE = 5000001;\n private final boolean[] result = new boolean[SIZE];\n\n public SumsOfPerfectPowers() {\n List&lt;Long&gt; numList = fillNumList();\n fillResults(numList);\n }\n\n private List&lt;Long&gt; fillNumList() {\n List&lt;Long&gt; numList = new ArrayList&lt;Long&gt;(SIZE);\n numList.add(0L);\n numList.add(1L);\n int limit = 1 + (int) Math.sqrt(SIZE);\n for (int i = 2; i &lt;= limit; i++) {\n for(long j = 2, value = i*i; value &lt; SIZE; j++, value = (long) Math.pow(i, j)) {\n numList.add(value);\n }\n }\n return numList;\n }\n\n private void fillResults(List&lt;Long&gt; numList) {\n int len = numList.size();\n for (int i = 0; i &lt; len; i++) {\n for (int j = 0; j &lt; len; j++) {\n int value = (int) (numList.get(i) + numList.get(j));\n if (value &lt; SIZE) {\n result[value] = true;\n }\n }\n }\n }\n\n public int howMany(int a, int b) {\n int sum = 0;\n for(int i=a; i&lt;=b; i++) {\n sum += result[i] ? 1 : 0;\n }\n return sum;\n }\n\n //...\n}\n</code></pre>\n\n<ul>\n<li>usually members should be private (there are exceptions, e.g. for final members it <em>might</em> be OK to make them public)</li>\n<li>don't use magic numbers, give them a name. Or let the client provide them (maybe have a sensible default)</li>\n<li>prefer <code>for</code> loops, note that you can have multiple init and step parts. Generally, try to limit the scope of your variables</li>\n<li>the \"assign then compare\" pattern in <code>while</code> is <strong>not kewl</strong></li>\n<li>try to make your methods smaller</li>\n<li>prefer interfaces over concrete classes (e.g. <code>List</code>)</li>\n<li>don't hold unnecessary data in your objects. For such a long list even uncle Bob would avoid it</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T14:49:37.627", "Id": "15083", "ParentId": "15060", "Score": "5" } }, { "body": "<h3>Constructor</h3>\n\n<ul>\n<li><strong>Magic numbers:</strong> You have unexplained constants all over the place: 5000001, 2237, 5000000. The limit should be defined just once, preferably as a parameter to the constructor.</li>\n<li><strong>Use of long:</strong> Array indices can only be <code>int</code>, not <code>long</code> (<a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.4\" rel=\"nofollow noreferrer\">JLS Sec 10.4</a>). Therefore, the largest limit you can support is <code>Integer.MAX_VALUE</code>. If that's the case, then <code>numList</code> should also store <code>Integer</code>s, not <code>Long</code>s. However, I would still recommend the use of <code>long</code> to store your intermediate sums and products to protect against overflow.</li>\n<li><p><strong>Use of floating point:</strong> Floating point calculations should <a href=\"http://falseproofs.blogspot.ca/2006/06/simpsons-and-fermats-last-theorem.html\" rel=\"nofollow noreferrer\">never</a> be used in proofs of integer arithmetic.</p>\n\n<p><img src=\"https://i.stack.imgur.com/b7355.jpg\" alt=\"enter image description here\"></p>\n\n<p>I would start your constructor like this:</p>\n\n<pre><code>public SumsOfPerfectPowers(int limit) {\n this.limit = limit;\n\n SortedSet&lt;Integer&gt; perfectPowers = new TreeSet&lt;Integer&gt;();\n perfectPowers.add(0);\n perfectPowers.add(1);\n for (int base = 2; base * base &lt; limit; base++) {\n for (long n = base * base; n &lt; limit; n *= base) {\n // n is long to guard against overflow.\n // Casting n to int is safe because n &lt; limit, which is an int.\n perfectPowers.add((int)n);\n }\n }\n // List traversal is faster than tree traversal\n this.perfectPowers = new ArrayList&lt;Integer&gt;(perfectPowers);\n\n // etc.\n}\n</code></pre></li>\n<li><p><strong>Commutativity:</strong> Since <em>a</em> + <em>b</em> = <em>b</em> + <em>a</em>, you can cut your inner loop in half, on average, when building <code>result</code>. If the list of perfect powers is sorted, like I have done so above, then more short-circuiting is possible.</p>\n\n<pre><code>this.sumOf2 = new boolean[limit];\nfor (int i = 0; i &lt; this.perfectPowers.size(); i++) {\n for (int j = 0; j &lt;= i; j++) {\n int n = this.perfectPowers.get(i) + this.perfectPowers.get(j);\n if (0 &lt; n &amp;&amp; n &lt; limit) {\n sumOf2[n] = true;\n } else {\n break;\n }\n }\n}\n</code></pre></li>\n</ul>\n\n<h3><code>howMany()</code></h3>\n\n<ul>\n<li><strong>Naming:</strong> It wasn't immediately obvious to me what the purpose of <code>howMany()</code> was until I read the code. I suggest renaming <code>howMany()</code> to <code>countInInterval()</code>.</li>\n<li><p><strong>Inclusive-inclusive <em>vs.</em> inclusive-exclusive bounds:</strong> Inclusive-exclusive bounds are a very common pattern, especially in languages whose arrays are indexed from 0. For-loop conditions usually check for <code>i &lt; n</code>, not <code>i &lt;= n</code>. For more examples, consider also:</p>\n\n<ul>\n<li><a href=\"http://www.cplusplus.com/reference/vector/vector/end/\" rel=\"nofollow noreferrer\"><code>std::vector::end</code></a> in C++</li>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)\" rel=\"nofollow noreferrer\"><code>String.substring(beginIndex, endIndex)</code></a> in Java</li>\n<li><a href=\"http://docs.python.org/2/library/functions.html#range\" rel=\"nofollow noreferrer\"><code>range(start, stop)</code></a> in Python</li>\n</ul>\n\n<p>Therefore, I would consider it reasonable for this function to take as parameters an inclusive lower bound and and exclusive upper bound.</p></li>\n</ul>\n\n<p>With a bit of variable renaming thrown in…</p>\n\n<pre><code>public int countInInterval(int lbIncl, int ubExcl) {\n int count = 0;\n for (int i = lbIncl; i &lt; ubExcl; i++) {\n if (this.sumOf2[i]) {\n count++;\n }\n }\n return count;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T07:06:29.543", "Id": "36684", "ParentId": "15060", "Score": "3" } } ]
{ "AcceptedAnswerId": "15075", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T14:18:46.600", "Id": "15060", "Score": "24", "Tags": [ "java", "algorithm", "mathematics" ], "Title": "Sums of perfect powers" }
15060
<p>I have this kind of file structure</p> <blockquote> <pre><code>MALE:FooBar:32 FEMALE:BarFoo:23 </code></pre> </blockquote> <p>Where I would want to identify the gender and age of person, <code>&lt;Gender&gt;:&lt;Name&gt;:&lt;age&gt;</code></p> <pre><code>try{ BufferedReader in = new BufferedReader(new FileReader("people.ser")); String s; while((s = in.readLine()) != null){ String[] var = s.split(":"); //var[0]=MALE etc etc addGender.add(var[0]); } }catch(Exception e){ e.printStackTrace(); } </code></pre> <ul> <li>Is using a delimiter (like a <code>:</code> in this case) to split string considered a bad practice? </li> <li>What about using the array from the splitted string to store it in some place? </li> <li>Are there any alternatives and better file structure?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T08:06:42.403", "Id": "24502", "Score": "0", "body": "String.split(RegEx) is the now recommended for new Java'versions (StringTokenizer for old version compatibility). With 'palacsint' advices, you code look fine." } ]
[ { "body": "<p>I don't think that using <code>:</code> is a bad practice but you have to escape it somehow if it occurs inside your data. Anyway, I'd consider using XML or JSON here.</p>\n\n<p>Some notes about the code:</p>\n\n<ol>\n<li>You should close the stream (in a <code>finally</code> block). See <em>Guideline 1-2: Release resources in all cases</em> in <a href=\"http://www.oracle.com/technetwork/java/seccodeguide-139067.html\">Secure Coding Guidelines for the Java Programming Language</a></li>\n<li>The <code>.ser</code> file extension is often used for serialized Java objects. I'd use something else to avoid the possible confusion.</li>\n<li><p>It's a good practice to set the character set when you read a text file. The used <code>FileReader</code> always uses the default charset which could vary from system to system. Consider using <code>InputStreamReader</code> and <code>FileInputStream</code> as the <a href=\"http://docs.oracle.com/javase/6/docs/api/java/io/FileReader.html\">documentation of <code>FileReader</code> says</a>. Here is an example:</p>\n\n<pre><code>FileInputStream fileInputStream = null;\nInputStreamReader inputStreamReader = null;\nBufferedReader bufferedReader = null;\ntry {\n fileInputStream = new FileInputStream(\"people.dat\");\n inputStreamReader = new InputStreamReader(fileInputStream, \"UTF-8\");\n bufferedReader = new BufferedReader(inputStreamReader);\n\n // use BufferedReader here\n} finally {\n IOUtils.closeQuietly(bufferedReader);\n IOUtils.closeQuietly(inputStreamReader);\n IOUtils.closeQuietly(fileInputStream);\n}\n</code></pre>\n\n<p>It uses <a href=\"http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html\"><code>IOUtils</code> from Apache Commons IO</a> and closes the <code>FileInputStream</code> even if the constructor of <code>InputStreamReader</code> or <code>BufferedReader</code> throws an exception.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T01:19:54.623", "Id": "24463", "Score": "0", "body": "How would I do number 3?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T01:27:21.730", "Id": "24464", "Score": "0", "body": "@KyelJmD: See the edit, please." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T05:39:10.017", "Id": "24466", "Score": "0", "body": "why did you use final?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T08:46:38.100", "Id": "24467", "Score": "0", "body": "@KyelJmD: `final` helps readers and maintainers, because they know that the reference always points to the same instance and it doesn't change later. http://programmers.stackexchange.com/questions/115690/why-declare-final-variables-inside-methods but you can find other questions on Programmers.SE in the topic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T09:50:24.200", "Id": "24472", "Score": "0", "body": "I would place those final variables in the class? or inside a method that calls them?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T18:01:03.820", "Id": "24488", "Score": "0", "body": "@KyelJmD: I've added a more detailed example." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T00:58:51.323", "Id": "15077", "ParentId": "15062", "Score": "8" } }, { "body": "<p>Scanner is a bit easier to use then BufferedReader...</p>\n\n<pre><code>import java.io.File;\nimport java.io.FileNotFoundException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Scanner;\n\n\npublic class Main {\n\n public static void main(String[] args) { \n try {\n File f = new File(\"people.ser\");\n Scanner sc = new Scanner(f);\n\n List&lt;Person&gt; people = new ArrayList&lt;Person&gt;();\n\n while(sc.hasNextLine()){\n String line = sc.nextLine();\n String[] details = line.split(\":\");\n String gender = details[0];\n String name = details[1];\n int age = Integer.parseInt(details[2]);\n Person p = new Person(gender, name, age);\n people.add(p);\n }\n\n for(Person p: people){\n System.out.println(p.toString());\n }\n\n } catch (FileNotFoundException e) { \n e.printStackTrace();\n }\n }\n}\n\nclass Person{\n\n private String gender;\n private String name;\n private int age;\n\n public Person(String gender, String name, int age){\n this.gender = gender;\n this.setName(name);\n this.age = age;\n }\n\n /**\n * @return the gender\n */\npublic String getGender() {\n return gender;\n}\n\n/**\n * @param gender the gender to set\n */\npublic void setGender(String gender) {\n this.gender = gender;\n}\n\n/**\n * @param name the name to set\n */\npublic void setName(String name) {\n this.name = name;\n}\n\n/**\n * @return the name\n */\npublic String getName() {\n return name;\n}\n\n/**\n * @return the age\n */\npublic int getAge() {\n return age;\n}\n\n/**\n * @param age the age to set\n */\npublic void setAge(int age) {\n this.age = age;\n}\n\npublic String toString(){\n return this.gender + \" \" + this.name + \" \" + this.age;\n}\n\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T00:39:18.730", "Id": "33042", "Score": "0", "body": "`toString()` method should use `StringBuilder` instead of concatenation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-25T09:02:04.677", "Id": "129354", "Score": "0", "body": "Since the toString() method is likely only used for debugging purposes, I'd say readability trumps performance here and the current implementation is a lot more readable. In case it is used in heavy iteration, that might be a different case." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-01T01:20:47.787", "Id": "15257", "ParentId": "15062", "Score": "4" } } ]
{ "AcceptedAnswerId": "15077", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T16:59:41.817", "Id": "15062", "Score": "5", "Tags": [ "java", "file", "file-structure" ], "Title": "Reading a line from a text file and splitting its contents" }
15062
<p>I am new to programming and have written this <code>Data Access Layer</code>. I am using this <code>DAL</code> in my projects. Now, I have a feeling that it is pathetic (when I wrote it, I was kind of happy). Do you guys also feel the same for this <code>DAL</code>. Kindly help me write a better one. There is no <code>Transaction</code> in my <code>DAL</code> and I have no idea how to implement it in this <code>DAL</code>. I am expecting some criticism.</p> <p><strong>Connections.vb Class File</strong></p> <pre><code>Option Explicit On Option Strict On Imports Microsoft.VisualBasic Imports System.Data.SqlClient Public Class Connection Public Shared Function GetDbConnection() As SqlConnection Dim _conString As String = ConfigurationManager.ConnectionStrings("CoachingConnectionString").ConnectionString Dim _connection As New SqlConnection(_conString) _connection.Open() Return _connection End Function End Class </code></pre> <p><strong>DataAccess.vb Class File</strong></p> <pre><code>Option Explicit On Option Strict On Imports Microsoft.VisualBasic Imports System.Data.SqlClient Imports System.Data Public Class DataAccess Public Overloads Shared Function GetDataTable(ByVal _sql As String, ByVal _parameterNames() As String, ByVal _parameterVals() As String) As DataTable Dim _connection As SqlConnection = Global.Connection.GetDbConnection() Dim _command As New SqlDataAdapter(_sql, _connection) Dim _table As New DataTable Try If _parameterNames IsNot Nothing Then For i = 0 To _parameterNames.Length - 1 _command.SelectCommand.Parameters.AddWithValue(_parameterNames(i), _parameterVals(i)) Next End If _command.Fill(_table) Catch ex As Exception 'MsgBox(ex.Message) _table = Nothing Finally If _connection.State = ConnectionState.Open Then _connection.Close() _connection.Dispose() _command.Dispose() End If End Try Return _table End Function Public Overloads Shared Function GetDataTable(ByVal _sql As String) As DataTable Dim _connection As SqlConnection = Global.Connection.GetDbConnection() Dim _command As New SqlDataAdapter(_sql, _connection) Dim _table As New DataTable Try _command.Fill(_table) Catch ex As Exception 'MsgBox(ex.Message) _table = Nothing Finally If _connection.State = ConnectionState.Open Then _connection.Close() _connection.Dispose() _command.Dispose() End If End Try Return _table End Function Public Shared Function SelectScalar(ByVal _sql As String, ByVal _parameterNames() As String, ByVal _parameterVals() As String) As String Dim _returnVal As String Dim _connection As SqlConnection = Global.Connection.GetDbConnection() Dim _command As New SqlCommand(_sql, _connection) Dim _value As String Try If _parameterNames IsNot Nothing Then For i = 0 To _parameterNames.Length - 1 _command.Parameters.AddWithValue(_parameterNames(i), _parameterVals(i)) Next End If _value = CStr(_command.ExecuteScalar) _returnVal = _value Catch ex As Exception _returnVal = Nothing Finally If _connection.State = ConnectionState.Open Then _connection.Close() _connection.Dispose() _command.Dispose() End If End Try Return _returnVal End Function Public Shared Function SelectScalar(ByVal _sql As String) As String Dim _returnVal As String Dim _connection As SqlConnection = Global.Connection.GetDbConnection() Dim _command As New SqlCommand(_sql, _connection) Dim _value As String Try _value = CStr(_command.ExecuteScalar) _returnVal = _value Catch ex As Exception _returnVal = Nothing Finally If _connection.State = ConnectionState.Open Then _connection.Close() _connection.Dispose() _command.Dispose() End If End Try Return _returnVal End Function Public Shared Function CRUD(ByVal _sql As String, ByVal _parameterNames() As String, ByVal _parameterVals() As String) As Integer Dim _noOfRowsAffected As Integer Dim _connection As SqlConnection = Global.Connection.GetDbConnection() Dim _command As New SqlCommand(_sql, _connection) Try If _parameterNames IsNot Nothing Then For i = 0 To _parameterNames.Length - 1 _command.Parameters.AddWithValue(_parameterNames(i), _parameterVals(i)) Next End If _noOfRowsAffected = _command.ExecuteNonQuery() Catch ex As Exception 'MsgBox(ex.Message) _noOfRowsAffected = -1 Finally If _connection.State = ConnectionState.Open Then _connection.Close() _connection.Dispose() _command.Dispose() End If End Try Return _noOfRowsAffected End Function End Class </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T18:17:25.387", "Id": "24444", "Score": "2", "body": "Why not use ORM / MVC / EF ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T18:21:48.313", "Id": "24445", "Score": "0", "body": "Actually am using ASP.NET web forms and new to programming...so i hope you understand..what is ORM..and kindly point out the major cons with my `DAL` so that i can learn what are my mistakes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T19:03:11.320", "Id": "24451", "Score": "0", "body": "Watch this whole video for a hint - the Object Relational Mapping (ORM) is taken care of by the Entity Framework http://www.youtube.com/watch?v=2AWVs7SzOXM&feature=related" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T19:13:43.190", "Id": "24453", "Score": "0", "body": "@Leonid Thanks for the link...i am watching it now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T09:54:52.883", "Id": "62779", "Score": "0", "body": "you can create <http://en.wikipedia.org/wiki/Strategy_pattern> if you have more than one database to connect, so that you can dynamically change your strategy (database type like msaccess, mysql, oracle etc). I recommend this approach." } ]
[ { "body": "<p>The first part of the answer has already been given by <a href=\"https://codereview.stackexchange.com/users/9778/leonid\">Leonid</a>: \"don't create your own data access methodology\". Use something like Entity Framework. This is a frequently-used \"wheel\": don't reinvent it.</p>\n\n<p>That said, there are a number of issues with your code:</p>\n\n<ol>\n<li>You do not need a separate class for your <code>GetDbConnection</code> function. Put it into your <code>DataAccess</code> class and make it <code>Private</code>.</li>\n<li>The <code>SqlConnection</code> and <code>SqlDataAdapter</code> classes implement the <code>IDisposable</code> interface. When you create an object of such a type, and consume it entirely within your method, you should place the object in a <code>Using</code> block. This ensures it gets cleaned up as you are doing in your <code>Finally</code>.</li>\n<li>Given #2, you don't need Try/Catch blocks at all. In your case, they have the primary effect of hiding any exceptions that may be thrown, so that you will never know what's wrong with your code.</li>\n<li>You have duplicated the code for filling the parameters. Extract that into a separate method.</li>\n<li>I recommend that you use a leading \"_\" only for class-level fields, and not for the parameters to a Function or Sub.</li>\n</ol>\n\n<p>Here's the result of a quick refactoring of your code to resolve those issues:</p>\n\n<pre><code>Option Explicit On\nOption Strict On\n\nImports System.Data.SqlClient\nImports System.Configuration\n\nPublic Class DataAccess\n Public Overloads Shared Function GetDataTable(ByVal sql As String, ByVal parameterNames() As String, ByVal parameterVals() As String) As DataTable\n Using connection As SqlConnection = GetDbConnection()\n Using da As SqlDataAdapter = New SqlDataAdapter(sql, connection)\n Dim table As New DataTable\n FillParameters(da.SelectCommand, parameterNames, parameterVals)\n da.Fill(table)\n Return table\n End Using\n End Using\n End Function\n\n Public Overloads Shared Function GetDataTable(ByVal sql As String) As DataTable\n Using connection As SqlConnection = GetDbConnection()\n Using da As New SqlDataAdapter(sql, connection)\n Dim table As New DataTable\n da.Fill(table)\n Return table\n End Using\n End Using\n End Function\n\n Public Shared Function SelectScalar(ByVal sql As String, ByVal parameterNames() As String, ByVal parameterVals() As String) As String\n Using connection As SqlConnection = GetDbConnection()\n Using command As SqlCommand = New SqlCommand(sql, connection)\n FillParameters(command, parameterNames, parameterVals)\n Return CStr(command.ExecuteScalar)\n End Using\n End Using\n End Function\n\n Public Shared Function SelectScalar(ByVal sql As String) As String\n Using connection As SqlConnection = GetDbConnection()\n Using command As New SqlCommand(sql, connection)\n Return CStr(command.ExecuteScalar)\n End Using\n End Using\n End Function\n\n Public Shared Function CRUD(ByVal sql As String, ByVal parameterNames() As String, ByVal parameterVals() As String) As Integer\n Using connection As SqlConnection = GetDbConnection()\n Using command As New SqlCommand(sql, connection)\n FillParameters(command, parameterNames, parameterVals)\n Return command.ExecuteNonQuery()\n End Using\n End Using\n End Function\n\n Private Shared Sub FillParameters(ByVal command As SqlCommand, ByVal parameterNames As String(), ByVal parameterVals As String())\n If parameterNames IsNot Nothing Then\n For i = 0 To parameterNames.Length - 1\n command.Parameters.AddWithValue(parameterNames(i), parameterVals(i))\n Next\n End If\n End Sub\n\n\n Private Shared Function GetDbConnection() As SqlConnection\n Dim conString As String = ConfigurationManager.ConnectionStrings(\"CoachingConnectionString\").ConnectionString\n Dim connection As SqlConnection = New SqlConnection(conString)\n connection.Open()\n Return connection\n End Function\nEnd Class\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T15:59:59.613", "Id": "24479", "Score": "0", "body": "Which `ORM` would you recommend?? I want something easy to learn with not a very steep learning curve. Which one would you prefer ?? `Microsoft Enterprise Library 5.0` or `MS Entity Framework` or `NHibernate`. Any other suggestions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T17:30:22.417", "Id": "24487", "Score": "1", "body": "Entity Framework. It's from Microsoft. Enterprise Library is not an ORM." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T21:18:15.807", "Id": "15076", "ParentId": "15063", "Score": "7" } } ]
{ "AcceptedAnswerId": "15076", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T17:14:55.600", "Id": "15063", "Score": "4", "Tags": [ "design-patterns", "asp.net", "vb.net" ], "Title": "Writing a Data Access Layer" }
15063
<p>I tried to solve the <a href="https://www.interviewstreet.com/challenges/dashboard/#problem/4f7272a8b9d15" rel="nofollow">Unfriendly Number</a> problem on InterviewStreet:</p> <blockquote> <p>There is one friendly number, K, and N unfriendly numbers. We want to find how many numbers are there which exactly divide the friendly number, but does not divide any of the unfriendly numbers. </p> <p>\$1 \le N \le 10^6\$</p> <p>\$1 \le K \le 10^13\$</p> <p>\$1 \le\$ unfriendly numbers \$\le 10^{18}\$</p> </blockquote> <p>The algorithm is quite simple: </p> <ol> <li>Find the set S. The set of gcd's of each unfriendly number with the friendly number.</li> <li>Find the set of divisors of the friendly number. </li> <li>Check if a divisor of the friendly number is a divisor of any element in S.</li> </ol> <p>My code, where <code>u</code> is the list of unfriendly numbers, <code>k</code> is the friendly number. <code>nubOrd</code> is the <code>O(n log n)</code> time version of <code>nub</code>.</p> <pre><code>test u k = length $ filter (not) $ map try divisors where try t = or $ map (t `divides` ) (nubOrd $ map (gcd k) u) divisors = concat [ [i,div k i] | i&lt;-[1..floor $ sqrt $ fromIntegral k], i `divides` k] d `divides` n = n `mod` d == 0 </code></pre> <p>This code exceeds the time limit. The Java version of this algorithm solves the problem fine. Are there any ways to improve this code or is Haskell too slow for solving this problem?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:30:52.913", "Id": "24440", "Score": "0", "body": "It might be more efficient to replace the `length . filter not . map try` chain with a fold like `foldl (\\count t -> if try t then count + 1 else count) 0` (probably with more strictness). But it's unlikely to make that much difference, since GHC is pretty smart." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:39:27.100", "Id": "24441", "Score": "0", "body": "can we see your `nubOrd`? You compile it with -O2 right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T16:10:18.047", "Id": "24442", "Score": "0", "body": "the nubOrd is the one here: http://stackoverflow.com/a/3100764/303863" } ]
[ { "body": "<p>Your divisors generation is lacking. As explained e.g. <a href=\"https://stackoverflow.com/a/12052561/849891\">here</a>, you should generate them from a number's prime factorization. It is much faster that way.</p>\n\n<p>You may try using <code>rem</code> instead of <code>mod</code>.</p>\n\n<p>Also try making <code>(nubOrd $ map (gcd k) u)</code> a separate expression and name it to ensure sharing, giving your function a concrete type signature too.</p>\n\n<p><strong>update</strong> so I tried my own advice and it only made the code run slower at the interviewstreet servers. The only reason I'm not removing this, is that the advice itself (and link) about divisor generation is valid in general. But here, it did not help improve the run time of <em>this algorithm</em>. The OP states that <em>same algorithm</em> in Java got through...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-17T06:22:39.847", "Id": "102297", "Score": "0", "body": "InterviewStreet may not compile Haskell code with -O2." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:28:57.153", "Id": "15065", "ParentId": "15064", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:19:07.650", "Id": "15064", "Score": "2", "Tags": [ "haskell", "time-limit-exceeded" ], "Title": "\"Unfriendly Number\" challenge" }
15064
<p>I often get lines like this in my Apache error log:</p> <blockquote> <p>File does not exist: /path/to/www/data:image/gif;base64,R0lGODlhBgAGAIAOAP/yH5BAEACAEALAAAAAAGGAYAAAIJhB0Xi5vOoFwFADs=</p> </blockquote> <p>Obviously, this is due to somebody using an outdated browser (or a robot) which doesn't handle inline images (Data URI/base64 encoded).</p> <p>I am thinking it must be easy to redirect requests starting with <code>"data:image/gif;base64,"</code> to a short perl CGI script which returns the requested value as a binary image, with the correct content header (both GIFs and PNGs are used), and without having to read any image files.</p> <p>I am thinking something along the lines of the following CGI (after a rewrite places the request URL in the query string):</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use MIME::Base64 (); $ENV{QUERY_STRING} =~ m{^data:(\w+/\w+);base64,(.+)$} or die "bad input"; print "Content-Type: $1\n\n"; print MIME::Base64::decode ($2); </code></pre> <p>Would that work and would there be any downsides to this approach (apart from accommodating people with last-century browsers)?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-25T18:23:58.363", "Id": "24446", "Score": "0", "body": "@W3Coder Asking about voting is inappropriate for the comments section. Please refrain from asking about downvotes in the future." } ]
[ { "body": "<p>The only real problem I see is that if the browser is really \"last century\" it probably won't support a long enough query string to contain the full image. So your returned image might be incomplete. Another thing is that this would waste a lot of bandwidth.</p>\n\n<p>I see two options</p>\n\n<ul>\n<li><p>To suppress those error messages you could just handle those URLs like you and make a header redirect (to use the browser cache!) to an error/empty image.</p></li>\n<li><p>Use conditional comments to load inline images on <code>IE &lt; 8</code> with a normal img:src attribute. Since your culprit is most likely an Internet Explorer (people who install alternate browsers usually keep them up to date)</p></li>\n</ul>\n\n<p>I would use the first actually, as it does not involve changing code.</p>\n\n<p>To test whether your solution works, start Internet Explorer (9), open the Web Development tools, and dial it back to IE 6 or 7 (best try both)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T09:02:23.130", "Id": "24607", "Score": "0", "body": "Good answer, will accept it within a couple of weeks if nothing else comes up. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T22:14:45.923", "Id": "15116", "ParentId": "15066", "Score": "2" } } ]
{ "AcceptedAnswerId": "15116", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-18T11:08:52.147", "Id": "15066", "Score": "1", "Tags": [ "regex", "error-handling", "perl", "base64", "cgi" ], "Title": "Perl CGI script to respond to erroneous Base64 image requests" }
15066
<p>I am trying to simplify the following massive conditional statement but have no idea how to. Does anyone have suggestions for it?</p> <pre><code>//regular elements use the normal position variables. var tooltipXPos = xPos; var tooltipYPos = yPos-$tooltipElement.height()-YOffset; //individual elements position shifting... //for sub_link on top if ($element.is('#uilder') || $element.is('#options')) { tooltipYPos = yPos + 35; } //expend button after do search in Search page if ($element.is('#extend')) { tooltipXPos = xPos - 240; } if ($element.is('#lis')) { tooltipXPos = xPos - 295; tooltipYPos = yPos - 80; } if ($element.is('#count')) { tooltipXPos = xPos + 180; tooltipYPos = yPos - 90; } if ($element.is('label')) { tooltipXPos = xPos + 80; tooltipYPos = yPos - 90; } if ($element.is('#add')) { tooltipXPos = xPos -280; tooltipYPos = yPos -120; } if ($element.is('title_label')) { tooltipXPos = xPos + 35; tooltipYPos = yPos -75; } //assign homework by class button under homework tab.. if ($element.is('#control')) { tooltipXPos = xPos -270; } //place the tutorial window $tooltipElement.css({ position: 'absolute', top: tooltipYPos, left: tooltipXPos, 'z-index': 9999 }) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:57:25.447", "Id": "24447", "Score": "0", "body": "Problem is, it's not a massive conditional. It's just a lot of individual conditionals. Could use a switch I guess..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:58:11.350", "Id": "24448", "Score": "0", "body": "Flagged as an nearly exact duplicate of the closed http://stackoverflow.com/questions/12096001/how-to-make-my-conditional-statement-less-ugly" } ]
[ { "body": "<p>Create an array which contains : </p>\n\n<ul>\n<li>the id of element</li>\n<li>the offset x</li>\n<li>the offset y </li>\n</ul>\n\n<p>then, loop on each element of this array and do a single if.</p>\n\n<p>Something like that (not tested)</p>\n\n<pre><code>var items = [\n {name: '#te_classbuilder', x: -120, y: -0},\n {name: '#lesson-details-extend-button', x: 0, y: 120},\n {name: 'label', x: 100, y: -120}\n];\n\nfor (var i = 0; i &lt; items.length; i++) {\n\n var item = items[i];\n\n if ($element.is(items[i].name) {\n tooltipXPos = xPos + item.x; \n tooltipYPos = yPos + item.y;\n }\n}\n</code></pre>\n\n<p>If you know the key, use a map and don't use a loop in the array, simply get the item of the map using the key.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:57:58.220", "Id": "15068", "ParentId": "15067", "Score": "4" } }, { "body": "<p>I would use an object. Since it seems you are switching off the individual ids of each element, I would set the ids as keys.</p>\n\n<pre><code>var positions = {\n '#te_classbuilder': {x: 100, y: 120},\n}\n</code></pre>\n\n<p>To get the <code>x,y</code> of an element, find the keyname by the id attribute of the element:</p>\n\n<pre><code>var obj = positions[$element.attr(\"id\")]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:58:36.040", "Id": "15069", "ParentId": "15067", "Score": "0" } }, { "body": "<p>You could make an id-to-position map first:</p>\n\n<pre><code> var offsetMap = { \n \"lesson-details-extend-button\": \n { y: 35 },\n \"te_classbuilder\":\n { x: -240 },\n \"asset-list-asset-add-button\":\n { x: -295, y: -80 },\n // etc...\n };\n</code></pre>\n\n<p>Then assign the values:</p>\n\n<pre><code>var offset = offsetMap[$element.attr('id')];\nif (offset.y) tooltipYPos=yPos + offset.y; \nif (offset.x) tooltipXPos=xPos + offset.x; \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T16:00:26.183", "Id": "15070", "ParentId": "15067", "Score": "0" } }, { "body": "<p>DRY and get rid of those \"Magic Numbers\". As in:</p>\n\n<pre><code>tooltipXPos = xPos + 180; \ntooltipYPos = yPos - 90;\n</code></pre>\n\n<p>Things like magic numbers will break your design and your code over time. Also, people coming into your code later won't know how or why you used those. It would be complete trial and error. Your code and design should be robust and pure enough to avoid having to use static numbers to increment xy coords.</p>\n\n<p>As it is, you really can't avoid using a lot of conditional statements, especially without seeing what you're moving around. But you could wrap in a function and use id and coords as arugments. Example</p>\n\n<pre><code>function moveElements(id, x, y, offsetX, offsetY) {\n tooltipXPos = x + offsetX; \n tooltipYPos = y - offsetY;\n}\n\nif ( $element.is('#someid', moveElements(id, x, y, offsetX, offsetY) )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-22T07:21:30.840", "Id": "283392", "Score": "0", "body": "For now, I've edited the post to format code. Please see [How do I format my code blocks?](//meta.stackoverflow.com/q/251361)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T17:44:05.323", "Id": "15071", "ParentId": "15067", "Score": "0" } } ]
{ "AcceptedAnswerId": "15068", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-24T15:55:03.257", "Id": "15067", "Score": "1", "Tags": [ "javascript", "jquery", "css" ], "Title": "Positioning a tooltip relative to various kinds of elements" }
15067
<p>Similar to, but distinct from <a href="https://codereview.stackexchange.com/questions/12112/poker-hand-identifier">Poker hand identifier</a>. I'm working towards solving <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataPokerHands" rel="nofollow noreferrer">this kata</a>. The below code doesn't print the result yet, and it reads hand strings rather than game strings.</p> <p>Take 4:</p> <pre><code>import Data.String import Data.List import Data.Ord data Rank = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace deriving (Eq, Ord, Show, Bounded, Enum) instance Read Rank where readsPrec _ value = let tbl = zip "23456789TJQKA" [Two .. Ace] in case lookup (head value) tbl of Just r -&gt; [(r, tail value)] Nothing -&gt; error $ "Invalid rank: " ++ value data Suit = H | C | D | S deriving (Eq, Ord, Show, Read) data Card = Card { rank :: Rank, suit :: Suit } deriving (Eq, Ord, Show) instance Read Card where readsPrec _ [r, s] = [(Card (read [r]) (read [s]), "")] readsPrec _ value = error $ "Invalid card: " ++ value data Hand = Hand { handRank :: HandRank, cards :: [Card] } deriving (Eq, Show, Ord) instance Read Hand where readsPrec _ value = [(Hand (getHandRank res) res, "")] where res = reverse . sort . map read $ words value data HandRank = HighCard [Rank] | Pair [Rank] | TwoPair [Rank] | ThreeOfAKind [Rank] | Straight [Rank] | Flush [Rank] | FullHouse [Rank] | FourOfAKind [Rank] | StraightFlush [Rank] deriving (Eq, Ord, Show) data GameOutcome = Winner String Hand | Tie deriving (Eq, Ord) instance Show GameOutcome where show o = case o of Winner player hand -&gt; player ++ " wins with " ++ show (handRank hand) Tie -&gt; "Tie" isFlush :: [Card] -&gt; Bool isFlush = (1==) . length . group . map suit isStraight :: [Card] -&gt; Bool isStraight cards = let rs = sort $ map rank cards run = [(head rs) .. (last rs)] in rs == run getHandRank :: [Card] -&gt; HandRank getHandRank cards = let ranks = map rank cards rankGroups = sortByLen $ group ranks relevantRanks = map (!!0) rankGroups handRank = case cards of _ | isFlush cards &amp;&amp; isStraight cards -&gt; StraightFlush | has4 rankGroups -&gt; FourOfAKind | has3 rankGroups &amp;&amp; has2 rankGroups -&gt; FullHouse | isFlush cards -&gt; Flush | isStraight cards -&gt; Straight | has3 rankGroups -&gt; ThreeOfAKind | countGroupsOf 2 rankGroups == 2 -&gt; TwoPair | has2 rankGroups -&gt; Pair | otherwise -&gt; HighCard in handRank relevantRanks winner :: Hand -&gt; Hand -&gt; GameOutcome winner h1 h2 = case compare h1 h2 of GT -&gt; Winner "Player 1" h1 LT -&gt; Winner "Player 2" h2 EQ -&gt; Tie ------------------------------- -- General Utility Functions -- ------------------------------- hasGroupOf :: Int -&gt; [[a]] -&gt; Bool hasGroupOf n groups = n `elem` map length groups has4 = hasGroupOf 4 has3 = hasGroupOf 3 has2 = hasGroupOf 2 countGroupsOf :: Int -&gt; [[a]] -&gt; Int countGroupsOf n groups = length $ filter (\g -&gt; length g == n) groups sortByLen :: [[a]] -&gt; [[a]] sortByLen = sortBy (flip $ comparing length) </code></pre> <ul> <li>Added comparison function</li> <li>Fixed a bug relating to improper sorting in some situations (replaced <code>nub</code> with <code>relevantRanks</code> in <code>getHandRank</code></li> <li>Ran it through <code>hlint</code></li> </ul> <p>My only experience with Haskell so far is some playing around with <code>Parsec</code> and a few half-read-throughs of <a href="https://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours" rel="nofollow noreferrer">WYAS48</a>, so please be obnoxious about style issues.</p> <p>All feedback welcome, but I would particularly like to ask</p> <ol> <li>Are there built-ins/better implementations of the "General Utility" functions defined at the bottom?</li> <li>Is there a clearer or more succinct way of writing <code>Read Rank</code>?</li> <li>Is there a clearer or more flexible way of writing <code>getHandRank</code>, with particular emphasis on closely connecting those predicates with the <code>data</code> entry?</li> </ol>
[]
[ { "body": "<p>It's generally a good idea to give explicit type signatures for your top level definitions. It helps your code's readers (e.g. us) understand your code.</p>\n\n<p><code>hasGroupOf</code> looks perfectly clear (save for the missing type signature), but I'd write the other two like this:</p>\n\n<pre><code>import Data.Ord (comparing)\n\ncountGroupsOf :: Int -&gt; [a] -&gt; Int\ncountGroupsOf n groups = length $ filter (\\g -&gt; length g == n) groups\n\nsortByLen :: [[a]] -&gt; [[a]]\nsortByLen = sortBy (flip $ comparing length)\n</code></pre>\n\n<p>Actually, for that last one, I'd probably want lists of equal length to sort in a predictable order:</p>\n\n<pre><code>import Data.Monoid\n\nsortByLen :: [[a]] -&gt; [[a]]\nsortByLen = sortBy (mconcat [flip $ comparing length, compare])\n</code></pre>\n\n<p>(You are expected to know that <code>Ordering</code> is a monoid, and that <code>a -&gt; b</code> is a monoid when <code>b</code> is a monoid. The monoid I'm using is <code>[a] -&gt; [a] -&gt; Ordering</code>.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T04:00:36.363", "Id": "24491", "Score": "0", "body": "I took your advice on the type signatures and simplified functions (note that `countGroupsOf` actually has a type signature of `Int -> [[a]] -> Int`; I assume this only matters because we're mapping `length` over the contents of that argument). The monadic `sortByLen` threw me a type error, and I'm not *entirely* sure what it's doing, so I stuck with your first version." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T18:09:35.253", "Id": "15087", "ParentId": "15079", "Score": "3" } }, { "body": "<p>I think your <code>instance Read Card</code> can be improved. There's no reason to use <code>length</code> if you just want to know whether the length is 2 or not 2. If the length is 2 then <code>value</code> is [r,s] (<code>String</code> is just <code>[Char]</code>), so you can write</p>\n\n<pre><code>readsPrec _ [r,s] = ...\nreadsPres _ _ = ...\n</code></pre>\n\n<p>Then you can just do <code>read [r]</code> and <code>read [s]</code>. I don't think you have to specify <code>(read r :: Rank)</code> either. The compiler should be able to figure it out from the way you're using it. And of course if you know that <code>value</code> is of length 2, you know what <code>drop 2 value</code> is.</p>\n\n<p>I'm kind of sleepy so I apologize for any horrible mistakes I've made in this answer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T14:02:17.593", "Id": "24671", "Score": "0", "body": "Right on all counts" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T07:01:14.180", "Id": "15204", "ParentId": "15079", "Score": "2" } }, { "body": "<p>Your<code>rankGroups</code> list is sorted by the size of the group. If you reverse sort it you can use:</p>\n\n<pre><code>case rankGroups of\n (4:_) -&gt; -- four of a kind\n (3:2:_) -&gt; -- full house\n (3:_) -&gt; -- trips but not a full house\n (2:2:_) -&gt; -- two pair\n (2:_) -&gt; -- a pair but not two pair\n (1:_) -&gt; -- check for straights and flushes\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-03T21:18:02.873", "Id": "16173", "ParentId": "15079", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T03:13:24.637", "Id": "15079", "Score": "2", "Tags": [ "haskell", "playing-cards" ], "Title": "Poker Hand Kata" }
15079
<p>I have a database schema for a game to hold save files where some tables have a one-to-one relationship to classes. I was wondering if I should split up some tables.</p> <p>Example: <code>troop_class table</code>. It could have a PK of</p> <blockquote> <pre><code>{ GameID,PostionX,PostionY,PostionZ,Team } </code></pre> </blockquote> <p>but then team don't really rely on the positions and could be split to two new tables</p> <blockquote> <pre><code>game_units Keys{GameID, troop_id} PK{GameID} </code></pre> </blockquote> <p>and</p> <blockquote> <pre><code>troop_team{troop_id, Team} PK{troop_id}. </code></pre> </blockquote> <p>I am wondering if I should break up the one-to-one mapping for table-class and start to normalize and create proper PK instead of using <code>id</code>.</p> <pre><code>CREATE TABLE accounts( AccountName VARCHAR(50) UNIQUE NOT NULL, Password BLOB NOT NULL, PRIMARY KEY(AccountName) ) Engine=InnoDB; CREATE TABLE maps( maps_id INT NOT NULL UNIQUE, MapName VARCHAR(30) NOT NULL, PRIMARY KEY (maps_id), INDEX(maps_id) ) ENGINE=InnoDB; CREATE TABLE game_searching_player( AccountName VARCHAR(50) NOT NULL, MapID INT NOT NULL, PRIMARY KEY (AccountName, MapID), FOREIGN KEY (AccountName) REFERENCES accounts(AccountName) ON DELETE CASCADE , FOREIGN KEY (MapID) REFERENCES maps(maps_id) ON DELETE CASCADE , INDEX(AccountName) ) ENGINE=InnoDB; CREATE TABLE games( games_id INT NOT NULL AUTO_INCREMENT UNIQUE, Player1 VARCHAR(50) NOT NULL, Player2 VARCHAR(50) NOT NULL, WhosTurn INT NOT NULL, TurnHasEnded BOOL NOT NULL, HaveWon BOOL NOT NULL, TurnNumber INT NOT NULL, MapID INT NOT NULL, Type VARCHAR(30) NOT NULL, PRIMARY KEY (games_id), FOREIGN KEY (Player1) REFERENCES accounts(AccountName) ON DELETE CASCADE , FOREIGN KEY (Player2) REFERENCES accounts(AccountName) ON DELETE CASCADE , FOREIGN KEY (MapID) REFERENCES maps(maps_id) ON DELETE CASCADE , INDEX(games_id,Player1, Player2 ) ) ENGINE=InnoDB; CREATE TABLE player( GameID INT NOT NULL, Player VARCHAR(30) NOT NULL, VictoryResources INT NOT NULL, UniversalResources INT NOT NULL, Type VARCHAR(30) NOT NULL, PRIMARY KEY (GameID, Player), FOREIGN KEY (GameID) REFERENCES games(games_id) ON DELETE CASCADE , INDEX(GameID) ) ENGINE=InnoDB; CREATE TABLE troop_class ( troop_class_id INT NOT NULL AUTO_INCREMENT UNIQUE, GameID INT NOT NULL, Health INT NOT NULL, CombatInitiative INT NOT NULL, Spotted BOOL NOT NULL, Entrenched INT NOT NULL, Initiative INT NOT NULL, Ammo INT NOT NULL, Petrol INT NOT NULL, ActionPoints INT NOT NULL, IsMoving BOOL NOT NULL, PositionX INT NOT NULL, PositionY INT NOT NULL, PositionZ INT NOT NULL, Team VARCHAR(30) NOT NULL, Name VARCHAR(30) NOT NULL, Type VARCHAR(30) NOT NULL, PRIMARY KEY (troop_class_id), FOREIGN KEY (GameID) REFERENCES games(games_id) ON DELETE CASCADE , INDEX(GameID) ) ENGINE=InnoDB; CREATE TABLE supply_unit( supply_unit_id INT NOT NULL UNIQUE, SupplyPetrol INT NOT NULL, SupplyAmmo INT NOT NULL, VictoryResources INT NOT NULL, LoadWeight INT NOT NULL, MaxWeight INT NOT NULL, PRIMARY KEY (supply_unit_id), FOREIGN KEY (supply_unit_id) REFERENCES troop_class(troop_class_id) ON DELETE CASCADE ) ENGINE=InnoDB; CREATE TABLE central_warehouse ( central_warehouse_id INT NOT NULL AUTO_INCREMENT UNIQUE, GameID INT NOT NULL, SupplyPetrol INT NOT NULL, SupplyAmmo INT NOT NULL, VictoryResources INT NOT NULL, LoadWeight INT NOT NULL, MaxWeight INT NOT NULL, PositionX INT NOT NULL, PositionY INT NOT NULL, PositionZ INT NOT NULL, Team VARCHAR(30) NOT NULL, Name VARCHAR(30) NOT NULL, Type VARCHAR(30) NOT NULL, PRIMARY KEY (central_warehouse_id), FOREIGN KEY (GameID) REFERENCES games(games_id) ON DELETE CASCADE , INDEX(GameID) ) ENGINE=InnoDB; </code></pre>
[]
[ { "body": "<p>Here are a few suggestions, many of which are just \"best practices\" I've picked up along the way (or simplifications that would make things a bit more concise and easier to read). There are also a few ideas that will likely prevent common errors from happening to the code as it's maintained in the future (that I've run across in many code reviews).</p>\n\n<ol>\n<li><p>I'd create an id column on the <code>accounts</code> table:</p>\n\n<pre><code>CREATE TABLE accounts(\n account_id INT UNIQUE NOT NULL,\n AccountName VARCHAR(50) UNIQUE NOT NULL,\n Password BLOB NOT NULL,\n PRIMARY KEY(account_id)\n) Engine=InnoDB;\n</code></pre>\n\n<p>Then the tables that reference <code>accounts</code> like <code>game_searching_player</code> will reference an <code>INT</code> instead of <code>VARCHAR(50)</code> - (I think I see at least 4 references to that column, which would be much simpler if they were <code>int</code>s.) You may also likely get a small amount of performance improvement by using <code>INT</code> for these keys instead of <code>VARCHAR</code>s.</p></li>\n<li><p>MySQL automatically indexes <code>PRIMARY KEY</code>s, so no need for those explicit <code>INDEX</code> lines.</p>\n\n<p>For example, this:</p>\n\n<pre><code>PRIMARY KEY (maps_id),\nINDEX(maps_id)\n</code></pre>\n\n<p>would become just</p>\n\n<pre><code> PRIMARY KEY (maps_id)\n</code></pre></li>\n<li><p>MySQL's InnoDB engine automatically indexes <code>FOREIGN KEY</code>s, so no need for those explicit <code>INDEX</code> lines either (<code>player</code> and <code>troop_class</code> and <code>game_searching_player</code>).</p>\n\n<p>For example, this:</p>\n\n<pre><code>CREATE TABLE player(\n ...\n\n PRIMARY KEY (GameID, Player),\n FOREIGN KEY (GameID) REFERENCES games(games_id)\n ON DELETE CASCADE ,\n INDEX(GameID)\n\n) ENGINE=InnoDB;\n</code></pre>\n\n<p>becomes this:</p>\n\n<pre><code>CREATE TABLE player(\n ...\n\n PRIMARY KEY (GameID, Player),\n FOREIGN KEY (GameID) REFERENCES games(games_id)\n ON DELETE CASCADE\n\n) ENGINE=InnoDB;\n</code></pre></li>\n<li><p>You don't have <code>AUTO_INCREMENT</code> on all your table IDs, but I suspect that you actually want it on them all, since it will simplify your insertion code.</p></li>\n<li><p>In MySQL all <code>PRIMARY KEY</code>s are also guaranteed to be <code>UNIQUE</code> and <code>NOT NULL</code>, so those attributes aren't really needed on those columns, though my personal preference is that it adds to the readability to leave those attributes on the columns, but thought I'd mention it for reference.</p></li>\n<li><p>Your <code>player</code> table should probably reference the (new) id in the <code>accounts</code> table (with a <code>ON DELETE CASCADE</code> setting too). It also looks like <code>player</code>s can have names up to 30 characters long, but <code>account</code>s can have names up to 50 characters. (The difference in lengths may also of course indicate that I completely mis-understand the purpose of the <code>player</code> and <code>account</code> tables, and that they really shouldn't be related in any way.)</p></li>\n<li><p>While it will work perfectly fine the way you have it shown here, in most of the environments and organizations I've worked with/in, it has been standard best practice to make the name of every table's \"id\" column be <code>id</code>, rather than including the table name in the column name (like <code>maps_id</code>). This \"coding style\" choice allows the code to be more concise and since this is a <em>very</em> common practice, it doesn't add any \"cognitive load\" as maintainers read your queries/schema/code. </p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T00:12:25.793", "Id": "37914", "Score": "0", "body": "I agree with all, though on my most recent project I switched to using the table's name in the ID column (#7), e.g., `player_id`. The reason is that this allows the use of the terse join form `account join player using (account_id)` as opposed to the longer where clause `account, player where account.id = player.account_id`. This comes up more when building reports and using the command-line client, but I definitely like it so far." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T00:14:01.627", "Id": "37915", "Score": "0", "body": "I'll also add that I've found using singular noun forms for table names to be more readable. Thus `map` instead of `maps`. Why? What's the name of the table that holds the foot items? `foots` or `feet`?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-30T22:50:08.340", "Id": "24554", "ParentId": "15082", "Score": "8" } }, { "body": "<p>I've found over the years that it's best to start with the <a href=\"http://en.wikipedia.org/wiki/Database_normalization\" rel=\"nofollow\">normalized form</a> and denormalize as-needed to solve performance and usability problems. Without a full description of what <code>troop_class</code> stores, we're left to guess about a lot of details.</p>\n\n<ol>\n<li><p>Is <code>Team</code> unique for each <code>troop_class</code>? If not--and there's a <code>team</code> table--add a unique <code>int</code> <a href=\"http://en.wikipedia.org/wiki/Surrogate_key\" rel=\"nofollow\">surrogate key</a> to it and use that throughout as Eric S suggested.</p></li>\n<li><p>Avoid using data attributes--especially those that may change over time--in primary keys. Adding the x, y, and z positions to the PK will severely complicate working with these rows since you'll need to update the foreign keys every time the unit moves.</p></li>\n<li><p>Similarly for <code>Type</code>. Is this what one would normally call the \"class\" of the unit, defining its characteristics that are the same across all units belonging to that class? This information should be extracted to its own <code>class</code> table.</p>\n\n<pre><code>team &lt;---- unit ----&gt; type\n 1 * * 1\n</code></pre>\n\n<p>Here each <code>unit</code> holds the specifics for a single unit belonging to a team: its position, health, action points, etc. The <code>type</code> table lists the things that don't change about a unit: its ammo and fuel capacity, strength, etc. This minimizes the data duplication across tables and allows you to load up all unit types at the start of the game or in tools for easy reuse throughout.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T00:28:09.353", "Id": "24556", "ParentId": "15082", "Score": "6" } }, { "body": "<p>In addition to the others review which are totally great, I would like to add a little thing!</p>\n\n<p>You name your tables and primary keys <strong>using_the_following_notation</strong> (underscores), but then you name your other fields <strong>usingTheFollowingNotation</strong> (camelCase).</p>\n\n<p>Both are valid and great notations. But try to be consistent and use one OR the other, not both at the same time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-31T03:18:52.327", "Id": "24559", "ParentId": "15082", "Score": "5" } } ]
{ "AcceptedAnswerId": "24554", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T11:04:23.513", "Id": "15082", "Score": "15", "Tags": [ "game", "sql", "mysql" ], "Title": "Database schema for holding game save files" }
15082
<p>I'm developing a <a href="http://duc.pagodabox.com/product.php" rel="nofollow noreferrer">JS-based app</a> that allows you to customize a product. I still consider myself a super newbie to javascript and especially to object oriented programming. So far, so good, the app does what I want it to do, so no trouble there.</p> <p>My background is mostly in jQuery, so my main concern is how I'm sharing and reusing variables between functions, and how I can make this code prettier and more maintainable through optimizing those functions and vars.</p> <p>The point of the app is:</p> <ol> <li>Click a product option</li> <li>Select a finish type</li> <li>Select a finish color</li> <li>If there is an additional price for that finish, update the price</li> </ol> <p>I broke up what was once one big file into 3 modules and am loading them using LABjs:</p> <pre><code>$LAB .script(homeUrl + "/assets/js/product/product.js").wait() .script(homeUrl + "/assets/js/product/product-color.js") .script(homeUrl + "/assets/js/product/product-events.js") </code></pre> <p><strong>PRODUCT.JS</strong></p> <pre><code>(function (window, document, $) { "use strict"; // Set some general element variables used throughout this script var $nodes = { list: $('.cust-list'), steps: $('.steps'), step: $('.cust-step'), stepsSlide: $('.steps-slide'), subtotal: $('.customizer .total .price'), allTypes: $('.finish-type a'), allColors: $('.finish-color a'), options: $('.cust-option'), checks: $('.cust-option-checklist a') }; function Product (name) { this.name = name; this.options = []; } // Loops through the options slide divs function optionsLoop($options, callback) { for(var i = 0; i &lt; $options.length; i++) { callback(i, $options[i]); } } // Loops through the array of product options within the product object function productOptionsLoop(productOptions, callback) { for(var i = 0; i &lt; productOptions.length; i++) { callback(i, productOptions[i]); } } // Populate the product object with an array of options function getProductOptions($nodes, product) { optionsLoop($nodes.options, function(index,value) { var $me = $(value), name = $me.attr('data-option'), type = $me.attr('data-option-type'), option = { option: name, type: type }; product.options.push(option); }); } // Change the cost according to the added options / variations function updateCost(addCost, productOptions, totalPrice, $subtotal, productPrice, $nodes) { var currentSubtotal = $subtotal.attr('data-subtotal'); addCost = 0; // Go through all the product options, if an additional cost has been set, add them up productOptionsLoop(productOptions, function(index,value){ var $me = value, cost = $me.cost; if(cost) { addCost += cost; } }); productPrice = +productPrice; totalPrice = productPrice + addCost; animateNumber($nodes.subtotal, currentSubtotal, totalPrice); // Update the data attribute on the subtotal to reflect the user's choices $nodes.subtotal.attr('data-subtotal',totalPrice); // animating number produces rounding errors, so shortly after we animate, update the text with the exact total setTimeout(function(){ $nodes.subtotal.text(totalPrice).digits(); },325); } function updateOptions(productOptions, myOption, myName, myCost, myType) { // Go through the array of options and add the selected color and cost to this option productOptionsLoop(productOptions, function(index,value) { var $this = value; if($this.option === myOption){ $this.name = myName; $this.cost = Math.floor(myCost); if(myType) { $this.type = myType; } return false; } }); }     $.extend(window, { '$nodes': $nodes, 'Product': Product, 'optionsLoop': optionsLoop, 'productOptionsLoop': productOptionsLoop, 'getProductOptions': getProductOptions, 'updateCost': updateCost, 'updateOptions': updateOptions     }); }(window, document, jQuery)); </code></pre> <p><strong>PRODUCT-COLOR.JS</strong></p> <pre><code>$(document).ready(function(){ var productName = $('#product').attr('data-product-name'), // Create a new product object with the name of the currently viewed product product = new Product(productName), // This is set to true when the slide animation has completed, to avoid multiple fast clicks animReady = true, productPrice, totalPrice, productOptions, addCost, inAnim = {}, outAnim = {opacity: 0}, outCss = {opacity: 1}; getProductOptions($nodes, product); productOptions = product.options; productPrice = $nodes.subtotal.attr('data-subtotal'); // Color selecting $nodes.checks.add($nodes.allColors).add($nodes.allTypes).on('click',function(){ if($(this).hasClass('current')) { return false; } var $me = $(this), $parent = $me.parent(), $granpa = $me.parents('.cust-step'), granpaEq = $granpa.index() - 1, myOption = $granpa.attr('data-option'), $myCheck = $('.option-list li:eq(' + granpaEq + ')'), myCost = $me.attr('data-option-cost'), myName = $me.attr('data-option-name'), myType = null, $optTypes, $optColors, $curColor, $curType, $myParentType, $myColors, className, $add, $remove, isCheck = $me.is('.cust-option-checklist a'), isColor = $me.is('.finish-color a'), isType = $me.is('.finish-type a'); if(isCheck) { var $curCheck = $granpa.find('a.selected'); className = 'selected'; $add = $me; $remove = $curCheck; } if(isColor || isType) { if(isColor) { // If we're clicking a color, select the &lt;a&gt; links myType = $parent.attr('data-finish-type'); $optColors = $granpa.find('.finish-color a'); } else { // If we're clicking a color, select the divs containing each color &lt;a&gt; myType = $me.attr('data-finish-type'); $optColors = $granpa.find('.finish-color'); } // All types and colors for the current option $optTypes = $granpa.find('.finish-type a'); $curColor = $optColors.filter('.current'); $curType = $optTypes.filter('.current'); if(isColor) { var myBg = $me.css('backgroundColor'), myBgImg = $me.css('backgroundImage'), bg = myBgImg; $myParentType = $optTypes.filter('[data-finish-type=' + myType + ']'); $remove = $curColor.add($optTypes); $add = $me.add($myParentType); className = 'current ic-check selected'; } else { $myColors = $optColors.filter('[data-finish-type=' + myType + ']'); className = 'current'; $remove = $curColor.add($curType); $add = $me.add($myColors); } } // Add selected class to chosen finish + type setCurrent($add,$remove,className); if(isColor) { $curType = $optTypes.filter('.current'); // Set the background image for parent type to reflect chosen color if(myBgImg === 'none') { bg = myBg; } $curType.css({'background' : bg}); } // If you select a color or a checkbox, mark the list item as selected if( (isColor || isCheck) &amp;&amp; !$myCheck.hasClass('.selected') ) { $myCheck.add($granpa).addClass('selected'); } updateOptions(productOptions, myOption, myName, myCost, myType); updateCost(addCost, productOptions, totalPrice, $nodes.subtotal, productPrice, $nodes); // Remove existing price indicator $myCheck.find('.price').remove(); // Add price indicator to checklist if there is an extra cost, or else if(myCost &gt; 0) { $myCheck.addClass('extra').find('a').append('&lt;span class="f9 price"&gt;$' + myCost + '&lt;/span&gt;'); } else { $myCheck.removeClass('extra'); } }); // Navigation $('.cust-btn:not(.go-back)').on('click',function(){ var $me = $(this), $curStep = $nodes.step.filter('.cust-step-cur'), $nextStep = $curStep.next(), $prevStep = $curStep.prev(), isPrev = $me.hasClass('prev'), $tar = $nextStep, curIndex, offset, speed = 350; if(isPrev) { $tar = $prevStep; if($tar.length === 0) { $tar = $nodes.step.filter(':last'); } } else { if($tar.length === 0) { $tar = $nodes.step.filter(':first'); speed = 0; } } setCurrent($tar, $curStep, 'cust-step-cur'); $curStep = $nodes.step.filter('.cust-step-cur'); curIndex = $curStep.index('.cust-step'); offset = curIndex * 160; $nodes.stepsSlide.animate({ right: -offset },speed); }); // Checklist Click $('.option-list a').on('click',function(){ var $me = $(this), myIndex = ($me.parent().index()) + 1, $mySlide = $nodes.step.eq(myIndex), offset = myIndex * 160; setCurrent($mySlide, $nodes.list, 'cust-step-cur'); $nodes.stepsSlide.animate({ right: -offset }, 0); }); $('.cust-btn.go-back').on('click',function(){ var $curStep = $nodes.step.filter('.cust-step-cur'); setCurrent($nodes.list, $curStep, 'cust-step-cur'); $nodes.stepsSlide.animate({ right: 0 }, 0); }); }); </code></pre> <p><strong>PRODUCT-EVENTS.JS</strong></p> <pre><code>$(document).ready(function(){ var $productImg = $('.customizer-wrap .image'), productImgUrl = $productImg.find('img').attr('src'), spinnner, $stepsSlide = $nodes.stepsSlide, slideCount = $stepsSlide.find('.cust-step').length, slidesLength = slideCount * 160; $stepsSlide.css({width: slidesLength}); // Initialize loading graphic if(!productImgUrl) { return false; } spinner = startSpinner('product-image', 10, 4, 15, false); // Preload the big image, when loaded, fade in $.imgpreload(productImgUrl, function(){ $productImg .zoom(); $('.spinner').fadeOut(2000, function(){ spinner.stop(); $('html').removeClass('img-loading'); }); }); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-03T21:16:22.047", "Id": "24819", "Score": "0", "body": "In `updateCost()`, why do you pass `addCost` when you set it to 0?" } ]
[ { "body": "<p>Here are few things that I noticed with Product.js:</p>\n\n<ol>\n<li><p>The Module design pattern is normally used to create private functions and variables. Unless if <code>\"use strict\"</code> is required, then there's no point in wrapping your code inside a closure when all the functions and variables are appended to the global namespace.</p></li>\n<li><p>Variables shouldn't be passed to a function that won't get used. This is a problem in <code>updateCost()</code> for the variables <code>addCost</code> and <code>totalPrice</code>. This is also a problem for the <code>document</code> variable.</p></li>\n<li><p>Try to only create varaibles for complex or redundant object references. So <code>name</code> and <code>type</code> aren't needed.</p>\n\n<p>Previous code:</p>\n\n<pre><code>var $me = $(value),\n name = $me.attr('data-option'),\n type = $me.attr('data-option-type'),\n option = {\n option: name,\n type: type\n };\nproduct.options.push(option);\n</code></pre>\n\n<p>New code:</p>\n\n<pre><code>var $me = $(value),\n option = {\n option: $me.attr('data-option'),\n type: $me.attr('data-option-type')\n };\nproduct.options.push(option);\n</code></pre></li>\n<li><p>Instead of extending to the window, just add <code>window.</code> to the desired global variable or function name.</p>\n\n<p>Example:</p>\n\n<pre><code>window.$nodes = {};\n</code></pre></li>\n<li><p>You should rename <code>getProductOptions()</code> to <code>addOptionsToProduct()</code> since the word <code>get</code> implies a return value.</p></li>\n<li><p>This is redundant:</p>\n\n<pre><code>productPrice = +productPrice;\ntotalPrice = productPrice + addCost;\n</code></pre>\n\n<p>Just add <code>productPrice</code> to the end of a numeric operation for it to convert to a number:</p>\n\n<pre><code>totalPrice = addCost + productPrice;\n</code></pre></li>\n<li><p>Use existing functions instead of writing new ones. For example, take advance of <code>jQuery.each</code> and <code>jQuery.map</code> for interating through collections.</p>\n\n<p>Example:</p>\n\n<p>Previous code:</p>\n\n<pre><code>function productOptionsLoop(productOptions, callback) {\n for(var i = 0; i &lt; productOptions.length; i++) {\n callback(i, productOptions[i]);\n }\n}\n</code></pre>\n\n<p>New code (<code>productOptionsLoop()</code> is the same as below):</p>\n\n<pre><code>// if jQuery object\nproductOptions.each( callback );\n// else\n$.each( productOptions, callback );\n</code></pre></li>\n<li><p>Just add the cost, since 0 doesn't affect the value. But it would be even better if you got rid of addCost and used <code>totalCost</code> instead.</p>\n\n<pre><code>productOptionsLoop(productOptions, function(index,value){\n var $me = value,\n cost = $me.cost;\n if(value.cost) {\n addCost += value.cost;\n }\n});\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code>productOptions.each(function(index,value){\n addCost += value.cost;\n});\n</code></pre></li>\n<li><p><code>animateNumber()</code> should call a callback once the animation part is complete. This way you don't need a <code>setTimeout</code> function.</p></li>\n</ol>\n\n<h1>Final code</h1>\n\n<pre><code>// Set some general element variables used throughout this script\nvar $nodes = {\n list: $('.cust-list'),\n steps: $('.steps'),\n step: $('.cust-step'),\n stepsSlide: $('.steps-slide'),\n subtotal: $('.customizer .total .price'),\n allTypes: $('.finish-type a'),\n allColors: $('.finish-color a'),\n options: $('.cust-option'),\n checks: $('.cust-option-checklist a')\n};\nvar Product = function(name) {\n this.name = name;\n this.options = [];\n};\n// Populate the product object with an array of options\nvar addProductOptions = function($nodes, product) {\n $nodes.options.each(function(index,value) {\n var $me = $(value),\n option = {\n option: $me.attr('data-option'),\n type: $me.attr('data-option-type')\n };\n\n product.options.push(option);\n });\n};\n// Change the cost according to the added options / variations\nvar updateCost = function(productOptions, $subtotal, productPrice, $nodes) {\n var totalPrice = productPrice, currentSubtotal = $subtotal.attr('data-subtotal');\n\n productOptions.each(function(index,value){\n totalPrice += value.cost;\n });\n animateNumber($nodes.subtotal, currentSubtotal, totalPrice, function(){\n $nodes.subtotal.text(totalPrice).digits();\n });\n $nodes.subtotal.attr('data-subtotal',totalPrice);\n};\nvar updateOptions = function(productOptions, myOption, myName, myCost, myType) {\n // Go through the array of options and add the selected color and cost to this option\n productOptions.each(function(index,$this) {\n if($this.option !== myOption){\n return;\n }\n $this.name = myName;\n $this.cost = Math.floor(myCost);\n if(myType) {\n $this.type = myType;\n }\n });\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-03T22:46:42.600", "Id": "15310", "ParentId": "15088", "Score": "3" } }, { "body": "<p>Larry has already mentioned avoiding adding your functions/variables to the global namespace. One way you can do this is to create an object and use it in your extend method like so -</p>\n\n<pre><code>(function (window, document, $) {\n \"use strict\";\n\n var myNamespace = myNamespace || {};\n\n // @param {string} name\n myNamespace.Product = function (name) {\n // do stuff\n };\n\n // etc\n ...\n\n $.extend(window, myNamespace);\n\n}(window, document, jQuery));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T09:12:03.973", "Id": "15315", "ParentId": "15088", "Score": "3" } } ]
{ "AcceptedAnswerId": "15310", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-26T19:33:00.723", "Id": "15088", "Score": "8", "Tags": [ "javascript", "object-oriented" ], "Title": "JavaScript-based product customization app" }
15088
<p>I put together this code to for the Udacity cs101 exam. It passes the test, but I feel their must be a more elegant way to manage this problem. Some help from a module (like itertools).</p> <p>Question 8: Longest Repetition</p> <p>Define a procedure, longest_repetition, that takes as input a list, and returns the element in the list that has the most consecutive repetitions. If there are multiple elements that have the same number of longest repetitions, the result should be the one that appears first. If the input list is empty, it should return None.</p> <pre><code>def longest_repetition(alist): alist.reverse() largest = [] contender = [] if not alist: return None for element in alist: if element in contender: contender.append(element) if len(contender) &gt;= len(largest): largest = contender else: contender = [] contender.append(element) if not largest: return contender[0] else: return largest[0] #For example, print longest_repetition([1, 2, 2, 3, 3, 3, 2, 2, 1]) # 3 print longest_repetition(['a', 'b', 'b', 'b', 'c', 'd', 'd', 'd']) # b print longest_repetition([1,2,3,4,5]) # 1 print longest_repetition([]) # None </code></pre>
[]
[ { "body": "<p>Take a look at <a href=\"http://docs.python.org/library/collections.html#collections.Counter\" rel=\"nofollow\">collections.Counter</a>. It will do your work for you.</p>\n\n<pre><code>&gt;&gt;&gt; Counter(['a', 'b', 'b', 'b', 'c', 'd', 'd', 'd']).most_common(1)\n[('b', 3)]\n</code></pre>\n\n<p>UPD. Full example:</p>\n\n<pre><code>from collections import Counter\n\ndef longest_repetition(alist):\n try:\n return Counter(alist).most_common(1)[0][0]\n except IndexError:\n return None\n</code></pre>\n\n<p>If you ask more question, please ask.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T09:30:53.583", "Id": "24507", "Score": "0", "body": "The OP wanted *consecutive* repetitions, but `Counter('abbbacada').most_common(1)` returns `[('a', 4)]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T13:12:57.420", "Id": "24511", "Score": "0", "body": "I've updated my answer for you, @Gareth Rees." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T13:23:06.110", "Id": "24512", "Score": "0", "body": "According to the OP, `longest_repetition([1, 2, 2, 3, 3, 3, 2, 2, 1])` should return `3`, but your updated function returns `2`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T13:31:26.580", "Id": "24514", "Score": "0", "body": "Ok, I didn't notice _consecutive_ word. So my solution doesn't work" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T05:59:55.403", "Id": "15091", "ParentId": "15089", "Score": "0" } }, { "body": "<p>First, I'll comment on your code, and then I'll discuss a more \"Pythonic\" way to do it using features in the Python standard library.</p>\n\n<ol>\n<li><p>There's no docstring. What does the function do?</p></li>\n<li><p>You start out by reversing the list. This is a destructive operation that changes the list. The caller might be surprised to find that their list has changed after they called <code>longest_repetition</code>! You could write <code>alist = reversed(alist)</code> instead, but it would be even better if you didn't reverse the list at all. By changing the <code>&gt;=</code> test to <code>&gt;</code> you can ensure that the earliest longest repetition is returned, while still iterating forwards over the input.</p></li>\n<li><p>You build up a list <code>contender</code> that contains the most recent series of repetitions in the input. This is wasteful: as <code>contender</code> gets longer, the operation <code>element in contender</code> takes longer. Since you know that this list consists only of repetitions of an element, why not just keep one instance of the element and a count of how many repetitions there have been?</p></li>\n<li><p>You only update <code>largest</code> when you found a repetition. That means that if there are no consecutive repetitions in the input, <code>largest</code> will never be updated. You work around this using an <code>if</code> statement at the end to decide what to return. But if you <em>always</em> updated <code>largest</code> (whether you found a repetition or not) then you wouldn't need the <code>if</code> statement.</p></li>\n<li><p>By suitable choice of initial values for your variables, you can avoid the <code>if not alist</code> special case. And that would allow your function to work for any Python iterable, not just for lists.</p></li>\n</ol>\n\n<p>So let's apply all those improvements:</p>\n\n<pre><code>def longest_repetition(iterable):\n \"\"\"\n Return the item with the most consecutive repetitions in `iterable`.\n If there are multiple such items, return the first one.\n If `iterable` is empty, return `None`.\n \"\"\"\n longest_element = current_element = None\n longest_repeats = current_repeats = 0\n for element in iterable:\n if current_element == element:\n current_repeats += 1\n else:\n current_element = element\n current_repeats = 1\n if current_repeats &gt; longest_repeats:\n longest_repeats = current_repeats\n longest_element = current_element\n return longest_element\n</code></pre>\n\n<hr>\n\n<p>So is there a more \"Pythonic\" way to implement this? Well, you could use <a href=\"http://docs.python.org/library/itertools.html#itertools.groupby\" rel=\"nofollow\"><code>itertools.groupby</code></a> from the Python standard library. Perhaps like this:</p>\n\n<pre><code>from itertools import groupby\n\ndef longest_repetition(iterable):\n \"\"\"\n Return the item with the most consecutive repetitions in `iterable`.\n If there are multiple such items, return the first one.\n If `iterable` is empty, return `None`.\n \"\"\"\n try:\n return max((sum(1 for _ in group), -i, item)\n for i, (item, group) in enumerate(groupby(iterable)))[2]\n except ValueError:\n return None\n</code></pre>\n\n<p>However, this code is not exactly clear and easy to understand, so I don't think it's actually an improvement over the plain and simple implementation I gave above.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-10T12:52:37.363", "Id": "25094", "Score": "0", "body": "I realize this has been up for a while, but I wanted to point out that there's a further small optimization that could be made in the \"easy to understand\" version. You can move the `if` block that checks `current_repeats > longest_repeats` into the preceding `else` block (before the code that's already there), and avoid it running every time the longest repeated sequence gets longer. You will also need to do the test at the end of the loop, though, just before returning (in case the longest consecutive repetition is at the end)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-10T13:09:03.410", "Id": "25096", "Score": "0", "body": "Yes, you could do that, but you'd have to balance the optimization against the duplication of the test. I came down on the side of simplicity here, but I can understand someone else deciding the other way." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T10:03:38.387", "Id": "15095", "ParentId": "15089", "Score": "4" } }, { "body": "<p>Gareth's itertools method can be written a bit better:</p>\n\n<pre><code>def iterator_len(iterator):\n return sum(1 for _ in iterator)\n\ndef longest_repetition(iterable):\n \"\"\"\n Return the item with the most consecutive repetitions in `iterable`.\n If there are multiple such items, return the first one.\n If `iterable` is empty, return `None`.\n \"\"\"\n try:\n return max(groupby(iterable), \n key = lambda (key, items): iterator_len(items))[0]\n except ValueError:\n return None\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:40:41.797", "Id": "24568", "Score": "0", "body": "The use of `key` is a definite improvement—good spot! But the use of `len(list(items))` is not an improvement on `sum(1 for _ in items)` as it builds an unnecessary temporary list in memory that is then immediately thrown away. This makes the memory usage O(*n*) instead of O(1)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T16:12:40.913", "Id": "24576", "Score": "0", "body": "@GarethRees you're right. I feel like using sum isn't the most clear, and I really wish python had a builtin function for it. I made myself feel a bit better by putting it into a function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T16:21:08.357", "Id": "24580", "Score": "0", "body": "Yes, it's a frustrating omission from `itertools`. Such a function gets proposed from time to time ([e.g. here](http://mail.python.org/pipermail/python-ideas/2010-August/007921.html)) but the opinion of the Python developers seems to be that such a function would be a bad idea because it would lead to an infinite loop if passed an infinite generator ([e.g. here](http://mail.python.org/pipermail/python-ideas/2010-August/007926.html))." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T13:04:57.493", "Id": "15139", "ParentId": "15089", "Score": "2" } } ]
{ "AcceptedAnswerId": "15095", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T04:58:16.900", "Id": "15089", "Score": "2", "Tags": [ "python" ], "Title": "pythonic longest repetition" }
15089
<p>I'm making a simple httpcode monitor as an example for teaching myself PHP OOP. I have written the code below and would be interested in having it improved.</p> <p>In particular, I'm not sure about this line:</p> <pre><code>$httpcode = $website-&gt;get_httpcode($url); </code></pre> <p>This seems very inefficient to me as I have to to pass the URL back to the website class right after I have already done just that two lines above. Shouldn't it already remember its URL? That might be a dumb question, but in my mind, I've already made an object called website and given it a URL. Then if I want the httpcode of the URL, then I feel there should be some way for it to remember its URL which I passed two lines above.</p> <pre><code>class website { var $url; function __construct($url) { $this-&gt;url = $url; } public function get_url() { return $this-&gt;url; } public function get_httpcode($url) { //get the http status code $agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"; $ch=curl_init(); curl_setopt ($ch, CURLOPT_URL,$url ); curl_setopt($ch, CURLOPT_USERAGENT, $agent); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_VERBOSE,false); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSLVERSION, 3); $page=curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return $httpcode; } } // create an instance of the website class and pass the url $website = new website("http://www.google.com"); $url = $website-&gt;get_url(); $httpcode = $website-&gt;get_httpcode($url); </code></pre>
[]
[ { "body": "<p>Two things:</p>\n\n<ol>\n<li><p><em>Always</em> specify the visibility. Don't use the old <code>var</code> keyword, use <code>public</code>, <code>private</code> or <code>protected</code>. Since the class-member <code>$url</code> contains internal information, you'll probably want to <a href=\"http://en.wikipedia.org/wiki/Information_hiding\">hide that information</a> (you've already implemented a getter method so that the information can be read but not written):</p>\n\n<pre><code>class website {\n protected $url;\n\n public function __construct($url) {\n $this-&gt;url = $url;\n }\n\n // ...\n</code></pre></li>\n<li><p>Every instance of this class seems to be meant to represent one website. But your method \"get_httpcode()\" works for <em>every</em> website (it expects a URL; this is exactly what you've already noticed by yourself). It would be more natural to skip the parameter and return the HTTP-Statuscode for the url that is bound to the instance (you've \"remembered\" the URL in the class-member variable <code>$this-&gt;url</code>):</p>\n\n<pre><code>class website {\n // ...\n\n public function get_httpcode() {\n // ...\n curl_setopt($ch, CURLOPT_URL, $this-&gt;url);\n // ...\n }\n}\n\n// Usage:\n$google = new website(\"http://www.google.com\");\n$statusCode = $google-&gt;get_httpcode();\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T08:22:04.657", "Id": "24504", "Score": "0", "body": "Thank you that is exactly what I couldn't figure out with get_httpcode() method. That's really helped, cheers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T08:14:35.227", "Id": "15094", "ParentId": "15093", "Score": "5" } } ]
{ "AcceptedAnswerId": "15094", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T08:10:32.767", "Id": "15093", "Score": "3", "Tags": [ "php", "object-oriented", "http", "url" ], "Title": "Simple httpcode monitor" }
15093
<p>I have a list of friends and new friends are added via a form. When you click on a friend you see all the information about him. There is also an <kbd>Edit</kbd> button. When clicking it, I want a form to be displayed (the same as the form for adding) but already filled with the current information about the friend.</p> <p>It is working this way:</p> <pre><code>class FriendController extends Controller { public function editDisplayAction($id, Request $request) { $em = $this-&gt;getDoctrine()-&gt;getEntityManager(); $friend = $em-&gt;getRepository('EMMyFriendsBundle:Friend')-&gt;find($id); if (!$friend) { throw $this-&gt;createNotFoundException('There is no such friend'); } $edit_fr_form = $this-&gt;createForm(new FriendType(), $friend); if($request-&gt;getMethod() != 'POST') { return $this-&gt;render('EMMyFriendsBundle:Friend:edit.html.twig', array( 'id'=&gt;$id, 'friend'=&gt;$friend, 'fr_form' =&gt; $edit_fr_form-&gt;createView())); } } /* * @Edits the friend with the current id */ public function editAction($id, Request $request) { $em = $this-&gt;getDoctrine()-&gt;getEntityManager(); $friend = $em-&gt;getRepository('EMMyFriendsBundle:Friend')-&gt;find($id); $edit_fr_form = $this-&gt;createForm(new FriendType(), $friend); //if($request-&gt;getMethod() == 'POST') { $edit_fr_form-&gt;bindRequest($request); if ($edit_fr_form-&gt;isValid()) { $em-&gt;flush(); } return $this-&gt;redirect($this-&gt;generateUrl('friend_id', array('id' =&gt; $id))); } } } </code></pre> <p>and this is the template:</p> <pre><code>{% block body %} {{ parent() }} &lt;div&gt; &lt;h2&gt;Edit a friend&lt;/h2&gt; &lt;form class="register" action="{{ path('friend_edit', {'id': friend.id})}}" method="post" {{ form_enctype(fr_form) }}&gt; {% form_theme fr_form 'form_table_layout.html.twig' %} &lt;div class="error"&gt; {{ form_errors(fr_form) }} &lt;/div&gt; {% for field in fr_form %} {{ form_row(field) }} {% endfor %} &lt;div class="woo"&gt; &lt;input class="button" type="submit" value="Submit"/&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; {% endblock %} </code></pre> <p>Is there some way for this to work properly, without having two actions in the controller? And isn't it irrational and not very optimized in my way?</p>
[]
[ { "body": "<p>That HTML looks like Jekyll, or something very similar... Just out of curiosity, what is that, twig?</p>\n\n<p>Anyways... The first thing you can do is follow the \"Don't Repeat Yourself\" (DRY) Principle. Both of your methods have very similar contents and could benefit from sharing those resources. For instance, you could set up the <code>$em, $friend, $edit_fr_form</code> all in a constructor as class properties, then do any specific work in the proper methods.</p>\n\n<p>Another improvement might be to work on your variables. The names should be more descriptive for one (<code>$entityManager</code> instead of <code>$em</code>). Another is that you could use more of them. Sometimes its helpful to have a variable, even if that variable isn't going to be reused, just to help with legibility. For instance, the return statement in your <code>editDisplayAction()</code> method is very cramped. If you were to abstract some of those parameters as variables before passing them to the <code>render()</code> method, it would be much more legible.</p>\n\n<p>As for two different methods/actions, what is wrong with that? Controllers don't have to be limited to having just one. Is there some specific reason that you are trying to change it, or does it just seem wrong to you? The only way to separate this would be to create another controller and HTML form. But this is unnecessary. It is perfectly understandable to reuse a controller for similar functionality. It would be a waste to separate this into multiple controllers and forms, just to avoid having more than one action in a controller.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T06:03:13.247", "Id": "24537", "Score": "0", "body": "Yes, the template it's Twig.The controller seems a bit unoptimized for me, bacause there is a bit code duplication and to do one thing - edit something I use two similar actions, so that's the reason I asked if there is a way to improve them or somehow use only one action. Thank you for your answer! :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T15:57:22.907", "Id": "15103", "ParentId": "15096", "Score": "1" } } ]
{ "AcceptedAnswerId": "15103", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T10:23:47.273", "Id": "15096", "Score": "3", "Tags": [ "php", "form", "symfony2" ], "Title": "Friends edit form" }
15096
<pre><code>forceTwoDigits = (val) -&gt; if val &lt; 10 return "0#{val}" return val formatDate = (date) -&gt; year = date.getFullYear() month = forceTwoDigits(date.getMonth()+1) day = forceTwoDigits(date.getDate()) hour = forceTwoDigits(date.getHours()) minute = forceTwoDigits(date.getMinutes()) second = forceTwoDigits(date.getSeconds()) return "#{year}#{month}#{day}#{hour}#{minute}#{second}" console.log(formatDate(new Date())) </code></pre> <p>Is there a better way to do this?</p>
[]
[ { "body": "<p>Updated:</p>\n\n<pre><code>formatDate = (date) -&gt;\n timeStamp = [date.getFullYear(), (date.getMonth() + 1), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()].join(\" \")\n RE_findSingleDigits = /\\b(\\d)\\b/g\n\n # Places a `0` in front of single digit numbers.\n timeStamp = timeStamp.replace( RE_findSingleDigits, \"0$1\" )\n timeStamp.replace /\\s/g, \"\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-09T22:53:57.440", "Id": "25056", "Score": "0", "body": "Thanks!, I'm not sure doing it all at once is clearer or more maintainable though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-09T23:12:25.577", "Id": "25057", "Score": "0", "body": "@VinkoVrsalovic Updated with code comment" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-03T10:46:24.507", "Id": "15299", "ParentId": "15097", "Score": "2" } }, { "body": "<p>If you're happy with UTC and your JS env supports it (you can use a <a href=\"https://github.com/kriskowal/es5-shim\" rel=\"nofollow\">shim</a> if it doesn't), you can do it as a one liner:</p>\n\n<pre><code>formatDate = (date) -&gt; date.toISOString().replace /\\..+$|[^\\d]/g, ''\n</code></pre>\n\n<p>If you want it in the local timezone, it's a little more code:</p>\n\n<pre><code>formatDate = (date) -&gt;\n normalisedDate = new Date(date - (date.getTimezoneOffset() * 60 * 1000))\n normalisedDate.toISOString().replace /\\..+$|[^\\d]/g, ''\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-24T09:53:10.047", "Id": "20857", "ParentId": "15097", "Score": "1" } } ]
{ "AcceptedAnswerId": "15299", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T11:27:26.923", "Id": "15097", "Score": "4", "Tags": [ "javascript", "strings", "coffeescript" ], "Title": "CoffeeScript date formatting" }
15097
<p>I have a byte array in a C# program.</p> <p>I want to determine as quickly as possible if the content is Xml. If it's the case, I also want to return the Xml itself.</p> <p>By now I have this method :</p> <pre><code> protected bool TryGetXElement(byte[] body, out XElement el) { el = null; // if there is no data, this is not xml :) if (body == null || body.Length == 0) { return false; } try { // Load the data into a memory stream using (var ms = new MemoryStream(body)) { using (var sr = new StreamReader(ms)) { // if the first character is not &lt;, this can't be xml var firstChar = (char)sr.Peek(); if (firstChar != '&lt;') { return false; } else { // ultimately, we try to parse the XML el = XElement.Load(sr); return true; } } } } catch { // if it failed, we suppose this is not XML return false; } } </code></pre> <p>Is there potential improvement?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T13:27:40.300", "Id": "24513", "Score": "0", "body": "Why do you need to do this? Can't you figure out whether it's XML some other way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T13:35:14.580", "Id": "24515", "Score": "1", "body": "The bytes are coming from a message streams (that I cannot control). I have to route the messages to either of my parsers, depending of the kind of data. Messages are sometimes binaries, sometimes xml." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T18:37:52.450", "Id": "24532", "Score": "1", "body": "Does the structure of the messages you are receiving have any metadata that could clue you in as to their contents (e.g., a MIME header)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T08:08:53.870", "Id": "25214", "Score": "0", "body": "Is there the possibility of having the xml start with a space?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T08:56:49.210", "Id": "25215", "Score": "0", "body": "@minibill: the XML standard states it must starts with a `<`. Moreover, as it's computer XML, i'm confident it wiki never starts with a sppace" } ]
[ { "body": "<p>Why not verify if a root node exists rather than check for a '&lt;' ?</p>\n\n<pre><code> public bool GetRootNode(XmlReader reader)\n {\n bool isValid;\n try\n {\n while (reader.Read())\n {\n if (reader.NodeType == XmlNodeType.Element)\n {\n isValid = true;\n break;\n }\n }\n }\n catch (XmlException x)\n {\n throw new XmlException(x.Message);\n }\n\n return isValid;\n }\n</code></pre>\n\n<p>You could also use the chain of responsibilities pattern to determine which parser you want to use. </p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Not sure if this will work, but here is an example on using the above code:</p>\n\n<pre><code>protected bool TryGetXElement(byte[] body, out XElement el)\n{\n el = null;\n // if there is no data, this is not xml :)\n if (body == null || body.Length == 0)\n {\n return false;\n }\n\n try\n {\n // Load the data into a memory stream\n using (var ms = new MemoryStream(body))\n {\n using (var sr = new StreamReader(ms))\n {\n XmlReaderSettings settings = XmlReaderSettings { CheckCharacters = true; };\n using(XmlReader reader = XmlReader.Create(ms, settings))\n {\n if (!GetRootNode(reader))\n {\n return false;\n }\n else\n {\n // ultimately, we try to parse the XML\n el = XElement.Load(sr);\n return true;\n }\n }\n }\n\n }\n }\n catch\n {\n // if it failed, we suppose this is not XML\n return false;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T16:37:11.940", "Id": "24524", "Score": "0", "body": "I cannot see why this would be an enhancement. Your code rely on exception catching (so I do ultimately), while mine check one char. I believe checking a single char is very cheap compared to catching an exception, and can reduce a great number of cases (the probability of having a < char in a non xml string is very low)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T16:43:00.403", "Id": "24525", "Score": "0", "body": "You could have a '<' in a string of html. That is not xml. Does your xml have to fit a particular schema? How are you handling invalid characters that cannot appear in an xml document? Do you have to handle those cases?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T16:47:05.840", "Id": "24526", "Score": "0", "body": "I don't have schema in the sense of XSD files. I have behind the scene a bunch of \"parsers\" that will analyse the returned XElement. Each parser can handle a well known xml structure. And I also have parsers for non-xml document, but it's another story" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T16:19:28.523", "Id": "15104", "ParentId": "15100", "Score": "1" } }, { "body": "<p>Just a few small readability notes:</p>\n\n<ol>\n<li><p><del><code>(body == null || body.Length == 0)</code> could be <a href=\"http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx\" rel=\"nofollow noreferrer\"><code>String.IsNullOrEmpty(body)</code></a></del></p></li>\n<li><p>Longer variable names than <code>sr</code>, <code>el</code> and <code>ms</code> could be a little bit easier to read. \"Without proper names, we are constantly decoding and reconstructing the information that should be apparent from reading the code alone.\" (From <a href=\"https://codereview.stackexchange.com/a/15939/7076\">codesparkle's former answer</a>.)</p></li>\n<li><p>The innermost else could be omitted:</p>\n\n<pre><code>if (firstChar != '&lt;')\n{\n return false;\n}\n\n// ultimately, we try to parse the XML\nel = XElement.Load(sr);\nreturn true;\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-27T07:51:25.797", "Id": "25960", "Score": "0", "body": "1. no.... **body** is a byte array not a string. 2. I agree with you at some point. I think I should rename `el` to `foundXElement` or something like this. Other very local variables like `ms` or `sr` can be stay like this. It's a consistent naming convention I use in very small methods. As always, naming convention is subject to developer's feelings. 3. Technically yes, it can be omitted. But I think it's more readable when the two path are visually on the same level. A matter of preference again. Thanks for your feeback anyways." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-26T19:28:23.663", "Id": "15962", "ParentId": "15100", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T12:41:33.010", "Id": "15100", "Score": "5", "Tags": [ "c#", "xml" ], "Title": "Checking and returning Xml from a byte array" }
15100
<p>The errors are passed through every callback, but in fact, it might be better to throw an error at higher levels. For example, look at the mongodb.js database function. It passes through an error in the callback. However, if there was an error at that level, it might be better to deal with it at that point and just fall back on <code>procces.on('uncaughtException')</code></p> <p>It is a lot of extra code each time, dealing with errors in callbacks. I am wondering if there is a better way around it.</p> <p><strong>controllers/users.js</strong></p> <pre><code>var usersModel = require('../models/users.js'); users.create = function(req, res){ usersModel.create(req.data.username, req.data.password, function(error, user){ if(error){ res.statusCode = 500; res.end('server-error'); return; } res.statusCode = 201; res.end(user._id); }); }; </code></pre> <p><strong>models/users.js</strong></p> <pre><code>var db = require('../mongodb.js'); module.exports.create = function(username, password, callback){ db.collection('main', 'users', function(error, collection){ if(error){ callback(error); return; } collection.insert({ username: username, password: password, createdOn: new Date() }, callback); }); }; </code></pre> <p><strong>mongodb.js</strong></p> <pre><code>var mongo = require('mongodb') , mongodb = module.exports , connections = {} , config = { main: { name: 'application-main', server: new mongo.Server('127.0.0.1', 27017, { auto_reconnect: true }) } }; mongodb.database = function(key, callback){ if(connections[key]){ callback(null, connections[key]); return; } var db = mongo.Db(config[key].name, config[key].server); db.open(function(error, connection){ if(error){ callback(error); return; } connection.on('close', function(){ delete(connections[key]); }); connections[key] = connection; callback(null, connection); } }; mongodb.collection = function(dbKey, collName, callback){ mongodb.database(dbKey, function(error, connection){ if(error){ callback(error); return; } connection.collection(collName, function(error, collection){ if(error){ callback(error); return; } callback(null, collection); }); }); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T23:02:37.490", "Id": "70058", "Score": "0", "body": "Have you tried https://github.com/caolan/async#waterfall ? I would use it and handle errors in the callback." } ]
[ { "body": "<p>First, there is a principle you should be reminded: \n<strong>Never deal with the error you don't know, just pop it up.</strong></p>\n\n<p>Which means, if you can't deal with or don't know about the error passed in the callback, you just pass it to next callback, or throw it(A pattern of <strong>CHAIN OF RESPONSIBILITY</strong>)!</p>\n\n<p>For the errors you know how to deal with it, you can define a module for error handling and deal with it according to the type of error and log the error for debugging, like the following way.</p>\n\n<p><strong>error-handler.js</strong></p>\n\n<pre><code>var log = require('./log'); // Log module(local or third-party);\n\nfunction handler(error){\n if(error instanceof error1){\n // log it\n // handler for error1\n }else if(error instanceof error2){\n // log it \n // handler for error2\n }else if ....\n};\n\nmodule.exports = handler;\n</code></pre>\n\n<p><strong>logic.js</strong></p>\n\n<pre><code>var errorHandler = require('./error-handler');\n\ndb.open(function(err, connection){\n if(err){ return errorHandler(err); }\n});\n</code></pre>\n\n<p>For good modules like mongoose will throw their customized Errors.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-02T02:10:39.843", "Id": "15272", "ParentId": "15106", "Score": "7" } } ]
{ "AcceptedAnswerId": "15272", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T16:43:24.880", "Id": "15106", "Score": "6", "Tags": [ "javascript", "node.js", "error-handling", "callback" ], "Title": "Node.js callback error pattern" }
15106
<p>I am studying descriptors. They work with class varibles out of the box, but I want them to operate on instance variables too, so I did this:</p> <pre><code>class NumberDescriptor(object): def __init__(self,name): self.name = name def __set__(self, instance, value): if not isinstance(value, int): raise ValueError("%s is not a number." % value) else: setattr(instance, self.name, value) def __get__(self, instance, owner): return getattr(instance, self.name) class Human(object): age = NumberDescriptor("_age") def __init__(self,age): self.age = age a = Human(12) print a.age b = Human("osman") print b.age </code></pre> <p>Is this the right way to go about this?</p>
[]
[ { "body": "<p>That looks reasonable; but you should handle the case of when the descriptor is invoked from the class: <code>Human.age</code>. In that case, <code>__get__</code> is invoked with None as an argument to instance. If you've no better use for it; you can just return the descriptor itself:</p>\n\n<pre><code>def __get__(self, instance, owner):\n if instance is None:\n return self\n else:\n return getattr(instance, self.name)\n</code></pre>\n\n<p>Another thing you can do, which is sometimes preferred, is to make the descriptor figure out its own name by inspecting the class it's attached to; this is a little more complicated, of course, but has the advantage of allowing you to specify the \"name\" of the descriptor attribute just one time.</p>\n\n<pre><code>class NumberDescriptor(object):\n def snoop_name(self, owner):\n for attr in dir(owner):\n if getattr(owner, attr) is self:\n return attr\n def __get__(self, instance, owner):\n if instance is None:\n return self\n name = self.snoop_name(self, owner)\n return getattr(instance, '_'+name)\n def __set__(self, instance, value):\n name = self.snoop_name(self, type(instance))\n setattr(instance, '_' + name, int(value))\n\nclass Human(object):\n age = NumberDescriptor()\n</code></pre>\n\n<p>Other variations to get a similar effect (without using <code>dir()</code>) would be to use a metaclass that knows to look for your descriptor and sets its name there. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:33:53.170", "Id": "24567", "Score": "0", "body": "Doesn't this make a lookup for every set and get action. It looks like a little bit waste to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:47:25.540", "Id": "24569", "Score": "0", "body": "yes, this version is a little inelegant; and meant mainly to give you some ideas about how you might use descriptors. A more reasonable implementation would probably use a metaclass or a weakref.WeakKeyDict to avoid the extra lookups, but I've decided to leave that as an exercise." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T12:33:45.957", "Id": "15131", "ParentId": "15108", "Score": "2" } }, { "body": "<p>Good question. I'm studying descriptors too.</p>\n\n<p>Why do you use <code>setattr()</code> and <code>getattr()</code>? I'm not clear on why you store <code>age</code> inside <code>instance</code>. What benefit does this have over this naive example?</p>\n\n<pre><code>class NumberDescriptor(object):\n def __set__(self, instance, value):\n if not isinstance(value, int):\n raise ValueError(\"%s is not a number.\" % value)\n else:\n self.value = value\n\n def __get__(self, instance, owner):\n return self.value\n\nclass Human(object):\n age = NumberDescriptor()\n worth = NumberDescriptor()\n\n def __init__(self,age,worth):\n self.age = age\n self.worth = worth\n\na = Human(12,5)\nprint a.age, a.worth\na.age = 13\na.worth = 6\nprint a.age, a.worth\nb = Human(\"osman\", 5.0)\nprint b.age\n</code></pre>\n\n<p>EDIT: responding to comment</p>\n\n<p>Not sure I have a firm handle on descriptors, but <a href=\"https://docs.python.org/2/howto/descriptor.html#descriptor-example\" rel=\"nofollow noreferrer\">the example</a> in the docs access <code>value</code> with <code>self</code> rather than invoking <code>getattr()</code> and <code>setattr()</code>.</p>\n\n<p>However, <a href=\"https://stackoverflow.com/a/12645321/1698426\">this answer</a> and <a href=\"https://stackoverflow.com/a/12645321/1698426\">this answer</a> do not user <code>getattr()</code>, they do not use <code>self</code> either. They access the use the <code>instance</code> argument. </p>\n\n<p>My example is slightly simpler. What are the trade-offs?</p>\n\n<p>Just as in the original question, the <code>b</code> instance demonstrates that a <code>ValueError</code> is raised. I added a <code>worth</code> attribute simply to demonstrate that there are in fact two distinct instances of <code>NumberDescriptor</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-07T22:20:18.553", "Id": "150156", "Score": "1", "body": "Welcome to Code Review and enjoy your stay! Your answer looks good except for the part where you construct `b`, as both arguments aren't `int`s, so maybe make the example runnable; you could also add a paragraph explaining directly why this setup is better than storing instance variables on the object itself rather than on the descriptor." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-07T21:20:17.290", "Id": "83519", "ParentId": "15108", "Score": "1" } }, { "body": "<p>Consider this example, assume I've used your Human class and Number:</p>\n\n<pre><code>a = Human(12,5)\nprint a.age, a.worth\nb = Human(13,5)\nprint b.age, b.worth\n\n# Check if a attributes has changed:\nprint a.age, a.worth\n</code></pre>\n\n<p>Then you realize, you've overrided also 'a' instance attributes because you actually overrided class attribute :) \nThis is why your way to do it isn't exactly right when you want to have descriptor as instance-related attribute.</p>\n\n<p>When you need to have instance-related attributes which are Descriptors, you should to it in some other way, for example store in your descriptor some kind of Dict where you can identify your instance-related attributes and return then when you need them for specified instance or return some kind of default when you call attributes from class (e.g. Human.attr). It would be a good idea to use weakref.WeakKeyDictionary if you want to hold your whole instances in dict.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-25T21:29:20.603", "Id": "91751", "ParentId": "15108", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T18:10:35.773", "Id": "15108", "Score": "2", "Tags": [ "python", "object-oriented" ], "Title": "Using descriptors with instance variables to store a human's age" }
15108
<p>I have an ASP.NET MVC3 web application that displays a list of parts (a part is a simple entity with a number and a description). </p> <p>I have updated the action method to support filtering and paging:</p> <pre><code>[HttpGet] public ViewResult Index(int page = 1, int pageSize = 30, string filter = "All") { IEnumerable&lt;Part&gt; parts; int totalParts; var acceptableFilters = new string[] { "All", "123", "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" }; // This checks that the filter value received by the method is an acceptable value. // E.G. If a user types in a value in the query string that is not contained in the // array above, then the filter is reset to 'All' and all records are queried. if (!acceptableFilters.Contains(filter)) { filter = "All"; } if (filter == "All") { parts = Database.Parts .OrderBy(p =&gt; p.Number) .Skip((page - 1) * pageSize) .Take(pageSize); totalParts = Database.Parts.Count(); } else if (filter == "123") { var numbers = new string[]{"1","2","3","4","5","6","7","8","9","0"}; parts = Database.Parts .OrderBy(p =&gt; p.Number) .Where(p=&gt; numbers.Contains(p.Number.Substring(0,1))) .Skip((page - 1) * pageSize) .Take(pageSize); totalParts = Database.Parts .Count(p =&gt; numbers.Contains(p.Number.Substring(0, 1))); } else { parts = Database.Parts .OrderBy(p =&gt; p.Number) .Where(p =&gt; p.Number.StartsWith(filter)) .Skip((page - 1) * pageSize) .Take(pageSize); totalParts = Database.Parts.Count(p =&gt; p.Number.StartsWith(filter)); } PartsListViewModel viewModel = new PartsListViewModel() { Filter = filter, PageInfo = new PageInfo(page, pageSize, totalParts), Parts = parts, }; return View(viewModel); } </code></pre> <p>The idea is this:</p> <ul> <li>If the filter is equal to <strong>'All'</strong> then query all records.</li> <li>If the filter is equal to <strong>'123'</strong> then query all records that start with a number.</li> <li>If the filter is equal to a letter (A, B, C) then query all records that begin with said letter.</li> </ul> <p>Once the required records have been queried I then need to do some calculations to determine how many pages I have and how many items to display on each page.</p> <p>This works perfectly but I do not like the code I currently have, specifically the if statement that determines the Linq query to be used as the majority of the code is identical except for the where clause (or lack of where clause if all records are being pulled down). I also don't like the fact that I have to run each query twice: once to get the records and a second time to determine the <em>total</em> record set size.</p> <p>So, is there a better way of achieving the same result? can the Linq queries be restructured in a more elegant way to reduce the redundant code or is this the best way?</p>
[]
[ { "body": "<p>You can construct LINQ queries step by step instead of writing them all at once</p>\n\n<pre><code>parts = Database.Parts;\nif (filter == \"123\") {\n parts = parts.Where(p =&gt; p.Number[0].IsDigit())\n} else if (filter != \"All\") { // Alphabetic filter\n parts = parts.Where(p =&gt; p.Number.StartsWith(filter))\n}\nint totalParts = parts.Count();\nparts = parts\n .OrderBy(p =&gt; p.Number)\n .Skip((page - 1) * pageSize)\n .Take(pageSize);\n</code></pre>\n\n<p>I followed the DRY software design principle here. DRY = Don't Repeat Yourself. If you repeat the same (or almost the same) code over and over, the code is less maintainable and is more susceptible to mistake. The fact that you have to write more, if you repeat yourself, is rather secondary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T20:37:35.217", "Id": "24533", "Score": "0", "body": "+ 1 - I especially like this answer as it does not make the code any more complex (the original intent is kept intact). Thank you very much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T16:50:33.893", "Id": "24584", "Score": "0", "body": "I simplified the code further (I un-nested the ifs) in response to Jeff Vanzella’s post and placed a totals count before the paging part." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T20:21:01.280", "Id": "15111", "ParentId": "15110", "Score": "11" } }, { "body": "<p>Oliver's looks simple, but you are nesting if statments, which gets really messy. </p>\n\n<p>I also don't like having the numbers array created everytime this method is called. The numbers array should be move to a class readonly Static, saving memory and processing time to create it.</p>\n\n<p>the but IF...else...else statement should be moved to a switch, keeping the code much cleaner.</p>\n\n<p>You don't have to, but I like the pattern of using a dictionary (again, static readonly) with and enum to determine which branch to use.</p>\n\n<p>Instead of getting the count from the source list, get the count from the items returned. This will eliminate one call to the source every time this method is called. I added the .ToList() to the end of the query to make sure the list is stored in memory, so the .Count will not query the data source again.</p>\n\n<p>I also created a method to return your list, this way your declaration and assignment are much closer together, making the method much easier to read.</p>\n\n<p>I can also see a problem with using All, there might be circumstances where it conflicts with a general string query. I would suggest moving the matching patterns in my dictionary into some kind of parsing routine (Regex maybe?) to make sure you are not stepping on toes so to speak. This will also shorten the dictionary to 3 entries.</p>\n\n<p>Anyways, my solution follows:</p>\n\n<pre><code>private enum FilterType\n{\n All,\n PartNumber,\n StringQuery\n}\n\nprivate static readonly IDictionary&lt;string, FilterType&gt; AcceptableFilters =\n new Dictionary&lt;string, FilterType&gt;\n {\n {\"All\", FilterType.All},\n {\"123\", FilterType.PartNumber},\n {\"A\", FilterType.StringQuery},\n {\"B\", FilterType.StringQuery},\n {\"C\", FilterType.StringQuery},\n {\"D\", FilterType.StringQuery},\n {\"E\", FilterType.StringQuery},\n {\"F\", FilterType.StringQuery},\n {\"G\", FilterType.StringQuery},\n {\"H\", FilterType.StringQuery},\n {\"I\", FilterType.StringQuery},\n {\"J\", FilterType.StringQuery},\n {\"K\", FilterType.StringQuery},\n {\"L\", FilterType.StringQuery},\n {\"M\", FilterType.StringQuery},\n {\"N\", FilterType.StringQuery},\n {\"O\", FilterType.StringQuery},\n {\"P\", FilterType.StringQuery},\n {\"Q\", FilterType.StringQuery},\n {\"R\", FilterType.StringQuery},\n {\"S\", FilterType.StringQuery},\n {\"T\", FilterType.StringQuery},\n {\"U\", FilterType.StringQuery},\n {\"V\", FilterType.StringQuery},\n {\"W\", FilterType.StringQuery},\n {\"X\", FilterType.StringQuery},\n {\"Y\", FilterType.StringQuery},\n {\"Z\", FilterType.StringQuery},\n };\n\nprivate static readonly IList&lt;string&gt; Numbers = new List&lt;string&gt;\n {\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"0\"};\n\n[HttpGet]\npublic ViewResult Index(int page = 1, int pageSize = 30, string filter = \"All\")\n{\n // This checks that the filter value received by the method is an acceptable value.\n // E.G. If a user types in a value in the query string that is not contained in the\n // array above, then the filter is reset to 'All' and all records are queried.\n if (!AcceptableFilters.Keys.Contains(filter))\n {\n filter = \"All\";\n }\n\n var parts = RetrievePartsAccordingToFilter(filter);\n var totalParts = parts.Count;\n\n var viewModel = new PartsListViewModel\n {\n Filter = filter,\n PageInfo = new PageInfo(page, pageSize, totalParts),\n Parts = parts,\n };\n\n return View(viewModel);\n}\n\nprivate IList&lt;Part&gt; RetrievePartsAccordingToFilter(string filter)\n{\n switch (AcceptableFilters[filter])\n {\n case FilterType.All:\n return (Database.Parts\n .OrderBy(p =&gt; p.Number)\n .Skip((page - 1)*pageSize)\n .Take(pageSize)).ToList();\n case FilterType.StringQuery:\n return (Database.Parts\n .OrderBy(p =&gt; p.Number)\n .Where(p =&gt; Numbers.Contains(p.Number.Substring(0, 1)))\n .Skip((page - 1)*pageSize)\n .Take(pageSize)).ToList();\n default:\n return (Database.Parts\n .OrderBy(p =&gt; p.Number)\n .Where(p =&gt; p.Number.StartsWith(filter))\n .Skip((page - 1)*pageSize)\n .Take(pageSize)).ToList();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T21:53:58.677", "Id": "24535", "Score": "0", "body": "Thank you for your comments. I had already moved the arrays to a static class to improve performance. The count needs to be performed separately because I need to know the total number of items rather than the amount per page (E.G. if I have 300 items matching my criteria but am only showing 30 per page then your method would only return 10). Olivers method actually makes the count very easy - I simply perform the count after all the If's have been evaluated (so I have selected all my items) but before the paging occurs. This only needs to be performed once." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T21:26:57.353", "Id": "15114", "ParentId": "15110", "Score": "3" } } ]
{ "AcceptedAnswerId": "15111", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T20:03:05.320", "Id": "15110", "Score": "5", "Tags": [ "c#", "linq", "asp.net-mvc-3" ], "Title": "Locating a list of parts" }
15110
<p>I'm toggling on/off series in chart and was wondering if I was doing anything crazy.</p> <p>Is the atom really a good idea here?</p> <pre><code>;; ================ Graph data ================ (def serie1 {:label "Bar" :data [[11 13] [19 11] [30 -7]]}) (def serie2 {:label "Foo" :data [[10 1] [17 -14] [30 5]]}) (def serie3 {:label "Zon" :data [[8 2] [18 7] [30 15]]}) (def series (for [serie [serie1 serie2 serie3]] {:label (:label serie) :action "toggle-serie" :param serie})) ;; ============ Chart state ================ (def !chart "Chart state" (atom [])) (defn toggle-serie! [serie] "Return the series collection minus/plus the given serie" (swap! !chart #(if (some #{serie} %) (remove #{serie} %) (conj % serie)))) (defn reset-chart [] "Reset chart state" (reset! !chart [])) ;;================ Page population ================ ; almost identical to ibdknox overtone example (defpartial button [{:keys [label action param]}] [:a.button {:href "#" :data-action action :data-param param} label]) (defn populate [container buttons] (doseq [b buttons] (append container (button b)))) (populate ($ :#series) series) ;; ================ Button functions ================ (defn plot "Plot the given series and return the chart as an object." [placeholder coll-data &amp; options] (js/jQuery.plot placeholder (clj-&gt;js coll-data) (clj-&gt;js options))) (def chart ($ :#chart)) (defn toggle-serie-and-update-chart! "Add or remove a serie form the chart atom and redraw the chart." [serie] (toggle-serie! serie) ;update the chart atom (plot chart @!chart)) ; redraw the chart (delegate ($ :#series) button :click (fn [e] (.preventDefault e) (this-as me (let [$me ($ me) param (cljs.reader/read-string (data $me :param))] (toggle-serie-and-update-chart! param))))) </code></pre>
[]
[ { "body": "<p>If your dataset were coming from an outside source, like an API call, I'd say the atom would make sense. In this case, your dataset is static. In that case, I think I might find it more intuitive to use a var for the series and then select the items out that you want to plot. In that case, your state is really just a list of which series (you are selecting). </p>\n\n<p>So, if you had all your series:</p>\n\n<pre><code>(def all-series\n {:series1 :...series1\n :series2 :...series2\n :series3 :...series3})\n</code></pre>\n\n<p><code>!chart</code> might contain <code>#{:series1 :series3}</code> and you could get all the values out using <code>(select-keys all-series @!chart)</code>. </p>\n\n<p>You might find you can avoid the atom altogether, but at the very least I'd always look for ways to keep that state as simple as </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-11T21:03:41.943", "Id": "96618", "ParentId": "15112", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T20:40:02.690", "Id": "15112", "Score": "3", "Tags": [ "clojure" ], "Title": "Toggle chart series in clojurescript" }
15112
<p>Here is a Python script I wrote earlier for rapidly requesting a file from a server and timing each transaction. Can I improve this script?</p> <pre><code>from time import time from urllib import urlopen # vars url = raw_input("Please enter the URL you want to test: ") for i in range(0,100): start_time = time() pic = urlopen(url) if pic.getcode() == 200: delta_time = time() - start_time print "%d" % (delta_time * 100) else: print "error" print "%d requests made. File size: %d B" % (i, len(pic.read())) </code></pre> <p>I'm new to Python, though, so I'm not sure if this is the best way to go about it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T20:53:26.160", "Id": "24534", "Score": "0", "body": "Are you trying to time the whole operation (checking the file 100 times) or just one opening? Are you interested in the number of times where you could get a proper `pic.getcode()` value, or the number of times where you tried to open the url (which is gonna be 100...) ?" } ]
[ { "body": "<p>Here are some comments on your code:</p>\n\n<ol>\n<li><p><code>raw_input</code> is a very inflexible way to get data into a program: it is only suitable for interactive use. For more general use, you should get your data into the program in some other way, for example via command-line arguments.</p></li>\n<li><p><code>urllib.urlopen</code> <a href=\"http://docs.python.org/library/urllib.html\" rel=\"nofollow\">was removed in Python 3</a>, so your program will be more forward-compatible if you use <code>urllib2.urlopen</code> instead. (You'll need to change the way your error handling works, because <code>urllib2.urlopen</code> deals with an error by raising an exception instead of returning a response object with a <code>getcode</code> method.)</p></li>\n<li><p>The comment <code># vars</code> does not seem to contain any information. Improve it or remove it.</p></li>\n<li><p>The <code>range</code> function starts at <code>0</code> by default, so <code>range(0,100)</code> can be written more simply as <code>range(100)</code>.</p></li>\n<li><p>100 seems rather arbitrary. Why not take this as a command-line parameter too?</p></li>\n<li><p>The variable <code>pic</code> seems poorly named. Is it short for <em>picture</em>? The <code>urlopen</code> function returns a <em>file-like object</em> from which the <em>resource</em> at the URL can be read. The <a href=\"http://docs.python.org/library/urllib2.html#examples\" rel=\"nofollow\">examples in the Python documentation</a> accordingly use <code>f</code> or <code>r</code> as variable names.</p></li>\n<li><p>I assume that this code is only going to be used for testing your own site. If it were going to be used to time the fetching of resources from public sites, it would be polite (a) to respect the <a href=\"http://en.wikipedia.org/wiki/Robots_exclusion_standard\" rel=\"nofollow\">robots exclusion standard</a> and (b) to not fetch resources as fast as possible, but to <code>sleep</code> for a while between each request.</p></li>\n<li><p>If an attempt to fetch the resource fails, you probably want to exit the loop rather than fail again many times.</p></li>\n<li><p>You say in your post that the code is supposed to time \"the entire transaction\", but it does not do this. It only times how long it takes to call <code>urlopen</code>. This generally completes quickly, because it just reads the headers, not the entire resource. You do read the resource once (at the very end), but outside the timing code.</p></li>\n<li><p>You multiply the time taken by 100 and then print it as an integer. This seems unnecessarily misleading: if you want two decimal places, then why not use <code>\"%.2f\"</code>?</p></li>\n<li><p>Finally, there's a built-in Python library <a href=\"http://docs.python.org/library/timeit.html\" rel=\"nofollow\"><code>timeit</code></a> for measuring the execution time of a piece of code, which compensates for things like the time taken to call <code>time</code>.</p></li>\n</ol>\n\n<p>So I might write something more like this:</p>\n\n<pre><code>from sys import argv\nfrom timeit import Timer\nfrom urllib2 import urlopen\n\nif __name__ == '__main__':\n url = argv[1]\n n = int(argv[2])\n length = 0\n\n def download():\n global length, url\n f = urlopen(url)\n length += len(f.read())\n f.close()\n\n t = Timer(download).timeit(number = n)\n print('{0:.2f} seconds/download ({1} downloads, average length = {2} bytes)'\n .format(t / n, n, length / n))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:58:35.447", "Id": "24571", "Score": "0", "body": "Great answer - lots of info! It's not working when I try to run it though. Could it be because I have Python 2.7 installed on my system? It's telling me that argv list index is out of range" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:59:29.457", "Id": "24572", "Score": "0", "body": "It takes two command-line arguments (the URL and the number of repetitions). Something like `python download.py http://my-server-address/ 100`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T15:07:42.747", "Id": "24573", "Score": "0", "body": "Okay I understand.. It's because I'm running the file directly when I should be opening it via command line so I can actually pass the arguments! Right?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:35:54.893", "Id": "15143", "ParentId": "15113", "Score": "3" } } ]
{ "AcceptedAnswerId": "15143", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T20:44:00.267", "Id": "15113", "Score": "4", "Tags": [ "python" ], "Title": "Rapidly requesting a file from a server" }
15113
<p>I just spent some time putting together a simple protocol and implementation for packetizing byte streams (<a href="https://github.com/nickpascucci/S3P" rel="nofollow noreferrer">on GitHub here</a>). The project is aimed at embedded systems that need a very lightweight way to pass discrete messages across serial lines. Since I've never had any of my C reviewed before, would you mind taking a look at it and seeing if there's anything that could be improved in the style, design, or best practices?</p> <p><strong>s3p.h:</strong></p> <pre><code>#ifndef S3P_H #define S3P_H #include &lt;stdint.h&gt; #define S3P_OVERHEAD 3 typedef enum { S3P_SUCCESS = 0, S3P_BUF_TOO_SMALL = 1, S3P_PAYLOAD_TOO_LARGE = 2, S3P_CHECKSUM_ERR = 3, S3P_PARSE_FAILURE = 4, } S3P_ERR; /** Build a new packet from the bytes in "data" into "out". S3P packets are limited to 256 bytes of data; attempting to packetize more will result in a S3P_PAYLOAD_TOO_LARGE error. "out" must be at least S3P_OVERHEAD bytes longer than the data that needs to be packetized; and this can increase to twofold depending on the number of bytes that need escaping. In general, unless memory usage is a concern, allocate twice as much space as the data you wish to packetize. Params: data: a byte array of data to be packetized. dsize: the length of "data". out: a byte array which will hold the built packet. osize: the length of "out". psize: a pointer to an int which will contain the length of the built packet. */ S3P_ERR s3p_build(uint8_t const *data, int dsize, uint8_t *out, int osize, int *psize); /** Read a packet from "in", and place unescaped data into "data". Breaking streams into packets is the responsibility of the caller. This function will only read the first packet in the "in" buffer; all other data will be ignored. This function guarantees that the length of the data retrieved from the packet will be strictly less than the size of the input packet. Params: in: byte array of raw, packetized data. isize: the length of "in". data: byte array which will contain the retrieved data. dsize: the length of "data". psize: pointer to an int which will contain the length of the retrieved data. */ S3P_ERR s3p_read(uint8_t const *in, int isize, uint8_t *data, int dsize, int *psize); #endif </code></pre> <p><strong>s3p.c:</strong></p> <pre><code>#include &lt;s3p.h&gt; enum S3P_CONTROL_CHARS { S3P_START = 0x56, // Marks the start of a packet S3P_ESCAPE = 0x25, // Marks escaped bytes S3P_MASK = 0x20, // Mask used for escaping chars. echar = char ^ S3P_MASK }; S3P_ERR s3p_build(uint8_t const *data, int dsize, uint8_t *out, int osize, int *psize){ if((dsize + S3P_OVERHEAD) &gt; osize){ return S3P_BUF_TOO_SMALL; } if(255 &lt; dsize){ return S3P_PAYLOAD_TOO_LARGE; } /* S3P packets follow this structure: START | LENGTH (N) | DATA 1 | DATA 2 | ... | DATA N | CHECKSUM */ out[0] = S3P_START; int dnext = 2; // Next data byte position in output buffer /* If the length of the data (dsize, in this case) is S3P_START or S3P_ESCAPE we need to escape it. */ if(S3P_START == dsize || S3P_ESCAPE == dsize){ out[1] = S3P_ESCAPE; out[2] = ((uint8_t) dsize) ^ S3P_MASK; dnext = 3; } else { out[1] = (uint8_t) dsize; } uint8_t check = 0; // Checksum int i; for(i=0; i&lt;dsize; i++){ // Check the size restrictions: dnext should contain the number of bytes // written so far less one (as the indices start at zero), and we need to // add a checksum byte after all is said and done. if(dnext + 2 &gt; osize){ return S3P_BUF_TOO_SMALL; } uint8_t dbyte = data[i]; check += dbyte; if(S3P_START == dbyte || S3P_ESCAPE == dbyte){ out[dnext] = S3P_ESCAPE; dnext++; out[dnext] = dbyte ^ S3P_MASK; } else { out[dnext] = dbyte; } dnext++; } out[dnext] = check; dnext++; *psize = dnext; return S3P_SUCCESS; } S3P_ERR s3p_read(uint8_t const *in, int isize, uint8_t *data, int dsize, int *psize){ if(dsize &lt; 1){ return S3P_BUF_TOO_SMALL; } if(isize &lt; S3P_OVERHEAD){ return S3P_PARSE_FAILURE; } // The first byte should be a start byte. If not, this is not an S3P packet // and we should not try to parse it. if(S3P_START != in[0]){ return S3P_PARSE_FAILURE; } int dnext = 2; int length; if(S3P_ESCAPE == in[1]){ length = in[2] ^ S3P_MASK; dnext++; } else { length = in[1]; } int dread = 0; // Number of data bytes read uint8_t check = 0; // Checksum while(dread &lt; length){ if(dread &gt;= dsize){ return S3P_BUF_TOO_SMALL; } if(dnext &gt;= isize){ return S3P_PARSE_FAILURE; } uint8_t dbyte = in[dnext]; if(S3P_START == dbyte){ return S3P_PARSE_FAILURE; } if(S3P_ESCAPE == dbyte){ dnext++; dbyte = in[dnext]; if(S3P_START == dbyte || S3P_ESCAPE == dbyte){ return S3P_PARSE_FAILURE; } dbyte = dbyte ^ S3P_MASK; } data[dread] = dbyte; check += dbyte; dnext++; dread++; } *psize = dread; uint8_t pcheck; if(S3P_ESCAPE == in[dnext]){ dnext++; pcheck = in[dnext] ^ S3P_MASK; } else { pcheck = in[dnext]; } if(pcheck != check){ return S3P_CHECKSUM_ERR; } return S3P_SUCCESS; } </code></pre> <p><strong>Update:</strong> I've incorporated some changes suggested by <a href="https://codereview.stackexchange.com/a/15128/16115">William Morris</a>, such as adding end markers and changing size parameters to unsigned values (size_t). This simplified the code a bit. The latest version is up on GitHub now.</p>
[]
[ { "body": "<p>A few comments...</p>\n\n<p>I'm no expert in data transmission, but there are sure to be some on StackOverflow who are. Perhaps you could discuss optimal encoding schemes there. Yours may or may not be optimal, but has some peculiarities. In particular, it is not easy to determine the packet length - only by looking for a start byte (or by counting more than 512 bytes) can you see that the last packet has ended. If you imagine packets being sent infrequently, perhaps once a second, the receiver cannot tell when to pass-on a completed packet to be decoded; it must wait until the next packet starts to know that the current one is complete. That implies a delay of a second! Ok, maybe some timeouts might help but that gets messy.</p>\n\n<p>I also wondered where the 0x56/0x25 codes came from. They seem strange values. Are they particularly easy to recognise on a scope/analyser? Another minor issue is that binary data dumped onto a terminal is unreadable - hex-encoded data on the other hand is not.</p>\n\n<p>To the code..</p>\n\n<ul>\n<li><p>First impressions - quite neat, but functions a bit stretched-out.</p></li>\n<li><p>negative input parameters are not trapped.</p></li>\n<li><p>a #include of your own header should use \"\" not &lt;></p></li>\n<li><p>exports stdint.h (i.e. stdint.h is part of the interface). This might be undesirable. Personally I see no advantage of <code>uint8_t</code> over <code>unsigned char</code> - CHAR_BIT is (I believe) guaranteed to be at least 8 and I can't see how an architecture that has CHAR_BIT > 8 could support uint8_t natively.</p></li>\n<li><p>comments within the functions look unnecessary.</p></li>\n</ul>\n\n<p>s3p_build:</p>\n\n<ul>\n<li><p>check for buffer too small is done twice. Doesn't the second suffice?</p></li>\n<li><p>code to escape characters is repeated - use a function.</p></li>\n<li><p>if variable <code>check</code> needs a comment to make it clear that it is a checksum, why not call it <code>checksum</code>. Either way, delete the comment.</p></li>\n</ul>\n\n<p>s3p_read:</p>\n\n<ul>\n<li><p>again, check for buffer too small is done twice. Doesn't the second suffice?</p></li>\n<li><p>code to un-escape characters is repeated 3 times - use a function</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T16:20:52.833", "Id": "24579", "Score": "0", "body": "Great, thanks for taking the time to look at this!\n\n- While this is certainly not an optimal encoding scheme, it wasn't ever meant to be; the key feature of this is simplicity. \n- You've got a very good point about not being able to detect packet endings; I'll go ahead and add that in. \n- Since the wire format specifies byte-delimited fields, I think uint8_t is more appropriate than unsigned char as it forces 8-bit elements.\n- The two checks for buffer too small are for input and output buffers.\n\nI'm taking another look to see what could be pulled into functions. Again, thanks for your help!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T11:43:04.410", "Id": "15128", "ParentId": "15119", "Score": "3" } }, { "body": "<p>Have you considered #defining <code>S3P_MASK</code> as <code>0x00</code> instead of <code>0x20</code>? It wouldn't change anything significant about your implementation, but it would make encoding and decoding more efficient, and it would make the protocol slightly less WTFy. Consider: When you want to embed a <code>\"</code> character inside a C string, how do you escape it? <code>\\\"</code>, of course, not <code>\\B</code>. (I chose <code>B</code> by xoring <code>\"</code> with an arbitrary mask. Couldn't you tell?)</p>\n\n<p>At least change <code>0x56</code>, <code>0x65</code>, <code>0x25</code> (that's <code>V</code>,<code>e</code>,<code>%</code> in ASCII-speak) to something that looks reasonable in a dump. Perhaps <code>0x7B</code>, <code>0x7D</code>, <code>0x5C</code> (that's <code>{</code>, <code>}</code>, <code>\\</code>). I notice that when you had to choose the two characters that required double-width escaping, you specifically chose one of them to be <code>e</code>, the most common letter in English text. ;)</p>\n\n<p>I'd also suggest swapping the \"termination marker\" and the \"checksum\". It doesn't really matter since they're only one byte apiece, but if the checksum were more complicated (say, CRC-32) or if the codepath to read some new input were more convoluted (say, it was coming from a pipe and you had to worry about EOF), then it would be kind of a hassle to have to deal with these bytes that might be data or might be checksum, we're not sure yet.</p>\n\n<pre><code>while (true) {\n dbyte = in[dnext++];\n if (in[dnext] != S3P_TERM) {\n out[out_idx++] = unescape(dbyte);\n } else {\n verify_checksum();\n break;\n }\n}\n</code></pre>\n\n<p>would become simply</p>\n\n<pre><code>while (in[dnext] != S3P_TERM) {\n out[out_idx++] = unescape(in[dnext++]);\n}\n++dnext;\nverify_checksum();\n</code></pre>\n\n<p>(where <code>unescape</code> and <code>verify_checksum</code> are pseudocode handwavey parts, of course).</p>\n\n<p>Your documentation for <code>s3p.build(str)</code> says it raises <code>ValueError</code> if the payload to be encoded is longer than 255 bytes. This looks wrong to me (both in the sense that it shouldn't be true, and in the sense that it isn't currently true).</p>\n\n<p>You have a potential overflow on the first line of <code>s3p_build</code>; and again on line 41. If you're going to sanity-check your inputs, make sure your sanity-checks are bulletproof.</p>\n\n<p>In <code>s3p_read</code>, <code>(dsize &lt; 1)</code> is equivalent to <code>(dsize == 0)</code>. But that <code>1</code> should actually have been <code>S3P_OVERHEAD</code>, I bet.</p>\n\n<p>I'd prefer to see function parameters consistently named <code>in</code> and <code>out</code>, or <code>encoded</code> and <code>decoded</code>, rather than <code>in</code> and <code>data</code> (resp. <code>data</code> and <code>out</code>).</p>\n\n<p>Instead of the in-parameter <code>osize</code> and the out-parameter <code>*psize</code>, you could just have one in/out-parameter <code>*osize</code>. On entry to the function, it holds the size of the user's buffer. On exit, it holds how many bytes were actually written. I feel like this is a common pattern in Unix networking land, but I admit I can't find any examples off the top of my head.</p>\n\n<p>You don't explicitly document that the user's output buffer is trashed on error — say, if we get halfway through decoding a packet and suddenly decide that it's bogus.</p>\n\n<p>Finally, style: Your code feels horizontally compressed to an unnatural degree (no whitespace around control structures; 2-space tabs), and at the same time you're stretching it out vertically. That's backwards from how most of us have our monitors configured. :) Here's a particularly bad stretch of your code, followed by how I personally would have styled it:</p>\n\n<pre><code>S3P_ERR s3p_build(uint8_t const *data, size_t dsize, uint8_t *out, size_t osize, \n size_t *psize){\n if((dsize + S3P_OVERHEAD) &gt; osize){\n return S3P_BUF_TOO_SMALL;\n }\n\n /*\n S3P packets follow this structure:\n START | DATA 1 | DATA 2 | ... | DATA N | CHECKSUM | TERM\n */\n\n out[0] = S3P_START;\n\n size_t data_next = 1;\n\n uint8_t checksum = 0;\n for(size_t i=0; i&lt;dsize; i++){\n</code></pre>\n\n<p>Mine:</p>\n\n<pre><code>S3P_ERR s3p_build(uint8_t const *data, size_t dsize,\n uint8_t *out, size_t osize, \n size_t *psize)\n{\n // S3P packets follow this structure:\n // START | DATA 1 | DATA 2 | ... | DATA N | CHECKSUM | TERM\n\n if (dsize + S3P_OVERHEAD &gt; osize) {\n return S3P_BUF_TOO_SMALL;\n }\n\n size_t data_next = 0;\n uint8_t checksum = 0;\n\n out[data_next++] = S3P_START;\n\n for (size_t i=0; i &lt; dsize; ++i) {\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T04:56:23.663", "Id": "25205", "Score": "1", "body": "These are good comments, thanks! I've incorporated some of your suggestions into the library - specifically, I changed the control chars to something more reasonable, fixed the documentation and consistency problems, and addressed the overflow in read(). Thanks for taking the time to read the code! You can read the commit here: https://github.com/nickpascucci/S3P/commit/7e97c1ae084cd1af7f4f414a66128d36ef831ee8" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T21:35:10.190", "Id": "25243", "Score": "0", "body": "`s3ptest.py` is still using `0x5B` etc. instead of `S3P_START` etc. Doesn't your Python binding expose these constants? If not, why not? (Personally I'd treat them as a private implementation detail in C _as well as_ Python, but you've already exposed them in C.) Incidentally, I see `psize` stood for **p**acket-size; I had assumed it was just Hungarian for **p**ointer-to-size. `packet_size` is a good change. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-08T00:12:06.697", "Id": "15430", "ParentId": "15119", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T04:06:32.073", "Id": "15119", "Score": "2", "Tags": [ "c", "networking" ], "Title": "Style and Best Practices for C99 Packetization Functions" }
15119
<p>This is from a C# library I'm writing that checks for updates through a PHP script.</p> <pre><code>public bool CheckForUpdate(Request Request) { HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(UpdateServerAddress + "http://{0}/update.php?{1}" + Request.ToString()); httpRequest.UserAgent = "KMUpdaterClient/" + Assembly.GetExecutingAssembly().GetName().Version.ToString(); httpRequest.Accept = "text/plain"; HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { string responseString = String.Empty; using(StreamReader sr = new StreamReader(response.GetResponseStream())) { responseString = sr.ReadToEnd(); } response.Close(); switch (responseString.Substring(0, 3)) { case "UTD": //Application is up to date return false; case "AVL": return true; case "ERR": throw new ApplicationException("An error occured on the server: " + responseString.Substring(4)); default: //Unexpected throw new ApplicationException("An unexpected response was recieved by the server: " + responseString); } } else { switch (response.StatusCode) { //Generated by web app case HttpStatusCode.BadRequest: throw new ArgumentException(String.Format("The Request passed to CheckForUpdate was incomplete: AppName:{1}; Channel:{2}; Version:{3}", Request.AppName, Request.Channel, Request.Version)); case HttpStatusCode.Unauthorized: throw new UnauthorizedAccessException("The serial number for this application was invalid."); case HttpStatusCode.ServiceUnavailable: throw new AppDomainUnloadedException("The web service is currently unavailable."); //Common server errors case HttpStatusCode.NotFound: throw new FileNotFoundException("The updater server page could not be accessed."); case HttpStatusCode.InternalServerError: throw new WebException("The web server encountered an error."); //Unexpected server errors default: throw new ApplicationException("An unexpected error occured: " + response.StatusCode); } } } </code></pre> <p>After writing it, I just felt that it was a bit too long. Is this an OK size for a web request? If not, where could I trim it down?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T07:49:07.677", "Id": "24538", "Score": "0", "body": "it looks fine to me, readable, does the job, I can't see how or why to reduce the code size." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T05:16:32.187", "Id": "531540", "Score": "0", "body": "The title of this question is inappropriate for CodeReview. A question's title is meant to describe what your script does -- not what your concern is / the type of review that you are seeking." } ]
[ { "body": "<p>You could use <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">guard statements</a> and extract out the <code>switch(response.StatusCode)</code> block to a method. Furthermore, I'd replace the three-letter magic strings with constants. Their name could come from the comment around the magic string (<code>UP_TO_DATE</code> for <code>\"UTD\"</code> etc.). It would make the comment(s) unnecessary.</p>\n\n<pre><code>private Exception CreateHttpStatusException(Request Request, HttpWebResponse response) {\n switch (response.StatusCode)\n {\n //Generated by web app\n case HttpStatusCode.BadRequest:\n return new ArgumentException(String.Format(\"The Request passed to CheckForUpdate was incomplete: AppName:{1}; Channel:{2}; Version:{3}\", Request.AppName, Request.Channel, Request.Version));\n case HttpStatusCode.Unauthorized:\n return new UnauthorizedAccessException(\"The serial number for this application was invalid.\");\n case HttpStatusCode.ServiceUnavailable:\n return new AppDomainUnloadedException(\"The web service is currently unavailable.\");\n //Common server errors\n case HttpStatusCode.NotFound:\n return new FileNotFoundException(\"The updater server page could not be accessed.\");\n case HttpStatusCode.InternalServerError:\n return new WebException(\"The web server encountered an error.\");\n //Unexpected server errors\n default:\n return new ApplicationException(\"An unexpected error occured: \" + response.StatusCode);\n }\n}\n\n\npublic bool CheckForUpdate(Request Request)\n{\n HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(UpdateServerAddress + \"http://{0}/update.php?{1}\" + Request.ToString());\n httpRequest.UserAgent = \"KMUpdaterClient/\" + Assembly.GetExecutingAssembly().GetName().Version.ToString();\n httpRequest.Accept = \"text/plain\";\n HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse();\n if (response.StatusCode != HttpStatusCode.OK)\n {\n throw CreateHttpStatusException(Request, response);\n }\n\n string responseString = String.Empty;\n using(StreamReader sr = new StreamReader(response.GetResponseStream()))\n {\n responseString = sr.ReadToEnd();\n }\n response.Close();\n switch (responseString.Substring(0, 3))\n {\n case \"UTD\":\n //Application is up to date\n return false;\n case \"AVL\":\n return true;\n case \"ERR\":\n throw new ApplicationException(\"An error occured on the server: \" + responseString.Substring(4));\n default:\n //Unexpected\n throw new ApplicationException(\"An unexpected response was recieved by the server: \" + responseString);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T13:07:37.807", "Id": "24562", "Score": "0", "body": "The HttpStatusCode.BadRequest case fails because there is no request object, but I'm going to omit it anyway.\nI see what you mean about the 3 char abbreviations and I'm going to add the const strings" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T13:16:20.660", "Id": "24563", "Score": "0", "body": "@KianMayne: Thanks, I've fixed that (I hope)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T12:18:08.097", "Id": "15129", "ParentId": "15120", "Score": "4" } } ]
{ "AcceptedAnswerId": "15129", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T05:05:20.383", "Id": "15120", "Score": "3", "Tags": [ "c#", ".net", "web-services" ], "Title": "Is this too long for a web request?" }
15120
<p>I was using such code:</p> <pre><code>class Counter { private int i = 0; public int Next() { lock (this) { return i++; } } public void Reset() { lock (this) { i = 0; } } } </code></pre> <p>I refactored it such a way:</p> <pre><code>class Counter { private int i = 0; public int Next() { return Interlocked.Increment(ref i); } public void Reset() { i = 0; } } </code></pre> <p>Will that work?</p> <p>I'm using .NET 4.5 if this matters.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T08:52:29.337", "Id": "24541", "Score": "0", "body": "I would use `Thread.VolatileWrite()` (or `Volatile.Write()`) in your `Reset()`, but I'm not sure whether it's actually necessary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T13:49:34.770", "Id": "24565", "Score": "3", "body": "Why would you make code harder to understand and possibly risk some kind of subtle issue for code that, at best, will function identically to the original code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T09:30:03.597", "Id": "98922", "Score": "1", "body": "In the reset method, use `System.Threading.Interlocked.Exchange(ref i, 0);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-06T18:54:30.783", "Id": "99039", "Score": "1", "body": "Whenever anyone is trying to build a lock-free construct to solve a synchronziation problem I like to point out http://msdn.microsoft.com/en-us/magazine/cc817398.aspx and http://blog.memsql.com/common-pitfalls-in-writing-lock-free-algorithms/" } ]
[ { "body": "<p>It should also be fine in earlier versions of .NET as you are not using any 4.5 specific classes or language features.</p>\n\n<p>The reset is fine as the assignment is atomic as you mentioned, however if you were using a <code>long</code> then you would want to use <code>Interlocked.Exchange</code> because the assignment of a 64bit number is not atomic on a 32bit operating system (as it is stored as 2 32bit values).</p>\n\n<p>The only changes I would suggest are purely from a coding standards perspective:</p>\n\n<pre><code>// seal the class as it's not designed to be inherited from.\npublic sealed class Counter\n{\n // use a meaningful name, 'i' by convention should only be used in a for loop.\n private int current = 0;\n\n // update the method name to imply that it returns something.\n public int NextValue()\n {\n // prefix fields with 'this'\n return Interlocked.Increment(ref this.current);\n }\n\n public void Reset()\n {\n this.current = 0;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-27T11:11:44.833", "Id": "28677", "Score": "0", "body": "are you saying that for next value you can use increment, but for resetting not used any lock stuffs. I don't it will work. Please explain better. sorry for my ignorance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-27T11:43:17.060", "Id": "28678", "Score": "1", "body": "You have to use Interlocked for NextValue because you need to read and write the current value as a single atomic operation, for reset you are only doing a write which is an atomic operation on its own." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-12T12:52:18.897", "Id": "357498", "Score": "3", "body": "I fear that the write operation in `Reset`, however atomic, is still not guaranteed to be seen by other threads, even those that use the `Interlocked` API. Since `current` isn't `volatile` the new value of `0` may never be flushed to main-memory on multi-core / multi-processor machines. See [Igor Ostrovsky's elaborate explanation](http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/) on the subject, and the [volatile keyword](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-27T10:30:45.770", "Id": "17985", "ParentId": "15121", "Score": "9" } } ]
{ "AcceptedAnswerId": "17985", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T08:01:32.427", "Id": "15121", "Score": "12", "Tags": [ "c#", ".net", "thread-safety", "lock-free" ], "Title": "Thread-safe lock-free counter" }
15121
<p>I have to check a given amount of regular expressions, which are defining number ranges for dial plans, against an input number range. The target is to check and see, if any of the numbers in the range are free, or which regular expression matches for the number. Last situation is said to be an occupied number, otherwise if no regex matches, the number is defined as free.</p> <p>I match every number from the input range against every regexp and generate some output code. The main problem is, that this sort of "brute force" causes huge load on server and for 50.000 numbers the default php timeout is thrown. Anyhow, this is in my eyes also too long to wait for. The output is not even the real problem (but could and will get optimized anyhow), but for now I need a more efficient way to match.</p> <p>Here is my code:</p> <pre><code>$start_time = microtime(true); // Startzeit $rangeStart = $_POST["search_numberrange_start"]; $rangeEnd = $_POST["search_numberrange_end"]; $this-&gt;applicationManager-&gt;sortAppsByNumber(); $isdn_applications = $this-&gt;applicationManager-&gt;getISDNapps(); $sip_applications = $this-&gt;applicationManager-&gt;getSIPapps(); $isdn_regexp = array(); $sip_regexp = array(); for($i = 0; $i &lt; count($isdn_applications); $i++) array_push($isdn_regexp, "/".$isdn_applications[$i]-&gt;getNumber()."/"); for($i = 0; $i &lt; count($sip_applications); $i++) array_push($sip_regexp, "/".$sip_applications[$i]-&gt;getNumber()."/"); $matched_sip = array(); $matched_isdn = array(); $number = $rangeStart; do { $matched = false; $code = $number; if($this-&gt;numberRangeCheckType == "default" || $this-&gt;numberRangeCheckType == "isdn") { for($i = 0; $i &lt; count($isdn_regexp); $i++) { if(preg_match($isdn_regexp[$i],$number)) { $code = $code." &lt;a href='#application_".$i."' class='applink'&gt;".$isdn_applications[$i]-&gt;getName()."&lt;/a&gt;"; $matched = true; } } } if(!$matched) { $code = "&lt;li class='free'&gt;".$number." FREI&lt;/li&gt;"; array_push($matched_isdn, array("code" =&gt; $code)); } else { $code = "&lt;li class='occupied'&gt;".$code."&lt;/li&gt;"; array_push($matched_isdn, array("code" =&gt; $code)); } $code = $number; $matched = false; if($this-&gt;numberRangeCheckType == "default" || $this-&gt;numberRangeCheckType == "sip") { for($i = 0; $i &lt; count($sip_regexp); $i++) { if(preg_match($sip_regexp[$i],$number)) { $code = $code." &lt;a href='#application_".$i."' class='applink'&gt;".$sip_applications[$i]-&gt;getName()."&lt;/a&gt;"; $matched = true; } } } if(!$matched) { $code = "&lt;li class='free'&gt;".$number." FREI&lt;/li&gt;"; array_push($matched_sip, array("code" =&gt; $code)); } else { $code = "&lt;li class='occupied'&gt;".$code."&lt;/li&gt;"; array_push($matched_sip, array("code" =&gt; $code)); } $number++; }while($number &lt; $rangeEnd); $end_time = microtime(true); $time = $end_time - $start_time; echo "&lt;p&gt;Seite generiert in ".round($time, 5)." Sekunden&lt;/p&gt;"; /*switch($this-&gt;numberRangeCheckType) { case "isdn": echo "&lt;p class='match_caption'&gt;ISDN:&lt;/p&gt;"; $this-&gt;printMatchedEntry($matched_isdn); break; case "sip": echo "&lt;p class='match_caption'&gt;SIP:&lt;/p&gt;"; $this-&gt;printMatchedEntry($matched_sip); break; case "default": echo "&lt;p class='match_caption'&gt;ISDN:&lt;/p&gt;"; $this-&gt;printMatchedEntry($matched_isdn); echo "&lt;p class='match_caption'&gt;SIP:&lt;/p&gt;"; $this-&gt;printMatchedEntry($matched_sip); break; } */ $end_time = microtime(true); $time = $end_time - $start_time; </code></pre> <p><code>$isdn_applications</code> are objects that hold a name and number for an application. (same for <code>sip_</code>) <code>$isdn_regexp</code> hold the regexp that are built from the numbers. (note: numbers itself are stored and hold regexp, only / / is missing for preg_match which is there attached).</p> <p>Feel free to ask questions if something is not clearly enough and thanks for taking time!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T08:35:24.230", "Id": "25496", "Score": "1", "body": "Welcome to Code Review! It's quite hard to see for ourselves what's taking a lot of time. How many regexes? How large can the range be? Is it possible to define a regex that would apply to `search_numberrange_start` or `search_numberrange_end` and thus avoiding the outer loop? Simple testable code that exhibits the problem would be a good way to get help." } ]
[ { "body": "<p>Well, REGEX is actually your first problem. A REGEX function is typically slower than its string/int counterparts. So, if you can do something with a normal function, or a few normal functions, it is normally preferable to REGEX. This is why so many people say REGEX is bad. Its not bad, just misused and misunderstood. REGEX should only be used when you can't find a normal function to do something for you, or when the normal function(s) required would just be too costly, and is usually justified by some sort of profiling attempt. However, maybe switching from REGEX isn't plausible in this situation. It appears that you might be working inside someone else's framework, at least with the procedural code mingled with OOP, I assume this is the case.</p>\n\n<p>Now, REGEX isn't your only problem. There are sections in your code that are redundant and are causing some inefficiency as well. For instance, your two for loops. First off, let me say that you should keep using braces on one line statements to enhance legibility and decrease the possibility of mistakes. That isn't effecting your program's efficiency, but it might effect yours. Now, the first inefficiency is that count. For and while loops, unlike foreach loops, call functions passed in as parameters on each iteration. So you are essentially asking for a new count every time the loop restarts. While this inefficiency is usually overlooked because of its triviality, I point it out because your program is going to need all the help it can get. And its just good practice anyways. The second inefficiency is the need for two loops at all. If you get the count of both arrays, then compare them to find the larger, then you can use that larger number to loop from and use if statements to ensure that you don't go over the maximum allowed for the smaller. The last inefficiency, at least here, would be that <code>array_push()</code> function. Why use a function that can more easily and legibly be accomplished without one?</p>\n\n<pre><code>for( $i = 0; $i &lt; $isdnCount || $i &lt; sipCount; $i++ ) {\n if( $i &lt; $isdnCount ) {\n $isdn_regexp[] = \"/{$isdn_applications[ $i ]-&gt;getNumber()}/\";\n }\n if( $i &lt; $sipCount ) {\n $sip_regexp[] = \"/{$sip_applications[ $i ]-&gt;getNumber()}/\";\n }\n}\n</code></pre>\n\n<p>Not to say the above is 100% efficient either. You should profile that and compare it, maybe all those comparisons made it just as bad or worse. Maybe moving the of <code>||</code> statement out of the for loop would make it better, after all, it is being queried on each iteration.</p>\n\n<p>Why did you define <code>$rangeStart</code> then assign it to <code>$number</code> without ever using it? Anyways, that's a micro-inefficiency, this do/while loop is the biggest concern. There is a principle that will really help you here and in your future endeavors: \"Don't Repeat Yourself\" (DRY). As the name implies, if you do something more than once, find some way of making that task repeatable without explicitly having to rewrite it. Typically you start with a loop. If the loop doesn't fix it for you, then you move on to functions, and finally, if functions don't fix it for you, then you move on to classes. Eventually you will be able to look at a problem and intuitively know what kind of solution it requires. Besides making your script more light weight and efficient, it also makes it easier to read, which is a big issue with your current code. Now, the first repetition I see actually makes that loop I showed you above redundant. Why loop over the source to extract a new array, if you are just going to loop over the new array to do something with the previous source? Do all of your looping at once, whenever possible.</p>\n\n<p>Speaking of DRY, your <code>$matched</code> statements can use it too. No need to tell it to push onto the end of the array twice, you've already set up your statements to pass it the same source, just move the push out of the statements so you'll only have to call it once.</p>\n\n<pre><code>if( ! $matched ) {\n $code = '&lt;li class=\"free\"&gt;' . $number . ' FREI&lt;/li&gt;';\n} else {\n $code = '&lt;li class=\"occupied\"&gt;' . $code . '&lt;/li&gt;';\n}\n\n$matched_isdn[] = array( \"code\" =&gt; $code );\n</code></pre>\n\n<p>As above, it appears that these for loops are redundant. You could probably combine them, similarly to the one showed above. I won't write this one out, as you can extract everything you need from that previous example and apply it here.</p>\n\n<p>That appears to be it for your inefficiencies. If the program is still running too slow, it is probably because you have a double loop and that internal loop is probably rather large. I can't think of any way around this, however. You have to loop over these arrays for each number. The only \"fix\" would be to limit the range of numbers you use on each run.</p>\n\n<p><strong>Here are some suggestions for your code</strong></p>\n\n<p>Be consistent with your naming. Your first variable uses under_score, then you switch to camelCase, then back and forth throughout the application. Choose one style, at least for the same datatype. I have seen people switch between them for functions and variables, and that is perfectly fine, but all of your variables should be the same, and all of your functions should be the same. If this means shifting your style to resemble the environment you are coding in, then so be it. Better consistent than a mess.</p>\n\n<p>Validate and sanitize any user input, unless the scope of this program is purely internal and you trust all input. But even then, people make mistakes, so basic validation wouldn't hurt.</p>\n\n<p>It appears that you are working with classes and OOP. In order to be effective with it, you should brush up on key OOP principles, such as the DRY principle I mentioned. There's also SOLID. Google those and you should get a whole bunch more to work with. You don't have to understand all of them right away. Just reading it so that you are aware of it is enough at first. Then, subconsciously you will be able to start looking at your code differently and can then start trying to apply these principles.</p>\n\n<p>I hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T05:34:27.737", "Id": "24656", "Score": "0", "body": "with some points you have mentioned and asynchronous processing I was able to boost the computation of a range with 50.000 numbers down to 6 seconds. Though your answer was general, I will set it as accepted because you really helped me!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:57:57.973", "Id": "15145", "ParentId": "15122", "Score": "1" } } ]
{ "AcceptedAnswerId": "15145", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T08:05:39.350", "Id": "15122", "Score": "3", "Tags": [ "php", "regex" ], "Title": "Lots of RegEx match against huge number range (PHP)" }
15122
<p>I know there are some answers about a user function to split chars and I have one already running (found one years ago in the net and modified it to my own needs).</p> <p>Since I use this function very often, I'd like to ask the best SQL professionals (which are probably here) to review this function for performance. Is the function ok or is there a faster or better way to do this now? Minimum requirements are SQL Server 2005 to work, but if there are better ways from 2008 I can roll out two versions (most usage of the DB is 2008, only a few 2005 left).</p> <pre><code>CREATE FUNCTION [dbo].[fn_Split](@text nvarchar(4000), @delimiter char(1) = ',') RETURNS @Strings TABLE ( position int IDENTITY PRIMARY KEY, value nvarchar(4000) ) AS BEGIN DECLARE @index int SET @index = -1 SET @text = RTRIM(LTRIM(@text)) WHILE (LEN(@text) &gt; 0) BEGIN SET @index = CHARINDEX(@delimiter , @text) IF (@index = 0) AND (LEN(@text) &gt; 0) BEGIN INSERT INTO @Strings VALUES (@text) BREAK END IF (@index &gt; 1) BEGIN INSERT INTO @Strings VALUES (LEFT(@text, @index - 1)) SET @text = RIGHT(@text, (LEN(@text) - @index)) END ELSE SET @text = RIGHT(@text, (LEN(@text) - @index)) END RETURN END </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T09:06:15.807", "Id": "24542", "Score": "0", "body": "Oh yes, my bad. Can a moderator move this post please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T11:06:01.740", "Id": "24544", "Score": "1", "body": "Here is a couple of alternatives evaluated for you. [Split strings the right way – or the next best way](http://www.sqlperformance.com/2012/07/t-sql-queries/split-strings)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T16:56:58.387", "Id": "24586", "Score": "0", "body": "@MikaelEriksson great link. Put this as answer, so I can upvote it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T10:53:17.177", "Id": "62855", "Score": "0", "body": "You can use below link: [1- SQL User Defined Function to Parse a Delimited String](http://www.codeproject.com/Articles/7938/SQL-User-Defined-Function-to-Parse-a-Delimited-Str) [2- INSERT INTO TABLE from comma separated varchar-list ](http://stackoverflow.com/a/6354838/1407421)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-28T15:27:14.117", "Id": "62856", "Score": "0", "body": "My own function I already have does what I need perfect. My approach to this question was to ask everyone if he knows a FASTER way to do this. The result should be the same. There are many other functions that does the same. The question was: which is the fastest..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:33:54.870", "Id": "62857", "Score": "0", "body": "For some interesting ways to approach this problem you might want to check this post: http://dba.stackexchange.com/questions/11506/why-are-numbers-tables-invaluable" } ]
[ { "body": "<p>try this:</p>\n\n<pre><code>Create function dbo.SplitString(@inputStr varchar(1000),@del varchar(5))\nRETURNS @table TABLE(col varchar(100))\nAs\nBEGIN\n\nDECLARE @t table(col1 varchar(100))\nINSERT INTO @t\nselect @inputStr\n\nif CHARINDEX(@del,@inputStr,1) &gt; 0\nBEGIN\n ;WITH CTE1 as (\n select ltrim(rtrim(LEFT(col1,CHARINDEX(@del,col1,1)-1))) as col,RIGHT(col1,LEN(col1)-CHARINDEX(@del,col1,1)) as rem from @t\n union all\n select ltrim(rtrim(LEFT(rem,CHARINDEX(@del,rem,1)-1))) as col,RIGHT(rem,LEN(rem)-CHARINDEX(@del,rem,1))\n from CTE1 c\n where CHARINDEX(@del,rem,1)&gt;0\n )\n\n INSERT INTO @table \n select col from CTE1\n union all\n select rem from CTE1 where CHARINDEX(@del,rem,1)=0\n END\nELSE\nBEGIN\n INSERT INTO @table \n select col1 from @t\nEND\n\nRETURN\n\nEND\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T09:17:11.573", "Id": "15126", "ParentId": "15125", "Score": "1" } }, { "body": "<p>ADD:</p>\n\n<p>Found a new one which is around 4 times faster then my one :)</p>\n\n<pre><code>CREATE FUNCTION [dbo].[fn_Split] (@text VARCHAR(MAX), @delimiter VARCHAR(32) = ',')\n\nRETURNS @t TABLE ( [position] INT IDENTITY PRIMARY KEY, [value] VARCHAR(MAX) ) \nAS\nBEGIN\n DECLARE @xml XML\n SET @XML = N'&lt;root&gt;&lt;r&gt;' + REPLACE(@text, @delimiter, '&lt;/r&gt;&lt;r&gt;') + '&lt;/r&gt;&lt;/root&gt;'\n\n INSERT INTO @t([value])\n SELECT r.value('.','VARCHAR(MAX)') as Item\n FROM @xml.nodes('//root/r') AS RECORDS(r)\n\n RETURN\nEND\n</code></pre>\n\n<p>Modified it to my needs, but taken from second answer from this link: <a href=\"https://stackoverflow.com/questions/314824/t-sql-opposite-to-string-concatenation-how-to-split-string-into-multiple-reco/314917#314917\">https://stackoverflow.com/questions/314824/t-sql-opposite-to-string-concatenation-how-to-split-string-into-multiple-reco/314917#314917</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T22:38:14.313", "Id": "23935", "ParentId": "15125", "Score": "1" } }, { "body": "<p>From my tests this function is faster than yours <em>fn_split()</em> and <em>SplitString()</em>.</p>\n\n<pre><code>CREATE FUNCTION [dbo].[fn_split](\n @input VARCHAR(8000),\n @delimiter VARCHAR(10) = ';'\n ) \n RETURNS @result TABLE (rownum int NOT NULL, item VARCHAR(max))\n\n BEGIN\n DECLARE @item VARCHAR(max), @rownum int = 0\n\n WHILE CHARINDEX(@delimiter,@input,0) &gt; 0\n BEGIN\n SELECT\n @item = ltrim(RTRIM(LTRIM(SUBSTRING(@input, 1, CHARINDEX(@delimiter, @input, 0) - 1)))),\n @input = ltrim(RTRIM(LTRIM(SUBSTRING(@input, CHARINDEX(@delimiter, @input, 0) + LEN(@delimiter), LEN(@input)))))\n\n IF LEN(@item) &gt; 0\n BEGIN\n SET @rownum += 1;\n INSERT INTO @result SELECT @rownum, @item\n END\n END\n\n IF LEN(@input) &gt; 0\n BEGIN\n SET @rownum += 1;\n INSERT INTO @result SELECT @rownum, @input\n END\n RETURN\nEND\nGO\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-04T15:37:30.697", "Id": "149590", "Score": "2", "body": "A plain code dump is not an ideal answer. Please explain why your implementation is better/faster/smaller and which improvement were made in relation to the OP." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-04T14:30:54.943", "Id": "83201", "ParentId": "15125", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T08:51:49.910", "Id": "15125", "Score": "4", "Tags": [ "sql", "sql-server" ], "Title": "SQL Server Split function" }
15125
<p>Let me start with a little introduction. I am in the process of learning OOP in PHP. I have also researched Design Patterns but have not yet fully grasped the different types of concepts. I am at the stage where every few months I realise that I am not doing things the correct way and have to change my style. <strong>This is so frustrating.</strong> Therefore I would like to find out the correct way of doing things once and for all. I have tried to fully read up on Stackoverflow about the following topics:</p> <p>ORM<br> Data Mapper<br> Singleton<br> Globals are evil<br> Everything related</p> <p>However I am still not clear about a few things. I am posting my code here in a clear and concise way and hope that people can point out <strong>both</strong> the good practices and the bad ones. I will list all my questions at the end.</p> <p><strong>Please do not close as a duplicate, I have honestly searched through almost every question on the topic but I still want to know a few things which I have not been able to clarify. Sorry it is so long but I have tried to organize it so it should read well!</strong> </p> <p>I will start by posting the essentials of my Database class.</p> <p><em><strong>Database.php</em></strong></p> <pre><code>&lt;?php class DatabaseMySQL{ private static $dbh; public function __construct(){ $this-&gt;open_connection(); } public function open_connection(){ if(!self::$dbh){ return (self::$dbh = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER,DB_PASSWORD)) ? true : false; } return true; } public function query($sql, $params=array()){ $this-&gt;last_query = $sql; $stmt = self::$dbh-&gt;prepare($sql); $result = $stmt-&gt;execute($params); return $result ? $stmt : $stmt-&gt;errorInfo(); } public function fetch_all($results, $class_name=''){ return $results-&gt;fetchAll(PDO::FETCH_CLASS, $class_name); } } ?&gt; </code></pre> <p>This is my Database class file. This class allows me to create as many instances as I like of this class and it will reuse the already instantiated PDO object stored as a Static property of the class. It also fetches the data from the result set using PDO to get the data as objects of a specified class.</p> <p>My next file I have is my class that all my other classes inherit from. I have called it MainModel. I have no idea if this follows convention or not.</p> <p><em><strong>MainModel.php</em></strong></p> <pre><code>&lt;?php abstract class MainModel{ protected static $table; public function __construct($array=array()){ $this-&gt;assign_known_properties($array); } public function assign_known_properties($array){ foreach($array as $key=&gt;$value){ $this-&gt;$key = $value; } } public static function find_by_id($id){ $db = new DatabaseMySQL(); self::intialise_table_name(); $id = (int) $id; $sql = "SELECT * FROM ".static::$table." "; $sql .= "WHERE id = {$id} "; $result = self::find_by_sql($sql); return array_shift($result); } public static function find_all(){ $db = new DatabaseMySQL(); self::intialise_table_name(); $sql = "SELECT * FROM ".self::$table." "; return self::find_by_sql($sql); } public static function fetch_as_objects($results){ $db = new DatabaseMySQL(); $called_class = get_called_class(); $results = $db-&gt;fetch_all($results, $called_class); return $results; } public static function find_by_sql($sql){ $db = new DatabaseMySQL(); $results = $db-&gt;query($sql); return $results ? self::fetch_as_objects($results) : false; } public static function intialise_table_name(){ $called_class = get_called_class(); static::$table = strtolower($called_class).'s'; } public function get_table_fields(){ self::intialise_table_name(); $sql = "SHOW FIELDS FROM ".static::$table." "; return self::find_by_sql($sql); } public function set_table_details(){ $fields = $this-&gt;get_table_fields(); $total = count($fields); $array = array(); foreach($fields as $object){ $array [] = $object-&gt;Field; } $this-&gt;table_details = array('objects'=&gt;$fields,'array'=&gt;$array,'total'=&gt;$total); $this-&gt;set_placeholders_for_new_record(); $this-&gt;set_properties_as_array(); $this-&gt;set_properties_as_array(true); } public function set_properties_as_array($assoc=false){ $array = array(); if (!$assoc){ foreach($this-&gt;table_details['array'] as $field){ if(isset($this-&gt;$field)){ $array [] = $this-&gt;$field; }else{ $array [] = NULL; } } $this-&gt;table_details['values'] = $array; }else{ foreach($this-&gt;table_details['array'] as $field){ if(isset($this-&gt;$field)){ $array[$field] = $this-&gt;$field; }else{ $array [$field] = NULL; } } $this-&gt;table_details['assoc_values'] = $array; } } public function set_placeholders_for_new_record(){ $string = ''; for($i=0; $i&lt;$this-&gt;table_details['total']; $i++){ $string .= '? '; if(($i+1) != $this-&gt;table_details['total'] ){ $string .= ", "; } } $this-&gt;table_details['placeholders'] = $string; } public function create(){ $db = new DatabaseMySQL(); $this-&gt;set_table_details(); $sql = "INSERT INTO ".static::$table." "; $sql .= " VALUES({$this-&gt;table_details['placeholders']}) "; $result = $db-&gt;query($sql, $this-&gt;table_details['values']); // If array is returned then there was an error. return is_array($result) ? $result : $db-&gt;insert_id(); } public function update(){ $db = new DatabaseMySQL(); $this-&gt;set_table_details(); $sql = "UPDATE ".static::$table." "; $sql .= " SET "; $count = 1; foreach($this-&gt;table_details['array'] as $field){ $sql .= "{$field} = :{$field} "; if($count &lt; $this-&gt;table_details['total']){ $sql .= ", "; } $count++; } $sql .= " WHERE id = {$this-&gt;id} "; $sql .= " LIMIT 1 "; $result = $db-&gt;query($sql, $this-&gt;table_details['assoc_values']); return $result; } public function save(){ return isset($this-&gt;id) ? $this-&gt;update() : $this-&gt;create(); } } ?&gt; </code></pre> <p>To summarise this file. I use static methods like <code>find_by_id($int)</code> that generate objects of the called class dynamically. I am using Late Static Bindings to gain access to the name of the called class and I use the <code>$stmt->fetchAll(PDO::FETCH_CLASS, $class_name)</code> to instantiate these objects with the data from the database automatically converted into objects. </p> <p>In each static method I instantiate an instance of the DatabaseMySQL class. In each static method I set the correct static <code>$table</code> name to be used in the SQL queries dynmically by getting the name of the class and appending an <code>s</code> to it. So if my class was <code>User</code>, that would make the table name <code>users</code>. </p> <p>In my constructer I have placed an optional array which can be used to insert some variables as properties of an object as it is created. This way everything is done dynamically which leaves me to the final stage of my project. My inheritance classes.</p> <p><em><strong>User.php</em></strong></p> <pre><code>class User extends MainModel{ } </code></pre> <p><em><strong>Question.php</em></strong></p> <pre><code>class Question extends MainModel{ } </code></pre> <p>What I do now is simple. I can say: </p> <pre><code>$user = new User(array('username'=&gt;'John Doe')); echo $user-&gt;username; // prints *John Doe* $user-&gt;save(); // saves (or updates) the user into the database. </code></pre> <p>I can retrieve a user with a static call to User.</p> <pre><code>$user = User::find_by_id(1); echo $user-&gt;username; // prints users name </code></pre> <p>So now for my questions:</p> <ul> <li><p>1) What name would you call this design pattern (if it even is one at all).Data Mapper? Dependency Injection? Domain Model (whatever that is)? Data Access Layer?</p></li> <li><p>2) As it stands now is this implementation considered well structured?</p></li> <li><p>3) If it is good, is there a naming convention I should be aware of that is missing in my code?</p></li> <li><p>4) If it is considered good, would you mind pointing out what particularly you liked so I will know which part to definitely keep?</p></li> <li><p>5) If you dont think it is good would you care to give a detailed explanation why this is so?</p></li> <li><p>6) Should my <code>create</code>, <code>update</code>, <code>delete</code> which are all methods of my objects be in the same class as my <code>find_by_id</code>, <code>find_all</code> which are only called statically and actually return objects. If they should be in two different classes, how do I go about that?</p></li> <li><p>7) Why is everyone else using <code>$load->('UserClass')</code> functions and fancy words like mappers and I havent yet needed them once?</p></li> </ul>
[]
[ { "body": "<p>Congratulations, that means you are learning. You'll be at that stage for some time. In fact, I don't think you'll ever truly leave it, or if you do, then you should be concerned. The time between \"changes\" might increase, but you should never stop learning and should always find some way you can improve. Its only natural. The first few months I was learning OOP I felt the same. Then I started hanging out here and applying what I was learning, or already had learned, to some of the problems people were having. In the process I affirmed the lessons I was attempting to learn and actually ended up learning quite a bit more than if I were still trying to puzzle it all out myself. I guess what they say about teaching others being a great tool for learning is true and is something I strive for in every answer now. For instance, what I am taking from this is that I need to look more closely into these other patterns you mentioned.</p>\n\n<p>If you have searched and shown effort, then you do not need to worry about your question being closed. If something obviously wasn't covered well enough for you, then it is obviously not a duplicate. Just be sure to show and cite appropriately, as you have done, otherwise you'll be told to google it and probably get downvoted.</p>\n\n<p>Using both private and static is awkward and wrong. A private property or method cannot be accessed outside of the class in which it is declared. A static property or method is used to specifically grant outside access by providing a property or method that is not associated with any, or rather with all, instances of the class. So you begin to see why this is awkward. This is wrong because static properties cannot be initialized using a return value from a function, an object, or some other variable. It must be initialized with static data, such as a string literal or integer or array. You should be receiving silent errors about this. I would consider turning up your error reporting so that you can see them. What you really want here is a private property, which, by the way, should be initialized in a private method, or in the constructor, to ensure that it is only ever initialized once. This will remove the need for checking if it has already been set. It is good to separate your code by functions, this follows the Single Responsibility Principle fairly well, but some things should just be left in the constructor for convenience.</p>\n\n<p>Your database class is backwards. You don't create a new instance of a class to do something different with the same data. You create an instance of the database class to have an instance of the database, then you call the proper methods to do those different things and save their returns as different variables.</p>\n\n<p>Variables, properties, methods, functions, constants; Pretty much anything that you can apply a name to should have a descriptive name so that it can easily be identified. Less descriptive names that are commonly used and so are easily identifiable are fine, such as <code>$dbh</code>. But those that you create yourself should be better named to ensure future understanding. So <code>$array</code> is a very vague name and you should consider renaming it.</p>\n\n<p>You really want to be careful with variable-variables and variable-functions. There are instances where these are fine, but typically they are avoided because they are difficult to spot and debug. The only place I can think of where I use such is in MVC frameworks between the controller and view.</p>\n\n<p>First, before I go too much farther, let me steer you away from the static keyword. Just forget you ever heard about it for now. I believe this is confusing you a little. I'll be honest, I haven't needed static for anything I've done yet. I know about it, know what it does, but I've never needed it. Its probably not anything you will ever need either, at least not in this application. Revisit the topic once you've gotten the rest straight.</p>\n\n<p>Now... You said that this <code>MainModel</code> is inherited from, but from the looks of it, you are actually doing it backwards again. Your model class is, in every method, reinstantiating the database class. This is redundant and wasteful. In fact, the model class, in a roundabout and awkward fashion, is actually inheriting from the database class. You have set up the model as an abstract class so that it can be extended. In fact, abstract classes MUST be extended. They cannot be instantiated without throwing errors, so it should not even have a constructor. Once extended, it can then work from the assumption that whatever class is extending it will have set up the information it needs to run, and the class extending it can assume that the methods it is inheriting will work with its data. In fact, the two classes should be able to share data seamlessly, as if they were one. So, what you really want to do here is have your database class properly inherit from the model class, and have your model class properly use its information. For instance:</p>\n\n<pre><code>class DatabaseMySQL extends MainModel {\n //etc...\n $db-&gt;find_by_id( $id );//for demonstration\n //etc...\n}\n\nabstract class MainModel {\n //etc...\n public function find_by_id( $id ) {\n //$db = new DatabaseMySQL();//no longer necessary, implied by $this\n $id = (int) $id;\n\n $this-&gt;intialise_table_name();\n $sql = \"SELECT * FROM {$this-&gt;table} \"\n . \"WHERE id = $id \"\n ;\n $result = $this-&gt;find_by_sql( $sql ); \n return array_shift( $result );\n }\n //etc...\n}\n</code></pre>\n\n<p>Hopefully the above will help you with some of your questions, now I'll attempt to answer the rest directly.</p>\n\n<p><strong>1) What name would you call this design pattern (if it even is one at all).Data Mapper? Dependency Injection? Domain Model (whatever that is)? Data Access Layer?</strong>\nI don't know, with \"model\" it appears that you are attempting to start an MVC, but obviously not. Maybe Domain Model? I honestly wouldn't be concerned with design patterns right now, though. Best thing is just to learn the theories and how to apply them. Once you have a firm grasp on this, then you can worry about design patterns and how they are applied. I learned OOP with MVC, so that's the one I'm most comfortable with. I've heard of these others, but have not looked into them as of yet.</p>\n\n<p><strong>As it stands now is this implementation considered well structured?</strong>\nSee review.</p>\n\n<p><strong>If it is good, is there a naming convention I should be aware of that is missing in my code?</strong>\nNaming conventions are purely stylistic choice. For instance, I would say camelCase is better because I think its easier to read, but someone else, maybe you, would say under_score is better. Its only when you start mingling your code with another's that you have to worry about changing your style. The important thing to remember is to stay consistent.</p>\n\n<p><strong>If it is considered good, would you mind pointing out what particularly you liked so I will know which part to definitely keep?</strong>\nAbstract classes are good. They sort of go hand in hand with interfaces. I didn't start learning about them until much later. They are a powerful tool and will help you out immensely. I only wish I had heard about them sooner... Then again, I did, they just confused me :)</p>\n\n<p><strong>If you dont think it is good would you care to give a detailed explanation why this is so?</strong>\nSee review.</p>\n\n<p><strong>Should my create, update, delete which are all methods of my objects be in the same class as my find_by_id, find_all which are only called statically and actually return objects. If they should be in two different classes, how do I go about that?</strong>\nI explained part of this. If we follow an MVC pattern, then your model would hold all of the methods it needs to fetch and manipulate data. So all of these methods look fine in the one class, but the implementation you use, as I pointed out in the review, could use some work.</p>\n\n<p><strong>Why is everyone else using $load->('UserClass') functions and fancy words like mappers and I havent yet needed them once?</strong>\nGot me, I'm still learning too. But if I were to hazard a guess, it is because we are essentially recreating what those other more advanced users are implementing. I'm not sure what that first example is supposed to be, whatever it is, it doesn't look like valid syntax, but the mapper is just a \"more efficient\" and \"easier\" way of doing it. Notice the air-quotes. Again, get comfortable with the concept before delving into the more advanced stuff.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T18:15:36.880", "Id": "24589", "Score": "0", "body": "What an unbelievable answer, thanks for taking the time to go through all of that. Your most important point to me at the moment (I gotta go through this a couple of times) is to forget about the `static` keyword. I see the way you have managed without it, i think its amazing. Still reading the post again, will come back when I understand the rest! +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T08:37:19.890", "Id": "25497", "Score": "1", "body": "Consider accepting mseancole's question by clicking on the tick below the score." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T17:35:02.643", "Id": "15155", "ParentId": "15130", "Score": "11" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T12:21:11.510", "Id": "15130", "Score": "4", "Tags": [ "php", "object-oriented", "design-patterns", "mysql" ], "Title": "What is the correct way to set up my classes in OOP programming in PHP?" }
15130
<p>I am just trying to use ASP.NET MVC using repository pattern. Could somebody see If I am doing something wrong here.</p> <p><strong>Model</strong> - Contains the model</p> <pre><code>public class Contact { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } } </code></pre> <p><strong>Repository interface</strong> - Interface</p> <pre><code> public interface IContactRepository { void Create(Contact contact); void Delete(int contactId); void Save(Contact contact); Contact Retrieve(int contactId); IEnumerable&lt;Contact&gt; Select(); } </code></pre> <p><strong>Repository class</strong></p> <pre><code>public class ContactRepository : IContactRepository { private AddressBookDb addressBookdb = new AddressBookDb(); public void Create(Contact contact) { addressBookdb.Contacts.Add(contact); addressBookdb.SaveChanges(); } public void Save(Contact contact) { Delete(contact.Id); Create(contact); } public void Delete(int contactId) { Contact contact = Retrieve(contactId); if (contact != null) { addressBookdb.Contacts.Remove(contact); addressBookdb.SaveChanges(); } } public Contact Retrieve(int contactId) { return addressBookdb.Contacts.FirstOrDefault&lt;Contact&gt;(c =&gt; c.Id == contactId); } public IEnumerable&lt;Models.Contact&gt; Select() { return addressBookdb.Contacts.ToList&lt;Contact&gt;(); } } </code></pre> <p><strong>Controller class</strong></p> <pre><code>public class ContactController : Controller { IContactRepository contactRepository = null; public ContactController() : this (new ContactRepository()) { } public ContactController(IContactRepository contactRepository) { this.contactRepository = contactRepository; } [HttpPost] public ActionResult Edit(Contact contact) { if (ModelState.IsValid) { contactRepository.Save(contact); return RedirectToAction("Index"); } return View(contact); } } </code></pre>
[]
[ { "body": "<p>You code shows not only your definition of your repository but also it's usage.</p>\n\n<p>What worries me is that i don't see how the DbContext (AddressBookDB in this case) is disposed off.</p>\n\n<p>I think i'd rather pass in the AddressBookDB object as a paramter to the repository constructor for usage so you can ensure it is diposed off properly by creating it in a using block.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-24T23:02:34.353", "Id": "24548", "Score": "0", "body": "then in that case the AddressBookDb should be instantiated in the controller and passed on to the repository constructor so that we have the repository object?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-24T23:04:34.853", "Id": "24549", "Score": "0", "body": "Depends on what you need, i typically use a singleton style approach ... the context is valid for the current request and any method needing it will use it. .. it is typically disposed at the end of the request ... handled by a httpmodule" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-24T23:06:40.130", "Id": "24550", "Score": "0", "body": "May I request for sample code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-24T23:15:32.790", "Id": "24551", "Score": "1", "body": "@user1052927 checkout this link cairey.wordpress.com/2009/10/14/… it refers to objectcontext but i'm sure u can easily modify to suit your scenario" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-24T22:55:43.797", "Id": "15134", "ParentId": "15132", "Score": "3" } }, { "body": "<h2>Additional layer depending on app complexity</h2>\n\n<p>Your code seems clean and fine but it all boils down to complexity of your application. If business processes are complex I'd suggest to put an additional layer between your controller and repository logic.</p>\n\n<p>So controller would be calling into service, and service would be calling into repositories (even many and several times if it needs to depending on the business process).</p>\n\n<h2>Prevent code duplication</h2>\n\n<p>Since you've provided such generic repository interface I'd suggest you actually create a generic one to prevent code duplication:</p>\n\n<pre><code>public interface IRepository&lt;TEntity&gt;\n{\n void Create(TEntity entity);\n void Delete(int entityId);\n void Save(TEntity entity);\n TEntity Retrieve(int entityId);\n IEnumerable&lt;TEntity&gt; Select();\n}\n</code></pre>\n\n<p>Your repositories would then implement this interface:</p>\n\n<pre><code>public class ContactRepository: IRepository&lt;Contact&gt;\n{\n ...\n}\n</code></pre>\n\n<p>And if some repository needs a more <em>powerful</em> interface you can write an additional repository interface, that will likely inherit from this generic <code>IRepository&lt;TEntity&gt;</code> interface.</p>\n\n<p>This would prevent you from having numerous repository interfaces with more or less identical definition.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-28T14:44:16.060", "Id": "15135", "ParentId": "15132", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-24T22:44:11.133", "Id": "15132", "Score": "3", "Tags": [ "c#", "asp.net", "asp.net-mvc-3" ], "Title": "ASP.NET MVC using Repository pattern - code review" }
15132
<p>I'm a Pthreads newbie and I've been giving myself a challenge: I want to have a resource that multiple threads can access at the same time as read. However, if a thread wants to write, then this need to be exclusive.</p> <p>Now, I know that there are read/write locks designed specifically for this purpose. I would not do this in production code; this is just to learn. For simplicity, I assume there is only one thread that can write (but of course, multiple that read).</p> <p>I have come up with two version. The first one does not use signals, the second one does. I tested it a little bit and both seem to work. However, multi-thread programming is tricky.</p> <p>Could someone review the two versions and let me know whether there might be a bug that my tests missed?</p> <p><strong>Version 1</strong></p> <pre><code>#include &lt;pthread.h&gt; #include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #include &lt;stdlib.h&gt; #include &lt;string&gt; class limited_resource { public: limited_resource() { pthread_mutex_init(&amp;d_mutext, NULL); d_write_request = false; d_nreading = 0; } virtual ~limited_resource() { pthread_mutex_destroy(&amp;d_mutext); } void read(int thread_id) { // Do a stupid waiting while(true) { pthread_mutex_lock(&amp;d_mutext); if(!d_write_request) { d_nreading++; break; } pthread_mutex_unlock(&amp;d_mutext); sleep(1); } pthread_mutex_unlock(&amp;d_mutext); // Do the actual reading char data[4]; for(int ii = 0; ii &lt; 4; ++ii) { data[ii] = d_data[ii]; sleep(1); // Super slow reading to create bugs on purpose } printf("Thread %d read \"%c%c%c%c\"\n", thread_id, data[0], data[1], data[2], data[3]); // Decrement the number of readers pthread_mutex_lock(&amp;d_mutext); d_nreading--; pthread_mutex_unlock(&amp;d_mutext); } void write(const char *str) { pthread_mutex_lock(&amp;d_mutext); d_write_request = true; pthread_mutex_unlock(&amp;d_mutext); // Do a stupid waiting while(true) { pthread_mutex_lock(&amp;d_mutext); if(d_nreading == 0) break; pthread_mutex_unlock(&amp;d_mutext); sleep(1); } pthread_mutex_unlock(&amp;d_mutext); // Do the work printf("Writing\n"); for(int ii = 0; ii &lt; 4; ++ii) { d_data[ii] = str[ii]; sleep(1); // Super slow writing to create bugs on purpose } // Release the writing pthread_mutex_lock(&amp;d_mutext); d_write_request = false; pthread_mutex_unlock(&amp;d_mutext); } protected: pthread_mutex_t d_mutext; int d_nreading; bool d_write_request; char d_data[4]; }; limited_resource lr; void* thread_function(void* input) { int thread_id = *((int*)input); while(true) { sleep(thread_id + 1); lr.read(thread_id); } return NULL; } int main(int argc, char **argv) { int N = 10; pthread_t tIDs[N]; int vals[N]; for(int ii = 0; ii &lt; N; ++ii) { vals[ii] = ii; pthread_create(tIDs + ii, NULL, thread_function, vals + ii); } char str[80]; while(true) { scanf("%s", str); lr.write(str); } return 0; } </code></pre> <p><strong>Version 2</strong></p> <pre><code>#include &lt;pthread.h&gt; #include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #include &lt;stdlib.h&gt; #include &lt;string&gt; class limited_resource { public: limited_resource() { pthread_mutex_init(&amp;d_mutext, NULL); d_write_request = false; pthread_cond_init(&amp;d_write_request_false, NULL); d_nreading = 0; pthread_cond_init(&amp;d_nreading_zero, NULL); } virtual ~limited_resource() { pthread_mutex_destroy(&amp;d_mutext); pthread_cond_destroy(&amp;d_write_request_false); pthread_cond_destroy(&amp;d_nreading_zero); } void read(int thread_id) { // Wait pthread_mutex_lock(&amp;d_mutext); while(d_write_request) pthread_cond_wait(&amp;d_write_request_false, &amp;d_mutext); d_nreading++; pthread_mutex_unlock(&amp;d_mutext); // Do the actual reading char data[4]; for(int ii = 0; ii &lt; 4; ++ii) { data[ii] = d_data[ii]; sleep(1); // Super slow reading to create bugs on purpose } printf("Thread %d read \"%c%c%c%c\"\n", thread_id, data[0], data[1], data[2], data[3]); // Decrement the number of readers pthread_mutex_lock(&amp;d_mutext); d_nreading--; if(d_nreading == 0) pthread_cond_signal(&amp;d_nreading_zero); pthread_mutex_unlock(&amp;d_mutext); } void write(const char *str) { pthread_mutex_lock(&amp;d_mutext); d_write_request = true; while(d_nreading != 0) pthread_cond_wait(&amp;d_nreading_zero, &amp;d_mutext); pthread_mutex_unlock(&amp;d_mutext); // Do a stupid waiting while(true) { pthread_mutex_lock(&amp;d_mutext); if(d_nreading == 0) break; pthread_mutex_unlock(&amp;d_mutext); sleep(1); } pthread_mutex_unlock(&amp;d_mutext); // Do the work printf("Writing\n"); for(int ii = 0; ii &lt; 4; ++ii) { d_data[ii] = str[ii]; sleep(1); // Super slow writing to create bugs on purpose } // Release the writing pthread_mutex_lock(&amp;d_mutext); d_write_request = false; pthread_cond_broadcast(&amp;d_write_request_false); pthread_mutex_unlock(&amp;d_mutext); } protected: pthread_mutex_t d_mutext; int d_nreading; pthread_cond_t d_nreading_zero; bool d_write_request; pthread_cond_t d_write_request_false; char d_data[4]; }; limited_resource lr; void* thread_function(void* input) { int thread_id = *((int*)input); while(true) { sleep(thread_id + 1); lr.read(thread_id); } return NULL; } int main(int argc, char **argv) { int N = 10; pthread_t tIDs[N]; int vals[N]; for(int ii = 0; ii &lt; N; ++ii) { vals[ii] = ii; pthread_create(tIDs + ii, NULL, thread_function, vals + ii); } char str[80]; while(true) { scanf("%s", str); lr.write(str); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-13T01:13:15.787", "Id": "24552", "Score": "0", "body": "This is a huge code dump. You're right for asking, because testing almost by definition won't find bugs in concurrency. But the answer to this is probably \"take an OS class\". As a quick and dirty answer, as long as you have one mutex per resource that you must obtain before writing, you won't have race conditions. But you could easily have problems with \"starvation\"; a thread that doesn't get to write ever, or \"deadlocks\"; where each is waiting for the other to give up a resource. People still don't know how to solve these generally, so you'd really need to study it properly to do it right." } ]
[ { "body": "<p>You forgot to remove the \"stupid waiting\" from version 2. Otherwise, it looks good. Not particularly efficient, but correct.</p>\n\n<p>You can and should remove this chunk of code from version 2. The code before it already does this:</p>\n\n<pre><code> // Do a stupid waiting\n while(true)\n {\n pthread_mutex_lock(&amp;d_mutext);\n if(d_nreading == 0)\n break;\n pthread_mutex_unlock(&amp;d_mutext);\n\n sleep(1);\n }\n pthread_mutex_unlock(&amp;d_mutext);\n</code></pre>\n\n<p>Here's an optimization for you. Change:</p>\n\n<pre><code> if(d_nreading == 0)\n pthread_cond_signal(&amp;d_nreading_zero);\n</code></pre>\n\n<p>to</p>\n\n<pre><code> if( (d_nreading == 0) &amp;&amp; d_write_request)\n pthread_cond_signal(&amp;d_nreading_zero);\n</code></pre>\n\n<p>Reader/writer locks are based on the assumption that reading is frequent and writing is rare. So the common case would be that there's no writing. Your code makes an extra call into the pthread library for each read unlock, even that call is not needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-13T01:36:22.880", "Id": "24553", "Score": "0", "body": "Both versions are definitely *not* correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-13T01:38:07.773", "Id": "24554", "Score": "0", "body": "@EmployedRussian Can you be just a bit more specific? (Perhaps you missed the problem statement that said it was okay to assume only one writing thread?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-13T01:47:53.600", "Id": "24555", "Score": "0", "body": "On the contrary: the problem statement says \"However, if a thread wants to write, then this need to be exclusive.\" Just like for reader/writer locks, this means multiple writers are not allowed simultaneous access, *not* that there could only exist a single writer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-13T02:10:06.567", "Id": "24556", "Score": "0", "body": "@EmployedRussian I understood that to mean that a write lock means there are no outstanding (or new) read locks. \"For simplicity, I assume there is only one thread that can write (but of course, multiple ones that read).\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-14T00:47:57.377", "Id": "24557", "Score": "0", "body": "Thanks everyone. I've written the version 3, which should support multiple writers. It seems OK so far. I've also added David's optimization; I tried to add it to write routine but it is not correct (it results in the program freezing up); search for \"cannot be\". Thanks again -- Tony" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-14T00:50:21.067", "Id": "24558", "Score": "0", "body": "@AntoineBruguier Just remember that real world reader/writer locks typically don't look much like this. They're typically *heavily* optimized on the *fast paths* (the no writer case), hard to understand, and very hard to confirm to be correct." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-13T01:09:59.453", "Id": "15137", "ParentId": "15136", "Score": "3" } }, { "body": "<p>Both versions are buggy: they allow multiple writers in at once!</p>\n\n<p>Consider what happens if there are no readers, and two writers call \"write\" at the same time. They will both set <code>d_write_request</code> to true, wait for readers to finish (there are none) and start writing at the same time.</p>\n\n<p>Your testing conveniently neglects to test for multiple writers.</p>\n\n<p>Also please don't call mutex a mutext. The mutex stands for \"mutual exclusion\", there is no T after E there.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-13T04:22:12.307", "Id": "24559", "Score": "0", "body": "Ah, I missed that. Still, it's trivial to write code that *doesn't* make such simplifying assumption. I am not sure what OP stands to learn from \"here is my simplified, inefficient implementation\" (actually two imeplmentations) \"of reader/writer lock that only solves half of the problem\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-13T04:33:14.133", "Id": "24560", "Score": "0", "body": "I agree. It's completely trivial to fix. It should at least, if nothing else, have code to assert in that case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-14T00:46:06.253", "Id": "24561", "Score": "0", "body": "Thanks for your reply. It is not trivial to fix for me. I will give it a try." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T13:47:56.953", "Id": "24564", "Score": "0", "body": "You could trivially fix it by just having the writer hold the mutex while it writes." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-13T01:42:39.450", "Id": "15138", "ParentId": "15136", "Score": "2" } } ]
{ "AcceptedAnswerId": "15137", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-13T01:06:02.430", "Id": "15136", "Score": "4", "Tags": [ "c++", "multithreading", "locking", "pthreads" ], "Title": "Accessing limited resources with Pthreads" }
15136
<p>I'm working on the floors of a building, using SVG objects generated by Raphael.js. All objects are clickable and all have different shapes, but all of them have the same actions. The code below is just a little sample. How could I optimize it?</p> <pre><code>// FLOOR 00 var budA4_0 = new Raphael(document.getElementById('inter-budynek-A4_0'), 302, 232); // A4.0.2 var A4_0_2 = budA4_0.path("M306,112v61c0,0-2.5,54-53,59.5s-137.5,0-137.5,0v-92H136v3.5h54.5v5H215v-37H306z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.0.2.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.0.2.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.0.2'); $('#pietro').text('0'); $('#liczbaPom').text('4'); $('#budynek').text('A4'); $('#powierzchnia').text('83'); $('#inter-budynek-wraper ul.info').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.0.3 var A4_0_3 = budA4_0.path("M115.5,139.875 115.5,233.875 10.5,233.875 10.5,136.875 55.5,136.875 55.625,140z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.0.3.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.0.3.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.0.3'); $('#pietro').text('0'); $('#liczbaPom').text('6'); $('#budynek').text('A4'); $('#powierzchnia').text('123'); $('#inter-budynek-wraper ul.info').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // FLOOR 01 var budA4_1 = new Raphael(document.getElementById('inter-budynek-A4_1'), 302, 232); // A4.1.1 var A4_1_1 = budA4_1.path("M0.338,0 L104.338,0 L104.338,80 L79.838,80 L79.838,87.5 L88.338,87.5 L88.338,111.5 L0.338,111.5Z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.1.1.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.1.1.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.1.1'); $('#pietro').text('1'); $('#liczbaPom').text('4'); $('#budynek').text('A4'); $('#powierzchnia').text('83'); $('#inter-budynek-wraper ul').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.1.2 var A4_1_2 = budA4_1.path("M300,111.5 L300,0 L104,0 L104,80 L123.75,80 L123.75,54.75 L165.5,54.75 L165.5,80.125 L196.5,80.125 L214,80.125 L214,85.5 L206,85.5 L206,111.5z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.1.2.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.1.2.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.1.2'); $('#pietro').text('1'); $('#liczbaPom').text('6'); $('#budynek').text('A4'); $('#powierzchnia').text('123'); $('#inter-budynek-wraper ul').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.1.3 var A4_1_3 = budA4_1.path("M106,231h124c0,0,67,6,70-64.625V111.5h-94V142h-21.125v-5.125H165v4.625h-37.5v-5H106V231z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.1.3.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.1.3.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.1.3'); $('#pietro').text('1'); $('#liczbaPom').text('3'); $('#budynek').text('A4'); $('#powierzchnia').text('73'); $('#inter-budynek-wraper ul.info').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.1.4 var A4_1_4 = budA4_1.path("M88.338,111.5 L0.338,111.5 L0.338,229.884 L106.338,229.884 L106.338,136.5 L88.338,136.5Z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.1.4.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.1.6.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.1.4'); $('#pietro').text('1'); $('#liczbaPom').text('4'); $('#budynek').text('A4'); $('#powierzchnia').text('98'); $('#inter-budynek-wraper ul.info').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // FLOOR 02 var budA4_2 = new Raphael(document.getElementById('inter-budynek-A4_2'), 302, 232); // A4.2.1 var A4_2_1 = budA4_2.path("M0,-0.212 105.167,-0.212 104.833,79.454 91.167,79.454 81.167,79.454 81.167,85.788 89.833,85.788 89.833,111.122 0,111.122z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.2.1.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.2.1.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.2.1'); $('#pietro').text('2'); $('#liczbaPom').text('4'); $('#budynek').text('A4'); $('#powierzchnia').text('83'); $('#inter-budynek-wraper ul').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.2.2 var A4_2_2 = budA4_2.path("M300,-0.212 105.5,-0.212 105.5,53.788 105.494,81.457 123.167,81.788 123.167,53.788 167.167,53.788 167.167,81.122 195.834,81.122 217.25,81.122 217.25,85.788 207.834,85.788 207.834,111.454 300,111.454z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.2.2.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.2.2.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.2.2'); $('#pietro').text('2'); $('#liczbaPom').text('6'); $('#budynek').text('A4'); $('#powierzchnia').text('123'); $('#inter-budynek-wraper ul').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.2.3 var A4_2_3 = budA4_2.path("M207.167,111.122H300c0,0,0,16.666,0,62.666c-5.577,60-67.5,57.406-67.5,57.406h-126 v-92.739h22v4h37.334v-4H184.5v6h22.667Z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.2.3.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.2.3.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.2.3'); $('#pietro').text('2'); $('#liczbaPom').text('3'); $('#budynek').text('A4'); $('#powierzchnia').text('73'); $('#inter-budynek-wraper ul.info').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.2.4 var A4_2_4 = budA4_2.path("M89.833,111.122 0,111.122 0,231.194 106.5,231.194 106.5,141.788 78.833,141.788 78.833,136.834 89.5,136.834 89.5,111.122Z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.2.4.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.2.4.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.2.4'); $('#pietro').text('2'); $('#liczbaPom').text('4'); $('#budynek').text('A4'); $('#powierzchnia').text('98'); $('#inter-budynek-wraper ul.info').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // FLOOR 03 var budA4_3 = new Raphael(document.getElementById('inter-budynek-A4_3'), 302, 232); // A4.3.1 var A4_3_1 = budA4_3.path("M0,-0.212 105.167,-0.212 104.833,79.454 91.167,79.454 81.167,79.454 81.167,85.788 89.833,85.788 89.833,111.122 0,111.122z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.3.1.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.3.1.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.3.1'); $('#pietro').text('3'); $('#liczbaPom').text('4'); $('#budynek').text('A4'); $('#powierzchnia').text('83'); $('#inter-budynek-wraper ul').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.3.2 var A4_3_2 = budA4_3.path("M300,-0.212 105.5,-0.212 105.5,53.788 105.494,81.457 123.167,81.788 123.167,53.788 167.167,53.788 167.167,81.122 195.834,81.122 217.25,81.122 217.25,85.788 207.834,85.788 207.834,111.454 300,111.454z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.3.2.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.3.2.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.3.2'); $('#pietro').text('3'); $('#liczbaPom').text('6'); $('#budynek').text('A4'); $('#powierzchnia').text('123'); $('#inter-budynek-wraper ul').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.3.3 var A4_3_3 = budA4_3.path("M207.167,111.122H300c0,0,0,16.666,0,62.666c-5.577,60-67.5,57.406-67.5,57.406h-126 v-92.739h22v4h37.334v-4H184.5v6h22.667Z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.3.3.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.3.3.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.3.3'); $('#pietro').text('3'); $('#liczbaPom').text('3'); $('#budynek').text('A4'); $('#powierzchnia').text('73'); $('#inter-budynek-wraper ul.info').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.3.4 var A4_3_4 = budA4_3.path("M89.833,111.122 0,111.122 0,231.194 106.5,231.194 106.5,141.788 78.833,141.788 78.833,136.834 89.5,136.834 89.5,111.122Z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.3.4.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.3.4.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.3.4'); $('#pietro').text('3'); $('#liczbaPom').text('4'); $('#budynek').text('A4'); $('#powierzchnia').text('98'); $('#inter-budynek-wraper ul.info').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // FLOOR 04 var budA4_4 = new Raphael(document.getElementById('inter-budynek-A4_4'), 302, 232); // A4.4.1 var A4_4_1 = budA4_4.path("M0,-0.212 105.167,-0.212 104.833,79.454 91.167,79.454 81.167,79.454 81.167,85.788 89.833,85.788 89.833,111.122 0,111.122z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.4.1.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.4.1.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.4.1'); $('#pietro').text('4'); $('#liczbaPom').text('4'); $('#budynek').text('A4'); $('#powierzchnia').text('83'); $('#inter-budynek-wraper ul').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.4.2 var A4_4_2 = budA4_4.path("M300,-0.212 105.5,-0.212 105.5,53.788 105.494,81.457 123.167,81.788 123.167,53.788 167.167,53.788 167.167,81.122 195.834,81.122 217.25,81.122 217.25,85.788 207.834,85.788 207.834,111.454 300,111.454z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.4.2.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.4.2.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.4.2'); $('#pietro').text('4'); $('#liczbaPom').text('6'); $('#budynek').text('A4'); $('#powierzchnia').text('123'); $('#inter-budynek-wraper ul').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.4.3 var A4_4_3 = budA4_4.path("M207.167,111.122H300c0,0,0,16.666,0,62.666c-5.577,60-67.5,57.406-67.5,57.406h-126 v-92.739h22v4h37.334v-4H184.5v6h22.667Z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.4.3.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.4.3.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.4.3'); $('#pietro').text('4'); $('#liczbaPom').text('3'); $('#budynek').text('A4'); $('#powierzchnia').text('73'); $('#inter-budynek-wraper ul.info').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.4.4 var A4_4_4 = budA4_4.path("M89.833,111.122 0,111.122 0,231.194 106.5,231.194 106.5,141.788 78.833,141.788 78.833,136.834 89.5,136.834 89.5,111.122Z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.4.4.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.4.4.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.4.4'); $('#pietro').text('4'); $('#liczbaPom').text('4'); $('#budynek').text('A4'); $('#powierzchnia').text('98'); $('#inter-budynek-wraper ul.info').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // FLOOR 05 var budA4_5 = new Raphael(document.getElementById('inter-budynek-A4_5'), 302, 232); // A4.5.3 var A4_5_3 = budA4_5.path("M207.167,111.122H300c0,0,0,16.666,0,62.666c-5.577,60-67.5,57.406-67.5,57.406h-126 v-92.739h22v4h37.334v-4H184.5v6h22.667z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.5.3.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.5.3.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.5.3'); $('#pietro').text('5'); $('#liczbaPom').text('4'); $('#budynek').text('A4'); $('#powierzchnia').text('83'); $('#inter-budynek-wraper ul').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.5.1 var A4_5_1 = budA4_5.path("M0,0 144.167,0 144.167,54.833 125.833,54.833 125.833,78.667 91.167,79.667 81.167,79.667 81.167,86 89.833,86 89.833,111.333 0,111.333z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.5.1.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.5.1.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.5.1'); $('#pietro').text('5'); $('#liczbaPom').text('4'); $('#budynek').text('A4'); $('#powierzchnia').text('83'); $('#inter-budynek-wraper ul').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.5.2 var A4_5_2 = budA4_5.path("M300,0 144.5,0 144.5,54 167.167,54 167.167,77.333 195.834,77.333 222.25,77.333 222.25,84 207.834,84 207.834,111.667 300,111.667z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.5.2.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.5.2.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.5.2'); $('#pietro').text('5'); $('#liczbaPom').text('4'); $('#budynek').text('A4'); $('#powierzchnia').text('83'); $('#inter-budynek-wraper ul').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); // A4.5.4 var A4_5_4 = budA4_5.path("M89.833,111.122 0,111.122 0,231.194 106.5,231.194 106.5,141.788 78.833,141.788 78.833,135.121 89.5,135.121 89.5,111.122z").click(function () { $.fancybox.open([ { href : 'img/rzuty/A4/A4.5.4.jpg', openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, } ], { beforeShow : function() { $('&lt;a class="pdf" href="img/rzuty/A4/A4.5.4.pdf" target="_blank"&gt;&lt;/a&gt;').appendTo(".fancybox-inner"); } }); }).mouseover( function () { this.animate({"fill-opacity": .5}, 200); $('#lokal').text('A4.5.4'); $('#pietro').text('5'); $('#liczbaPom').text('4'); $('#budynek').text('A4'); $('#powierzchnia').text('83'); $('#inter-budynek-wraper ul').removeClass('invisible'); }).mouseout(function () { this.animate({"fill-opacity": .0}, 200); $('#inter-budynek-wraper ul.info').addClass('invisible'); }); </code></pre>
[]
[ { "body": "<p>As you noticed, you are violating DRY ( Dont repeat yourself ).</p>\n\n<p>Your code has plenty of repetitions, part of the trick is try and catch them all</p>\n\n<ul>\n<li>My assumption is that <code>A4</code> is the name or number of the building, that should be 1 variable in the whole code</li>\n<li>My assumption is that you have 6 floors, every floor is initialized the same way</li>\n<li>My assumption is that per room ( I assume your paths are rooms ), the only different data points are the <code>path</code>, the <code>floor</code> the room belongs to, the <code>nr</code> of the room and the <code>pietro</code>, <code>liczbaPom</code>, and <code>powierzchnia</code></li>\n<li>Which brings me to: names must be in English, always, no exceptions!!</li>\n</ul>\n\n<p>You can synthezize all that information into something like this : </p>\n\n<pre><code>var building = 'A4',\n floorCount = 6,\n rooms = \n [ \n { floor: 1 , nr: 1 , pietro : 1 , liczbaPom: 4 , powierzchnia : 83,\n path : \"M0.338,0 L104.338,0 L104.338,80 L79.838,80 L79.838,87.5 L88.338,87.5 L88.338,111.5 L0.338,111.5Z\" },\n { floor: 1 , nr: 2 , pietro : 1 , liczbaPom: 4 , powierzchnia : 83,\n path : \"M300,111.5 L300,0 L104,0 L104,80 L123.75,80 L123.75,54.75 L165.5,54.75 L165.5,80.125 L196.5,80.125 L214,80.125 L214,85.5 L206,85.5 L206,111.5z\") },\n { floor: 0 , nr: 3 , pietro : 1 , liczbaPom: 4 , powierzchnia : 83,\n path : \"M115.5,139.875 115.5,233.875 10.5,233.875 10.5,136.875 55.5,136.875 55.625,140z\" },\n ];\n</code></pre>\n\n<p>Of course you still have to type the other rooms, but the pattern should be obvious.</p>\n\n<p>Creating the floors then becomes a simple <code>for</code> loop : </p>\n\n<pre><code>//This creates each floor\nfor( var floor = 0 ; floor &lt; floorCount ; floor ++ ){\n window['bud' + building + '_' + floor] = \n new Raphael(document.getElementById('inter-budynek-' + building + '_' + floor), 302, 232);\n}\n</code></pre>\n\n<p>And creating each and every room becomes something like this : </p>\n\n<pre><code>rooms.forEach( function(room){\n\n var varNameFloor = 'bud' + building + '_' + room.floor,\n varNameRoom = varNameFloor + \"_\" + room.nr,\n buildingName = building + '.' + room.floor + '.' + room.nr,\n fileNameRoot = 'img/rzuty/' + building + '/' + buildingName,\n jpgFile = fileNameRoot + '.jpg',\n pdfFile = fileNameRoot + '.pdf';\n\n window[varNameRoom] = window[varNameFloor].path( room.path ).click( function(){\n $.fancybox.open([{href : jpgFile , openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150 }], \n { beforeShow : function() {\n $('&lt;a class=\"pdf\" href=\"' + pdfFile + '\" target=\"_blank\"&gt;&lt;/a&gt;').appendTo(\".fancybox-inner\"); \n }\n });\n }).mouseover( function (){\n this.animate({\"fill-opacity\": .5}, 200);\n $('#lokal').text( buildingName );\n $('#pietro').text( room.pietro );\n $('#liczbaPom').text( room.liczbaPom);\n $('#budynek').text('A4');\n $('#powierzchnia').text( room.powierzchnia );\n $('#inter-budynek-wraper ul').removeClass('invisible');\n }).mouseout(function () {\n this.animate({\"fill-opacity\": .0}, 200);\n $('#inter-budynek-wraper ul.info').addClass('invisible');\n }); \n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T21:26:03.280", "Id": "40782", "ParentId": "15141", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:27:22.900", "Id": "15141", "Score": "1", "Tags": [ "javascript", "raphael.js", "fancybox" ], "Title": "Combining Raphael.js objects for working on floors of a building" }
15141
<p>I used the following Javascript to sort an unnumbered list of numeric li-tags as follows:</p> <pre><code>// 1. get the &lt;UL&gt;-element from the BODY var nList = document.getElementById("allItems"); // 2. extract all the &lt;LI&gt;-elements from that &lt;UL&gt; and put it in a NodeList var nEntry = nList.getElementsByTagName('li'); // 3. we can't sort a NodeList, so first make it an Array var nEntryArray = Array.prototype.slice.call(nEntry, 0); // 4. sort the array, the normal sort()-function won't do because it is an alphabetical sort // to sort() numeric values, see http://www.w3schools.com/jsref/jsref_sort.asp example, as "Default sort order is alphabetic and ascending. When numbers are sorted alphabetically, "40" comes before "5". To perform a numeric sort, you must pass a function as an argument when calling the sort method." // the numeric value of the &lt;LI&gt; nodes can be located in nEntryArray[i].firstChild.nodeValue , so compare those nEntryArray.sort(function(a,b){ return a.firstChild.nodeValue - b.firstChild.nodeValue }) // 5. empty the nList and refill it with those in the correct order at the nEntryArray while (nList.lastChild) { nList.removeChild(nList.lastChild); } for (i=0; i&lt;nEntryArray.length; i++) { nList.appendChild(nEntryArray[i]); } </code></pre> <p>If a HTML-code is given with a list as such:</p> <pre><code>&lt;ul id='allItems'&gt; &lt;li class="black"&gt;100&lt;/li&gt; &lt;li id="note10"&gt;10&lt;/li&gt; &lt;li&gt;1&lt;/li&gt; &lt;li&gt;20&lt;/li&gt; &lt;li class="order2"&gt;16&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>it will order the list numerically without omitting the attributes of the <code>&lt;LI&gt;</code>-tags.</p> <p>It is one of my first JavaScript-attempts, and I was wondering if this is indeed correct or whether it could be simplified. Especially the conversion from Nodelist to Array seems redundant to me, but I haven't found a more gracious solution.</p> <p>I post this code-block as I was looking on StackOverflow and through Google for a piece of code to help me solve this particular problem, but I couldn't find something that was understandable to a beginner like me. I easily found ways to sort lists , but then the attributes would be omitted and in the end it took me two days (yep, beginner :-)) to come up with this solution.</p> <p>Any comments?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:56:45.297", "Id": "24570", "Score": "0", "body": "sources that I based this code on: [sorting a node list](http://stackoverflow.com/questions/4760080/how-can-i-reorder-sort-a-nodelist-in-javascript), [changing the order of `<LI>`-tags](http://www.webdeveloper.com/forum/archive/index.php/t-232520.html) and [W3school sort()](http://www.w3schools.com/jsref/jsref_sort.asp)" } ]
[ { "body": "<p>There are a few clear improvements I can see when you are reinserting the nodes back into the DOM tree. </p>\n\n<pre><code>for (i=0; i&lt;nEntryArray.length; i++)\n{\n nList.appendChild(nEntryArray[i]);\n}\n</code></pre>\n\n<p>1) You may benefit from using a documentFragment to build up your elements then submit them all at once to the <code>nList</code></p>\n\n<p>2) (micro), cache the length of your array in the for loop. </p>\n\n<pre><code>var df = document.createDocumentFragment();\nfor( var i = 0, l = nEntryArray.length; i &lt; l; i++) {\n df.appendChild(nEntryArray[i]);\n}\nnList.appendChild(df);\n</code></pre>\n\n<p>Otherwise I do not see any issues with this code. <a href=\"http://jsfiddle.net/rlemon/faY3Z/\" rel=\"nofollow\">http://jsfiddle.net/rlemon/faY3Z/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T15:49:49.047", "Id": "24574", "Score": "0", "body": "thanks for the suggestion (and for rickrolling me at the same time :-)). What is the use of the cache ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T19:11:57.683", "Id": "24590", "Score": "0", "body": "each iteration of the for loop you recalculate the length of the array, this is costly.. and can lead to unexpected results (if you are modifying the length of the array). By caching the length you don't have to recalculate it each time and if you alter the length within the loop the loop is unaffected." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T06:42:35.397", "Id": "24658", "Score": "0", "body": "Since length is an attribute and not a method call, would it really be 'recalculating the length of the array' on every access?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T15:13:29.950", "Id": "15146", "ParentId": "15144", "Score": "2" } } ]
{ "AcceptedAnswerId": "15146", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T14:48:48.290", "Id": "15144", "Score": "4", "Tags": [ "javascript", "sorting" ], "Title": "Sorting numeric <LI> tags without omitting the attributes" }
15144
<p>This code works, but I get the feeling that it could be shorter and simpler. Any ideas?</p> <pre><code>private void CheckNameCase(Models.PersonalInformationModels.PersonalInformationModel model) { // if first middle and last names are all upper or lower case then title case the name //Name string firstName = model.NameModel.FirstName; string upperFirstName; string lowerFirstName; if (firstName == null) { upperFirstName = null; lowerFirstName = null; } else { upperFirstName = model.NameModel.FirstName.ToUpper(new CultureInfo("en-US", false)); lowerFirstName = model.NameModel.FirstName.ToLower(new CultureInfo("en-US", false)); } string middleName = model.NameModel.MiddleName; string upperMiddleName; string lowerMiddleName; if (middleName == null) { upperMiddleName = null; lowerMiddleName = null; } else { upperMiddleName = model.NameModel.MiddleName.ToUpper(new CultureInfo("en-US", false)); lowerMiddleName = model.NameModel.MiddleName.ToLower(new CultureInfo("en-US", false)); } string lastName = model.NameModel.LastName; string upperLastName; string lowerLastName; if (lastName == null) { upperLastName = null; lowerLastName = null; } else { upperLastName = model.NameModel.LastName.ToUpper(new CultureInfo("en-US", false)); lowerLastName = model.NameModel.LastName.ToLower(new CultureInfo("en-US", false)); } if ((firstName == upperFirstName || firstName == lowerFirstName) &amp;&amp; (middleName == upperMiddleName || middleName == lowerMiddleName) &amp;&amp; (lastName == upperLastName || lastName == lowerLastName)) { if(!String.IsNullOrEmpty(model.NameModel.FirstName)){ model.NameModel.FirstName = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(firstName.ToLower(new CultureInfo("en-US", false))); } if(!String.IsNullOrEmpty(model.NameModel.MiddleName)){ model.NameModel.MiddleName = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(middleName.ToLower(new CultureInfo("en-US", false))); } if(!String.IsNullOrEmpty(model.NameModel.LastName)){model.NameModel.LastName = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(lastName.ToLower(new CultureInfo("en-US", false))); } } //Alternate Name string altFirstName = model.AlternateNameModel.FirstName; string upperAltFirstName; string lowerAltFirstName; if(altFirstName==null) { upperAltFirstName = null; lowerAltFirstName = null; }else { upperAltFirstName = model.AlternateNameModel.FirstName.ToUpper(new CultureInfo("en-US", false)); lowerAltFirstName = model.AlternateNameModel.FirstName.ToLower(new CultureInfo("en-US", false)); } string altMiddleName = model.AlternateNameModel.MiddleName; string upperAltMiddleName; string lowerAltMiddleName; if(altMiddleName==null) { upperAltMiddleName = null; lowerAltMiddleName = null; }else { upperAltMiddleName = model.AlternateNameModel.MiddleName.ToUpper(new CultureInfo("en-US", false)); lowerAltMiddleName = model.AlternateNameModel.MiddleName.ToLower(new CultureInfo("en-US", false)); } string altLastName = model.AlternateNameModel.LastName; string upperAltLastName; string lowerAltLastName; if (altLastName==null) { upperAltLastName = null; lowerAltLastName = null; } else { upperAltLastName = model.AlternateNameModel.LastName.ToUpper(new CultureInfo("en-US", false)); lowerAltLastName = model.AlternateNameModel.LastName.ToLower(new CultureInfo("en-US", false)); } if ((altFirstName == upperAltFirstName || altFirstName == lowerAltFirstName) &amp;&amp; (altMiddleName == upperAltMiddleName || altMiddleName == lowerAltMiddleName) &amp;&amp; (altLastName == upperAltLastName || altLastName == lowerAltLastName)) { if(!String.IsNullOrEmpty(model.AlternateNameModel.FirstName)){model.AlternateNameModel.FirstName = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(altFirstName.ToLower(new CultureInfo("en-US", false)));} if(!String.IsNullOrEmpty(model.AlternateNameModel.MiddleName)){model.AlternateNameModel.MiddleName = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(altMiddleName.ToLower(new CultureInfo("en-US", false)));} if(!String.IsNullOrEmpty(model.AlternateNameModel.LastName)){ model.AlternateNameModel.LastName = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(altLastName.ToLower(new CultureInfo("en-US", false))); } } } </code></pre>
[]
[ { "body": "<p>Good layout and spacing.</p>\n\n<p>My first observation is that you are repeating yourself many times over. If you look closely, all of the checks are the same. If you find duplicate code, move them out into a function.</p>\n\n<p>Second observation is you are coding lengthy namespaces. Learn about the using ; syntax at the top of your file. Will save tonnes of tracing through.</p>\n\n<p>Also try to avoid nesting if statements. Nested if's really clutter up the code and make it hard to follow.</p>\n\n<p>Here is they way I'd clean up up:</p>\n\n<pre><code>private class UpperAndLowerString\n{\n public string UpperCase { get; set; }\n public string LowerCase { get; set; }\n\n public UpperAndLowerString(string name)\n {\n UpperCase = name == null ? null : name.ToUpper(new CultureInfo(\"en-US\", false));\n LowerCase = name == null ? null : name.ToLower(new CultureInfo(\"en-US\", false));\n }\n\n public bool EqualsUpperCase(string check)\n {\n return UpperCase == check;\n }\n\n public bool EqualsLowerCase(string check)\n {\n return LowerCase == check;\n }\n\n public bool Equals(string check)\n {\n return EqualsUpperCase(check) || EqualsLowerCase(check);\n }\n}\n\nprivate static string ConvertToTitleCase(string name)\n{\n return string.IsNullOrEmpty(name) ? null : TextInfo.ToTitleCase(name);\n}\n\n\nprivate static string ProcessSingleName(string name)\n{\n var casedName = new UpperAndLowerString(name);\n\n return casedName.Equals(name) ? ConvertToTitleCase(name) : name;\n}\n\nprivate void CheckNameCase(Models.PersonalInformationModels.PersonalInformationModel model)\n{\n model.NameModel.FirstName = ProcessSingleName(model.NameModel.FirstName) ?? model.NameModel.FirstName;\n model.NameModel.MiddleName = ProcessSingleName(model.NameModel.MiddleName) ?? model.NameModel.MiddleName;\n model.NameModel.LastName = ProcessSingleName(model.NameModel.LastName) ?? model.NameModel.LastName ;\n\n model.AlternateNameModel.FirstName = ProcessSingleName(model.AlternateNameModel.FirstName) ?? model.AlternateNameModel.FirstName;\n model.AlternateNameModel.MiddleName = ProcessSingleName(model.AlternateNameModel.MiddleName) ?? model.AlternateNameModel.MiddleName;\n model.AlternateNameModel.LastName = ProcessSingleName(model.AlternateNameModel.LastName) ?? model.AlternateNameModel.LastName;\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T21:35:14.527", "Id": "24592", "Score": "0", "body": "+1 Good comments. Made some further suggestions in an answer as too much for a comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T13:32:20.950", "Id": "24619", "Score": "0", "body": "It looks like you are checking and title casing each name part individually. It only needs to be title cased if the first middle and last are all three upper or lower cased by the user." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T15:37:17.660", "Id": "24623", "Score": "0", "body": "Oops, missed that part. You can modify the logic, but the basic principles should be the same." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T16:24:26.013", "Id": "15150", "ParentId": "15148", "Score": "6" } }, { "body": "<p>This is more a suggested slight tweak to the excellant ideas and solution provided by Jeff. I would potentially look adjusting the <strong>ProcessedSingleName</strong> method as below</p>\n\n<pre><code>private static string ProcessSingleName(string name)\n{\n var processedName = string.Empty;\n\n if(casedName.Equals(name))\n {\n processedName = ConvertToTitleCase(name);\n }\n\n return processedName ?? name;\n}\n</code></pre>\n\n<p>Then the CheckNameCase would be adjusted to:</p>\n\n<pre><code>private void CheckNameCase(Models.PersonalInformationModels.PersonalInformationModel model)\n{\n model.NameModel.FirstName = ProcessSingleName(model.NameModel.FirstName);\n model.NameModel.MiddleName = ProcessSingleName(model.NameModel.MiddleName);\n model.NameModel.LastName = ProcessSingleName(model.NameModel.LastName);\n\n model.AlternateNameModel.FirstName = ProcessSingleName(model.AlternateNameModel.FirstName);\n model.AlternateNameModel.MiddleName = ProcessSingleName(model.AlternateNameModel.MiddleName);\n model.AlternateNameModel.LastName = ProcessSingleName(model.AlternateNameModel.LastName);\n}\n</code></pre>\n\n<p><strong>Further thoughts</strong>: During typing this I thought you could even look at making an extension method on the PersonalInformationModel class (or on the class itself maybe?) to do the name conversion:</p>\n\n<pre><code>public static void NameCase(this PersonalInformationModel person, Func&lt;string, string&gt; processName)\n{\n person.NameModel.FirstName = processName(model.NameModel.FirstName);\n person.NameModel.MiddleName = processName(model.NameModel.MiddleName);\n person.NameModel.LastName = processName(model.NameModel.LastName); \n}\n</code></pre>\n\n<p>Which would further lead to refactoring of <strong>CheckNameCase</strong>():</p>\n\n<pre><code>private void CheckNameCase(Models.PersonalInformationModels.PersonalInformationModel model)\n{\n model.NameModel.NameCase(ProcessSingleName);\n model.AlternateNameModel.NameCase(ProcessSingleName); \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T21:33:57.527", "Id": "15161", "ParentId": "15148", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T15:24:58.603", "Id": "15148", "Score": "5", "Tags": [ "c#", "strings" ], "Title": "Title case name when first, middle and last are all upper or lower case" }
15148
<p>In a project I'm working on, the data access layer has evolved to something that somewhat resembles the Unit Of Work and Repository patterns, at least they started with those names, I'm not entirely sure with how far they've drifted, if they can still be called that.</p> <p>For classes data access, an implementation <code>IWorkUnitFactory</code> is passed as a constructor parameter from the IoC container. This is a rather simple interface:</p> <pre><code>public interface IWorkUnitFactory { IWorkUnit Begin(); } </code></pre> <p>The <code>IWorkUnit</code> interface it returns looks like this:</p> <pre><code>public interface IWorkUnit : IDisposable { T Insert&lt;T&gt;(T entity) where T : class; T Load&lt;T&gt;(int id) where T : class; void Delete&lt;T&gt;(int id) where T : class; void Delete&lt;T&gt;(T entity) where T : class; T Update&lt;T&gt;(T entity) where T : class; T InsertOrUpdate&lt;T&gt;(T entity) where T : class; IQueryable&lt;T&gt; Query&lt;T&gt;() where T : class; IEnumerable&lt;T&gt; Execute&lt;T&gt;(string queryName, IDictionary&lt;string, object&gt; parameters); void Commit(); void Rollback(); } </code></pre> <p>My <code>IWorkUnitFactory</code> implementation for NHibernate basically just creates an NHibernate session, and passes it to the NHibernate implementation of <code>IWorkUnit</code>, which is just a rather thin wrapper around the NHibernate session, which starts a transaction in its constructor, and rolls it back in the <code>Dispose</code> implementation unless the <code>Commit</code> method is called.</p> <p>Then, anywhere data access happens, it follows this pattern:</p> <pre><code>using(var workUnit = WorkUnitFactory.Begin()) { //Boring data access code here workUnit.Commit(); } </code></pre> <p>Next up are the <code>Repository</code> classes. These don't have any common inheritance or interface implementations, they just follow a few conventions, the main one being taking an <code>IWorkUnit</code> in its constructor. These classes contain the interaction with the <code>IWorkUnit</code> for operations like <code>GetById</code>, <code>Find</code>, <code>Insert</code>, <code>Update</code>, etc, and are responsible for small bits of logic (the <code>Update</code> method updates the <code>LastUpdated</code> field on the entity, <code>Find</code> determines what fields to search based on its parameters, etc).</p> <p>So, for example, a Repository for the User entity might look something like this:</p> <pre><code>public class UserRepository { private readonly IWorkUnit workUnit; public UserRepository(IWorkUnit workUnit) { this.workUnit = workUnit; } public virtual User GetByEmail(string email) { return workUnit.Query&lt;User&gt;().FirstOrDefault(u =&gt; u.Email == email); } public virtual User Update(User user, User updater) { user.ModifiedBy = updater; user.Modified = DateTimeOffset.Now; return workUnit.Update(user); } } </code></pre> <p>Then, code to update a user would look something like this:</p> <pre><code>using(var workUnit = WorkUnitFactory.Begin()) { var userRepo = new UserRepository(workUnit); var userToEdit = userRepo.GetByEmail("test@example.com"); //Do some stuff to userToEdit here userRepo.Update(userToEdit, currentRequestUser); //currentRequestUser is just whoever is performing the action workUnit.Commit(); } </code></pre> <p>Any feedback on better naming for these things, or better methods? This has served me rather well, with the only thing I don't really like is creating the repository instances like that, But I can't think of a way to handle transactions and keep the somewhat lower level data access code away from higher level business logic.</p>
[]
[ { "body": "<p>If all your business classes (e.g., <strong>User</strong>) could inherit from a common class or interface that has <strong>Modified</strong> and <strong>ModifiedBy</strong> properties, you could make your <strong>Repository</strong> a generic <strong>Repository&lt;T&gt;</strong>. Class-specific methods like <strong>GetByEmail</strong> would be replaced with generalized methods that take <strong>Expressions</strong>. Would that address your concern about \"creating the repository instances like that\", while keeping the business-level concerns (e.g., the fact that you're retrieving by email and not something else) away from your data access code?</p>\n\n<p>Here's an untested and even uncompiled example of what I'm talking about.</p>\n\n<pre><code>public interface IBusinessEntity\n{\n User ModifiedBy { get; set; }\n DateTime Modified { get; set; }\n}\n\npublic class Repository&lt;T&gt; where T : IBusinessEntity\n{\n private readonly IWorkUnit workUnit;\n public Repository(IWorkUnit workUnit)\n {\n this.workUnit = workUnit;\n }\n public virtual T Get(Expression&lt;Func&lt;T,bool&gt;&gt; expression)\n {\n return workUnit.Query&lt;T&gt;().FirstOrDefault(expression);\n }\n public virtual T Update(T objToUpdate, User updater)\n {\n objToUpdater.ModifiedBy = updater;\n objToUpdate.Modified = DateTimeOffset.Now;\n return workUnit.Update(objToUpdate);\n } \n}\n</code></pre>\n\n<p>As for your naming conventions, they make sense to me.</p>\n\n<p>Just one more idea: Unless your application will always be used in just one timezone, and hosted in the same timezone, you might consider storing your Modified property as UTC.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-07T07:41:03.020", "Id": "24985", "Score": "0", "body": "Will it work in SOA environment, for example like an Enteprise Domain Repository service?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-14T18:04:10.813", "Id": "121428", "Score": "0", "body": "It's very hard to mock LINQ Expressions. If you are going to unit test your business layer, you may want to avoid them." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T18:20:50.577", "Id": "15189", "ParentId": "15149", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T16:01:38.120", "Id": "15149", "Score": "4", "Tags": [ "c#", "design-patterns" ], "Title": "Unit Of Work/Repository usage" }
15149
<p>I have this rather verbose piece of code. How can I get it shorter and simpler?</p> <p>This function aggregate results of test by population and by different keys:</p> <pre><code>def aggregate(f): """ Aggregate population by several keys """ byMerchant = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0])) byPlat = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0])) byDay = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0])) byAffiliate = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0])) byCountry = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0])) byType = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0])) byPop = col.defaultdict(lambda: [0,0,0,0]) for line in f: fields = line.strip().split("^A") if fields[2] == '\\N': continue day = fields[0] popid = int(fields[1]) affiliate_id = int(fields[2]) merchant_id = int(fields[3]) clicks = int(fields[4]) displays = int(fields[5]) sales = float(fields[6]) gross = float(fields[7]) merchant_plat = partners_info[merchant_id][1] merchant_name = partners_info[merchant_id][0] publisher_name = publisher_info[affiliate_id][0] publisher_country = publisher_info[affiliate_id][1] publisher_type = publisher_info[affiliate_id][2] data = [clicks,displays,sales,gross] for k in xrange(len(data)): byMerchant[merchant_name][popid][k] += data[k] byPlat[merchant_plat][popid][k] += data[k] byAffiliate[publisher_name][popid][k] += data[k] byCountry[publisher_country][popid][k] += data[k] byDay[day][popid][k] += data[k] byType[publisher_type][popid][k] += data[k] byPop[popid][k] += data[k] return byPop, byMerchant, byPlat, byDay, byAffiliate, byCountry, byType </code></pre>
[]
[ { "body": "<p>If I try to split on the empty string I get an error:</p>\n\n<pre><code>&gt;&gt;&gt; 'a b c'.split('')\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\nValueError: empty separator\n</code></pre>\n\n<p>Perhaps you meant <code>.split()</code>?</p>\n\n<p>Anyway, here are some ideas for simplifying your code.</p>\n\n<ol>\n<li><p>Use <code>from collections import defaultdict</code> to avoid the need to refer to <code>col</code> (I presume you have <code>import collections as col</code>).</p></li>\n<li><p>Put a dummy key into the <code>byPop</code> aggregation so that its structure matches the others.</p></li>\n<li><p>Put the aggregates into a dictionary instead of having a bunch of variables. That way you can manipulate them systematically in loops.</p></li>\n<li><p>Use <code>enumerate</code> in your last loop to get the index as well as the value from the <code>data</code> list.</p></li>\n</ol>\n\n<p>That leads to this:</p>\n\n<pre><code>from collections import defaultdict\n\ndef aggregate(f):\n \"\"\"\n Aggregate population by several keys.\n \"\"\"\n aggregates = 'pop merchant plat day affiliate country type'.split()\n result = dict()\n for a in aggregates:\n result[a] = defaultdict(lambda: defaultdict(lambda: [0,0,0,0]))\n\n for line in f:\n fields = line.strip().split()\n if fields[2] == '\\\\N': continue\n\n # Decode fields from this record.\n day = fields[0]\n popid = int(fields[1])\n affiliate_id = int(fields[2])\n merchant_id = int(fields[3])\n clicks = int(fields[4])\n displays = int(fields[5])\n sales = float(fields[6])\n gross = float(fields[7])\n\n # Keys under which to aggregate the data from this record.\n keys = dict(merchant = partners_info[merchant_id][0],\n plat = partners_info[merchant_id][1],\n day = day,\n affiliate = publisher_info[affiliate_id][0],\n country = publisher_info[affiliate_id][1],\n type = publisher_info[affiliate_id][2],\n pop = 0) # dummy key\n\n # Update all aggregates.\n for i, value in enumerate([clicks, displays, sales, gross]):\n for a in aggregates:\n result[a][keys[a]][popid][i] += value\n\n return (result['pop'][0],) + tuple(result[a] for a in aggregates[1:])\n</code></pre>\n\n<p>It's not really a vast improvement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T21:36:30.387", "Id": "24593", "Score": "0", "body": "The split is on a special character, sorry it has been striped during copy and paste. It is a good idea to directly import the dictionary. I did not think about the dummy key. It makes it possible to factor the code. Thank you. The resulting code is quite complex though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T23:07:24.253", "Id": "24595", "Score": "0", "body": "Yes, I couldn't simplify it all that much, sorry! Maybe some other person will have some better ideas." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T18:26:59.833", "Id": "15156", "ParentId": "15151", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T16:49:46.280", "Id": "15151", "Score": "2", "Tags": [ "python" ], "Title": "Aggregate by several keys" }
15151
<p>I've seen the pattern:</p> <pre><code>&lt;?php if ($node = node_load(30) &amp;&amp; $node-&gt;type == 'bogus') { print $node-&gt;title . 'is bogus'; } </code></pre> <p>But when I tried to use it I got a warning: variable not defined... Has this pattern of declaring variables while you loop in an if been deprecated?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-06T09:26:26.060", "Id": "24926", "Score": "0", "body": "Where is the loop?" } ]
[ { "body": "<p>I could only wish... No, it has not been deprecated, but it should be. I seriously suggest that you don't use this syntax. It is too easy to accidentally assign a variable in a statement, which can result in similar errors. If you make a habit of avoiding this syntax it will make debugging that much easier. Say you get a similar error to this and while debugging you spot an assignment in one of your statements, then you will be able to stop debugging right there, because more than likely you have just found your error. Not just this, but it will make reading your code that much easier. Say this assignment is nested deep in a tree of statements. It can quickly become difficult to track those assignments.</p>\n\n<p>The reason you are probably getting an error is because if the first variable proves to be FALSE, the second will not get assigned due to the <code>&amp;&amp;</code> shortcircuiting and breaking from the statement early. This would result in <code>$node-&gt;type</code> not getting set.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T20:29:45.847", "Id": "15159", "ParentId": "15157", "Score": "0" } }, { "body": "<p>I have created the following function and class to test your code with:-</p>\n\n<pre><code>function node_load($load)\n{\n return new node();\n}\n\nclass node\n{\n public $type = 'bogus';\n public $title = 'Node title ';\n}\n</code></pre>\n\n<p>Let's take a look at your code step by step, so we can work out what is wrong with it.</p>\n\n<p>First let's see what happens if we var_dump the output of node_load():-</p>\n\n<pre><code>$node = node_load(1);\nvar_dump($node);\n</code></pre>\n\n<p>Output:-</p>\n\n<pre><code>object(node)[35]\n public 'type' =&gt; string 'bogus' (length=5)\n public 'title' =&gt; string 'Node title ' (length=11)\n</code></pre>\n\n<p>That looks about right, so let's see what happens if we put it in an if statement.</p>\n\n<pre><code>if($node = node_load(1)){\n var_dump($node);\n }\n</code></pre>\n\n<p>Output:-</p>\n\n<pre><code>object(node)[36]\n public 'type' =&gt; string 'bogus' (length=5)\n public 'title' =&gt; string 'Node title ' (length=11)\n</code></pre>\n\n<p>There doesn't seem to be any problem there either. So, lets try the compound if statement you have:-</p>\n\n<pre><code>if($node = node_load(1) &amp;&amp; $node-&gt;type = 'bogus' ){\n var_dump($node);\n}\n</code></pre>\n\n<p>Output:-</p>\n\n<pre><code>boolean true\n</code></pre>\n\n<p>Hmm, what's happened here? Well if you take a look at how <a href=\"http://php.net/manual/en/language.operators.logical.php\" rel=\"nofollow\">logical operators</a> work, you'll see that the result of a logical statement like <code>node_load(1) &amp;&amp; $node-&gt;type = 'bogus'</code> is a boolean <code>true</code> or <code>false</code>, which you've just assigned to the variable $node. You've lost the object that was previously referenced by that variable. Hence when you try to do:-</p>\n\n<pre><code>print $node-&gt;title . 'is bogus';\n</code></pre>\n\n<p>you will get a \"Warning: Attempt to assign property of non-object \" as $node is now a boolean and not the object you were expecting.</p>\n\n<p>That seems to me to be a pretty good reason for not assigning variable in an if statement as you are doing. Assign before the if statement and then test:-</p>\n\n<pre><code>$node = node_load(30);\nif ('bogus' === $node-&gt;type) {\n print $node-&gt;title . 'is bogus';\n}\n</code></pre>\n\n<p>Output:-</p>\n\n<blockquote>\n <p>Node title is bogus</p>\n</blockquote>\n\n<p>Which is what is wanted. I'm sure you'll agree the re-factored code is much easier to read and as an added bonus, it works! </p>\n\n<p>You may notice that I have reversed the normal order of the comparison, using <code>'bogus' === $node-&gt;type</code> rather than <code>$node-&gt;type === 'bogus'</code>. This will raise an exception if you type '=' instead of '==' or '===' by mistake and make debugging much easier. It is a good habit to get into, as is using strict type comparisons with '===' rather than loose comparisons with '=='.</p>\n\n<p>I might add that doing little step by step tests like this is a good way of working out what code actually does and reinforces the concepts of programming in your mind. I always do it when I come across functions/concepts that are new to me.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-05T14:48:11.880", "Id": "24868", "Score": "0", "body": "Good catch. I completely forgot about that. Your points are perfectly valid, but to prove that this still works, as OP asked, you would have to wrap those assignments in the if statement in parenthesis to separate them from the `&&` operator. However, I'm not abdicating its use, this is a much better solution +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-05T14:50:36.513", "Id": "24869", "Score": "0", "body": "@mseancole Thanks. if the OP did `if(($node = node_load(1)) && ($node->type = 'bogus') ){` the second part would always evaluate to true anyway as he is making an assignment, so it still wouldn't work as intended." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-05T15:30:15.400", "Id": "24870", "Score": "0", "body": "I don't think he's trying to compare it, I think he just wants to set two variables at once, assuming the first is successful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-05T16:17:02.233", "Id": "24876", "Score": "1", "body": "@mseancole but he is trying to compare it, I think the print statement is only supposed to execute for that type of node. Another type should skip the print statement, which it won't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-05T18:08:14.707", "Id": "24888", "Score": "1", "body": "Well then, his code had more than one error in it. I misunderstood this to mean that he wanted to set both variables in the if statement. @barraponto: I went ahead and edited your post so that the second parameter is being compared instead of assigned. Please try to ensure future posts don't have such confusing typos. This also helps to illustrate why doing this is such a bad idea. Its too easy to accidentally do something you didn't mean to, and others reading your code will have no idea if its right or wrong." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-05T12:46:01.067", "Id": "15343", "ParentId": "15157", "Score": "5" } } ]
{ "AcceptedAnswerId": "15343", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T19:30:37.760", "Id": "15157", "Score": "1", "Tags": [ "php" ], "Title": "Setting a variable during an if loop" }
15157
<p>I am getting information from an XML document and for the most part everything runs as it should. Occasionally, I get a php fatal error Call to a member function children() on a non-object. I have tried to use this</p> <pre><code>if(isset($current-&gt;AttributeSets-&gt;children('ns2', true)-&gt;ItemAttributes-&gt;ListPrice-&gt;Amount)) { $listPrice = $current-&gt;AttributeSets-&gt;children('ns2', true)-&gt;ItemAttributes-&gt;ListPrice-&gt;Amount; } else { $listPrice = 0; } </code></pre> <p>to catch any times there is no information in <code>$current</code>, but it does not always work. How do I handle the errors so it works all the time?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T20:38:20.237", "Id": "24591", "Score": "0", "body": "This should really be moved to SO as this is not a request for a review, but for help. Also, you might think about adding more information. There isn't nearly enough here to answer this question. A sample from the XML would be helpful, as would a full error stack." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T12:35:49.370", "Id": "24616", "Score": "0", "body": "I think it depends what is being reviewed here. The error handling approach can be commented upon at least." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T13:06:15.640", "Id": "24667", "Score": "0", "body": "True, and for the OP to have gotten this deep into the XML tree I would have expected those pointers to have been abstracted more first. Instead it appears that he is navigating directly to them, which is causing some really unnecessary repetition and could cause mistakes/typos in the future. Try using variables to abstract the different sections of that XML while you are parsing it, such as `$attributes = $current->AttributeSets;` etc..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T13:37:25.517", "Id": "24669", "Score": "0", "body": "The tree is pretty large, and $current holds all of the items that are static. Once I need to get custom variables, ie list price, then I just go to them directly ($current->AttributeSets->children('ns2', true)->ItemAttributes->ListPrice->Amount;" } ]
[ { "body": "<p>The trouble is that your check can fail. Before you can call the <code>children</code> method you need to be sure that you are dealing with an object (that provides the <code>children</code> method). This is actually what your fatal error is telling you (<code>$current-&gt;AttributeSets</code> is a non-object). You get this in your if statement within your <code>isset</code> call.</p>\n\n<p>The trouble with fatal errors is that they are fatal. There is no way to recover from them. The PHP engine is about to shutdown. You can read more about handling errors in an answer I wrote <a href=\"https://stackoverflow.com/questions/10331084/error-logging-in-a-smooth-way/10538836#10538836\">here</a>. The only way is to avoid fatal errors. Don't call functions that don't exist, or methods on something that is <code>NULL</code>.</p>\n\n<p>Possibly the reason you have this problem is breaking the <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow noreferrer\">Law of Demeter</a>. I don't know how the XML objects you are working with are built, etc.</p>\n\n<p>You could solve it by checking each component.</p>\n\n<p>Unfortunately you <strong>can't</strong> do this because <code>isset</code> can't use a function's return value:</p>\n\n<pre><code>// THIS WON'T WORK\nisset($current-&gt;AttributeSets,\n $current-&gt;AttributeSets-&gt;children('ns2', true)) // Function Return Value\n</code></pre>\n\n<p>However as <a href=\"https://codereview.stackexchange.com/questions/15158/error-handling-data-from-xml-document/15184#comment24667_15158\">mseancole commented</a> you can set the components as variables.</p>\n\n<pre><code>if (isset($current-&gt;AttributeSets))\n{\n $children = $current-&gt;AttributeSets-&gt;children('ns2', true);\n\n if (isset($children,\n $children-&gt;ItemAttributes,\n $children-&gt;ItemAttributes-&gt;ListPrice, // etc.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T14:37:03.377", "Id": "24674", "Score": "0", "body": "does it matter if the information from the xml document is extracted as a simple_load_string in the function? I was trying your suggestion and it was not working. Thanks for any help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T04:56:05.587", "Id": "24705", "Score": "0", "body": "sorry, i have fixed it. It basically becomes what mseancole wrote in the comment. @mseancole I'd be happy to upvote your comment if it was an answer (I think it really is very appropriate advice)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T12:48:49.887", "Id": "15184", "ParentId": "15158", "Score": "1" } } ]
{ "AcceptedAnswerId": "15184", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T19:49:14.987", "Id": "15158", "Score": "1", "Tags": [ "php", "xml" ], "Title": "Error handling data from XML document" }
15158
<p>In an attempt to learn more about Clojure's parallel computation functions, I devised the following task: calculate a factorial in parallel using <code>pmap</code>, <code>pcalls</code> and <code>pvalues</code>. </p> <p>The idea is to split the factorial sequence into sub-computations, reducing the final output of each.</p> <p>Here is the obvious non-parallel function:</p> <pre class="lang-lisp prettyprint-override"><code>(defn factorial [n] (reduce * (range 1 (inc n)) </code></pre> <p>pmap is fairly straight-forward:</p> <pre class="lang-lisp prettyprint-override"><code>(defn pmap-factorial [n psz] (let [parts (partition-all psz (range 1 (inc n)))] (reduce * (pmap #(apply * %) parts)))) </code></pre> <p>However, with pvalues I had to resort to macros that return a computation function.</p> <pre class="lang-lisp prettyprint-override"><code>(defmacro pvalues-factorial [n psz] (let [exprs (for [p (partition-all psz (range 1 (inc n)))] (cons '* p))] `(fn [] (reduce * (pvalues ~@exprs))))) </code></pre> <p>Similar approach with pcalls:</p> <pre class="lang-lisp prettyprint-override"><code>(defmacro pcalls-factorial [n psz] (let [exprs (for [p (partition-all psz (range 1 (inc n)))] `(fn [] (* ~@p)))] `(fn [] (reduce * (pcalls ~@exprs))))) </code></pre> <p>So, I had to use macros for <code>pcalls</code> and <code>pvalues</code>. Does not seem ideal, but it was the only way I could accomplish the above (and perhaps indicates that <code>pmaps</code> is the best practice for this use case).</p> <p><strong>Questions:</strong></p> <p>1) How could the code be made more correct / idiomatic?</p> <p>2) Did I have to resort to macros for pvalues and pcalls, or have I overlooked another way of accomplishing my goal with these functions?</p>
[]
[ { "body": "<p>1) that is quite idomatic Clojure from what I have seen.</p>\n\n<p>2) macros are \"contagious\" if the thing you are trying to call is a macro and you want to do anything requiring first-class-functions (map apply reduce etc...) then the thing doing the <code>apply</code>ing must it's self be a macro.</p>\n\n<p>This is why the coding standards for clojure.contrib stable releases require that your library provide a non-macro way to access it's services in addition to the macro one. as your problem nicely demonstrates. \n<b>macros are incredibly useful, and they are not first class</b> </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T22:06:05.957", "Id": "15162", "ParentId": "15160", "Score": "1" } } ]
{ "AcceptedAnswerId": "15162", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-28T21:24:53.850", "Id": "15160", "Score": "0", "Tags": [ "clojure" ], "Title": "Calculating a factorial with parallel sub-computations using pmap, pvalues and pcalls" }
15160
<p>I'm a bit concerned about function usage. There are so many different libraries/possible ways to do something that I'm not sure if the way I'm working at the moment is reasonable, or what I could modify to have a better code.</p> <p>Also, I'm searching on how to optimize this code, since for a small 25MB file the memory use goes to 800MB, and a bigger file goes OOM. What makes the memory to go so high?</p> <p>Before I had strict IO writing, and was expecting to be it that caused to evaluate everything on the code, but going lazy didn't solve anything.</p> <pre><code>{-# LANGUAGE OverloadedStrings,BangPatterns #-} import qualified Data.Attoparsec.Char8 as Ap import Data.Attoparsec import Control.Monad import System.IO import System.Environment import Data.Maybe import Data.List (unzip4,zip4,foldl') import Data.List.Split import Data.Bits import Numeric.FFT --import Data.Vector.Storable (fromList) import Data.Complex import Data.String (fromString) import Data.ByteString.Internal import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as Bl newtype FourD b a = FourD { getFourD :: (a,a,a,b) } instance (Show b, Show a) =&gt; Show (FourD b a) where show (FourD (a,b,c,d)) = "( "++show a++" , "++show b++" , "++show c++" , "++show d++" )" instance Functor (FourD c) where fmap f (FourD (x,y,z,d)) = FourD (f x,f y,f z,d) mgrav_per_bit = [ 18, 36, 71, 143, 286, 571, 1142 ] aToG a = sign * uresult where twocomp = if a&gt;128 then 256-a else a uresult = foldr (+) 0 $ zipWith (*) mgrav_per_bit (map ( g . testBit twocomp) [0..7] ) sign = if a&gt;128 then -1 else 1 g True = 1; g False = 0 amap f g = map FourD . uncurry4 zip4 . map4 f g . unzip4 . map getFourD where map4 f g (a,b,c,d) = ( f a,f b,f c, g d) uncurry4 f (a,b,c,d) = f a b c d splitN n x = helper x 0 where l = length x helper x c = if (c+n)&gt;l then [] else (Prelude.take n x):(helper (drop 1 x) (c + 1)) quare = foldr (\a b-&gt; b+(magnitude a)) 0 getTime :: (FourD String a)-&gt; String getTime (FourD (_,_,_,t)) = t filterAcc (FourD (x,_,_,t)) = if x &gt; 50 then (Bl.pack . B.unpack) $ "yes" `B.append` t else Bl.pack "" parseAcc :: Parser (FourD B.ByteString Int) parseAcc = do satisfy (== 40) x &lt;- Ap.decimal string "," y &lt;- Ap.decimal string "," z &lt;- Ap.decimal string "," time &lt;- takeTill (== 41) return $ FourD (x,y,z,time) where isDigit w = w &gt;= 48 &amp;&amp; w &lt;= 57 isNot w = w/=29 readExpr input = case parse parseAcc input of Done b val -&gt; val Partial p-&gt; undefined Fail a b c -&gt; undefined fftAcross = map ( map (/32) . fft ) . splitN 32 main = do filename &lt;- liftM head getArgs filehandle &lt;- openFile "lol.txt" WriteMode contents &lt;- liftM B.lines $ B.readFile filename Bl.hPutStr (filehandle) . Bl.concat . map (filterAcc) . splitAndApply . convertComplex $ contents where convertComplex = map ( fmap( fromIntegral . aToG). readExpr ) splitAndApply = (amap (map (floor .quare .(drop 1) ). fftAcross) ((map head) . splitN 32)) -- B.hPutStrLn (filehandle) . B.unlines . map (B.pack . show ) . amap (map (floor .quare) . (filter (/=[])) . map ( (drop 1) . (map (/32)) . fft ) . splitN 32) . map ( fmap(fromIntegral . aToG)) . map readExpr $ contents </code></pre>
[]
[ { "body": "<p>You can use <code>HLint</code> tool to get rid of few extra parentheses, and use <code>&lt;$&gt;</code> instead of <code>liftM</code>:</p>\n\n<pre><code>contents &lt;- B.lines &lt;$&gt; B.readFile filename\n</code></pre>\n\n<p>Other than that I don't see anything to be improved in your code at low level. To help with high level design there's not enough info in your question. Can you explain what do you want to achieve with your code?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T17:46:52.857", "Id": "15331", "ParentId": "15164", "Score": "1" } } ]
{ "AcceptedAnswerId": "15331", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T00:18:20.390", "Id": "15164", "Score": "3", "Tags": [ "haskell", "memory-management", "csv", "signal-processing" ], "Title": "Reading a data file for performing a FFT" }
15164
<p>I have the following Ruby code snippet:</p> <pre><code> url = "http://somewiki.com/index.php?book=#{author}:#{title}&amp;action=edit" encoded = URI.encode(url) encoded.gsub(/&amp;/, "%26").sub(/%26action/, "&amp;action") </code></pre> <p>The last line is needed since I have to encode the ampersands (<code>&amp;</code>) in the author and title but I need to leave the last one (<code>&amp;action...</code>) intact.</p> <p>Consider this example for clarity:</p> <pre><code>author = "John &amp; Diane" title = "Our Life &amp; Work" url = "http://somewiki.com/index.php?book=#{author}:#{title}&amp;action=edit" encoded = URI.encode(url) encoded.gsub(/&amp;/, "%26").sub(/%26action/, "&amp;action") # =&gt; "http://somewiki.com/index.php?book=John%20%26%20Diane:Our%20Life%20%26%20Work&amp;action=edit" </code></pre> <p>Although this result is satisfactory, I'd like to clean the original code with the <code>gsub/sub</code> calls. Any ideas?</p> <p>PS: I could "clean" both params before passing them to the <code>url = ...</code> line but then the <code>%</code> characters will be re-encoded as <code>%25</code> by the <code>URI.encode</code> call so I don't think that's an option. I'd love to be proved wrong here though.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-08T13:51:33.040", "Id": "507244", "Score": "0", "body": "See https://stackoverflow.com/a/36191180/520567 , you can use a specified parser." } ]
[ { "body": "<p>Unless you need the unencoded url (for logging?), I would just:</p>\n\n<pre><code>encoded_url = \"http://somewiki.com/index.php?book=#{CGI.escape(author)}:#{CGI.escape(title)}&amp;action=edit\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-02T07:56:34.960", "Id": "24764", "Score": "0", "body": "`URI.encode` does not encode & as %26." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-03T04:02:26.040", "Id": "24794", "Score": "0", "body": "Correct, I meant CGI.escape(). I should review my review next time" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-02T00:37:07.590", "Id": "15271", "ParentId": "15165", "Score": "8" } } ]
{ "AcceptedAnswerId": "15271", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T00:35:13.457", "Id": "15165", "Score": "5", "Tags": [ "ruby" ], "Title": "Encoding special characters in URLs with Ruby" }
15165
<p>I'm in the process of building a website for the company I work for and I'm trying to think of the best way to namespace and organize the site's JavaScript code.</p> <p>I've written several jQuery/JavaScript plugins for the big chunks of code, but now I'd like a namespaced place to "call" said plugins and any other random JavaScript that's needed throughout the site.</p> <p>I'm considering using a singleton (<code>NAMESPACE.js</code>):</p> <pre><code>// http://stackoverflow.com/a/1479341/922323 var NAMESPACE = (function() { //var privateVar = ''; function weather() { var $weather = $('#weather'); if ($weather.length) { // Do jQuery stuff with $weather here. } } // weather() function navigation() { var $baz = $('#baz'), $html = $('html'); $baz .myOtherPlugin({ cloneRemove : 'li &gt; div', cloneId : false }) .anotherPlugin({ eventType : 'hoverIntent', onStartOutside : function() { $html.addClass('mw-outside'); }, onEndOutside : function() { $html.removeClass('mw-outside'); } }); } // navigation() function footer() { $('footer ul').myPlugin({ //openTab : true, currentPage : true }); } // footer() return { init : function() { weather(); navigation(); footer(); // Add more here as project grows... } // init() }; })(); </code></pre> <p>HTML would look like so (in foot of document):</p> <pre><code>&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="plugins.js"&gt;&lt;/script&gt; &lt;script src="NAMESPACE.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; &lt;!-- $(document).ready(function() { NAMESPACE.init(); }); //--&gt; &lt;/script&gt; </code></pre> <h3>Question(s):</h3> <ol> <li>Do you see anything out of the ordianary with my (pseudo) code above?</li> <li>Am I headed in the right direction? If not, could you suggest an alternative?</li> <li>Am I over-complicating things?</li> <li>I really like how <a href="http://www.yuiblog.com/blog/2007/06/12/module-pattern/" rel="nofollow">Yahoo! does</a>: <code>YAHOO.namespace("myProject"); YAHOO.myProject.myModule = function () { ... }</code> ... it seems like if I did <a href="https://github.com/yui/yui2/tree/master/src/yahoo/js" rel="nofollow">something similar</a>, that would allow me to <strong>easily</strong> add/remove "modules" on a "per page" basis. Would anyone recommend this approach? If so, how could I modify my example to mimic YUI's functionality (I'm going to research YUI's <code>namespace()</code> code and post back my results if I figure it out). </li> </ol>
[]
[ { "body": "<p>One problem in your code is that the \"modules\" aren't standalone. You'd be adding the \"modules\" for calling into the <code>init</code> every time a new on is made.</p>\n\n<p>To avoid doing so, each module should register itself for <code>init</code>. You can do this by adding a \"register\" functionality in your singleton.</p>\n\n<pre><code>(function(exports){\n\n var registry = []; //collection of module\n\n //adds module to collection\n exports.register = function(moduleDeclaration){\n registry.push(moduleDeclaration);\n }\n\n //executes every module\n exports.init = function(){\n var registryLength,i;\n\n registryLength = registry.length\n\n //loop through each module and execute\n for(i=0;i&lt;registry.length;i++){\n registry[i].call(this);\n }\n }\n\n//use existing namespace or make a new object of that namespace\n}(window.Lib = window.Lib || {}));\n\n//To register a module\nLib.register(function(){\n //do what you have to do here\n});\n\n//executing the init\nLib.init();\n</code></pre>\n\n<p>See? The modules register themselves and don't need to be added manually for <code>init</code>. A developer can create a module on a separate file, add it into the page without editing the main <code>Lib</code> singleton.</p>\n\n<p>Also, you'd have to consider what you'd do if you include a module dynamically <em>after</em> <code>init</code> is called. You should have some internal flag to indicate that init was already called, and that dynamically added module should register and execute immediately.</p>\n\n<hr>\n\n<p>A vaguely known library called <a href=\"http://alanlindsay.me/kerneljs/\">KernelJS</a> already does this and contains many more features like core abstraction, pub-sub inter-module communication, register-remove modules, loose coupling pattern and so on. I suggest you try it or base from it.</p>\n\n<hr>\n\n<p>As an answer to your add-on question of exposing modules, sure you can. However, according to scalability principles, modules or \"widgets\" as they call them, should not know each exists. This is to prevent tight-coupling and avoid breakage when, for example, you take out a certain module out. </p>\n\n<p>Also, naming modules isn't good for portability as you are setting a fixed name for a set of code. What if you changed it's name? You'd have to look for all code that depends on that module and change the name.</p>\n\n<p>However, if you want to have named modules and fetching badly, you could expose another function to retrieve a module and return that module if it exists, or <code>undefined</code> or a custom error if it doesn't. Here's modified code for <code>Lib</code>. Since we are using named modules, instead of an array, <code>registry</code> is now an object.</p>\n\n<pre><code>var registry = {}\n\nexports.register = function(name,declaration){\n registry[name] = declaration;\n}\n\nexports.init = function(){\n var module,i;\n\n registryLength = registry.length\n\n //loop through each module and execute\n for(name in registry){\n if(registry.hasOwnProperty(name)){\n registry[name].call(this);\n }\n }\n}\n\nexports.getModule = function(moduleName){\n\n //default to undefined\n var module;\n\n //if module exists, assign\n if(registry.hasOwnProperty('moduleName')){\n module = registry[moduleName];\n }\n\n return module\n}\n\n//to register a module\nLib.register('moduleName',function(){\n //module code\n});\n</code></pre>\n\n<p>Additionally, you can call each module's <code>init</code> from <code>Lib</code>'s <code>init</code>. Just make sure each module exposes an <code>init</code> function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T17:42:35.620", "Id": "24628", "Score": "0", "body": "Joseph... **YOU ROCK!!!** Thank you so much for the very helpful and informative reply! I'm playing with your example now (KernelJS looks awesome also... I'll play with that second). I'll be back shortly with my findings. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T23:04:27.520", "Id": "24637", "Score": "0", "body": "Based off of your **AWESOME** code, I've got a working example [here](http://jsbin.com/aluvij). I've updated my question with the code (for easy access/viewing). I love it! My only question: Would there ever be a situation where I'd want to access modules after `init()`? I played around with exposing the `registry`, but I'd have to know the `key` of the module I want to access... Would it be worth it to add some sort of named `key` to the `registry` and publicly expose it for later access? Does any of that make sense? :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T03:24:11.863", "Id": "24652", "Score": "0", "body": "@MickyHulse updated the answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T17:07:49.970", "Id": "24679", "Score": "0", "body": "Joseph... You, sir, are a **genius**!!!! Thanks a billion for all of your pro help! I greatly appreciate it! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T17:10:39.220", "Id": "24680", "Score": "0", "body": "I do have one last question, does my `if (initialized) moduleDeclaration.call(this);` line meet your standards? Is that how/where you would handle registering and executing a module immediately?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T04:23:16.003", "Id": "24704", "Score": "0", "body": "@MickyHulse that would be fine, but I suggest wrapping the block in `{}` to avoid future issues." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T17:28:56.450", "Id": "24725", "Score": "0", "body": "Thank you Joseph! I really appreciate your pro help! Hopefully one of these days I can help you with something. Have a great day! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T17:34:51.683", "Id": "24726", "Score": "0", "body": "I've updated my example code to include curly braces (sorry, I guess that's a bad habit I've picked up over the years)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T23:48:51.353", "Id": "24747", "Score": "0", "body": "@MickyHulse regarding the yahoo-like package namespacing scheme, it's not much of use. It emulates JAVA-like class packaging. Try looking at [AMD](http://requirejs.org/docs/whyamd.html) instead. It's a common module import scheme for browser JS." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-01T01:10:41.080", "Id": "24749", "Score": "0", "body": "Oh, nice! Excellent tip! Thanks so much Joseph, I really owe you one... Let me know if you have an Amazon wishlist or something similar. :)" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T12:33:07.767", "Id": "15181", "ParentId": "15166", "Score": "7" } } ]
{ "AcceptedAnswerId": "15181", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T01:03:23.577", "Id": "15166", "Score": "7", "Tags": [ "javascript" ], "Title": "Organizing JavaScript code for a website" }
15166
<p>I have the following code in a portion of my program that hides/shows certain elements based on the status of a certain checkbox:</p> <pre><code>private void enableFolderVariableRemoval_CheckedChanged(object sender, EventArgs e) { if (enableFolderVariableRemoval.Checked) { cleanFolderTextPanel.Visible = true; cleanTextPanel.Visible = true; } else { cleanFolderTextPanel.Visible = false; if (cleanFilenameTextPanel.Visible == false) { cleanTextPanel.Visible = false; } } } </code></pre> <p>Is there a better way to handle this without a whole bunch of conditionals that set other controls to hide/show?</p>
[]
[ { "body": "<p>Not sure if there are any other constraints but here is one possible solution:</p>\n\n<pre><code>private void enableFolderVariableRemoval_CheckedChanged(object sender, EventArgs e)\n{\n cleanFolderTextPanel.Visible = enableFolderVariableRemoval.Checked; \n cleanTextPanel.Visible = cleanFolderTextPanel.Visible || cleanFilenameTextPanel.Visible; \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T02:36:36.047", "Id": "15170", "ParentId": "15168", "Score": "6" } }, { "body": "<p>I'm not sure what the logic is in your code, the else and nested if in it is really confusing. But from what I can understand:</p>\n\n<p>You can set the Visible Attribute for cleanFolderTextPanel straight from the checked value of enableFolderVariableRemoval.</p>\n\n<p>The Visible Attribute for cleanTextPanel can then be calculated using a new Method and an inline if:</p>\n\n<pre><code>private void enableFolderVariableRemoval_CheckedChanged(object sender, EventArgs e)\n{\n var enableFolderVariableRemoval = enableFolderVariableRemoval.Checked;\n\n cleanFolderTextPanel.Visible = enableFolderVariableRemoval;\n cleanTextPanel.Visible = CleanTextPanelShouldBeHidden(enableFolderVariableRemoval ) ? false : cleanTextPanel.Visible\n}\n\n...\n\nprivate static void CleanTextPanelShouldBeHidden(bool enableFolderVariableRemoval)\n{\n return !cleanFilenameTextPanel.Visible &amp;&amp; !enableFolderVariableRemoval\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T02:41:42.337", "Id": "15171", "ParentId": "15168", "Score": "2" } }, { "body": "<p>Assuming you already moved your controls into logical panels, Perhaps you are asking a more general question: how do you prevent the following construct from going wild?</p>\n\n<pre><code>Some Event...\nIf GUI = 1\n Panel1.Show()\n Panel2.Hide()\n Panel3.Hide()\n ...\nIf GUI = 2\n Panel1.Hide()\n Panel2.Show()\n ...\nIf GUI = 3\n ...\n</code></pre>\n\n<p>Make the GUI <code>Panel</code>s implement a <code>View_I</code> interface which has a <code>.Show()</code> and <code>.Hide()</code> methods, then the code becomes more like:</p>\n\n<pre><code>Some Event...\n// hide the previous View if one exists\nIf View_I != Null\n View_I.Hide()\n\nIf GUI = 1\n View_I = Panel1\nIf GUI = 2\n View_I = Panel2\n ...\n// Show the new View\nView_I.Show() \n ...\n</code></pre>\n\n<p>Now you can add other <code>Panels</code> without code management proliferation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-16T04:27:44.270", "Id": "147161", "ParentId": "15168", "Score": "0" } } ]
{ "AcceptedAnswerId": "15170", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T01:14:05.530", "Id": "15168", "Score": "3", "Tags": [ "c#", ".net", "winforms" ], "Title": "Showing/hiding controls based on event" }
15168
<p>To help learn the SharePoint object model (primarily for SharePoint 2007), I've been working on a class library with a number of useful functions. I'm a junior developer and this is my first C# project of this nature.</p> <p>With this in mind, how can I improve the class below? What bad habits do I have or what should I study so I can code better?</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint; using System.Diagnostics; // todo: Lists // MoveListItems // MoveListItemsSiteToSite // DeleteListItem // WriteFileMetadata // AddListEntry // Throttling on copy methods namespace DEVTEST.SharePoint { /// &lt;summary&gt; /// Class to encapsulate methods that interact with SharePoint Lists and Libraries /// &lt;/summary&gt; public class ListsAndItems { /// &lt;summary&gt; /// Access and modify items in SharePoint lists within the same site /// &lt;/summary&gt; /// &lt;param name="siteURL"&gt;&lt;/param&gt; /// &lt;param name="sourceList"&gt;&lt;/param&gt; /// &lt;param name="destinationList"&gt;&lt;/param&gt; /// &lt;param name="retainMeta"&gt;&lt;/param&gt; public static void MoveListItems(string siteURL, string sourceList, string destinationList, bool retainMeta) { Console.WriteLine("[{0}] Opening site: {1}", DateTime.Now.ToShortTimeString(), siteURL); using (var site = new SPSite(siteURL)) { Console.WriteLine("[{0}] Opened site: {1}", DateTime.Now.ToShortTimeString(), siteURL); using (var web = site.OpenWeb()) { Console.WriteLine("[{0}] Web Relative URL is: {1}", DateTime.Now.ToShortTimeString(), web.ServerRelativeUrl); try { // Get your source and destination libraries var source = web.GetList(web.ServerRelativeUrl + sourceList); var destination = web.GetList(web.ServerRelativeUrl + destinationList); Console.WriteLine("[{0}] Source set to: {1}", DateTime.Now.ToShortTimeString(), source); Console.WriteLine("[{0}] Destination set to: {1}", DateTime.Now.ToShortTimeString(), destination); // Get the collection of items to move, use source.GetItems(SPQuery) if you want a subset SPListItemCollection items = source.Items; // Get the root folder of the destination we'll use this to add the files SPFolder folder = web.GetFolder(destination.RootFolder.Url); Console.WriteLine("[{0}] Moving {1} files from {2} to {3} - please wait...", DateTime.Now.ToShortTimeString(), items.Count, source, destination); var fileCount = 0; // Now to move the files and the metadata foreach (SPListItem item in items) { //Get the file associated with the item SPFile file = item.File; // Create a new file in the destination library with the same properties SPFile newFile = folder.Files.Add(folder.Url + "/" + file.Name, file.OpenBinary(), file.Properties, true); // Optionally copy across the created/modified metadata if (retainMeta) { SPListItem newItem = newFile.Item; WriteFileMetaDataFiletoFile(item, newItem); } // Delete the original version of the file // todo: make local backup before deleting? file.Delete(); fileCount++; } Console.WriteLine("[{0}] Completed moving {1} files to {2}", DateTime.Now.ToShortTimeString(), fileCount, destination); } catch (System.IO.FileNotFoundException) { Console.WriteLine( "[{0}] Unable to set a location. Please check that paths for source and destination libraries are correct and relative to the site collection.", DateTime.Now.ToShortTimeString()); throw; } catch (Exception ex) { Console.WriteLine("[{0}] Exception: {1}", DateTime.Now.ToShortTimeString(), ex); throw; } } } } /// &lt;summary&gt; /// Access and modify items in SharePoint lists in differing sites /// &lt;/summary&gt; /// &lt;param name="sourceSiteURL"&gt;&lt;/param&gt; /// &lt;param name="sourceList"&gt;&lt;/param&gt; /// &lt;param name="destinationSiteURL"&gt;&lt;/param&gt; /// &lt;param name="destinationList"&gt;&lt;/param&gt; /// &lt;param name="retainMeta"&gt;&lt;/param&gt; public static void MoveListItemsSiteToSite(string sourceSiteURL, string sourceList, string destinationSiteURL, string destinationList, bool retainMeta) { Console.WriteLine("[{0}] Opening Source site: {1}", DateTime.Now.ToShortTimeString(), sourceSiteURL); using (var sourceSite = new SPSite(sourceSiteURL)) { Console.WriteLine("[{0}] Opened Source site: {1}", DateTime.Now.ToShortTimeString(), sourceSiteURL); using (var sourceWeb = sourceSite.OpenWeb()) { Console.WriteLine("[{0}] Source Web Relative URL is: {1}", DateTime.Now.ToShortTimeString(), sourceWeb.ServerRelativeUrl); try { // Get your source library var source = sourceWeb.GetList(sourceWeb.ServerRelativeUrl + sourceList); Console.WriteLine("[{0}] Source set to: {1}", DateTime.Now.ToShortTimeString(), source); // Get the collection of items to move, use source.GetItems(SPQuery) if you want a subset SPListItemCollection items = source.Items; var fileCount = 0; Console.WriteLine("[{0}] Opening Destination site: {1}", DateTime.Now.ToShortTimeString(), destinationSiteURL); using (var destSite = new SPSite(destinationSiteURL)) { Console.WriteLine("[{0}] Opened Destination site: {1}", DateTime.Now.ToShortTimeString(), destSite); using (var destinationWeb = destSite.OpenWeb()) { Console.WriteLine("[{0}] Destination Web Relative URL is: {1}", DateTime.Now.ToShortTimeString(), destinationWeb.ServerRelativeUrl); // get destination library var destination = destinationWeb.GetList(destinationWeb.ServerRelativeUrl + destinationList); Console.WriteLine("[{0}] Destination set to: {1}", DateTime.Now.ToShortTimeString(), destination); // Get the root folder of the destination we'll use this to add the files SPFolder destinationFolder = destinationWeb.GetFolder(destination.RootFolder.Url); Console.WriteLine("[{0}] Moving {1} files from {2} to {3} - please wait...", DateTime.Now.ToShortTimeString(), items.Count, source, destination); // Now to move the files and the metadata foreach (SPListItem item in items) { //Get the file associated with the item SPFile file = item.File; // Create a new file in the destination library with the same properties SPFile newFile = destinationFolder.Files.Add(destinationFolder.Url + "/" + file.Name, file.OpenBinary(), file.Properties, true); // Optionally copy across the created/modified metadata if (retainMeta) { SPListItem newItem = newFile.Item; WriteFileMetaDataFiletoFile(item, newItem); } // Delete the original version of the file // todo: make local backup before deleting? file.Delete(); fileCount++; } Console.WriteLine("[{0}] Completed moving {1} files to {2}", DateTime.Now.ToShortTimeString(), fileCount, destination); } } } catch (System.IO.FileNotFoundException) { Console.WriteLine( "[{0}] Unable to set a location. Please check that paths for source and destination libraries are correct and relative to the site collection.", DateTime.Now.ToShortTimeString()); throw; } catch (Exception ex) { Console.WriteLine("[{0}] Exception: {1}", DateTime.Now.ToShortTimeString(), ex); throw; } } } } /// &lt;summary&gt; /// Overwrite existing meta data for a file with meta data from another file /// &lt;/summary&gt; /// &lt;param name="sourceItem"&gt;Source file to take meta data from&lt;/param&gt; /// &lt;param name="destinationItem"&gt;Destination file to write meta data to&lt;/param&gt; public static void WriteFileMetaDataFiletoFile(SPListItem sourceItem, SPListItem destinationItem) // overwrites a list items meta data with meta data from another file { //todo: change to write individual items instead of using source item destinationItem["Editor"] = sourceItem["Editor"]; destinationItem["Modified"] = sourceItem["Modified"]; destinationItem["Modified By"] = sourceItem["Modified By"]; destinationItem["Author"] = sourceItem["Author"]; destinationItem["Created"] = sourceItem["Created"]; destinationItem["Created By"] = sourceItem["Created By"]; // UpdateOverwriteVersion() will preserve the metadata added above. destinationItem.UpdateOverwriteVersion(); } /// &lt;summary&gt; /// /// &lt;/summary&gt; /// &lt;param name="item"&gt;&lt;/param&gt; /// &lt;param name="editor"&gt;&lt;/param&gt; /// &lt;param name="modified"&gt;&lt;/param&gt; /// &lt;param name="modifiedBy"&gt;&lt;/param&gt; /// &lt;param name="author"&gt;&lt;/param&gt; /// &lt;param name="created"&gt;&lt;/param&gt; /// &lt;param name="createdBy"&gt;&lt;/param&gt; public static void WriteFileMetaData(SPList item, string editor, DateTime modified, string modifiedBy, string author, DateTime created, string createdBy) { // todo } } } </code></pre>
[]
[ { "body": "<p>Good job on the formatting and using using.</p>\n\n<p>There's a few things I can see to clean this up.</p>\n\n<p>Is there a reason you are not using var to declare obvious variables? I would suggest to use it whenever you can.</p>\n\n<p>I would move the Console.WriteLine logging into a separate class, probably that had an interface, that is injected or set in your class. This will allow you to easily change where the log information is going. Say in production you want it to go into a text file??</p>\n\n<p>Instead of rethrowing the exception in the catch statements, throw a new exception with the original one as the inner exception:</p>\n\n<pre><code>catch (System.IO.FileNotFoundException ex)\n{\n _logger.Log(string.Format(\"[{0}] Unable to set a location. Please check that paths for source and destination libraries are correct and relative to the site collection.\",\n DateTime.Now.ToShortTimeString()));\n\n throw new UnableToProcessFileException(fileName, ex);\n}\n</code></pre>\n\n<p>This will give a bit more meaning when the exception is finally caught and displayed.</p>\n\n<p>You could create a function to deal with the code inside the ForEach loop. Then you could use the link ForEach(func&lt;>) method:</p>\n\n<pre><code>private static void ProcessSPListItem(SPListItem item)\n{\n SPFile file = item.File;\n\n SPFile newFile = folder.Files.Add(folder.Url + \"/\" + file.Name, file.OpenBinary(), file.Properties, true);\n\n if (retainMeta)\n {\n SPListItem newItem = newFile.Item;\n WriteFileMetaDataFiletoFile(item, newItem);\n }\n\n // todo: make local backup before deleting?\n file.Delete();\n\n fileCount++;\n}\n\n...\n\nitems.ForEach(ProcessSPListItem);\n</code></pre>\n\n<p>I also think there is too many unnecessary comments in your code. If you have to describe what the code is doing, you need to refactor to make the intent more clear.</p>\n\n<p>i.e.</p>\n\n<pre><code>// Delete the original version of the file\n// todo: make local backup before deleting?\nfile.Delete();\n</code></pre>\n\n<p>If it is important to portray you are deleting the original version, this would be much better:</p>\n\n<pre><code>DeleteOriginalVersion(file);\n</code></pre>\n\n<p>where</p>\n\n<pre><code>private static void DeleteOriginalVersion(File file)\n{\n file.Delete();\n}\n</code></pre>\n\n<p>but for this, I would say file.Delete() speaks for itself.</p>\n\n<p>I also think you have too many parameters in your function calls. The Max I ever have is 3, but I do my best to limit it to 2.</p>\n\n<p>If you need more, create a class with like parameters.</p>\n\n<pre><code>internal class ListInformation\n{ \n public string Url{ get; private set; }\n public string List{ get; private set; } \n\n public ListInformation(string url, string list)\n {\n Url = url;\n List = list;\n }\n}\n\ninternal class MoveSourceToDestinationParameters\n{\n public ListInformation Source { get; private set; }\n public ListInformation Destination { get; private set; }\n\n public MoveSourceToDestinationParameters(ListInformation source, ListInformation destination)\n {\n Source = source;\n Destination = destination;\n }\n}\n</code></pre>\n\n<p>I'd rename the variable retainMeta to copyMetaDataWithMove, this will allow removal of more unneeded comments.</p>\n\n<p>Another thing is to check for duplicate code. It's a little late, my head is not fully functioning, and I'm doing this without VS open, but I am seeing similar patterns in MoveListItems and MoveListItemsSiteToSite. If you want, I'll check tomorrow and come up with a solution.</p>\n\n<p>I think overall, its not bad, but like any code (including mine) there is a bit of room for improvement.</p>\n\n<p>Let me know if you have any questions.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Here is the file as I see it.</p>\n\n<pre><code>public class UnableToProcessFileException : Exception\n{\n public UnableToProcessFileException(string message, Exception innerException)\n : base(message, innerException)\n {\n\n }\n}\n\npublic class ListInformation\n{\n public string Url { get; private set; }\n public string List { get; private set; }\n\n public ListInformation(string url, string list)\n {\n Url = url;\n List = list;\n }\n}\n\npublic class MoveSourceToDestinationParameters\n{\n public ListInformation Source { get; private set; }\n public ListInformation Destination { get; private set; }\n\n public MoveSourceToDestinationParameters(ListInformation source, ListInformation destination)\n {\n Source = source;\n Destination = destination;\n }\n}\n\n/// &lt;summary&gt;\n/// Class to encapsulate methods that interact with SharePoint Lists and Libraries\n/// &lt;/summary&gt;\npublic class ListsAndItems\n{\n private bool _copyMetaDataWithMove;\n\n /// &lt;summary&gt;\n /// Access and modify items in SharePoint lists within the same site\n /// &lt;/summary&gt;\n /// &lt;param name=\"parameters\"&gt; &lt;/param&gt;\n /// &lt;param name=\"retainMeta\"&gt;&lt;/param&gt;\n public void MoveListItems(MoveSourceToDestinationParameters parameters, bool retainMeta)\n {\n _copyMetaDataWithMove = retainMeta;\n\n DisplayMessage(string.Format(\"[{0}] Opening site: {1}\", DateTime.Now.ToShortTimeString(), parameters.Source.Url));\n\n using (var site = new SPSite(siteURL))\n {\n DisplayMessage(string.Format(\"[{0}] Opened site: {1}\", DateTime.Now.ToShortTimeString(), parameters.Source.Url));\n\n using (var web = site.OpenWeb())\n {\n DisplayMessage(string.Format(\"[{0}] Web Relative URL is: {1}\", DateTime.Now.ToShortTimeString(), web.ServerRelativeUrl));\n\n ProcessLists(parameters, web, web);\n }\n }\n }\n\n /// &lt;summary&gt;\n /// Access and modify items in SharePoint lists in differing sites\n /// &lt;/summary&gt;\n /// &lt;param name=\"parameters\"&gt; &lt;/param&gt;\n /// &lt;param name=\"retainMeta\"&gt;&lt;/param&gt;\n public void MoveListItemsSiteToSite(MoveSourceToDestinationParameters parameters, bool retainMeta)\n {\n _copyMetaDataWithMove = retainMeta;\n\n DisplayMessage(string.Format(\"[{0}] Opening Source site: {1}\", DateTime.Now.ToShortTimeString(), parameters.Source.Url);\n\n using (var sourceSite = new SPSite(parameters.Source.Url))\n {\n DisplayMessage(string.Format(\"[{0}] Opened Source site: {1}\", DateTime.Now.ToShortTimeString(), parameters.Source.Url);\n\n using (var sourceWeb = sourceSite.OpenWeb())\n {\n DisplayMessage(string.Format(\"[{0}] Source Web Relative URL is: {1}\", DateTime.Now.ToShortTimeString(), sourceWeb.ServerRelativeUrl);\n\n DisplayMessage(string.Format(\"[{0}] Opening Destination site: {1}\", DateTime.Now.ToShortTimeString(), parameters.Destination.Url));\n\n using (var destinationSite = new SPSite(parameters.Destination.Url))\n {\n DisplayMessage(string.Format(\"[{0}] Opened Destination site: {1}\", DateTime.Now.ToShortTimeString(), destinationSite));\n\n using (var destinationWeb = destinationSite.OpenWeb())\n {\n\n ProcessLists(parameters, sourceWeb, destinationWeb);\n }\n\n }\n }\n }\n }\n\n private void ProcessLists(MoveSourceToDestinationParameters parameters, object sourceWeb, object destinationWeb)\n {\n try\n { \n var sourceList = sourceWeb.GetList(sourceWeb.ServerRelativeUrl + parameters.Source.List);\n\n DisplayMessage(string.Format(\"[{0}] Source list set to: {1}\", DateTime.Now.ToShortTimeString(), sourceList));\n\n DisplayMessage(string.Format(\"[{0}] Destination Web Relative URL is: {1}\", DateTime.Now.ToShortTimeString(),\n destinationWeb.ServerRelativeUrl));\n\n var desinationList = destinationWeb.GetList(destinationWeb.ServerRelativeUrl + parameters.Destination.List);\n\n DisplayMessage(string.Format(\"[{0}] Destination list set to: {1}\", DateTime.Now.ToShortTimeString(), desinationList));\n\n MoveFiles(desinationList, sourceList, destinationWeb.GetFolder(desinationList.RootFolder.Url));\n }\n catch (System.IO.FileNotFoundException ex)\n {\n throw new UnableToProcessFileException(\n string.Format(\"Unable to set a location to {0}.\", ex.FileName), ex);\n }\n catch (Exception ex)\n {\n throw new UnableToProcessFileException(\"Unknown error moving files.\", ex);\n }\n }\n\n private void MoveFiles(object destination, object source, SPFolder destinationFolder)\n {\n var items = source.Items;\n\n DisplayMessage(string.Format(\"[{0}] Moving {1} files from {2} to {3} - please wait...\",\n DateTime.Now.ToShortTimeString(),\n items.Count, source, destination));\n\n var fileCount = items.Count;\n\n items.ForEach(item =&gt; MoveSourceFileToDestinationFolder(item, destinationFolder));\n\n DisplayMessage(string.Format(\"[{0}] Completed moving {1} files to {2}\", DateTime.Now.ToShortTimeString(), fileCount,\n destination));\n }\n\n private void MoveSourceFileToDestinationFolder(SPFile item, SPFolder destination)\n {\n SPFile file = item.File;\n\n SPFile newFile = destination.Files.Add(destination.Url + \"/\" + file.Name, file.OpenBinary(), file.Properties, true);\n\n if (_copyMetaDataWithMove)\n {\n SPListItem newItem = newFile.Item;\n WriteFileMetaDataFiletoFile(item, newItem);\n }\n\n // todo: make local backup before deleting?\n file.Delete();\n }\n\n private static void DisplayMessage(string msg)\n {\n Console.WriteLine(msg);\n }\n\n...\n</code></pre>\n\n<p>}</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T04:32:55.747", "Id": "24605", "Score": "0", "body": "That would be great. I tried to combine the two previously but I couldn't find a way to do it and not have two site objects when it wasn't needed (it's only needed when moving across sites). I was considering just making an override for the method - but maybe there's a better way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T16:45:18.683", "Id": "24624", "Score": "0", "body": "Refactored code attached." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T23:04:49.407", "Id": "24638", "Score": "0", "body": "This is excellent and provides me with some valuable insight into better using properties / managing parameters. Thank-you! If I can ever pay this forward I certainly will!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T03:28:33.673", "Id": "15174", "ParentId": "15169", "Score": "2" } } ]
{ "AcceptedAnswerId": "15174", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T01:35:59.150", "Id": "15169", "Score": "1", "Tags": [ "c#", "object-oriented", "sharepoint" ], "Title": "SharePoint class" }
15169
<p>I'm using this form to submit articles into the database:</p> <pre class="lang-html prettyprint-override"><code>&lt;form enctype="multipart/form-data" method="post" action="add.php"&gt; &lt;input name="title" type="text"&gt; &lt;input name="image" type="file"&gt; &lt;textarea name="text"&gt;&lt;/textarea&gt; &lt;input type="submit" name="go" value="Spremi"&gt; &lt;/form&gt; </code></pre> <p></p> <pre><code>include ("database.php"); $upload_path = "files/images/"; $prefix= date("Hi-mdY")."-"; $file_name = $HTTP_POST_FILES['image']['name']; $file_name = str_replace(' ', '-', $file_name); $file_name = str_replace('_', '-', $file_name); $file_name = strtolower($file_name); $upload_path = $upload_path . basename($prefix.$file_name); move_uploaded_file($_FILES['image']['tmp_name'], $upload_path); $final_file_name = ("/files/images/".$prefix.$file_name); $date=date("Y.m.d"); $sql="INSERT INTO articles (title, image_link, text, date) VALUES ('$_POST[title]', '$final_file_name', '$_POST[text]', '$date')" if (mysql_query($sql)){ echo "done"; } else { echo "error&lt;br&gt;" . mysql_error(); } </code></pre> <p>And here is the problem:</p> <p>One of my friends told me that the PHP code in <code>add.php</code> is incorrect.</p> <p>This is working for me, but can someone correct the code please.</p> <h2>EDIT:</h2> <p>Thanks guys, I've corrected the code :</p> <pre><code>&lt;form enctype="multipart/form-data" method="post" action=""&gt; &lt;input name="title" type="text"&gt; &lt;input name="image" type="file"&gt; &lt;textarea name="text"&gt;&lt;/textarea&gt; &lt;input type="submit" name="go" value="Submit"&gt; &lt;/form&gt; </code></pre> <p> </p> <pre><code>&lt;?php if (isset($_POST['go'])){ include ("database.php"); $upload_path = "files/images/"; $prefix= date("Hi-mdY")."-"; $file_name = $_FILES['image']['name']; $file_name = str_replace(' ', '-', $file_name); $file_name = str_replace('_', '-', $file_name); $file_name = strtolower($file_name); $upload_path = $upload_path . basename($prefix.$file_name); move_uploaded_file($_FILES['image']['tmp_name'], $upload_path); $final_file_name = ("/files/images/".$prefix.$file_name); $title=$_POST['title']; $text=$_POST['text']; $date=date("Y.m.d"); $title = mysql_real_escape_string($title); $final_file_name = mysql_real_escape_string($final_file_name); $text = mysql_real_escape_string($text); $sql="INSERT INTO articles (title, image_link, text, date) VALUES ('$title', '$final_file_name', '$text', '$date')"; if (mysql_query($sql)){ echo "done"; } else { echo "error&lt;br&gt;" . mysql_error(); } } ?&gt; </code></pre> <p>Now it's good?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2010-12-27T15:57:21.727", "Id": "24601", "Score": "0", "body": "I would be able to upload a script and take over your server :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-06T12:06:17.370", "Id": "98994", "Score": "0", "body": "Use MySQLi as MySQL is deprecated http://www.php.net/manual/en/book.mysqli.php using prepared statements will also help secure your form http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php these type of forms are available for download if you google upload forms. You should also create a whitelist for file types allowed" } ]
[ { "body": "<p>There are quite few things to note in your code.</p>\n\n<p>First of all, you are using deprecated <code>$HTTP_POST_FILES</code> where as you should use <code>$_FILES</code></p>\n\n<p>You are not using <a href=\"http://php.net/manual/en/function.mysql-real-escape-string.php\"><code>mysql_real_escape_string</code></a> function in your query variables and therefore are vulnerable to <strong><a href=\"http://en.wikipedia.org/wiki/SQL_injection\">sql injection</a></strong> which is caused through poor sql queries.</p>\n\n<p>You are not checking whether or not the submit button was clicked, you should wrap your entire code in between:</p>\n\n<pre><code>if (isset($_POST['go'])){\n // your code\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2010-12-27T12:43:26.710", "Id": "24602", "Score": "0", "body": "just that is incorrect?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2010-12-27T12:50:18.060", "Id": "24603", "Score": "2", "body": "@user554943: It is correct otherwise and will work but you should also consider the points i have told above." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2010-12-27T12:34:46.217", "Id": "15173", "ParentId": "15172", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2010-12-27T12:31:00.850", "Id": "15172", "Score": "8", "Tags": [ "php", "network-file-transfer" ], "Title": "Bad code to handle image upload" }
15172
<p>I have a rather large class that needs to provide a reasonable amount of output for debugging purposes. I've done this with the following:</p> <pre><code>#if DEBUG Console.WriteLine("Source Site Set to: {0}", archiveQueueEntity.SourceSite); Console.WriteLine("Source List Set to: {0}", archiveQueueEntity.SourceUrl); Console.WriteLine("Destination Site Set to {0}", archiveQueueEntity.DestinationSite); Console.WriteLine("Destination List Set to: {0}", archiveQueueEntity.DestinationUrl); #endif </code></pre> <p>Is there a better way to do this though? </p> <p>After googling this I tried using <code>Debug.WriteLine</code> but it appears that this will only output to the 'output' window in Visual Studio, and not the console. </p> <p>Am I missing something?</p>
[]
[ { "body": "<p>I think it would be much cleaner to utilize partial methods to create your logging statements. That way you can log wherever you need it and can disable the code my omitting it the logging function definition. By using partial methods, if the definition is omitted, no IL is generated for the method and calls to the partial method are ignored as if it was never there.</p>\n\n<p>Just mark the class <code>partial</code>, define the signature of the partial method and call it like normal. Then wrap the actual implementation in the conditional compilation blocks.</p>\n\n<pre><code>partial class MyClass\n{\n // declare the partial method\n static partial void Log(string format, params object[] arguments);\n\n static void SomeMethod()\n {\n // call the log method like usual\n Log(\"Source Site Set to: {0}\", archiveQueueEntity.SourceSite);\n Log(\"Source List Set to: {0}\", archiveQueueEntity.SourceUrl);\n Log(\"Destination Site Set to {0}\", archiveQueueEntity.DestinationSite);\n Log(\"Destination List Set to: {0}\", archiveQueueEntity.DestinationUrl);\n }\n\n#if DEBUG\n static partial void Log(string format, params object[] arguments)\n {\n Console.WriteLine(format, arguments);\n }\n#endif\n}\n</code></pre>\n\n<p>Otherwise if you're not able to change it, you should still create a separate logging method and disable to actual printing in the method there. That way your method is called but does nothing.</p>\n\n<pre><code>static void Log(string format, params object[] arguments)\n{\n#if DEBUG\n Console.WriteLine(format, arguments);\n#endif\n}\n</code></pre>\n\n<p>Or alternatively, use the <a href=\"http://msdn.microsoft.com/en-us/library/36hhw2t6\"><code>Trace</code></a> class to do your logging. As long as you have no listeners registered, you will not see any of the logging messages. When debugging, add a <code>ConsoleTraceListener</code> to the <code>Listeners</code> collection.</p>\n\n<pre><code>#if DEBUG\n Trace.Listeners.Add(new ConsoleTraceListener());\n#endif\n\nTrace.WriteLine(\"Source Site Set to: {0}\", archiveQueueEntity.SourceSite);\nTrace.WriteLine(\"Source List Set to: {0}\", archiveQueueEntity.SourceUrl);\nTrace.WriteLine(\"Destination Site Set to {0}\", archiveQueueEntity.DestinationSite);\nTrace.WriteLine(\"Destination List Set to: {0}\", archiveQueueEntity.DestinationUrl);\n</code></pre>\n\n<p>Something that eluded me until now, use the <code>ConditionalAttribute</code> attribute on the log function for both cases to achieve the same effect.</p>\n\n<pre><code>[Conditional(\"DEBUG\")]\nstatic void Log(string format, params object[] arguments)\n{\n Console.WriteLine(format, arguments);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T11:44:28.690", "Id": "24608", "Score": "3", "body": "Even better, use `[Conditional(\"DEBUG\")]` on the `Log` method and you don't even need to have a `partial` class and a `partial` method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T13:16:47.103", "Id": "24617", "Score": "0", "body": "svick: Well, I think that Jeff Mercado thought about using partial to have the debugging-stuff in a different file. So you don't mix up \"real code\" with \"test code\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T13:54:15.640", "Id": "24620", "Score": "1", "body": "@svick: Ah, I keep forgetting about that one. Definitely nicer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T14:11:43.100", "Id": "24621", "Score": "1", "body": "@chiffre: That would still be possible whether it was a partial method or not, the class could still be made partial and the log function could be placed there regardless. I guess I'm just looking for excuses to use partial methods, there's not very many everyday uses for them." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T07:48:49.707", "Id": "15178", "ParentId": "15176", "Score": "17" } }, { "body": "<p>I would suggest something similar to the Trace option Jeff provided, with some differences:</p>\n\n<ol>\n<li>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.tracesource.aspx\" rel=\"nofollow\">TraceSource</a> instead. It is the suggested replacement for the Trace class.</li>\n<li>I would not use a compiler directive to switch the logging on and off. Omit the .Listeners.Add line (which also exists for TraceSource) entirely.</li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms229349.aspx\" rel=\"nofollow\">Utilize app.config files</a> to control whether or not the logging occurs and how it is output.</li>\n</ol>\n\n<p>This saves you from swapping out binaries to troubleshoot an issue, which can in rare cases impact whether a bug is reproduced. Instead, you drop a modified app.config file in and restart the program/service.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T18:09:34.003", "Id": "15245", "ParentId": "15176", "Score": "1" } }, { "body": "<p>Also take a look at a proper logging framework like NLog (my favorite, <a href=\"https://stackoverflow.com/questions/4091606/most-useful-nlog-configurations\">for these reasons</a> and more) or log4net.</p>\n\n<p>If you really want to get esoteric but automated with logging (and other cross-cutting concerns), read up on aspect-oriented programming (AOP). PostSharp is the leading product in that area for .NET (at least as far as I know).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-02T04:17:57.003", "Id": "15273", "ParentId": "15176", "Score": "4" } } ]
{ "AcceptedAnswerId": "15178", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T06:44:20.543", "Id": "15176", "Score": "14", "Tags": [ "c#" ], "Title": "Is there a cleaner way to add DEBUG comments?" }
15176
<p>I am using this code to insert and retrieve:</p> <pre><code>namespace Gridwebpart.VisualWebPart1 { public partial class VisualWebPart1UserControl : UserControl { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { SPWeb site = SPContext.Current.Web; SPList list = site.Lists["GridList"]; SPListItemCollection items = list.Items; DataTable dt = items.GetDataTable(); Gridnames.DataSource = dt; Gridnames.DataBind(); } } protected void btnSave_Click(object sender, EventArgs e) { SPWeb site = SPContext.Current.Web; SPList list = site.Lists["GridList"]; SPListItemCollection items = list.Items; //SPListItem item = list.GetItemById(1); SPListItem item = items.Add(); item["Title"] = txtName.Text; item["Description"] = txtDescription.Text; item["IS Sharepoint 2010 Developer"] = chkbox.Checked; item.Update(); site.AllowUnsafeUpdates = false; txtName.Text = ""; txtDescription.Text = ""; chkbox.Checked=false; items = list.Items; DataTable dt = items.GetDataTable(); Gridnames.DataSource = dt; Gridnames.DataBind(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T13:22:44.227", "Id": "24618", "Score": "0", "body": "Nope, looks like the textbook example to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T05:37:12.800", "Id": "24657", "Score": "0", "body": "what if i use updatelistitems sharepoint web service" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T07:45:36.287", "Id": "15177", "Score": "2", "Tags": [ "c#", "sharepoint" ], "Title": "Is there any better way to insert and retrieve data into SPList?" }
15177
<p>I'm a developer at a networking company that really has no peers that work above me that I can use for any sort of sounding board for my code, so it's just me. I was wondering if anyone would be willing to take a look at some of my code and just give me a few notes, bullet points, etc... on things that are wrong, things I should look into and so on. If anyone is interested please feel free to comment. </p> <p>I'm concerned with the JavaScript/jQuery. It seems very coupled and I was wondering if there are any better ways to accomplish the things that I'm doing with this code. </p> <p>Everything works, but I'm always sure there is room for improvement.</p> <pre><code>//Global networkInfo Object. var networkInfo = {}; $(function () { // Bind custom events $(networkInfo).bind('updateNetworkInfo', updateNetworkAddress); $(networkInfo).bind('updateNetworkRanges', updateNetworkRangeDropDowns); $(networkInfo).bind('selectNetworkRanges', selectNetworkRanges); // Set form validation $('form').validate({ messages: { tbSiteName: "This is an invalid site code" } }); </code></pre> <p>Add custom rule for site name. This rule has been a pain because this is a webforms application and the name of the input can't be controlled. </p> <pre><code> $('#tbSiteName').rules("add", { required: true, remote: function () { var r = { url: "/webservices/ipmws.asmx/SiteValid", type: "POST", data: "{'tbSiteName': '" + $('#tbSiteName').val() + "'}", dataType: "json", contentType: "application/json; charset=utf-8", dataFilter: function (data) { return (JSON.parse(data)).d; } } return r; } }); </code></pre> <p><code>DrillDownProvisioning.aspx</code> doesn't allow the user to change the Subnet mask. They should only be allowed to change this value by clicking on nodes in the <code>DrillDown Tree</code>.</p> <pre><code> $('#ddSubnetMask').change(function (e) { $(this).val(networkInfo.SubnetMask); $('#lblMessageBox') .removeClass('hidden') .addClass('error') .text("Please do not change this value manually"); }); // Populate drop down with all the available vlans. $.ajax({ type: 'POST', url: '/webservices/ipmws.asmx/GetVlans', data: '{}', dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) { $('#ddNumber').append($('&lt;option /&gt;').val("").text("")); $.each(data.d, function (index) { $('#ddNumber').append($('&lt;option /&gt;').val(this.VlanId).text(this.Number)); }); } }); // When a vlan number is change auto populate the standard name and description input fields with the predefined values $('#ddNumber').change(function () { var number = $(this); var standardName = $('#tbStandName'); var description = $('#tbDescription') if (number.val() === "") { standardName.val(""); description.val(""); } else { $.ajax({ type: 'POST', url: '/webservices/ipmws.asmx/GetVlanInfo', data: "{'number': " + $('#ddNumber').val() + "}", success: function (data) { standardName.val(data.d.StandardName); description.val(data.d.StandardName); standardName.valid(); description.valid(); }, dataType: 'json', contentType: 'application/json; charset=utf-8' }); } }); // Populate drop down populateSubnetMask(); // When the network type drop down is changed update the network ranges drop downs. $('#ddNetworkTypes').change(function () { $(networkInfo).trigger('selectNetworkRanges'); }); /* * toggle the 6 drop down menus. If the check box is not marked * reset all the values to empty so they don't post. */ $('#enableRange').change(function () { if (this.checked) { $(networkInfo).trigger('selectNetworkRanges'); } else { $('.mask').val(0); } $('#networkRangeSelectors').slideToggle(); }); /* * Open drill down tree for selection */ $('.open').click(function () { $('#drilldowntreecontainer').toggle('1000'); $(this).toggle(); }); // Close drill down tree $('.close').click(function () { $('#drilldowntreecontainer').toggle('1000'); $('.open').toggle(); }); </code></pre> <p>Because the page no longer posts back to itself the <code>document.referrer</code> should always be the previous page they visited from. If for some reason a post back is required this will no longer work.</p> <pre><code> $('#btnCancel').click(function (e) { e.preventDefault(); window.location.replace(document.referrer); }); }); /* * Populate the dropdown box with the default * range of 1 through 31 */ function populateSubnetMask() { var dropDown = $('#ddSubnetMask'); dropDown.append($('&lt;option /&gt;').val("").text("")); for (var i = 31; i &gt; 0; i--) { dropDown.append($('&lt;option /&gt;').val(i).text("/" + i)); } } </code></pre> <p>Fetches the predefinied subnet start and stop values from webservice. Populates select boxes with start to stop ranges to be selected.</p> <pre><code>function updateNetworkRangeDropDowns(e, network, bits) { $.ajax({ type: 'POST', url: '/webservices/ipmws.asmx/GetNetworkRanges', data: "{'network': '" + network + "', 'bits': " + bits + "}", success: function (data) { networkInfo.networkRanges = data.d; var html = "&lt;option value=''&gt;&lt;/option&gt;"; for (var i = data.d.Start; i &lt; data.d.End; i++) { html += "&lt;option value='" + i + "'&gt;" + i + "&lt;/option&gt;"; } $(".mask").empty().append(html); $(networkInfo).trigger('selectNetworkRanges'); }, dataType: 'json', contentType: 'application/json; charset=utf-8' }); } </code></pre> <p>Looks at the <code>networkInfo.networkRanges</code> object and selects the correct values in the drop down based on the values in the object. Should only select values if the network type is a <code>VLAN(type=9)</code>. Will reset all the values to empty if network type is not a <code>VLAN</code>.</p> <pre><code>function selectNetworkRanges() { if ($('#ddNetworkStart option').size() &gt; 0 &amp;&amp; $('#ddNetworkTypes').val() == 9) { $('#ddNetworkStart').val(this.networkRanges.NetworkStartSelected); $('#ddNetworkEnd').val(this.networkRanges.NetworkEndSelected); $('#ddFixedStart').val(this.networkRanges.FixedStartSelected); $('#ddFixedEnd').val(this.networkRanges.FixedEndSelected); $('#ddDHCPStart').val(this.networkRanges.DhcpStartSelected); $('#ddDHCPEnd').val(this.networkRanges.DhcpEndSelected); } else { $('.mask').val(0); } } </code></pre> <p>Custom event that updates the values in the form inputs for <code>SubnetAddress</code>/<code>SubnetMask</code> with the values in the <code>networkInfo</code> object. Because this function is bound as a custom event you can access the <code>networkInfo</code> object with <code>this</code></p> <pre><code>function updateNetworkAddress() { $('#tbSubnetAddress').val(this.SubnetAddress); $('#ddSubnetMask').val(this.SubnetMask); $('#lblMessageBox').addClass('hidden'); $('#tbSubnetAddress, #ddSubnetMask').valid(); } </code></pre> <p>This will only be required on the <code>drillDown</code> page, this gets the <code>subnet mask</code>/<code>address</code> from the <code>Radtree</code> on the left and inserts the values into the appropriate form <code>input</code>/<code>select</code> This gets called by <code>DrillDownProvisioning.aspx</code> in the <code>Radtree</code> <code>OnClientNodeClicked="drillDownNodeClick"</code></p> <pre><code>function drillDownNodeClick(sender, eventArgs) { var node = eventArgs.get_node(); var address = node.get_value().split("/"); networkInfo.SubnetAddress = address[0]; networkInfo.SubnetMask = address[1]; $(networkInfo).trigger('updateNetworkInfo'); $(networkInfo).trigger('updateNetworkRanges', [$('#tbSubnetAddress').val(), $('#ddSubnetMask').val()]); } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2010-12-27T15:55:04.973", "Id": "24612", "Score": "4", "body": "Your code looks very clean and your naming convention is pretty good. The only thing I would prefer to do is to make the code object oriented by using functions as objects. Otherwise, looking at the code without great networking knowledge, it looks very good." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2010-12-27T15:57:29.567", "Id": "24613", "Score": "0", "body": "Couple of questions: 1) Why put `populateSubnetMask` in to a JS function? I don't see any dependencies off-hand, so why not just hard-code the values? 2) That same control (ddSubnetMask), why not also just disable/readonly it?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2010-12-27T16:01:33.590", "Id": "24614", "Score": "0", "body": "@Brad Christie - 1.) Probably not necessary. 2.) I wasn't aware a select box could be set to readonly? If I set it to disable it wouldn't post back the values when you submit the form." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2010-12-27T16:06:23.970", "Id": "24615", "Score": "0", "body": "@KyleRogers: Touché, didn't think about it being a submitted value. And you're right, can't be \"readonly\" specifically, but more eluding to disabling the element. Everything looks good though from here, without having a live page to test how it plays out on. ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T21:31:39.057", "Id": "78833", "Score": "0", "body": "@KyleRogers, did you ever find a cleaner way to write your code? please post a self answer if you have." } ]
[ { "body": "<p>From perusing your code a few times:</p>\n\n<p><strong>Custom event abuse</strong></p>\n\n<p>While it's very cool to have custom events, I would simply remove this extra layer of logic. It does not make sense to call <code>$(networkInfo).trigger('selectNetworkRanges');</code> if you could just call <code>selectNetworkRanges()</code>. I understand that you would loose access to <code>this</code> but you are accessing <code>networkInfo</code> directly in <code>updateNetworkRangeDropDowns</code> anyway.</p>\n\n<p><strong>DRY (Don't Repeat Yourself)</strong></p>\n\n<ul>\n<li><p>In <code>selectNetworkRanges</code> you could do <code>var ranges = this.networkRanges;</code> and then access <code>ranges</code> instead of <code>this.networkRanges</code> every time</p></li>\n<li><p>You are building a dropdown in <code>populateSubnetMask</code> and in <code>updateNetworkRangeDropDowns</code> in a different way even though the functionality is very close. With some deep thoughts you could create a helper function that could build a dropdown for both <code>#ddSubnetMask</code> and <code>.mask</code></p></li>\n<li><p><code>$('.open').click</code> and <code>$('.close').click</code> do the same really, you could just do this:</p>\n\n<pre><code>$('.close,.open').click(function () {\n $('#drilldowntreecontainer').toggle('1000');\n $('.open').toggle();\n});\n</code></pre></li>\n</ul>\n\n<p><strong>What's in a name?</strong></p>\n\n<ul>\n<li><p>Please avoid short names like <code>r</code> , <code>d</code></p></li>\n<li><p>It is considered good practice to prefix jQuery results with $ so <code>var $dropDown = $('#ddSubnetMask');</code> for example</p></li>\n</ul>\n\n<p><strong>Style</strong></p>\n\n<ul>\n<li><p>Comma separated variables with a single <code>var</code> are considered better so</p>\n\n<pre><code>var node = eventArgs.get_node(),\n address = node.get_value().split(\"/\");\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>var node = eventArgs.get_node();\nvar address = node.get_value().split(\"/\");\n</code></pre></li>\n<li><p>You are using both double quotes and single quotes for your string constants, you should stick single quote string constants. With the possible exception of your <code>data:</code> statements.</p></li>\n</ul>\n\n<p><strong>Comments</strong> </p>\n\n<ul>\n<li><p>Great commenting in general, maybe a tad too verbose at times</p></li>\n<li><p>You should mention in the top that this code relies on the jQuery Validation Plugin, in fact it would have saved time if you mentioned that in your question ;)</p></li>\n</ul>\n\n<p><strong>Design</strong></p>\n\n<ul>\n<li><p><code>ddSubnetMask</code> could be set as <code>disabled</code>, you would need a hidden input that contains the actual value to be submitted as per <a href=\"https://stackoverflow.com/a/368834/7602\">https://stackoverflow.com/a/368834/7602</a></p></li>\n<li><p>The last few functions starting with <code>populateSubnetMask</code> are not within your <code>$(function () {</code>, I would keep it all together</p></li>\n</ul>\n\n<p><strong>Magic Numbers</strong></p>\n\n<ul>\n<li><p>You are commenting that VLAN(type=9), I would still advocate to create a <code>var IS_VLAN = 9</code> and then use that constant</p></li>\n<li><p>Not a magic number per se, <code>'application/json; charset=utf-8'</code> should be a properly named constant ( it's a DRY issue as well ).</p></li>\n</ul>\n\n<p><strong>Dancing in the rain</strong></p>\n\n<ul>\n<li>Your <code>$.ajax</code> calls should deal with <code>error</code>, it will happen at some point</li>\n</ul>\n\n<p>All in all, I could work with this code. You are correct that the code is tightly coupled. I think that's because of the data you have to work with, so I would not worry about it too much.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T02:05:57.880", "Id": "45277", "ParentId": "15182", "Score": "20" } } ]
{ "AcceptedAnswerId": "45277", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2010-12-27T15:43:51.290", "Id": "15182", "Score": "29", "Tags": [ "javascript", "jquery", "networking" ], "Title": "Managing network address information" }
15182
<p>So I have a view model (asp.net mcv 3 app) that when instantiated with a particular parameter, populates it's properties via a couple of calls to a web service in it's constructor. </p> <pre><code>public class QuizPreviewViewModel { private IQuizServiceWrapper _service; public string QuizName { get; set; } public List&lt;QuizQuestion&gt; QuizQuestions { get; set; } public List&lt;AnswerChoice&gt; AnswerChoices { get; set; } public int QuizId { get; set; } public QuizPreviewViewModel() { } public QuizPreviewViewModel(int quizId ) { _service = new QuizServiceWrapper(); var quiz = _service.GetQuizHeader(quizId); var questions = _service.GetQuizQuestionsByQuiz(quizId).OrderBy(x =&gt; x.Order).ToList(); QuizId = quizId; QuizName = quiz.QuizName; QuizQuestions = questions; } } </code></pre> <p>I know I could just as easily perform the population in the controller, or possibly extract the code to populate the properties into a separate method or helper class.</p> <p>I have read in various books/articles that both view models and controllers should be kept as clean as possible. So I'm wondering what you all think of populating the view model in it's constructor. Is this a decent practice, or a horrible idea? Where is the best place to populate the view model?</p>
[]
[ { "body": "<p>IMHO, you're asking the constructor to do too much work. To put it another way, the constructor has too many points of failure.</p>\n\n<ol>\n<li>You nicely set up <strong>_service</strong> to be a dependency-injectable interface; doesn't it make sense to follow that up by injecting a concrete instance into the constructor rather than having the constructor new-up the <strong>QuizServiceWrapper</strong> instance?</li>\n<li>What happens if the call to <strong>GetQuizHeader</strong> fails?</li>\n<li>Likewise for the call to <strong>GetQuizQuestionsByQuiz</strong>.</li>\n<li>More trivially, why bother with the variables <strong>quiz</strong> and <strong>questions</strong>? Why not just assign to the properties in the first place?</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T19:15:11.320", "Id": "24630", "Score": "0", "body": "#1--Good point! / #2 & #3--I have a try catch around the call to the constructor that exits the Action Method in the case of a fault / #4--another good point. Thanks for the feedback." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T19:06:41.597", "Id": "15190", "ParentId": "15188", "Score": "2" } }, { "body": "<p>Personally I try to keep the view models as close to DTO's as possible. That way you can have any number of objects populating the data from any number of sources. And, as you mentioned, it helps keep them lean and free of domain logic. </p>\n\n<p>If there was only one particular method of doing the transformation I might look at existing mapping solutions i.e. <a href=\"http://automapper.codeplex.com/\" rel=\"noreferrer\">AutoMapper</a>. Alternatively as you suggested I might create a separate builder class that was responsible for doing the building. </p>\n\n<p>The main problem I have with doing it your way (apart from those mentioned by Larry already) is that it tightly couples the ViewModel with your model. Re-using the viewModel in different contexts becomes harder.</p>\n\n<p>Also, if you were to to TDD, I might find it a bit strange writing a test like:</p>\n\n<pre><code>public void TestMyViewModel()\n{\n try\n {\n // Act\n var viewModel = QuizPreviewViewModel(1);\n\n // nothing to arrange???\n\n // Assert\n Assert.AreEqual(1, viewModel.QuizId);\n }\n catch(Exception ex)\n {\n Assert.Fail();\n } \n}\n</code></pre>\n\n<p>I think I would prefer something like:</p>\n\n<pre><code>public class QuizPreviewViewModelBuilder\n{\n private readonly IQuizServiceWrapper _service;\n\n public QuizPreviewViewModel(IQuizServiceWrapper service)\n {\n _service = service; \n }\n\n public QuizPreviewViewModel GetViewModel(int quizId)\n {\n var viewModel = new QuizPreviewViewModel(); \n var quiz = _service.GetQuizHeader(quizId);\n\n viewModel.QuizId = quizId;\n viewModel.QuizName = quiz.QuizName;\n viewModel.QuizQuestions = quiz.questions;\n\n return viewModel;\n }\n}\n</code></pre>\n\n<p>then your test class would look like:</p>\n\n<pre><code>public void TestMyViewModelBuilder()\n{\n // Act\n var mockService = // new mock service however this works\n var builder = QuizPreviewViewModelBuilder(mockService);\n\n // arrange\n var viewModel = builder.GetViewModel(1);\n\n // Assert\n Assert.AreEqual(1, viewModel.QuizId); \n}\n</code></pre>\n\n<p>Even this has a potential downside I guess in the fact that you have to have a bit of knowledge as to how to build up the service in order for the GetViewModel to work, so I'm not completely sold on that idea.</p>\n\n<p>Although this really just moves the logic of the building from the controller to another class I think it better allows for re-useability of the ViewModel while also providing a DRY approach to doing the actual building. </p>\n\n<p>Just a couple of different thoughts for you to mull over.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T20:44:27.087", "Id": "24632", "Score": "0", "body": "Nice feedback, thanks! Yes, I think I am leaning toward the idea of populating the view model in a separate helper class. That way both the view model and the controller stay lean. The only drawback that I see to this at the moment is the possibility of a 'class explosion' with the need to populate many view models. (Though I suppose one builder class could build multiple models...)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T21:25:13.257", "Id": "24635", "Score": "0", "body": "Yes, that can lean towards that which also might be needless complexity and like you say class explosion. I have heard good things about modules like AutoMapper but have never used them myself." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T20:32:05.200", "Id": "15194", "ParentId": "15188", "Score": "6" } }, { "body": "<p>I have no problem doing that in the Controller. Who else but the controller knows what to do when <code>_service.GetQuizHeader(quizId);</code> returns a null quiz? The controller can return a 404.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T21:13:13.030", "Id": "15195", "ParentId": "15188", "Score": "2" } } ]
{ "AcceptedAnswerId": "15194", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T17:39:31.827", "Id": "15188", "Score": "6", "Tags": [ "c#", "asp.net-mvc-3", "constructor" ], "Title": "Self populating view models" }
15188
<p>For logging purposes, I need to output a double[,] to the log file. So I need to represent the array as a string.</p> <p>The following code gets the job done using basic C# 1 features, but I was wondering if there is a more elegant solution using Linq:</p> <pre><code>private static string OneRowPerLine(double[,] numbers) { var ret = new StringBuilder(); for(var i=numbers.GetLowerBound(0);i&lt;=numbers.GetUpperBound(0);i++) { for (var j = numbers.GetLowerBound(1); j &lt;= numbers.GetUpperBound(1); j++) { if(j&gt;numbers.GetLowerBound(1)) { ret.Append(","); } ret.Append(numbers[i, j]); } ret.Append(Environment.NewLine); } return ret.ToString(); } </code></pre>
[]
[ { "body": "<p>First off, I think there may be bugs in your code. Specifically in the dimension parameters of some of the <code>GetLowerBound()</code> parameters. Based on a quick glance, it should be:</p>\n\n<pre><code>private static string OneRowPerLine(double[,] numbers)\n{\n var ret = new StringBuilder();\n for(var i=numbers.GetLowerBound(0);i&lt;=numbers.GetUpperBound(0);i++)\n {\n for (var j = numbers.GetLowerBound(1); j &lt;= numbers.GetUpperBound(1); j++)\n {\n if(j&gt;numbers.GetLowerBound(1))\n {\n ret.Append(\",\");\n }\n ret.Append(numbers[i, j]);\n }\n ret.Append(Environment.NewLine);\n }\n return ret.ToString();\n}\n</code></pre>\n\n<p>I'll update this answer in a moment with some enhancements, but wanted to get this bit out of the way.</p>\n\n<p><strong>EDIT: here's a pair of methods which will do it a little more generically and without LINQ.</strong> It does employ generics (<code>&lt;T&gt;</code>) and extension methods (<code>this</code>), one of which is an iterator (<code>yield return</code>):</p>\n\n<pre><code> private static string OneRowPerLine&lt;T&gt;(this T[,] numbers)\n {\n return string.Join(Environment.NewLine, numbers.FormatOneRow());\n }\n\n private static IEnumerable&lt;string&gt; FormatOneRow&lt;T&gt;(this T[,] numbers)\n {\n for (var i = numbers.GetLowerBound(0); i &lt;= numbers.GetUpperBound(0); i++)\n {\n var row = new T[numbers.GetLength(1)];\n\n for (var j = numbers.GetLowerBound(1); j &lt;= numbers.GetUpperBound(1); j++)\n {\n row[j] = numbers[i, j];\n }\n\n yield return string.Join(\",\", row);\n }\n }\n</code></pre>\n\n<p>call like this:</p>\n\n<pre><code> double[,] stuff = {{1,2}, {3,4}, {5,6}};\n Console.WriteLine(stuff.OneRowPerLine());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T20:47:25.677", "Id": "24633", "Score": "0", "body": "I have fixed the bugs in my code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T17:58:25.057", "Id": "24683", "Score": "0", "body": "It works for me." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T20:19:15.890", "Id": "15192", "ParentId": "15191", "Score": "5" } }, { "body": "<p>\"Better\"? I don't know. There is a <strong>different</strong> way to deal with this in LINQ. You can use <code>Cast&lt;T&gt;</code> to flatten an <code>IEnumerable</code> and the use <code>Aggregate</code> to generate a single string from all the elements in the enumerable. You can then \"group\" items by line depending on how far you are in the array. If you have a <code>double[,]</code>, you might do something like this:</p>\n\n<pre><code>var text = numbers.Cast&lt;double&gt;()\n .Aggregate(string.Empty, (s, i) =&gt;\n {\n if ((temp%(numbers.GetUpperBound(1) + 1)) == 0)\n {\n s = s + Environment.NewLine;\n }\n temp++;\n return s + i.ToString(CultureInfo.InvariantCulture) + \", \";\n });\n</code></pre>\n\n<p>If you like <code>StringBuilder</code> better:</p>\n\n<pre><code>var text = numbers.Cast&lt;double&gt;()\n .Aggregate(new StringBuilder, (s, i) =&gt;\n {\n if ((temp%(numbers.GetUpperBound(1) + 1)) == 0)\n {\n s.Append(Environment.NewLine);\n }\n temp++;\n return s.Append( i.ToString(CultureInfo.InvariantCulture)).Append(\", \");\n }).ToString();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T06:50:02.310", "Id": "24659", "Score": "2", "body": "I think the math here makes is non-obvious what the code actually does and whether it's correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T13:10:44.530", "Id": "24668", "Score": "0", "body": "Can you use a StringBuilder instead of a string in you solution?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T14:52:44.600", "Id": "24675", "Score": "0", "body": "@svick Hence my comment about \"different\"" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T21:16:41.777", "Id": "15196", "ParentId": "15191", "Score": "2" } } ]
{ "AcceptedAnswerId": "15192", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T20:05:34.403", "Id": "15191", "Score": "3", "Tags": [ "c#", "linq" ], "Title": "Is there a better way to convert two-dimentional array to string?" }
15191
<p>I am developing a webapp with Ruby on Rails to expand the features of <a href="http://mite.yo.lk" rel="nofollow">mite</a> (online time-tracking app) with the help of the offical mite API. Unfortuanaly, the API can't return all projects by a specific customer id. Because of that, i am developing a workaround.</p> <p>At first, i get all customers and save them in a hash. Then i iterate throug all projects and save each project object to a hash inside the customer hash. </p> <p>My code looks like this:</p> <pre><code>def index # Mite authentication Mite.account = '...' Mite.authenticate('...','...') # get all customers from Mite @customers = Hash.new Mite::Customer.all.each do |customer| @customers[customer.id] = {:name =&gt; customer.name, :projects =&gt; Hash.new} end # get all projects from Mite Mite::Project.all.each do |project| @customers[project.customer_id][:projects] = {:project =&gt; project} end end </code></pre> <p>Unfortuanaly, only the last project is saved in the ":projects" hash. But why? Adding customers works with this method too. In general, is this "the ruby way"? I'm very new to it :)</p>
[]
[ { "body": "<p>You should save projects in array or something like it, not hash. For example</p>\n\n<pre><code> Mite::Customer.all.each do |customer|\n @customers[customer.id] = {:name =&gt; customer.name, :projects =&gt; []} # !!!\n end\n\n Mite::Project.all.each do |project|\n @customers[project.customer_id][:projects] &lt;&lt; project # !!!\n end\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T14:14:41.607", "Id": "24672", "Score": "0", "body": "Thank you so much! :)\nBut can you explain WHY i have to use an array and not a hash?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T19:10:14.253", "Id": "24686", "Score": "0", "body": "Actually you can use and array and hash (but array imho more convenient in your case). When you use hash you need unique keys for every value (but now you use not unique key :project and every time update value for this key). So if you want to use hash you need write: @customers[project.customer_id][:projects][project.id] = project" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T09:04:38.723", "Id": "15206", "ParentId": "15193", "Score": "1" } } ]
{ "AcceptedAnswerId": "15206", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T20:20:06.573", "Id": "15193", "Score": "0", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "How to create associative hashs in Ruby (on Rails) dynamicly" }
15193
<p>Also, how would I go about putting my class in another file? Thanks!</p> <pre><code>#include &lt;iostream&gt; using std::cout; using std::endl; class Array { int *arrayPointer; public: Array(int size); ~Array(); int get(int index); void set(int index, int value); protected: int array[]; int size; }; Array::Array(int theSize){ size = theSize; arrayPointer = new int[size]; } Array::~Array(){ delete[] arrayPointer; } int Array::get(int index){ return *(arrayPointer + index); } void Array::set(int index, int value){ if(index &gt;= size || index &lt; 0){ cout &lt;&lt; "Ooops, index out of bounds" &lt;&lt; endl; } else{ *(arrayPointer + index) = value; } } /* Let's see it in action now! */ int main(){ int size = 3; Array array (size); array.set(0, 1); array.set(1, 2); array.set(2,3); cout &lt;&lt; "Index 0 = " &lt;&lt; array.get(0) &lt;&lt; endl; cout &lt;&lt; "Index 1 = " &lt;&lt; array.get(1) &lt;&lt; endl; cout &lt;&lt; "Index 2 = " &lt;&lt; array.get(2) &lt;&lt; endl; array.set(4, 3); array.set(-1, 2); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-05T21:38:17.927", "Id": "24906", "Score": "0", "body": "At least IMO, not very well, no. I wrote a rather [lengthy post](http://coderscentral.blogspot.com/2012/08/c-dynamic-arrays.html) about this recently." } ]
[ { "body": "<p>First of all, you have no copy constructor (or assignment operator). This will be a problem in this case:</p>\n\n<pre><code>void foo(Array a) {\n //...\n}\n\nint main() {\n Array a(10);\n foo(a);\n //a is still around, but the pointer has been destroyed.\n}\n</code></pre>\n\n<p>Since there will be two instances of Array using the same pointer. Once one of them goes out of scope, the destructor is called, so the delete[] happens. However, there is still <em>another</em> instance of Array with that same pointer, which has no way to know that delete happened. This is solved by following the \"<a href=\"https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three\">Rule of Three</a>\" See \"<a href=\"https://stackoverflow.com/q/255612/14065\">Dynamically allocating an array of objects</a> for a simple example.</p>\n\n<p>In second place, you have a member called <code>array</code>. What's it for? It's never used so why have it?</p>\n\n<p>In third place, some members are <code>protected</code>. Why? Does this mean you plan to have Array be inherited? In that case, you might want to make the destructor virtual. But I'd advise <em>against</em> inheritance, as it would feel counter-intuitive.</p>\n\n<p>The implementation of <code>get</code> and <code>set</code> use unnecessary pointer arithmetic.\nJust do:</p>\n\n<pre><code>return arrayPointer[index];\n</code></pre>\n\n<p>This does the same thing and it's much cleaner to look at.</p>\n\n<p>In fourth place, you do a check on the values of index for <code>set</code>, but not for <code>get</code>. Why not?</p>\n\n<p>In fifth place, index is a signed integer. You may want to consider using <code>size_t</code> instead. It will also make the <code>&lt; 0</code> check redundant.</p>\n\n<p>In sixth place, usage of <code>get</code> and <code>set</code> feels unnatural. You may want to look at <em>operator overloading</em>.</p>\n\n<p>In seventh place, I would not use <code>cout</code> for the error message. Use <code>assert()</code>, <code>cerr</code> or an exception, depending on what your exact needs are.</p>\n\n<p>In eighth place, you call it <code>Array</code> but you only allow integers to be stored. I'd either name it <code>IntArray</code> or make it a template to allow other types to be stored.</p>\n\n<p>As for \"Putting your class in another file\", that might be a good idea, especially if you want <code>Array</code> to be used in multiple files. Put it in a header file.</p>\n\n<p>Also, why create your own <code>Array</code> class? Is this for learning purposes? If not, you may want to use <code>std::array</code> or <code>std::vector</code> instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T23:03:18.957", "Id": "24636", "Score": "1", "body": "Very helpful! And yes it is for learning purposes, I just wanted to play around with pointer arithmetic and learn some basics of C++. My issue now is, how do I go about putting my class in a header file and linking it up.\n\nSo far what I understand is, the class definition goes in a .h file, but the actual implementation of functions go in another. I don't understand how to get that last part to work though . . ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T23:06:45.707", "Id": "24639", "Score": "0", "body": "@Breedly You could have an \"array.cpp\" and an \"array.h\". \"array.cpp\" would `#include \"array.h\"`. `class Array{ ... }` would go in the header, `Array::stuff` would go in the C++. Either that, or you could merge the whole thing in the header, with `class Array { Array(int theSize) { size = theSize; } ... }`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T22:33:52.453", "Id": "15198", "ParentId": "15197", "Score": "7" } }, { "body": "<p>Two quick things:</p>\n\n<hr>\n\n<p>Always make single variable constructors explicit (unless you actually want implicit construction, but you very rarely should).</p>\n\n<pre><code> void f(Array a) { }\n f(5); //&lt;-- runs fine. basically does Array(5). \n</code></pre>\n\n<hr>\n\n<p>Unless a class is specifically designed to handle output (a logging adapter, a formatter, etc), you shouldn't have output in a class.</p>\n\n<p>What if this Array class were to be used in a GUI based application? That <code>cout</code> would be useless then. luiscubal suggested either assert or <code>cerr</code>, but I would argue that you should either throw an exception or give the method a bool return and return a flag of whether or not it was set. (There's no particularly pleasant way to recover from a failed assert, and <code>cerr</code> has the same problem of putting output in a class that has no business doing output.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T23:01:32.657", "Id": "15199", "ParentId": "15197", "Score": "4" } } ]
{ "AcceptedAnswerId": "15198", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T22:18:47.347", "Id": "15197", "Score": "3", "Tags": [ "c++", "memory-management" ], "Title": "C++: Am I managing memory the right way?" }
15197
<p>How is this function?</p> <pre><code>/// &lt;summary&gt;Extension methods used by RedViewerLibrary.&lt;/summary&gt; internal static class Extensions { /// &lt;summary&gt;A string array extension method that gets the human readable enumerated version of the array.&lt;/summary&gt; /// &lt;param name="items"&gt;The strings to act on.&lt;/param&gt; /// &lt;returns&gt;A string containing the enumerated results.&lt;/returns&gt; /// &lt;example&gt;null =&gt; ""&lt;/example&gt; /// &lt;example&gt;{} =&gt; ""&lt;/example&gt; /// &lt;example&gt;{"foo"} =&gt; "foo"&lt;/example&gt; /// &lt;example&gt;{"foo", "bar"} =&gt; "foo, and bar"&lt;/example&gt; /// &lt;example&gt;{"foo", "bar", "baz"} =&gt; "foo, bar, and baz"&lt;/example&gt; internal static string GetEnumerated(this string[] items) { if (items == null || items.Length == 0) { return string.Empty; } else if (items.Length == 1) { return items[0]; } const string COMMA_SPACE = ", "; const string AND_STRING = "and "; var totalNamesLength = items.Aggregate(0, (oldValue, name) =&gt; name.Length + oldValue); var numberOfCommaSpaces = items.Length - 1; var commaSpacesLength = numberOfCommaSpaces * COMMA_SPACE.Length; var predictedLength = totalNamesLength + commaSpacesLength + AND_STRING.Length; var sb = new StringBuilder(predictedLength); int loopCount = items.Length - 1; sb.Append(items[0]); for (int idx = 1; idx != loopCount; ++idx) { sb.Append(COMMA_SPACE); sb.Append(items[idx]); } sb.Append(COMMA_SPACE); sb.Append(AND_STRING); sb.Append(items[items.Length - 1]); return sb.ToString(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T11:57:12.113", "Id": "24663", "Score": "3", "body": "Does this \"and\" make it human readable? A lot of code for what could be just `String.Join(\", \", array)`." } ]
[ { "body": "<p>It's ok. A bit hard to follow however since you're taking steps that really aren't necessary.</p>\n\n<ul>\n<li><p>It is not necessary to give the <code>StringBuilder</code> a starting capacity. Just let it do its business and you do yours, it will just work.</p>\n\n<p>However if you really wanted to do this, then that's not a problem. You can clean it up a bit. Rather than aggregating over the items when adding up all the lengths, just use <code>Sum()</code> instead.</p>\n\n<pre><code>var totalNamesLength = items.Sum(s =&gt; s.Length);\n</code></pre></li>\n<li><p>Don't really have much of a comment on the rest of your code. I'd be careful of using <code>==</code>/<code>!=</code> comparisons in a loop that goes over consecutive values, if the loop variable were to ever change in the body of the loop, you'll have a hell of a time trying to debug any problems you have with that. I'd stick to using <code>&lt;</code> (or appropriate operator) there exclusively.</p>\n\n<pre><code>for (int idx = 1; idx &lt; loopCount; ++idx)\n // ...\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>I'd write this differently however as this is much more readable to me and compact.</p>\n\n<pre><code>internal static string GetEnumerated(this string[] items)\n{\n if (items == null)\n return \"\";\n\n if (items.Length &lt;= 1)\n // concatenates all the (0 or 1) items into a single string\n return String.Concat(items);\n\n // place all but the last in a comma-separated string\n var commaSeparated = String.Join(\", \", items.Take(items.Length - 1));\n // include the last item\n return commaSeparated + \", and \" + items.Last();\n}\n</code></pre>\n\n<p>Since we know we are dealing with arrays, you won't be paying for much in terms of performance in the LINQ calls. If that bothers you, it is simple to write the equivalent without using LINQ.</p>\n\n<pre><code>internal static string GetEnumerated(this string[] items)\n{\n // I'd leave these in separate conditions\n // to make it clear they are separate cases\n if (items == null)\n return \"\";\n if (items.Length &lt;= 1)\n return String.Concat(items);\n\n var commaSeparated = String.Join(\", \", items, 0, items.Length - 1);\n return commaSeparated + \", and \" + items[items.Length - 1];\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T01:55:20.513", "Id": "15203", "ParentId": "15200", "Score": "8" } }, { "body": "<p>I'd make it a little more applicable than just to arrays (via <code>IEnumerable&lt;string&gt;</code>) and even further, use it with lists of all kinds as long as the <code>ToString()</code> gives a readable version:</p>\n\n<pre><code>/// &lt;summary&gt;Extension methods used by RedViewerLibrary.&lt;/summary&gt;\ninternal static class Extensions\n{\n /// &lt;summary&gt;A string array extension method that gets the human readable enumerated version of the array.&lt;/summary&gt;\n /// &lt;param name=\"items\"&gt;The strings to act on.&lt;/param&gt;\n /// &lt;returns&gt;A string containing the enumerated results.&lt;/returns&gt;\n /// &lt;example&gt;null =&gt; \"\"&lt;/example&gt;\n /// &lt;example&gt;{} =&gt; \"\"&lt;/example&gt;\n /// &lt;example&gt;{\"foo\"} =&gt; \"foo\"&lt;/example&gt;\n /// &lt;example&gt;{\"foo\", \"bar\"} =&gt; \"foo, and bar\"&lt;/example&gt;\n /// &lt;example&gt;{\"foo\", \"bar\", \"baz\"} =&gt; \"foo, bar, and baz\"&lt;/example&gt;\n internal static string GetEnumerated&lt;T&gt;(this IEnumerable&lt;T&gt; items)\n {\n if (items == null || !items.Any())\n {\n return string.Empty;\n }\n\n var count = items.Count();\n\n if (count == 1)\n {\n return items.First().ToString();\n }\n\n const string CommaSpace = \", \";\n const string AndString = \"and \";\n var sb = new StringBuilder();\n\n sb.Append(items.First());\n foreach(var item in items.Skip(1).Take(count - 2))\n {\n sb.Append(CommaSpace);\n sb.Append(item);\n }\n\n sb.Append(CommaSpace);\n sb.Append(AndString);\n sb.Append(items.Last());\n return sb.ToString();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-05T01:48:45.807", "Id": "181582", "Score": "0", "body": "The downside of doing this over the array version is that it allocates much more memory and will have much worse constant factors (`.Count()` is linear time, `n` virtual dispatches for `ToString` calls, allocations for enumerators and such). (using `IEnumerator<T>` directly helps but doesn't completely eliminate these factors)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-05T01:52:46.753", "Id": "181583", "Score": "0", "body": "Similar to http://ideone.com/z1l1oy" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-05T03:28:20.190", "Id": "181586", "Score": "0", "body": "`.Count()` is not necessarily linear time. It does a check to see if the underlying type implements `ICollection` or `ICollection<T>` (which arrays and lists do) and simply passes it along from the `.Count` property." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-05T04:11:03.610", "Id": "181593", "Score": "0", "body": "Sure, but with a large percentage of IEnumerables, ICollection isn't in use. Even simple things like \"foArray.Skip(2)\" fail that test." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-05T00:30:35.213", "Id": "99061", "ParentId": "15200", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T00:41:31.057", "Id": "15200", "Score": "0", "Tags": [ "c#", "array", "formatting" ], "Title": "Making a list human-readable" }
15200
<p>I'm writing a library which calls a RESTful API and then performs some work on the data.</p> <p>I've architected my code like this:</p> <p>I have a class (let's call it <code>APIRequestor</code>) that initiates a call to the API via an injected <code>HTTPRequestor</code> library (which basically wraps a <code>cURL</code> request). That class, after retrieving the response, will perform some operations on that data and then return an <code>APIResult</code> object to the caller.</p> <p>In order to test the <code>APIRequestor</code>, I created a <code>HTTPRequestorMock</code> which extends <code>HTTPRequestor</code> that, rather than wrapping a <code>cURL</code> request, it simply reads a result from a file I have on disk that way I can test different scenarios.</p> <p>Below is the code for the <code>APIRequestor</code> object:</p> <pre><code>&lt;?php namespace APITests; require_once "PHPUnit/Autoload.php"; require_once "../classes/APIRequestor.php"; require_once 'HTTPRequestorMock.php'; class APIRequestor extends \PHPUnit_Framework_TestCase { public function setUp() {} public function tearDown() {} public function getMockedRequestor() { $requestor = new \APIClasses\APIRequestor(); $requestor-&gt;HTTPLibrary = new HTTPRequestorMock(); return $requestor; } public function testResponseIDsNoResults() { $requestor = $this-&gt;getMockedRequestor(); $requestor-&gt;HTTPLibrary-&gt;overrideFilepath = "./mock_assets/ResponseIDsNoResults.xml"; $responseIDs = $requestor-&gt;getResponseIDsSinceResponseID(0); $this-&gt;assertTrue(count($responseIDs) === 0, "More than zero results returned."); } } </code></pre> <ol> <li>Is this a <em>good</em> design?</li> <li>Can I improve this design in order to make future additions more testable?</li> <li>Is this the common practice for removing a dependency on an external server for the sake of my unit tests?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T02:58:55.363", "Id": "24640", "Score": "1", "body": "\"I created a HTTPRequestorMock which extends HTTPRequestor\" --- why don't you use native `$this->getMock` phpunit thing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T03:00:36.427", "Id": "24641", "Score": "0", "body": "I could use that. I originally figured it'd be cleaner to just override the method in the subclass." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T03:01:26.530", "Id": "24642", "Score": "0", "body": "not sure about \"cleaner\" but for me it's much easier to see the test case and mock setup near, so I could understand what's happening without requirement to explore another class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T03:01:36.547", "Id": "24643", "Score": "0", "body": "While I applaud your good intentions in testing your code (and +1'd to show it), the \"is this a good design\" questions are generally more appropriate on programmers.stackexchange.com ... also, I agree with @zerkms that you're best served to learn and utilize the phpunit mocking capabilities. Tests are at least as much for others as they are for you -- and other people will immediately understand your tests if you use a common API. Maybe you could tweak your question a bit so it doesn't ask for qualitative evaluation?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T03:03:14.410", "Id": "24644", "Score": "0", "body": "Roger to the both of you. This is the feedback I need." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T03:03:59.913", "Id": "24645", "Score": "0", "body": "Also as a side note - I would create `setHttpLibrary()` setter instead of direct assignment" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T03:06:02.773", "Id": "24646", "Score": "0", "body": "Cool. So what about the `assertTrue` line? Is the error message clear enough? Is the logic clear?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T07:21:47.503", "Id": "24647", "Score": "0", "body": "@JesseBunch this is the right way to do APIs **unit** testing. However, you loose an important thing by mocking your calls, you can't detect regressions. I believe you should not **unit** test your APIs but use **functional** tests instead. The Symfony2 framework provides a [Client](http://symfony.com/doc/current/book/testing.html#working-with-the-test-client) you can use in your tests. Combining to data fixtures, it becomes really powerful and maintenance is easy. (this is my opinion)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T00:09:03.843", "Id": "24648", "Score": "0", "body": "@WilliamDURAND I was about to give a similar reply, but then I realized the OP is intending to unit test the part of his code that \"performs some work on the data\" from the RESTful API. Not testing the API itself. Of course, like you, I'd also support it with at least a couple of functional tests, to keep the mocks honest. (I.e. so you have something that breaks when the 3rd party changes their API.)" } ]
[ { "body": "<p>Yes, it looks like a reasonable design and approach.</p>\n\n<p>At the nit-pick level <code>getMockedRequestor</code> should be private or protected, to document that it is a helper for the tests. Also, if every test is going to be calling it, some people might move that code into setUp(). But that only saves one line (<code>$requestor = $this-&gt;getMockedRequestor();</code>) in each unit test, so I'd keep it where it is: I like to avoid using member variables, but that is personal preference.</p>\n\n<p>You could use the phpUnit mock interface, but you don't have to. It gives you some very useful things, such as when you say you expect a function to be called once with \"Hello World\":</p>\n\n<pre><code>$requestor-&gt;expects($this-&gt;once())\n -&gt;method('afunction')\n -&gt;with($this-&gt;equalTo('Hello World'));\n</code></pre>\n\n<p>Then it will not only complain if <code>afunction()</code> never gets called, but also if it gets called <em>twice</em>.</p>\n\n<p>But structure like this also brings restrictions. Have a poke around some of the phpunit mock questions on StackOverflow to see if you will hit them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T23:46:48.423", "Id": "24697", "Score": "0", "body": "Thanks for your help. I had already implemented some of the things you mentioned based on things mentioned on Stack Overflow so it was good to hear confirmation here." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T00:22:05.810", "Id": "15202", "ParentId": "15201", "Score": "4" } } ]
{ "AcceptedAnswerId": "15202", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-29T02:55:58.020", "Id": "15201", "Score": "5", "Tags": [ "php", "api", "unit-testing" ], "Title": "Unit testing code that calls RESTful API" }
15201
<p>I have tables that use BulkManager to save data to database. I moved common functionality to <code>BulkTableBase</code>. Because creation of <code>BulkManager</code> depends on params of each Table I create the <code>BulkManager</code> in .ctor of the Table. The <code>Add</code> method of each Table is also different.</p> <p>But I feel that calling <code>CreateBulkManager</code> method in .ctor is wrong! What if someone who derive from <code>BulkTableBase</code> would forget to call <code>CreateBulkManager</code>.</p> <p>Is my <code>BulkTableBase</code> class constructed well?</p> <pre><code>public class Table1 : BulkTableBase { public Table1(int param1, int param2) { _dt = new DataTable(); _dt.Columns.Add(new DataColumn("Id", typeof(int))); _dt.Columns.Add(new DataColumn("Name", typeof(int))); _config = ConfigurationManager.GetSection("Table1_Config"); CreateBulkManager(_dt, new Dictionary&lt;string, object&gt; { { "param1", param1 }, { "param2", param2 } }, _config); } public void Add(string name, int id) { var row = _dt.NewRow(); row["Name"] = name; row["Name"] = id; BulkManager.Add(row); } } public class Table2 : BulkTableBase { public Table2(int param3, string param4, byte param5) { _dt = new DataTable(); _dt.Columns.Add(new DataColumn("CustomerId", typeof(int))); _dt.Columns.Add(new DataColumn("Address", typeof(string))); _dt.Columns.Add(new DataColumn("Tel", typeof(string))); _config = ConfigurationManager.GetSection("Table2_Config"); CreateBulkManager(_dt, new Dictionary&lt;string, object&gt; { { "param3", param3 }, { "param4", param4 }, { "param5", param5 } }, _config); } public void Add(int customerId, string address, string tel) { var row = _dt.NewRow(); row["CustomerId"] = customerId; row["Address"] = address; row["Tel"] = tel; BulkManager.Add(row); } } public abstract class BulkTableBase : IDisposable { private SqlBulkManager _bulkManager; protected SqlBulkManager BulkManager { get { return _bulkManager; } } protected SqlBulkManagerBase CreateBulkManager(DataTable tableScheme, IDictionary&lt;string, object&gt; parameters, SqlBulkManagerConfig config) { var sqlParams = new List&lt;SqlParameter&gt;(); foreach (var param in parameters) { sqlParams.Add(new SqlParameter(param.Key, param.Value)); } _bulkManager = new SPSqlBulkManager(tableScheme, config, sqlParams); _bulkManager.Start(); } // wait until all data is saved public void SaveAll() { BulkManager.Flush(); } public void Dispose() { BulkManager.Stop(); } } public class SqlBulkManager { //... public SqlBulkManager(DataTable scheme, BulkManagerConfig config, IEnumerable&lt;SqlParameter&gt; extraParams) { } public void Add(DataRow item) { // add item to table and when number of rows reaches N the data is saved to DB } //... } </code></pre> <p><strong>UPDATED</strong></p> <p>I understand that I violate the Liskov substitution principle, but I wanted that eventually all bulks to be saved either exception occurred or not. Therefore, I needed <code>BulkTableBase</code>. So, I moved the code to <code>FileParser-&gt;HandleWork</code> method, creates <code>BulkTable</code> table there and pass to <code>Parse</code> method of the implemented parser.</p> <pre><code>public abstract class FileParser : MyThreadPool { protected sealed override void HandleWork() { // some common checking //... BulkTableBase bulkTable = CreateBulkTable(); try { OnBeforeParse(); Parse(bulkTable); OnAfterParse(); } catch(Exception ex) { ... } finally { //... if (bulkTable != null) { // The BulkManager may have many bulks that hasn't saved yet, so by // calling "SaveAll()" it waits untill all threads accomplished the saving bulkTable.SaveAll(); bulkTable.Dispose(); } } } protected abstract void Parse(BulkTableBase bulkTable, ...); protected abstract BulkTableBase CreateBulkTable(); } public class Parser1 : FileParser { protected override void Parse(BulkTableBase bulkTable, ...) { var table = (Table1)bulkTable; //... } protected override BulkTableBase CreateBulkTable() { return new Table1(...); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T14:15:05.803", "Id": "24673", "Score": "0", "body": "Why not use a factory to create the correct class instead?" } ]
[ { "body": "<p>Calling that function from sub-classes is not that bad, I think the problem is your classes are trying to do too much and are stepping on each others toes, so to speak. I'll touch on this as I go through this. </p>\n\n<p>You are doing too much in the constructors for the Table#. The constructor should be to setup the class only. I think adding a record right in the constructor is awkward, especially since you have an .Add() method. </p>\n\n<p>I also don't like that you are using ConfigurationManager within your class. That class / value should be injected.</p>\n\n<p>This would also require a change to the BulkManager class to remove the parameters variable:</p>\n\n<pre><code>public SqlBulkManager(DataTable scheme, BulkManagerConfig config)\n{\n // Assign as required\n}\n\n// -----\n\npublic Table1(SqlBulkManagerConfig config)\n{\n var dataTable = new DataTable();\n dataTable.Columns.Add(new DataColumn(\"Id\", typeof(int)));\n dataTable.Columns.Add(new DataColumn(\"Name\", typeof(int)));\n\n AssignBulkManager(new SqlBulkManager(dataTable, config));\n}\n\n// -----\n\npublic Table2(SqlBulkManagerConfig config)\n{ \n\n var dataTable = new DataTable();\n dataTable.Columns.Add(new DataColumn(\"CustomerId\", typeof(int)));\n dataTable.Columns.Add(new DataColumn(\"Address\", typeof(string)));\n dataTable.Columns.Add(new DataColumn(\"Tel\", typeof(string)));\n\n AssignBulkManager(new SqlBulkManager(dataTable, config));\n}\n</code></pre>\n\n<p>Having to create the DataRow in the add method on your tables is a code smell. You should just modify the parameters and pass off to the SqlBulkManager. This will allow the DataTable to be reference only in one class, SqlBulkManager. </p>\n\n<p>Add an AddToBulkManager method to BulkTableBase which accepts an IEnumerable>. The parameter should just be passed off to the SqlBulkManager.</p>\n\n<pre><code>protected void AddToBulkManager(IEnumerable&lt;KeyValuePair&lt;string, object&gt;&gt; item)\n{\n BulkManager.Add(item);\n}\n</code></pre>\n\n<p>You would have to change the signature of the Add function in SqlBulkManager to accept an IEnumerable>.</p>\n\n<pre><code>public void Add(IEnumerable&lt;KeyValuePair&lt;string, object&gt;&gt; item)\n{\n var row = _scheme.NewRow();\n\n // Do some error checking to make sure item is compatible\n\n foreach (var field in item)\n {\n row[field.Key] = field.Value;\n }\n\n // More Processing\n}\n</code></pre>\n\n<p>now your Add() method in Table1, and Table2 would be</p>\n\n<pre><code>// Table1\npublic void Add(string name, int id)\n{\n var parameters = new Dictionary&lt;string, object&gt; { { \"Id\", param1 }, { \"Name\", param2 } };\n\n AddToBulkManager(parameters);\n}\n\n// Table2\npublic void Add(int customerId, string address, string tel)\n{\n var parameters = new Dictionary&lt;string, object&gt; { { \"CustomerId\", customerId }, { \"Address\", address }, { \"Tel\", tel } };\n\n AddToBulkManager(parameters);\n}\n</code></pre>\n\n<p><strong>Important</strong></p>\n\n<p>Your Table# classes are a major violation of the Liskov Substitution Principle. Having the Add() method in each one accept different parameters means that Table1 could not be substituted for Table2, and vice versa.</p>\n\n<p>It would be better to remove the super class BulkTableBase from each one. Rename BulkTableBase to TableProcessor(or something that makes sense in your app). You will also have to remove the abstract from the declaration</p>\n\n<pre><code>public class TableProcessor : IDisposable\n</code></pre>\n\n<p>You could then either inject that class, or instantiate the class in your Table# classes</p>\n\n<pre><code>public class Table1\n{\n private readonly TableProcessor _tableProcessor;\n\n public Table1(SqlBulkManagerConfig config)\n {\n _tableProcessor = new TableProcessor();\n\n var dataTable = new DataTable();\n dataTable.Columns.Add(new DataColumn(\"Id\", typeof(int)));\n dataTable.Columns.Add(new DataColumn(\"Name\", typeof(int)));\n\n _tableProcessor.AssignBulkManager(new SqlBulkManager(dataTable, config));\n }\n</code></pre>\n\n<p>Or injected</p>\n\n<pre><code>public class Table2 : BulkTableBase\n{\n private readonly TableProcessor _tableProcessor;\n\n public Table2(TableProcessor tableProcessor, SqlBulkManagerConfig config)\n { \n\n _tableProcessor = tableProcessor;\n\n var dataTable = new DataTable();\n dataTable.Columns.Add(new DataColumn(\"CustomerId\", typeof(int)));\n dataTable.Columns.Add(new DataColumn(\"Address\", typeof(string)));\n dataTable.Columns.Add(new DataColumn(\"Tel\", typeof(string)));\n\n _tableProcessor.AssignBulkManager(new SqlBulkManager(dataTable, config));\n }\n</code></pre>\n\n<p>To wrap this up, here is the entire code base, I think it looks a lot cleaner and is much easier to follow:</p>\n\n<p>You might have to implement IDisposable in the Table# classes, without a full code base to test, I'm not sure how that will work.</p>\n\n<pre><code>public class Table1\n{\n private readonly TableProcessor _tableProcessor;\n\n public Table1(SqlBulkManagerConfig config)\n {\n _tableProcessor = new TableProcessor();\n\n var dataTable = new DataTable();\n dataTable.Columns.Add(new DataColumn(\"Id\", typeof(int)));\n dataTable.Columns.Add(new DataColumn(\"Name\", typeof(int)));\n\n _tableProcessor.AssignBulkManager(new SqlBulkManager(dataTable, config));\n }\n\n // wait until all data is saved\n public void SaveAll()\n {\n _tableProcessor.SaveAll();\n }\n\n public void Add(string name, int id)\n {\n var parameters = new Dictionary&lt;string, object&gt; { { \"Id\", param1 }, { \"Name\", param2 } };\n\n _tableProcessor.Add(parameters);\n }\n}\n\npublic class Table2\n{\n private readonly TableProcessor _tableProcessor;\n\n public Table2(TableProcessor tableProcessor, SqlBulkManagerConfig config)\n {\n _tableProcessor = tableProcessor;\n\n var dataTable = new DataTable();\n dataTable.Columns.Add(new DataColumn(\"CustomerId\", typeof(int)));\n dataTable.Columns.Add(new DataColumn(\"Address\", typeof(string)));\n dataTable.Columns.Add(new DataColumn(\"Tel\", typeof(string)));\n\n _tableProcessor.AssignBulkManager(new SqlBulkManager(dataTable, config));\n }\n\n // wait until all data is saved\n public void SaveAll()\n {\n _tableProcessor.SaveAll();\n }\n\n public void Add(int customerId, string address, string tel)\n {\n var parameters = new Dictionary&lt;string, object&gt; { { \"CustomerId\", customerId }, { \"Address\", address }, { \"Tel\", tel } };\n\n _tableProcessor.Add(parameters);\n }\n}\n\npublic class TableProcessor : IDisposable\n{\n private SqlBulkManager BulkManager { get; set; }\n\n public void AssignBulkManager(SqlBulkManager manager)\n {\n if (BulkManager != null &amp;&amp; BulkManager.IsStarted)\n {\n // Cleanup somehow\n }\n\n BulkManager = manager;\n BulkManager.Start();\n }\n\n public void Add(IEnumerable&lt;KeyValuePair&lt;string, object&gt;&gt; item)\n {\n BulkManager.Add(item);\n }\n\n // wait until all data is saved\n public void SaveAll()\n {\n BulkManager.Flush();\n }\n\n public void Dispose()\n {\n BulkManager.Stop();\n }\n}\n\npublic class SqlBulkManager\n{\n //...\n public SqlBulkManager(DataTable scheme, BulkManagerConfig config)\n {\n }\n\n public void Add(IEnumerable&lt;KeyValuePair&lt;string, object&gt;&gt; item)\n {\n var row = _scheme.NewRow();\n\n // Do some error checking to make sure item is compatible\n\n foreach (var field in item)\n {\n row[field.Key] = field.Value;\n }\n\n // More Processing\n }\n\n //...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T19:32:13.977", "Id": "24731", "Score": "0", "body": "If both Table1 and Table2 have to accept SqlBulkManagerConfig as parameter, pass that parameter to the base class i.e. Table1(SqlBulkManagerConfig config) : Base(config)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T19:59:37.267", "Id": "24733", "Score": "0", "body": "There are 2 problems with your suggestion 1) As noted, the base class should be eliminated because it causes a violation of the Liskov Substitution Principle. 2) The base class makes no use of the SqlBulkManagerConfig parameter. It is passed directly into the BulkManager class to be consumed there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-02T08:17:47.573", "Id": "24765", "Score": "0", "body": "@JeffVanzella, I updated my post and tried to explain the reason I used `BulkTableBase` at the first place. I'll appreciate your opinion about that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-02T19:09:58.907", "Id": "24780", "Score": "0", "body": "You could make BulkTableBase an interface that implements everything but the add method. The your CreateBulkTable could just return the interface? Or, you could include the Add() method and change the parameter to Type params object[]. The method body would then parse it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T18:26:01.223", "Id": "15247", "ParentId": "15207", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T08:44:47.313", "Id": "15207", "Score": "3", "Tags": [ "c#", "database", "classes", ".net-datatable" ], "Title": "Is my base class constructed correctly?" }
15207
<p>I have a time-based signal (Raw signal) sampled at 6 MHz and need to analyze it in freq. domain. I'm learning DSP and this is very first time I work with DSP. Could you please help to check if this code is correct or not. And I have couple of questions needed to be clarify:</p> <ol> <li><p>I've heard about linear scale and logarithm scale in order to observe the amplitude easier. Could you please explain to me, in this case, how can I get the logarithm scale?</p></li> <li><p>for some function in Matlab (for example fft, spectrogram, etc), how can I get the code (just in case I want to change something to adapt my need)?</p></li> </ol> <pre><code>input=V5k_a100; N=2048; L=4096; Fs=6e6; spectrumTemp=[]; for index=1:length(input)/L slice = input(1+(index-1)*L:index*L); abcd = hann(L) .* slice; NFFT = 2^nextpow2(N); spectrumTemp(index, :) = fft(abcd, NFFT)/L; end f = [0:NFFT-1]*Fs/NFFT; freq = f(1:length(f)/2); time = [0:length(input)/L-1]*L/Fs; spectrum = spectrumTemp(:, 1:length(f)/2); mesh(time,freq',abs(spectrum')); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T15:44:04.773", "Id": "31925", "Score": "0", "body": "If you want verification that the code is correct more information will be required. In particular encountered problems." } ]
[ { "body": "<ol>\n<li><p>The easy way to plot something with a logarithmic scale would be to just take the logarithm of the variable. </p>\n\n<p><code>logspectrum = log(spectrum);</code></p></li>\n<li><p>The source of some files is available when you type edit function name, example:</p>\n\n<p><code>edit unique</code></p></li>\n</ol>\n\n<p>However, not all Matlab source is available, so unfortunately you cannot customize everything this easily.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T15:42:57.703", "Id": "19972", "ParentId": "15208", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T13:49:26.527", "Id": "15208", "Score": "3", "Tags": [ "matlab", "signal-processing" ], "Title": "Calculate FFT from windowed time-based signal" }
15208
<p>I've written this code that I've been using for a while now to check for browser geolocation services for Google Maps applications. I have to say that I am not very happy with it as I've had to hack it quite a bit to work in IE9.</p> <p>Could I please get some critical assessment of the following and possible suggestions for an elegant solution? I need to stress that I do not want to use Modernizr or Gears. However, if there are good arguments, I'm willing to listen.</p> <p><strong>Notes</strong>: All the vars and functions in this script do pretty much as the function or var describes. All variables are declared as jQuery objects. <code>start()</code> launches Google Maps once the latitudes/longitudes are set.</p> <pre><code>function checkGeolocate() { return 'geolocation' in navigator; } if (checkGeolocate()) { // Note that the if condition does not start until the end of the // entire geolocation procedure. if(navigator.geolocation.getCurrentPosition(function(position) { userLat.val(position.coords.latitude); userLng.val(position.coords.longitude); userDist.val(25); start(); mapControls.fadeIn(200); mapOverlay.fadeOut(100); }, function(error) { console.log(error); displayPostcodeSelect(); }, { timeout : 5000, maximumAge : 90000, enableHighAccuracy : true })) { // Do nothing as script has started // This if clause is to force IE9 to error out // instead of hanging when geolocation throws a PERMISSION_DENIED error. } else { displayPostcodeSelect(); } } else { console.log('no geo support'); displayPostcodeSelect(); } </code></pre>
[]
[ { "body": "<p>A tricky question,</p>\n\n<p><code>navigator.geolocation.getCurrentPosition</code> will always return <code>undefined</code>, regardless of browser or whether or not the the user allowed the location to be retrieved.</p>\n\n<p>That means that <code>//Do nothing as script has started, This if clause is to force IE9 to error out instead of hanging when geolocation throws a PERMISSION_DENIED error.</code> sounds like a superstitious approach. I believe you that it works, but it's not because you provided an empty <code>if</code>.</p>\n\n<p>Also please read <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Geolocation.getCurrentPosition\">this</a>, if you must provide callbacks, then that means that <code>//Note that the if condition does not start until the end of the entire geolocation procedure.</code> is wrong.</p>\n\n<p>From the little code in your question, I believe you should always call <code>displayPostcodeSelect</code> first, and if there is a geoLocation success you trigger your function. This means you no longer need to catch failures anymore since you want <code>displayPostcodeSelect</code> in that case anyway.</p>\n\n<p>Furthermore, production code should not have <code>console.log</code>, it just looks bad.</p>\n\n<p>Finally, 1 liner function that are used only once do not make sense, you should inline the <code>checkGeolocate</code> function.</p>\n\n<p>All in all, I would counter propose: </p>\n\n<pre><code>//Start by showing the PostcodeSelect\ndisplayPostcodeSelect();\nif ('geolocation' in navigator) \n{\n var geoOptions =\n {\n timeout : 5000, //5 seconds\n maximumAge : 90000, //1.5 minutes\n enableHighAccuracy : true\n }; \n navigator.geolocation.getCurrentPosition(function(position) \n {\n userLat.val(position.coords.latitude);\n userLng.val(position.coords.longitude);\n userDist.val(25);\n\n start();\n\n mapControls.fadeIn(200);\n mapOverlay.fadeOut(100);\n }, function(){}, geoOptions );\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-23T11:15:45.763", "Id": "158639", "Score": "0", "body": "Apologies I haven't accepted this in such a long time." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T13:56:17.657", "Id": "40846", "ParentId": "15210", "Score": "5" } } ]
{ "AcceptedAnswerId": "40846", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T15:28:01.920", "Id": "15210", "Score": "5", "Tags": [ "javascript", "jquery", "html5", "google-maps" ], "Title": "Geolocation check and error management for Google Maps" }
15210
<p>I implemented a MVC Framework with Generic DAO and I would like know if is correct. I did not have developed yet the MySQLDAO.</p> <p>My controller class</p> <pre><code>class ClienteController { public function __construct() { } public function actionSubmit(){ $objCliente = new Cliente(); $objCliente-&gt;setNome($_POST['nome']); $objCliente-&gt;setCodigo($_POST['codigo']); $objCliente-&gt;getDAOFactory()-&gt;insert(); } } </code></pre> <p>DAO Class for client, persistence.</p> <pre><code>class ClienteDAO implements IRecord { const TABLE = 'cliente'; private $campos = array( "codigo" =&gt; "cliCod", "nome" =&gt; "cliNom" ); private $DAOFactory; public function __construct() { $this-&gt;DAOFactory = new DAOFactory($this); } public function getDAOFactory() { return $this-&gt;DAOFactory-&gt;getInstance(); } } </code></pre> <p>Model class</p> <pre><code>class Cliente extends ClienteDAO { private $codigo; private $nome; public function __construct(){ } public function getCodigo() { return $this-&gt;codigo; } public function setCodigo( $codigo ) { if ( $codigo &gt; 0 ) { $this-&gt;codigo = $codigo; } } public function getNome() { return $this-&gt;nome; } public function setNome( $nome ) { $this-&gt;nome = $nome; } } </code></pre> <p>Database class</p> <pre><code>class MySQLDao implements iDAO { public function insert() { } public function update() { } public function delete() { } public function limit() { } public function orderBy() { } public function findAll() { } public function addColumns() { } public function addGroupBy() { } public function addOrderBy() { } public function addHaving() { } public function addCustomizedHaving() { } public function addColumSubQuery() { } public function addAnd() { } public function addOr() { } public function checkExistanceColumn() { } } </code></pre> <p>Factory class</p> <pre><code>class DAOFactory { private $objeto; private $factory; public function __construct($obj, $banco = null) { $this-&gt;factory = $banco; $this-&gt;objeto = $obj; } public function getFactory() { return $this-&gt;factory; } public function setFactory($factory) { $this-&gt;factory = $factory; } public static function getInstance() { if ($this-&gt;getFactory() == null) { return new MySQLDAO($this-&gt;getObjeto()); } } public function getObjeto() { return $this-&gt;objeto; } } </code></pre> <p>Interfaces</p> <pre><code>interface IDAO { public function insert(); public function update(); public function delete(); public function limit(); public function orderBy(); public function findAll(); public function addColumns(); public function addGroupBy(); public function addOrderBy(); public function addHaving(); public function addCustomizedHaving(); public function addColumSubQuery(); public function addAnd(); public function addOr(); public function checkExistanceColumn(); } interface IRecord { public function getDAOFactory(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-17T08:32:09.180", "Id": "25495", "Score": "0", "body": "Welcome to Code Review! I'm not familiar with DAO, but I think that we need more explanation to understand what you want to do. Also, make sure your code works before submitting it here. Have a good day." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-11T16:04:45.237", "Id": "46836", "Score": "0", "body": "The Data Access Object pattern is described here. It is an abstraction above the database layer.\n\nhttp://www.oracle.com/technetwork/java/dataaccessobject-138824.html" } ]
[ { "body": "<p>I don't feel that this post really qualifies as an answer as I don't know enough about the main subjects in the OP's post, DAO and the factory pattern. I am unfamiliar with both, but there are a few things unrelated that I noticed and couldn't hurt to be pointed out. I would have just posted this as a comment, but it was too large.</p>\n\n<p>There is no need to declare a class constructor or inherited method unless you are actually going to do something with it. To clarify on the inherited method, you only need to redefine the method if you are adding or manipulating the data passed to it or returned by it. I only mention this last bit because of how frequently I see people trying to do this. It does not appear to be an issue here, just figured I'd cover it.</p>\n\n<p>You should not pass raw user input to your code. Sanitize and validate it. Check out PHP's <code>filter_input()</code> for a simple example.</p>\n\n<pre><code>$nome = filter_input( INPUT_POST, 'nome', FILTER_SANITIZE_STRING );\n//etc...\n\nif( ! $nome || ! $codigo ) {\n throw new Exception( 'Not enough information to process this request.' );\n}\n\n$objCliente-&gt;setNome( $nome );\n//etc...\n</code></pre>\n\n<p>The <code>$codigo</code> property in your <code>Cliente</code> class should be instantiated as an integer if you plan on comparing it to zero before allowing it to be set. Your current setter probably only works because of PHP's loose type conversion, but you shouldn't rely too heavily on that.</p>\n\n<p>Your <code>MySQLDao</code> class, if none of its methods are going to be defined, should be an abstract class or another interface. Probably another interface since all of the methods appear to be public and empty. Just remember, an interface <code>extends</code> another interface, not <code>implements</code> it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T19:18:05.330", "Id": "24687", "Score": "0", "body": "Thanks for answer, but this model is conceptual. I would like know \"if the concept is correct\". So, if is confused, please! I explain again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T19:08:02.307", "Id": "15213", "ParentId": "15211", "Score": "0" } }, { "body": "<p>Some recommendations:</p>\n\n<ul>\n<li><p>Instead of creating monolithic DAOs, you should split it in <a href=\"http://c2.com/cgi/wiki?DomainObject\" rel=\"nofollow noreferrer\">domain objects</a> and <a href=\"http://martinfowler.com/eaaCatalog/dataMapper.html\" rel=\"nofollow noreferrer\">data mappers</a>. This way you would separate the entity-specific business logic from storage.</p></li>\n<li><p>Do not ever use <a href=\"http://martinfowler.com/eaaCatalog/activeRecord.html\" rel=\"nofollow noreferrer\">active record</a> as default solution in any code. It has very specific and limited use-case, and when you exceed those limitation, your code becomes convoluted and hackish. Active records are good for two things: fast prototyping (creating temporary throw-away code) and implementation extremely simple domain entities with almost no business logic (glorified <a href=\"http://c2.com/cgi/wiki?ValueObject\" rel=\"nofollow noreferrer\">value objects</a> with hard-coded storage).</p></li>\n<li><p>Look into <a href=\"http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers\" rel=\"nofollow noreferrer\">use of PDO</a>. It should provide you with a bit more flexible storage infrastructure when dealing with SQL databases.</p></li>\n<li><p>You currently have domain business logic from model layer leaking in the controller. This is kinda bad. Controller should only change the state of model layer. It should not know how to create and save entities. You might benefit from reading <a href=\"https://stackoverflow.com/a/5864000/727208\">this answer</a>.</p></li>\n<li><p>Watch every lecture, that is listed <a href=\"https://stackoverflow.com/a/9855170/727208\">here</a>. Your code seems to suffer from tight and violations of Law of Demeter. You won't be able to understand everything, that is talked about, at first (at least , I didn't). If that happens, watch the listing till the end ad start again. Each time you will understand more of it.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T12:38:39.940", "Id": "24715", "Score": "0", "body": "Thanks teresko, I will follow your suggestions. Do you don't like of pattern DAO?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T13:41:36.610", "Id": "24716", "Score": "0", "body": "I have no problems with DAO pattern (as defined [here](http://wiki.lifetype.net/index.php/Data_Access_Object_(DAO)_classes) and [here](http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html)) as such. But you are not implementing DAO there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T14:05:38.460", "Id": "24729", "Score": "0", "body": "Is Generic DAO, why don't will be?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T23:45:26.197", "Id": "15223", "ParentId": "15211", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T16:43:36.647", "Id": "15211", "Score": "2", "Tags": [ "php", "object-oriented", "design-patterns" ], "Title": "Correct GenericDAO implementation?" }
15211
<p>I have files with over 100 million lines in each:</p> <blockquote> <pre><code>... 01-AUG-2012 02:29:44 important data 01-AUG-2012 02:29:44 important data 01-AUG-2012 02:36:02 important data some unimportant data blahblah (also unimportant data) some unimportant data 01-AUG-2012 02:40:15 important data some unimportant data ... </code></pre> </blockquote> <p>As you can see, there are important data (starting with date and time) and unimportant data. Also in each second, there can be many lines of important data.</p> <p>My goal is to count the number of "important data" in each second (or minute or hour...) and reformat date/time format. My script also lets me count data in each minute, hour etc using <code>options.dlen</code>:</p> <blockquote> <pre><code>options.dlen = 10 takes YYYY-MM-DDD options.dlen = 13 takes YYYY-MM-DDD HH options.dlen = 16 takes YYYY-MM-DDD HH:MM options.dlen = 20 takes YYYY-MM-DDD HH:MM:SS </code></pre> </blockquote> <p>I have written the following script (this is the main part - I skip all the file openings, parameters etc).</p> <pre><code>DATA = {} # search for DD-MMM-YYYY HH:MM:SS # e.g. "01-JUL-2012 02:29:36 important data" pattern = re.compile('^\d{2}-[A-Z]{3}-\d{4} \d{2}:\d{2}:\d{2} important data') DATA = defaultdict(int) i = 0 f = open(options.infilename, 'r') for line in f: if re.match(pattern, line): if options.verbose: i += 1 # print out every 1000 iterations if i % 1000 == 0: print str(i) + '\r', # converts data date/time format to YYYY-MM-DD HH:MM:SS format (but still keep it as datetime !) d = datetime.strptime( line [0:20], '%d-%b-%Y %H:%M:%S') # converts d, which is datetime to string again day_string = d.strftime('%Y-%m-%d %H:%M:%S') DATA [ str(day_string[0:int(options.dlen)]) ] += 1 f.close() #L2 = sorted(DATA.iteritems(), key=operator.itemgetter(1), reverse=True) #L2 = sorted(DATA.iteritems(), key=operator.itemgetter(1)) L2 = sorted(DATA.iteritems(), key=operator.itemgetter(0)) </code></pre> <p>It takes about 3 hours to process over 100 million lines. Can you suggest performance improvements for this script?</p> <p>Update: I have just used PyPy and the same task on the same server took 45 minutes. I will try to add profile statistics.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T08:44:35.590", "Id": "24688", "Score": "0", "body": "Without proper profiling we can only guess where the bottleneck is. Create a smaller test file (http://www.manpagez.com/man/1/head/) and run your script under [profiler](http://docs.python.org/library/profile.html)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T09:06:49.460", "Id": "24690", "Score": "0", "body": "Without knowing whether your program is CPU-bound or IO-bound, it's hard to say how to optimize this. You can tell with the `time(1)` command." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T18:21:13.463", "Id": "24691", "Score": "1", "body": "One way to quickly improve your script's time would be to trim down the number of lines it has to deal with - pipe your input file through something like `grep '^[0-9]'` before your script gets to it, so that you only process the lines that are important." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T09:02:21.913", "Id": "64518", "Score": "0", "body": "You can use **Python** [**Multiprocessing**](http://docs.python.org/library/multiprocessing.html) to process the lines concurrently" } ]
[ { "body": "<p>Use string operations instead of regular expression matching. RE uses a fully featured engine which is redundant in this situation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T08:51:19.117", "Id": "15215", "ParentId": "15214", "Score": "3" } }, { "body": "<pre><code>DATA = {}\n</code></pre>\n\n<p>Python convention is for ALL_CAPS to be reserved for constants</p>\n\n<pre><code># search for DD-MMM-YYYY HH:MM:SS\n# e.g. \"01-JUL-2012 02:29:36 important data\"\npattern = re.compile('^\\d{2}-[A-Z]{3}-\\d{4} \\d{2}:\\d{2}:\\d{2} important data')\n\nDATA = defaultdict(int)\ni = 0\nf = open(options.infilename, 'r')\n</code></pre>\n\n<p>I recommend using <code>with</code> to make sure the file is closed</p>\n\n<pre><code>for line in f:\n</code></pre>\n\n<p>You should put this loop in a function. Code inside a function runs faster then code at the top level</p>\n\n<pre><code> if re.match(pattern, line):\n</code></pre>\n\n<p>Do you really need a regular expression? From the file listing you gave maybe you should be checking <code>line[20:] == 'important data'</code></p>\n\n<p>Also, use <code>pattern.match(line)</code>, <code>re.match</code> works passing a precompiled pattern, but I've found that it has much worse performance.</p>\n\n<pre><code> if options.verbose:\n i += 1\n # print out every 1000 iterations\n if i % 1000 == 0:\n print str(i) + '\\r',\n\n\n\n\n # converts data date/time format to YYYY-MM-DD HH:MM:SS format (but still keep it as datetime !)\n d = datetime.strptime( line [0:20], '%d-%b-%Y %H:%M:%S')\n # converts d, which is datetime to string again\n day_string = d.strftime('%Y-%m-%d %H:%M:%S')\n DATA [ str(day_string[0:int(options.dlen)]) ] += 1\n</code></pre>\n\n<p>There's a good chance you might be better off storing the datetime object rather then the string. On the other hand, is the file already in sorted order? In that case all you need to do is check whether the time string has changed, and you can avoid storing things in a dictionary</p>\n\n<pre><code>f.close()\n#L2 = sorted(DATA.iteritems(), key=operator.itemgetter(1), reverse=True)\n#L2 = sorted(DATA.iteritems(), key=operator.itemgetter(1))\nL2 = sorted(DATA.iteritems(), key=operator.itemgetter(0))\n</code></pre>\n\n<p>If the incoming file is already sorted, you'll save a lot of time by maintaining that sort.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T11:49:21.287", "Id": "24712", "Score": "0", "body": "This code is in def main(): which is then run by if __name__ == \"__main__\":\n main()\nIs that what you say about putting inside function ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T12:20:56.453", "Id": "24713", "Score": "0", "body": "@przemol, yes that's what I mean by putting inside a function. If you've already done that: good." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T19:40:31.690", "Id": "15217", "ParentId": "15214", "Score": "4" } }, { "body": "<p>Here are a few ideas, none of them tested:</p>\n\n<ol>\n<li><p>Use a quick test to skip lines that can't possibly match the format.</p>\n\n<pre><code>if line[:2].isdigit():\n</code></pre></li>\n<li><p>Skip the regular expression entirely and let <code>strptime</code> raise an exception if the format isn't correct.</p></li>\n<li>Skip <code>strptime</code> and <code>strftime</code> and use the original date string directly in your dictionary. Use a second step to convert the strings before you sort, or use a custom sort key and retain the original format.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T19:43:28.160", "Id": "15218", "ParentId": "15214", "Score": "2" } }, { "body": "<h2>1. Make a test case</h2>\n\n<p>The first thing to do is to establish the existence of the performance problem, so let's knock up some test data.</p>\n\n<pre><code>def make_test_file(filename, n, t, delta):\n \"\"\"\n Write `n` lines of test data to `filename`, starting at `t` (a\n datetime object) and stepping by `delta` (a timedelta object) each\n line.\n \"\"\"\n with open(filename, 'w') as f:\n for _ in xrange(n):\n f.write(t.strftime('%d-%b-%Y %H:%M:%S ').upper())\n f.write('important data\\n')\n t += delta\n\n&gt;&gt;&gt; from datetime import datetime, timedelta\n&gt;&gt;&gt; make_test_file('data.txt', 10**5, datetime.now(), timedelta(seconds=1))\n</code></pre>\n\n<p>And then with the OP's code in the function <code>aggregate1(filename, dlen)</code>:</p>\n\n<pre><code>&gt;&gt;&gt; import timeit\n&gt;&gt;&gt; timeit.timeit(lambda:aggregate1('data.txt', 16), number = 1)\n5.786283016204834\n</code></pre>\n\n<p>So on the real file (1000 times bigger) that would take an hour and a half on my machine (or longer, if the time complexity is worse than linear). So yes, there's a real performance problem.</p>\n\n<h2>2. Clean up the code</h2>\n\n<p>Let's try a bunch of obvious minor improvements and optimizations (mostly as suggested in other answers):</p>\n\n<ol>\n<li><p>Convert <code>dlen</code> to an integer once (not every for every line).</p></li>\n<li><p>Write <code>day_string[:dlen]</code> instead of <code>str(day_string[0:dlen])</code>.</p></li>\n<li><p>Write <code>pattern.match(line)</code> instead of <code>re.match(pattern, line)</code>.</p></li>\n<li><p>There's no need for <code>key = operator.itemgetter(0)</code> because the sort will proceed on the first element of the pair in any case.</p></li>\n<li><p>Rename <code>DATA</code> as <code>count</code> and <code>day_string</code> with <code>s</code> (it's really a date-time string, not a day string).</p></li>\n<li><p>Use <code>with</code> to ensure that the file is closed in the event of an error.</p></li>\n<li><p>Import the name <code>strptime</code> so it doesn't have to be looked up for every line.</p></li>\n</ol>\n\n<p>Let's try that:</p>\n\n<pre><code>def aggregate2(filename, dlen):\n strptime = datetime.datetime.strptime\n dlen = int(dlen)\n pattern = re.compile(r'^\\d{2}-[A-Z]{3}-\\d{4} \\d{2}:\\d{2}:\\d{2} important data')\n count = defaultdict(int)\n with open(filename, 'r') as f:\n for line in f:\n if pattern.match(line):\n d = strptime(line[:20], '%d-%b-%Y %H:%M:%S')\n s = d.strftime('%Y-%m-%d %H:%M:%S')\n count[s[:dlen]] += 1\n return sorted(count.iteritems())\n\n&gt;&gt;&gt; timeit.timeit(lambda:aggregate2('data.txt', 10), number = 1)\n5.200263977050781\n</code></pre>\n\n<p>A small improvement, 10% or so, but clean code makes the next step easier.</p>\n\n<h2>3. Profile</h2>\n\n<pre><code>&gt;&gt;&gt; import cProfile\n&gt;&gt;&gt; cProfile.run(\"aggregate2('data.txt', 10)\")\n 2700009 function calls in 6.262 seconds\n\n Ordered by: standard name\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 6.262 6.262 &lt;string&gt;:1(&lt;module&gt;)\n 100000 0.088 0.000 1.020 0.000 _strptime.py:27(_getlang)\n 100000 2.098 0.000 4.033 0.000 _strptime.py:295(_strptime)\n 100000 0.393 0.000 0.642 0.000 locale.py:339(normalize)\n 100000 0.105 0.000 0.747 0.000 locale.py:407(_parse_localename)\n 100000 0.119 0.000 0.933 0.000 locale.py:506(getlocale)\n 100000 0.067 0.000 0.067 0.000 {_locale.setlocale}\n 100000 0.515 0.000 4.548 0.000 {built-in method strptime}\n 100000 0.079 0.000 0.079 0.000 {isinstance}\n 200000 0.035 0.000 0.035 0.000 {len}\n 100000 0.043 0.000 0.043 0.000 {method 'end' of '_sre.SRE_Match' objects}\n 300001 0.076 0.000 0.076 0.000 {method 'get' of 'dict' objects}\n 100000 0.276 0.000 0.276 0.000 {method 'groupdict' of '_sre.SRE_Match' objects}\n 100000 0.090 0.000 0.090 0.000 {method 'index' of 'list' objects}\n 100000 0.025 0.000 0.025 0.000 {method 'iterkeys' of 'dict' objects}\n 100000 0.046 0.000 0.046 0.000 {method 'lower' of 'str' objects}\n 200000 0.553 0.000 0.553 0.000 {method 'match' of '_sre.SRE_Pattern' objects}\n 100000 1.144 0.000 1.144 0.000 {method 'strftime' of 'datetime.date' objects}\n</code></pre>\n\n<p>I've cut some of the output for clarity. It should be clear that the culprits are <code>strptime</code> (73% of runtime), <code>strftime</code> (18%), and <code>match</code> (9%). Everything else is either called by one of those, or negligible.</p>\n\n<h2>4. Pluck the low-hanging fruit</h2>\n\n<p>We can avoid calling <em>both</em> <code>strptime</code> and <code>strftime</code> if we recognize that the only things we are achieving by calling these two functions are (a) to translate the months from names (<code>AUG</code>) to numbers (<code>08</code>), and (b) to reorder the components into ISO standard order. So let's do that ourselves:</p>\n\n<pre><code>def aggregate3(filename, dlen):\n dlen = int(dlen)\n months = dict(JAN = '01', FEB = '02', MAR = '03', APR = '04',\n MAY = '05', JUN = '06', JUL = '07', AUG = '08',\n SEP = '09', OCT = '10', NOV = '11', DEC = '12')\n pattern = re.compile(r'^(\\d{2})-([A-Z]{3})-(\\d{4}) (\\d{2}:\\d{2}:\\d{2}) '\n 'important data')\n count = defaultdict(int)\n with open(filename, 'r') as f:\n for line in f:\n m = pattern.match(line)\n if m:\n s = '{3}-{0}-{1} {4}'.format(months[m.group(2)], *m.groups())\n count[s[:dlen]] += 1\n return sorted(count.iteritems())\n\n&gt;&gt;&gt; timeit.timeit(lambda:aggregate3('data.txt', 10), number = 1)\n0.5073871612548828\n</code></pre>\n\n<p>There you go: a 90% speedup! That should get you down from three hours to 20 minutes or so. There are a few more things one might try (for example, doing the aggregations for all the different values of <code>dlen</code> in a single pass). But I think this is enough to be going on with.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-31T23:09:13.373", "Id": "15253", "ParentId": "15214", "Score": "11" } } ]
{ "AcceptedAnswerId": "15253", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-30T08:38:50.370", "Id": "15214", "Score": "12", "Tags": [ "python", "performance", "datetime", "regex" ], "Title": "Script for analyzing millions of lines" }
15214