body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I recently came up with the idea to attempt generating ungodly large prime numbers and their generators modulo N in php. I don't know much about number theory and just wanted to get some comments to see if this code should be sucessful. The output is just directed to a file at the moment because I didn't want to wast time on making it nice until I got the fundamentals right.</p> <pre><code>&lt;?php set_time_limit(150); #keeps us from reaching max execution so soon. Giant primes take time to find $bits = 32; #*32 for how many bits will be in the smaller prime, *64 for how many bits will be in larger prime $attempts = 300; #maximum number of trys to find a safe prime $prime_fail = true; for($i = 0; $i &lt; $attempts; $i++){ $prime = gmp_random($bits); #generate a large random number $prime = gmp_nextprime($prime); #find the next prime $safe_prime = gmp_add(gmp_mul($prime, 2), 1); #manufacture the bigger prime candidate so we can make sure it is indeed prime if( gmp_prob_prime($safe_prime) == 0 ){ $prime_fail = true; #set the pimality fail flag $safe_prime = NULL; #number was not prime for sure }else{ $prime_fail = false; #did not fail probable primality break; #no use going on, we found a safe prime } } if(!$prime_fail){ #we found the safe prime we were looking for so lets get the generator $generator_found = false; $g_upper_limit = 10; #this limits the highest value that g will be selected at, this method will always return the smalles g possible for convinience $onemod = gmp_intval(gmp_mod(1, $safe_prime)); #go ahead and calculate 1 % N just to make sure the math of the proceedure is clear. for($g = 1; $g &lt;= $g_upper_limit; $g++){ #For N where N is prime and N=2p+1 where p is prime #g is a generator mod N if #g^((N-1)/2) != 1 % N and g^((N-1)/p) != 1 % N #since N = 2p +1, N-1 = 2p #g^(2p/2) != 1 % N and g^(2p/p) != 1 % N #g^p != 1 % N and g^2 != 1 % N #remember that the = and != are congruent and not congruent #that means we need to use modulo exponentiation as congruency measeures if the remainder is the same between two operations if(gmp_intval(gmp_powm($g, $prime, $safe_prime)) != $onemod &amp;&amp; gmp_intval(gmp_powm($g, 2, $safe_prime)) != $onemod){ $generator_found = true; break; } } if(!$generator_found){ #failed to find generator die("&lt;h1 style='text-align: center;'&gt;failed to find generator modulo N. Please run setup again.&lt;/h1&gt;"); exit; } #we have both so lets do the setup $setupfile = "Prime.inc"; $safe_prime = gmp_strval($safe_prime, 16); $g = "$g\n"; @touch($setupfile) or die("&lt;h1 style='text-align: center;'&gt;Unable to create setup file at this time. Please rerun setup.&lt;/h1&gt;"); @$fh = fopen($setupfile, 'x') or die("&lt;h1 style='text-align: center;'&gt;Unable to write to setup file/setup file already exists.(Prime.inc)&lt;/h1&gt;"); @fwrite($fh, $g) or die("&lt;h1 style='text-align: center;'&gt;Unable to write generator to setup file.(Prime.inc)&lt;/h1&gt;"); @fwrite($fh, $safe_prime) or die("&lt;h1 style='text-align: center;'&gt;Unable to write prime to setup file.(Prime.inc)&lt;/h1&gt;"); @fclose($fh); echo "&lt;h1 style='text-align: center;'&gt;Prime.inc created and populated sucessfully.&lt;/h1&gt;"; }else{ #we did not find the safe prime we were looking for echo "&lt;h1 style='text-align: center;'&gt;Setup Unsuccessful&lt;/h1&gt;&lt;br /&gt;"; echo "&lt;p style='text-align: center;'&gt;Please Rerun Setup&lt;/p&gt;"; } exit; ?&gt; </code></pre>
[]
[ { "body": "<p>Instead of a global conditional operator is much more advantageous to use the boundary conditions</p>\n\n<p>For example:</p>\n\n<pre><code>if ($prime_fail){\n message_error(PRIME_FAIL);\n exit;\n}\n\n$generator_found = false;\n$g_upper_limit = 10; \n$onemod = gmp_intval(gmp_mod(1, $safe_prime));\n// ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T09:19:25.620", "Id": "2249", "ParentId": "2215", "Score": "3" } }, { "body": "<p>1, I'd extract out a custom <code>die</code> function:</p>\n\n<pre><code>function myDie($msg) {\n $prefix = \"&lt;h1 style='text-align: center;'&gt;\";\n $postfix = \"&lt;/h1&gt;\";\n die($prefix . $postfix . $msg);\n}\n</code></pre>\n\n<p>2, Maybe you should lock the <code>$setupfile</code>: <a href=\"https://stackoverflow.com/questions/293601/php-and-concurrent-file-access\">https://stackoverflow.com/questions/293601/php-and-concurrent-file-access</a></p>\n\n<p>3, The <code>exit</code> never runs, so it's unnecessary:</p>\n\n<pre><code>if(!$generator_found){\n #failed to find generator\n die(\"&lt;h1 style='text-align: center;'&gt;failed to ... Please run setup again.&lt;/h1&gt;\");\n exit; // remove it\n}\n</code></pre>\n\n<p>4, If you have a variable for the file name, use that variable in the error messages too:</p>\n\n<pre><code>$setupfile = \"Prime.inc\";\n...\n@$fh = fopen($setupfile, 'x') or myDie(\"Unable to ... (\" . $setupfile . \")\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-05T00:15:47.110", "Id": "6536", "ParentId": "2215", "Score": "3" } }, { "body": "<p>This is not worth an answer but as everything else as been said...</p>\n\n<p>You can make things a bit more concise in :</p>\n\n<pre><code>$prime_fail = true;\nfor($i = 0; $i &lt; $attempts; $i++){\n $prime = gmp_random($bits); # generate a large random number\n $prime = gmp_nextprime($prime); # find the next prime\n $safe_prime = gmp_add(gmp_mul($prime, 2), 1); # manufacture the bigger prime candidate so we can make sure it is indeed prime\n if( gmp_prob_prime($safe_prime) == 0 ){\n $prime_fail = true; # set the pimality fail flag\n $safe_prime = NULL; # number was not prime for sure\n }else{\n $prime_fail = false; # did not fail probable primality\n break; # no use going on, we found a safe prime\n }\n}\nif(!$prime_fail){\n</code></pre>\n\n<p>By :</p>\n\n<ul>\n<li><p>assigning to <code>$prime</code> the value you want it to have</p></li>\n<li><p>getting rid of <code>$prime_fail</code> as the value of <code>$safe_prime</code> should be enough.</p></li>\n</ul>\n\n<p>Result is :</p>\n\n<pre><code>for($i = 0; $i &lt; $attempts; $i++){\n $prime = gmp_nextprime(gmp_random($bits)); # find the prime after a large random number\n $safe_prime = gmp_add(gmp_mul($prime, 2), 1); # manufacture a bigger prime candidate\n if(gmp_prob_prime($safe_prime)){ # make sure it is indeed prime\n break; # no use going on, we found a safe prime\n }\n $safe_prime = NULL; #number was not prime for sure\n}\nif($safe_prime){\n</code></pre>\n\n<p>As for the maths, I wish I could check the validity but I have no background in that field.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-04T00:29:16.003", "Id": "24689", "ParentId": "2215", "Score": "2" } } ]
{ "AcceptedAnswerId": "6536", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-03T19:24:43.333", "Id": "2215", "Score": "8", "Tags": [ "php", "optimization", "primes" ], "Title": "Generating very large prime numbers and their generator modulo N in php" }
2215
<p>This is the first time I've written a start-stop-daemon script, so I would love some feedback. :) The goal is to have it start late, when the network and everything is ready. I also have 2 other start-stop-daemons that depend on this once being started before they launch and are nearly identical.</p> <pre><code>#! /bin/sh # chkconfig 345 85 60 # description: startup script for foo # processname: foo NAME=foo DIR=/etc/foo/services EXEC=foo.py PID_FILE=/var/run/foo.pid IEXE=/etc/init.d/foo RUN_AS=root ### BEGIN INIT INFO # Provides: foo # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 5 # Default-Stop: 0 1 2 3 6 # Description: Starts the foo service ### END INIT INFO if [ ! -f $DIR/$EXEC ] then echo "$DIR/$EXEC not found." exit fi case "$1" in start) echo -n "Starting $NAME" cd $DIR start-stop-daemon -d $DIR --start --background --pidfile $PID_FILE --make-pidfile --exec $EXEC --quiet echo "$NAME are now running." ;; stop) echo -n "Stopping $NAME" kill -TERM `cat $PID_FILE` rm $PID_FILE echo "$NAME." ;; force-reload|restart) $0 stop $0 start ;; *) echo "Use: /etc/init.d/$NAME {start|stop|restart|force-reload}" exit 1 ;; esac exit 0 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T05:05:49.137", "Id": "4377", "Score": "0", "body": "Awesome script. I see you activated the --background flag. In fact, this ties into my interest on this question (http://codereview.stackexchange.com/q/2841/4307). I plan on making a Daemon too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T05:30:02.880", "Id": "4378", "Score": "0", "body": "You might want to look on Ubuntu with the /etc/init.d/skeleton sample script, and then edit that. That way, you get the status command, etc." } ]
[ { "body": "<p>Probably, you also may implement <code>condrestart</code>:</p>\n\n<blockquote>\n <p>The condrestart (conditional restart) option only starts the daemon if it is currently running.\n This option is useful for scripts, because it does not start the daemon if it is not running.</p>\n</blockquote>\n\n<p>Quote from <a href=\"http://www.linuxquestions.org/questions/linux-general-1/condrestart-531071/\" rel=\"nofollow\">question about <code>condrestart</code> at LinuxQuestions</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T09:16:46.683", "Id": "2231", "ParentId": "2217", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-03T19:43:52.430", "Id": "2217", "Score": "5", "Tags": [ "bash" ], "Title": "Is this a decent way of writing a start-stop-daemon script?" }
2217
<p>I was trying to write a program that will read a collection of strings from the user, and then end the moment it encounters a <code>"."</code>. So then I write a <code>do</code>-<code>while</code> loop.</p> <p>I came across a something like this:</p> <pre><code>string temp; vector&lt;string&gt; params; do { cin &gt;&gt; temp; if (temp == ".") break; params.push_back(temp); } while (temp != "."); </code></pre> <p>I realized that no matter what, the loop will always end from within its body -- which is the <em>exact</em> result that <em>want</em>.</p> <p>But there something about piece of code that smells fishy. Are there any better ways?</p> <p>Another thing to note: I don't want the <code>"."</code> to be pushed onto the vector, hence that's why I added that little <code>if (temp == ".") break;</code> statement.</p>
[]
[ { "body": "<p>I prefer:</p>\n\n<pre><code>cin &gt;&gt; temp;\nwhile (temp != \".\")\n{\n params.push_back(temp);\n cin &gt;&gt; temp;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T00:36:49.633", "Id": "2221", "ParentId": "2220", "Score": "20" } }, { "body": "<pre><code>string temp;\nvector&lt;string&gt; params;\nwhile (true)\n{\n cin &gt;&gt; temp;\n if (temp == \".\")\n break;\n\n params.push_back(temp);\n\n}\n</code></pre>\n\n<p>That test - <code>true</code> in my case, <code>temp != \".\"</code> in yours, never really gets run, except when it's true. So it might as well be <code>true</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T03:14:20.533", "Id": "3573", "Score": "3", "body": "This would be my suggestion, with the modification of using for(;;) rather than do {} while(true); I prefer it to Michael K's answer because it doesn't repeat the \"body\" of the loop (cin>>temp) and is no slower (while still needs to execute a branch). If the \"body\" of the loop was more than one line, it would more clearly be code duplication." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T09:36:29.503", "Id": "3576", "Score": "4", "body": "I would suggest that `while(true)` (without `do`) would be clearer for intentions, even for less experienced programmers, than `for(;;)` or `do while(true)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T13:32:26.147", "Id": "3583", "Score": "0", "body": "Good call, @Hosam Aly; I have updated with your suggestion. Thanks!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T01:29:30.057", "Id": "2222", "ParentId": "2220", "Score": "9" } }, { "body": "<p>Don't forget to check the stream status for errors or EOF.</p>\n\n<pre><code>while (cin &gt;&gt; temp &amp;&amp; temp != \".\")\n{\n params.push_back(temp);\n}\n</code></pre>\n\n<hr>\n\n<p>EDIT: You do not necessarily need to invent your own break condition. There's one already — end of file. You can just read strings until you reach it. This way, your program will also work with non-interactive input nicely. To generate an end of file on a terminal, type Ctrl+D on Unix/Linux and Ctrl+Z on Windows.</p>\n\n<pre><code>while (cin &gt;&gt; temp)\n{\n params.push_back(temp);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T12:18:00.080", "Id": "3578", "Score": "2", "body": "Almost an extremely nice solution – it just lacks the {} which I strongly prefer to see even for one-line bodies." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T13:17:39.803", "Id": "3582", "Score": "1", "body": "@Christopher: This is a matter of personal style. I will nevertheless edit this answer for better clarity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T14:27:32.797", "Id": "3586", "Score": "0", "body": "Yes it is, and I didn't mean it any other way. (But note that some versions of gcc will flag such “missing braces” with `-Wall`, which really should be among the standard settings for any developer.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T02:40:20.797", "Id": "3607", "Score": "5", "body": "Almost an extremely nice solution -- it just has those ugly, completely unnecessary {} polluting and obfuscating otherwise nice code. :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-21T01:52:37.957", "Id": "17624", "Score": "0", "body": "@Christopher Which versions of GCC flag this? I always use `-Wall` (and more), never put the braces and have never seen this warning." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-22T18:33:01.067", "Id": "17655", "Score": "0", "body": "@Konrad: I am sorry, but I'm rather fuzzy in my memory there. I believe it involved cases with nested `if` statements some of which had an `else` clause. I did not mean to imply I had seen gcc flag all uses of `if` with an unadorned statement." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T07:13:32.160", "Id": "2227", "ParentId": "2220", "Score": "29" } }, { "body": "<p>If we are not talking about language-specific details then I would prefer something like this: </p>\n\n<pre><code>// this is inspired by LINQ and C#\nvar params = Enumerable.Generate&lt;string&gt;(() =&gt; {string temp; cin &gt;&gt; temp; return temp; })\n .TakeWhile(s =&gt; s != \".\")\n .ToVector();\n</code></pre>\n\n<p>Where Enumerable.Generate() is some lambda which reads data from <code>cin</code>. Generally answering the question 'how to use breaks?' I think breaks should not be used, at least not in such trivial scenarios.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T15:07:34.640", "Id": "3592", "Score": "2", "body": "I am not a fan of this particular syntax, but I like the methodology." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T11:13:31.360", "Id": "2232", "ParentId": "2220", "Score": "3" } }, { "body": "<p>I prefer to build some infrastructure that will make the rest of the code trivial. The infrastructure may be a little extra work, but the long-term savings can be substantial. In this case, it takes the form of a special iterator that allows you to specify the \"sentinel\" that will end the input. It acts like a normal <code>istream_iterator</code>, except that you specify the sentinel value when you construct the \"end of range\" iterator.</p>\n\n<pre><code>// sentinel_iterator.h\n#pragma once\n#if !defined(SENTINEL_ITERATOR_H_)\n#define SENTINEL_ITERATOR_H_\n#include &lt;istream&gt;\n#include &lt;iterator&gt;\n\ntemplate &lt;class T,\n class charT=char,\n class traits=std::char_traits&lt;charT&gt;,\n class distance = ptrdiff_t&gt;\n\nclass sentinel_iterator :\n public std::iterator&lt;std::input_iterator_tag,distance,void,void,void&gt;\n{\n std::basic_istream&lt;charT,traits&gt; *is;\n T value;\npublic:\n typedef charT char_type;\n typedef traits traits_type;\n typedef std::basic_istream&lt;charT,traits&gt; istream_type;\n\n sentinel_iterator(istream_type&amp; s)\n : is(&amp;s)\n { s &gt;&gt; value; }\n\n sentinel_iterator(T const &amp;s) : is(0), value(s) { }\n\n const T &amp;operator*() const { return value; }\n const T *operator-&gt;() const { return &amp;value; }\n\n sentinel_iterator &amp;operator++() {\n (*is)&gt;&gt;value;\n return *this;\n }\n\n sentinel_iterator &amp;operator++(int) {\n sentinel_iterator tmp = *this;\n (*is)&gt;&gt;value;\n return (tmp);\n }\n\n bool operator==(sentinel_iterator&lt;T,charT,traits,distance&gt; const &amp;x) {\n return value == x.value;\n }\n\n bool operator!=(sentinel_iterator&lt;T,charT,traits,distance&gt; const &amp;x) {\n return !(value == x.value);\n }\n};\n\n#endif \n</code></pre>\n\n<p>With that in place, reading the data becomes trivial:</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include \"sentinel_iterator.h\"\n\nint main() { \n // As per spec, read until a \".\" is entered:\n std::vector&lt;std::string&gt; strings(\n sentinel_iterator&lt;std::string&gt;(std::cin), \n sentinel_iterator&lt;std::string&gt;(\".\"));\n\n // It's not restricted to strings either. Read numbers until -1 is entered:\n std::vector&lt;int&gt; numbers(\n sentinel_iterator&lt;int&gt;(std::cin),\n sentinel_iterator&lt;int&gt;(-1));\n\n // show the strings:\n std::copy(strings.begin(), strings.end(),\n std::ostream_iterator&lt;std::string&gt;(std::cout, \"\\n\"));\n\n // show the numbers:\n std::copy(numbers.begin(), numbers.end(),\n std::ostream_iterator&lt;int&gt;(std::cout, \"\\n\"));\n return 0;\n}\n</code></pre>\n\n<p>Given an input of:</p>\n\n<pre><code>This is a string .\n1 2 3 5 -1\n</code></pre>\n\n<p>It produces an output of:</p>\n\n<pre><code>This\nis\na\nstring\n1\n2\n3\n5\n</code></pre>\n\n<p>It should work for essentially any type that defines a stream extractor and testing for equality (i.e., saying <code>x==y</code> will compile and produce meaningful results).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T09:36:31.370", "Id": "50039", "Score": "0", "body": "I like the idea (and +1). In contrast, `std::istream_iterator` is comparing stream pointers instead of read values. This has a small efficiency cost because both the constructor and `operator++` need an extra `if()` to see if the read has failed in order to null out the stream pointer. Your `sentinel_iterator` doesn't need that. Could you also use it to read from `std::cin` until a read fails?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T03:17:29.427", "Id": "2244", "ParentId": "2220", "Score": "5" } } ]
{ "AcceptedAnswerId": "2227", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T00:30:56.843", "Id": "2220", "Score": "24", "Tags": [ "c++" ], "Title": "Reading a collection of strings from the user" }
2220
<p>I have the task to create a function that adds some messages to the page and another to show them in last to first order with a jQuery <code>slideDown()</code> effect.</p> <p><a href="http://jsfiddle.net/WjaDE/5/" rel="nofollow noreferrer">jsFiddle</a></p> <pre><code>jQuery("#input1").click(function() { //Represents the first function to add the messages jQuery.each(["&lt;div&gt;1&lt;/div&gt;", "&lt;div&gt;2&lt;/div&gt;", "&lt;div&gt;3&lt;/div&gt;"], function(index, item) { var jDiv =jQuery(item); jDiv.hide(); jQuery(".parent").prepend(jDiv); }); //represents the second function to show them. var jParent = jQuery(".parent"); jParent.children().reverse().each(function() { var jThis= jQuery(this); jParent.queue( function() { jThis.slideDown(function() { jParent.dequeue(); }); }); }); }); </code></pre> <p>(reverse from <a href="https://stackoverflow.com/questions/1394020/jquery-each-backwards/5386150#5386150">this</a> answer)</p> <pre><code>jQuery.fn.reverse = [].reverse; </code></pre> <p>This seems to be an awful bunch of code just to show them one after another. Is there any way to clean up/remove redundant code?</p>
[]
[ { "body": "<p>I skipped the second button for simplicity's sake.</p>\n\n<p><a href=\"http://jsfiddle.net/WjaDE/7/\" rel=\"nofollow\">http://jsfiddle.net/WjaDE/7/</a></p>\n\n<pre><code>var jParent = $(\"#parent\"); \n// used an id for the unique element\n// cached the element up front\nvar DURATION = 500;\n\n$(\"#input1\").click(function() {\n $.each(['1', '2', '3'], // simplified the array\n function(index, item) {\n var jDiv = $('&lt;div class=box&gt;&lt;/div&gt;');\n // added a class to each to improve the css and eliminated the .hide()\n jDiv.html( item );\n jParent.prepend(jDiv);\n jDiv.delay(DURATION * index);\n // used a variable delay to deal with the timing\n jDiv.slideDown(DURATION);\n });\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T05:17:35.960", "Id": "3680", "Score": "0", "body": "The second button was from the jQuery site. I just had it there for testing earlier. The code was in separate sections as they are in different functions. They can't be combined together. But i do like the idea of a Delay." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-07T01:34:07.390", "Id": "2297", "ParentId": "2223", "Score": "1" } }, { "body": "<p>I would use function recursion in place of a jQuery queue.</p>\n<p>The central piece is the <code>displayNextHiddenMessagesIn</code> function. As the name implies, it grabs the next hidden message and displays it. After the message is displayed, it calls this function again... looping until all messages are visible.</p>\n<p>To me, this seems much more readable and easier to maintain. Also, it would be trivial to have a another message parent and reuse this same code (i.e. error messages and information messages).</p>\n<pre><code>(function($) {\n\n function createMessageFor(parent, contents) {\n var $parent = $(parent);\n \n for(var content in contents) {\n var $message = newMessage(contents[content]);\n \n $parent.prepend($message);\n }\n \n function newMessage(text) {\n return $(&quot;&lt;div /&gt;&quot;).text(text).hide();\n };\n }\n \n var displayNextHiddenMessagesIn = function(parent) {\n var $parent = $(parent);\n\n $parent.find('div:hidden:last').slideDown(function() {\n displayNextHiddenMessagesIn($parent); \n });\n };\n\n $(&quot;#input1&quot;).click(function()\n {\n createMessageFor('.parent', [1,2,3]);\n displayNextHiddenMessagesIn('.parent');\n });\n \n})(jQuery);\n</code></pre>\n<p>see it in action: <a href=\"http://jsfiddle.net/natedavisolds/TP66b/6/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/natedavisolds/TP66b/6/</a></p>\n<h3>Update</h3>\n<p>Here's what it looks like as a plugin:</p>\n<pre><code>(function($) {\n $.fn.fanDownHiddens = function() {\n return this.each(function() { \n var $parent = $(this);\n \n $parent.find('div:hidden:last').slideDown(function() {\n $parent.fanDownHiddens(); \n });\n });\n } \n})(jQuery);\n</code></pre>\n<p>And then the onload with the test data.</p>\n<pre><code>(function($) {\n \n $(function() {\n $(&quot;#input1&quot;).click(function() {\n setupTestMessages('.parent');\n $('.parent').fanDownHiddens();\n });\n });\n \n function setupTestMessages(parent) {\n var $parent = $(parent),\n testData = [1,2,3];\n \n for(var content in testData) {\n var $message = newMessage(testData[content]);\n \n $parent.prepend($message);\n }\n \n function newMessage(text) {\n return $(&quot;&lt;div /&gt;&quot;).text(text).hide();\n };\n }\n})(jQuery);\n</code></pre>\n<p>Here's the plugin working: <a href=\"http://jsfiddle.net/natedavisolds/TP66b/12/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/natedavisolds/TP66b/12/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T01:30:46.247", "Id": "15381", "Score": "0", "body": "That looks interesting but I'd like to note two things : 1. has message seems unnecessary. if `$nextMessage` is empty nothing will happen. 2. Doesn't seem any real different to mine except that it looks for the last hidden ... or did I miss something. I like that thought though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T01:32:03.157", "Id": "15382", "Score": "0", "body": "Also the function you've named `createMessageFor` is just a stub for another unrelated ajax method. I only added it to the question so people could see what I was getting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T03:00:04.703", "Id": "15383", "Score": "0", "body": "@JamesKhoury yep.. you are absolutely right. I missed that. I've corrected it above. The `find` is the main difference and not using queue. I wonder how this would look as a plugin." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T04:06:18.817", "Id": "15384", "Score": "0", "body": "@JamesKhoury I also added the plugin for review." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-02T14:23:48.653", "Id": "9636", "ParentId": "2223", "Score": "2" } } ]
{ "AcceptedAnswerId": "9636", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T03:17:43.620", "Id": "2223", "Score": "3", "Tags": [ "javascript", "jquery", "jquery-ui" ], "Title": "jQuery Delay slideDown using Queue" }
2223
<p>The question of the cleanest way to write a loop that executes some action between each iteration has always interested me.</p> <p>In a sense, what is the best way in c/c++ to implement this fictional construct:</p> <pre><code>for (...) { } between { } </code></pre> <p>Using such a construct you could trivially implement string join(): (pseudocode)</p> <pre><code>result = ""; foreach ( item : input ) { result += str(item); } between { result += sep; } </code></pre> <p>I have looked through some popular code libraries to see how these types of loops are implemented, and there are some common strategies:</p> <ul> <li>move the "between" code into an "if (!first/last iteration)" inside the loop. <ul> <li>This is the go-to method when the index/iterator/result freely stores the notion of first/last iteration (such as checks for values of 0, .empty(), NULL etc).</li> </ul></li> <li>transform the "loop body" into a function and call it from two places: before and during the loop, and change the loop to skip the first element. (minor code duplication) <ul> <li>This is the go-to method when the "loop body" <em>is</em> a single function call</li> </ul></li> </ul> <p>Neither of these is a completely generalized solution, and while its only a few lines + a state variable, I'm trying to find an ideal solution.</p> <p>Priorities:</p> <ul> <li>No needless source code duplication (but willing to accept binary code duplication)</li> <li>Efficiency</li> <li>Clear semantics</li> <li>Trivially usable (aka simple syntax, few library requirements)</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T05:27:45.983", "Id": "3574", "Score": "4", "body": "This seems more appropriate for Stack Overflow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T21:46:11.127", "Id": "3604", "Score": "0", "body": "Though it doesn't generalize all situations, for the specific example you give, I'd use an infix_iterator: http://stackoverflow.com/questions/3496982/printing-lists-with-commas-c/3497021#3497021. This is similar to your first option, except that the iterator and the iteration are separated from each other." } ]
[ { "body": "<p>The closest I've come to this in C or C++ is a slight modification to Knuth's <a href=\"http://www.google.com/search?q=%22loop+and+a+half%22\" rel=\"nofollow\">loop-and-a-half</a>:</p>\n\n<pre><code>template&lt;class T&gt;\nvoid print(std::vector&lt;T&gt; const &amp;x) {\n std::cout &lt;&lt; '[';\n typename std::vector&lt;T&gt;::const_iterator\n begin = x.begin(),\n end = x.end();\n if (begin != end) { // Duplicated condition to handle the empty case.\n while (true) { // Here is the \"loop and a half\".\n std::cout &lt;&lt; *begin;\n if (++begin == end) break;\n std::cout &lt;&lt; \", \";\n }\n }\n std::cout &lt;&lt; \"]\\n\";\n}\n</code></pre>\n\n<p>C++0x allows you to generalize:</p>\n\n<pre><code>template&lt;class Iter, class Body, class Between&gt;\nvoid foreach(Iter begin, Iter end, Body body, Between between) {\n if (begin != end) { // This duplication doesn't matter as it is\n // wrapped up in a library function.\n while (true) {\n body(*begin);\n if (++begin == end) break;\n between();\n }\n }\n}\n\ntemplate&lt;class T&gt;\nvoid print(std::vector&lt;T&gt; const &amp;x) {\n std::cout &lt;&lt; '[';\n foreach(x.begin(), x.end(),\n [](T const&amp; v) {\n std::cout &lt;&lt; v;\n // Long code here is still readable.\n },\n []{\n std::cout &lt;&lt; \", \";\n // Long code here is still readable.\n });\n std::cout &lt;&lt; \"]\\n\";\n}\n</code></pre>\n\n<p>Lambda capture even allows you to modify local variables in the function calling foreach.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T14:57:55.387", "Id": "3589", "Score": "0", "body": "I really like this solution, and like that you have provided a C++0x generalization (I am an avid user of C++0x though admittedly most are not). I would also add a Range overload to use c++0x range based for loop, and I would also add a version that accepts four lambdas \"check\" \"increment\" \"body\" \"between\". I am going to play with this solution today." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T05:26:19.840", "Id": "2226", "ParentId": "2225", "Score": "5" } }, { "body": "<p>Read about visitor pattern...</p>\n\n<p>For more complex object, sample:</p>\n\n<pre><code>template&lt;class T&gt;\nstruct Walker\n{\n Walker(Item *parent): m_parent(parent){}\n Walker(Item *parent, T const&amp; f): m_parent(parent), f(f){}\n // visit all elements\n Walker&amp; Walk()\n {\n TestClass::iterator it = parent-&gt;begin(), end = parent-&gt;end();\n for( ; it != end; ++it)\n {\n f.Visit(*it);\n }\n return *this;\n }\n // get visited result\n T const&amp; GetF()const { return f; }\nprivate:\n Walker&amp; operator = (Walker const&amp; rhs);\n Item* m_parent;\n T f;\n};\n</code></pre>\n\n<p>and define class, for example:</p>\n\n<pre><code>struct VisitorClass\n{\n void Visit(TestClass*){}\n};\n</code></pre>\n\n<p>after that use it:</p>\n\n<pre><code>Walker&lt;VisitorClass&gt; testVisit(this);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T15:00:58.970", "Id": "3590", "Score": "2", "body": "I don't think this answers the question.. and I very well know about the visitor pattern and don't think your implementation is very well done.." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T08:15:19.820", "Id": "2228", "ParentId": "2225", "Score": "-2" } } ]
{ "AcceptedAnswerId": "2226", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T04:41:34.090", "Id": "2225", "Score": "3", "Tags": [ "c++", "c" ], "Title": "Best syntax for executing an action between each loop iteration." }
2225
<p>I'm pretty new to Haskell and was playing around with some number manipulation in different bases when I had to write an integer logarithm function for my task.</p> <p>I don't mean discrete/modular logs, but simply <code>greatest x s/t b^x &lt;= n</code></p> <p>I developed a few versions and can't decide which I like best. Was hoping to hear what some of you think, or if you have other alternatives to suggest</p> <p>All have signature: <code>intlog :: (Integral a) =&gt; a -&gt; a -&gt; a</code></p> <pre><code>intlog :: (Integral a) =&gt; a -&gt; a -&gt; a intlog n b | n &lt; b = 0 | otherwise = succ (intlog (div n b) b) intlog' :: (Integral a) =&gt; a -&gt; a -&gt; a intlog' n b = maximum [i | i&lt;-[0..n], b^i &lt;= n] logg = log . fromIntegral intlog'' :: (Integral a) =&gt; a -&gt; a -&gt; a intlog'' intlog n b = floor $ logg n / logg b </code></pre> <p>The 'best' one relies on haskell's standard natural log function which I was hoping to avoid (as an exercise) and somewhat messy type conversion. Of the remaining two, one is probably fastest but seems nearly procedural in nature. The other feels very functional and 'haskelly' (looking for word analogous to pythonic, meaning in haskells best style) but i cant see it being too efficient unless there is really really good optimization under the hood.</p> <p>Would love to hear what you guys think.</p> <p>BTW - i know that for the second one, <code>intlog'</code> i could find a better upperbound than <code>n</code> but im looking for feedback and/or different way to code it. not incremental improvement like that</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-22T09:55:46.760", "Id": "393659", "Score": "0", "body": "I don't really know haskell, and so can't say which one is best, but `intlog''` is clearly the worst, as it will produce the wrong output! `log` returns floating point values, which aren't always exact - for example `3^5 == 243`, but `logg 243 / logg 3 == 4.999999999999999`, so `floor $ logg 243 / logg 3 == 4`, instead of the correct `5`. (And yes, `logBase 3 243` has the same problem)" } ]
[ { "body": "<p>The problem with your <code>intLog'</code> function is definitely that it goes through all <code>n</code> numbers in the list. As a result of this it takes ages for large <code>n</code> (for <code>n = 2^130</code> it ran until I killed it, while your other solutions all returned the result instantly).</p>\n\n<p>The reason that it has to go through all the numbers is of course that using a condition in a list comprehension is like using <code>filter</code> and does not make use of the fact that once the condition is false for the first time, it will always be false thereafter. What you should use instead is <code>takeWhile</code> which takes elements from the list while the condition is true and then stops the first time the condition is false. This way the code would look like this:</p>\n\n<pre><code>intlog n b = maximum $ takeWhile (\\i -&gt; b^i &lt;= n) [0..]\n</code></pre>\n\n<p>Since it will no longer go through the list to its end, we also no longer need to pick an upper bound and can just leave it off. This function will instantly return a result like the other solutions.</p>\n\n<hr>\n\n<p>Of course, except for learning purposes, the best solution is still to just use the built-in functionality with conversion as there is no point reinventing the wheel. Regarding that you should note that you can use the prelude function <code>logBase</code> instead of dividing the <code>log</code>s of <code>n</code> and <code>b</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T18:00:11.420", "Id": "3596", "Score": "1", "body": "hah i didnt even know about logBase. but thanks for suggesting the `takeWhile` that is exactly the kind of thing i was looking for. i liked that solution the best due to its conciseness except for the obvious efficiency problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T18:26:19.650", "Id": "3597", "Score": "0", "body": "also noticed `logBase` has arguments with other order, which makes sense since the base is the argument you'd more likely want to curry. i need to get in the habit of thinking like that when specifying argument order" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-22T10:00:39.657", "Id": "393660", "Score": "0", "body": "You are right that in most cases one should use the built-in functionality, but we're talking about an integer version of a floating-point function here; Using the built-in `log` or `logBase` with conversion in this case will give incorrect results! `log` and `logBase` both return floating point values, which aren't always exact - for example `3^5 == 243`, but `logg 243 / logg 3 == 4.999999999999999`, so `floor $ logg 243 / logg 3 == 4`, instead of the correct `5`. (And `logBase 3 243` gives the same result, too)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T17:47:31.057", "Id": "2235", "ParentId": "2233", "Score": "6" } } ]
{ "AcceptedAnswerId": "2235", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T15:06:19.783", "Id": "2233", "Score": "5", "Tags": [ "algorithm", "haskell" ], "Title": "Haskell - Different log methods" }
2233
<p>I have a WCF client which passes Self-Tracking Entities to a WPF application built with MVVM. The application itself has a dynamic interface. Users can select which objects they want visible in their Work area depending on what role they are in or what task they are doing.</p> <p>My self-tracking entities have quite a few Navigation Properties, and a lot of them are not needed. Since some of these objects can be quite large, I'd like to only load these properties on request.</p> <p>My application looks like this:</p> <p><code>[WCF] &lt;---&gt; [ClientSide Repository] &lt;---&gt; [ViewModel] &lt;---&gt; [View]</code></p> <p>My Models are Self-Tracking Entities. The Client-Side Repository hooks up a LazyLoad method (if needed) before returning the Model to the ViewModel that requested it. All WCF Service calls are asyncronous, which means the LazyLoad methods are also asyncronous.</p> <p>The actual implementation of the LazyLoad is giving me some trouble. Here are the options I have come up with. I apologize for the walls of text, they're options with code samples.</p> <p><strong>Option A</strong></p> <p>LazyLoad the Model's properties upon request in the Getter</p> <pre><code>[DataMember] public TrackableCollection&lt;ConsumerDocument&gt; ConsumerDocuments { get { if (_consumerDocuments == null &amp;&amp; !IsDeserializing &amp;&amp; !IsSerializing) { _consumerDocuments = new TrackableCollection&lt;ConsumerDocument&gt;(); _consumerDocuments.CollectionChanged += FixupConsumerDocuments; LoadConsumerDocuments(); } return _consumerDocuments; } set { /* Default T4 STE Set removed for space */ } } private async void LoadConsumerDocuments() { var obj = await LazyLoadData("ConsumerDocuments", new object[] { Ident }); if (obj != null &amp;&amp; obj is IEnumerable&lt;ConsumerDocument&gt;) { ConsumerDocuments.AddRange((IEnumerable&lt;ConsumerDocument&gt;)obj); } } </code></pre> <p><strong>Good:</strong> Loading data is so simple it's not worth mentioning. Creating a binding in your XAML loads the data when needed, and skips it when not. For example, <code>&lt;ItemsControl ItemsSource="{Binding CurrentConsumer.ConsumerDocuments}" /&gt;</code> will load the data, however if the Documents section of the interface is not there then nothing gets loaded.</p> <p><strong>Bad:</strong> Cannot use this property in any other code before it has been initiated because it will return an empty list. For example, the following call will always return false if documents have not been loaded.</p> <pre><code>public bool HasDocuments { get { return ConsumerDocuments.Count &gt; 0; } } </code></pre> <p><strong>OPTION B</strong></p> <p>Use the default GET for the property and manually make a call to load data when needed</p> <p><strong>Good:</strong> Can use these properties anywhere</p> <p><strong>Bad:</strong> Must remember to load the data before trying to access it. This might seem simple, but it can get out of hand quickly. For example, each ConsumerDocument has a UserCreated and UserLastModified. There is a DataTemplate that defines the UserModel with a ToolTip displaying additional User data such as extension, email, teams, roles, etc. So in my ViewModel that displays documents I would have to call <code>LoadDocuments</code>, then loop through them and call <code>LoadConsumerModified</code> and <code>LoadConsumerCreated</code>. Basically anything that is displayed in a UI binding needs to be Loaded first.</p> <p><strong>OPTION C</strong></p> <p>Create two ways to access the property. One for the binding, and one for any other code</p> <pre><code>// Properties used in Bindings [DataMember] public TrackableCollection&lt;ConsumerDocument&gt; ConsumerDocuments { get { if (_consumerDocuments == null &amp;&amp; !IsDeserializing &amp;&amp; !IsSerializing) { _consumerDocuments = new TrackableCollection&lt;ConsumerDocument&gt;(); _consumerDocuments.CollectionChanged += FixupConsumerDocuments; LoadConsumerDocuments(); } return _consumerDocuments; } set { /* Default T4 STE Set removed for space */ } } private async void LoadConsumerDocuments() { var consumerDocuments = await GetConsumerDocuments(); if (consumerDocuments != null) ConsumerDocuments.AddRange(await GetConsumerDocuments()); IsConsumerDocumentsLoaded = true; } // Method used for non-binding code calls public async Task&lt;TrackableCollection&lt;ConsumerDocument&gt;&gt; GetConsumerDocuments() { if (IsConsumerDocumentsLoaded) { return ConsumerDocuments; } else { // Do something like call Getter to initialize collection if (this.ConsumerDocuments == null) { } var obj = await LazyLoadData("ConsumerDocuments", new object[] { Ident }); if (obj != null &amp;&amp; obj is IEnumerable&lt;ConsumerDocument&gt;) { return new TrackableCollection&lt;ConsumerDocument&gt;((IEnumerable&lt;ConsumerDocument&gt;)obj); } } return null; } </code></pre> <p><strong>Good:</strong> Data is loaded asynchronously as needed - Exactly what I want.</p> <p><strong>Bad:</strong> Having two ways to access the same data seems inefficient and confusing. You'd need to remember when you should use <code>Consumer.GetConsumerDocuments()</code> instead of <code>Consumer.ConsumerDocuments</code> and vise versa. There is also the chance that the WCF Service call gets run multiple times.</p> <p><strong>OPTION D</strong></p> <p>Skip the Asyncronous loading and just load everything synchronously in the setters. </p> <p><strong>Good:</strong> Very simple, no extra work needed</p> <p><strong>Bad:</strong> Would lock the UI when data loads. Don't want this.</p> <p><strong>OPTION E</strong></p> <p>Have someone on SO tell me that there is another way to do this and point me to code samples :)</p> <p><strong>Other Notes</strong></p> <p>Some of the NavigationProperties will be loaded on the WCF server prior to returning the object to the client, however others are too expensive to do that with.</p> <p>With the exception of manually calling the Load events in Option C, these can all be done through the T4 template so there is very little coding for me to do. All I have to do is hook up the LazyLoad event in the client-side repository and point it to the right service calls.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T16:46:59.053", "Id": "3595", "Score": "2", "body": "Just passing right now but initially what I'll say immediately is _don't use properties that have side effects_, and if a **method** is asynchronous then explicitly mark it so by naming convention using `BeginX` or `XAsync`, you could even use `XTask` but that's a little weird when you think about it - decide on something and stick to it. Remember that while you might know this code intimately, your contemporary colleagues and/or successors and users might not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-03T06:44:24.153", "Id": "4331", "Score": "2", "body": "Forgive me if I am missing something critical here, but the WCF proxy types generated won't have any concept of navigational properties, or lazy loading. At the point of serialisation, those properties would be read and the resultant data passed to the client, no?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T21:08:42.080", "Id": "8273", "Score": "0", "body": "We are currently facing a performance problem in a Web application with STE over WCF and thinking about implementing Lazy Loading. As a matter of fact, I would like to know wich option you've picked up in the end and why ? Also, if you could provide a code snipett of your T4 template, it would be very helpfull." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T01:47:24.743", "Id": "8274", "Score": "0", "body": "I ended up creating two public properties for the lazy-loaded data: a Sync version and an Async version. They both reference the same private property, so no extra data was transferred to/from the WCF server. You can view the following SO answer for additional information: http://stackoverflow.com/questions/5875271/asynchronously-lazy-loading-navigation-properties-of-detached-self-tracking-enti/5955268#5955268 I'm not 100% happy with it, but the project I was using it on got cancelled shortly after, so I never got to revisit it and improve it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-19T01:48:41.153", "Id": "8275", "Score": "0", "body": "Also, I'm not sure I still have access to the T4 template, but what part of it were you interested in?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-30T14:50:01.960", "Id": "16710", "Score": "0", "body": "@Rachel shouldn't you link your SO answer as the answer to this question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-30T14:52:13.697", "Id": "16711", "Score": "0", "body": "@JoshuaDrake Sure, I actually forgot all about this question since I never got an answer here." } ]
[ { "body": "<p>I had <a href=\"https://stackoverflow.com/a/5955268/302677\">cross-posted this question on SO</a>, and got some good answers there. The answer I ended up going with was my own, although it was based on some of the other answers given to the SO question.</p>\n\n<p>Here's a copy of the answer I ended up going with:</p>\n\n<hr />\n\n<p>The solution I came up with was to modify the T4 template for the self-tracking entities to make the changes shown below. The actual implementation has been omitted to make this easier to read, but the property/method names should make it clear what everything does.</p>\n\n<p><strong>Old T4 Generated Navigation Properties</strong></p>\n\n<pre><code>[DataMember]\npublic MyClass MyProperty { get; set;}\n\nprivate MyClass _myProperty;\n</code></pre>\n\n<p><strong>New T4 Generated Navigation Properties</strong></p>\n\n<pre><code>[DataMember]\ninternal MyClass MyProperty {get; set;}\npublic MyClass MyPropertySync {get; set;}\npublic MyClass MyPropertyAsync {get; set;}\n\nprivate MyClass _myProperty;\nprivate bool _isMyPropertyLoaded;\n\nprivate async void LoadMyPropertyAsync();\nprivate async Task&lt;MyClass&gt; GetMyPropertyAsync();\nprivate MyClass GetMyPropertySync();\n</code></pre>\n\n<p>I created three copies of the property, which point to the same private property. The internal copy is for EF. I could probably get rid of it, but its easiest to just leave it in since EF expects a property by that name and its easier to leave it than to fix up EF to use a new property name. It is internal since I don't want anything outside of the class namespace to use it. </p>\n\n<p>The other two copies of the property run the exact same way once the value has been loaded, however they load the property differently.</p>\n\n<p>The Async version runs <code>LoadMyPropertyAsync()</code>, which simply runs <code>GetMyPropertyAsync()</code>. I needed two methods for this because I cannot put the <code>async</code> modifier on a getter, and I need to return a void if calling from a non-async method.</p>\n\n<p>The Sync version runs <code>GetMyPropertySync()</code> which in turn runs <code>GetMyPropertyAsync()</code> synchronously</p>\n\n<p>Since this is all T4-generated, I don't need to do a thing except hook up the async lazy load delegate when the entity is obtained from the WCF service. </p>\n\n<p>My bindings point to the Async version of the property and any other code points to the Sync version of the property and both work correctly without any extra coding.</p>\n\n<pre><code>&lt;ItemsControl ItemsSource=\"{Binding CurrentConsumer.DocumentsAsync}\" /&gt;\n\nCurrentConsumer.DocumentsSync.Clear();\n</code></pre>\n\n<hr />\n\n<p>As a side note, I wasn't thrilled with this solution once in place because I kept forgetting to add the <code>Sync</code>/<code>Async</code> suffix in the XAML, and would have preferred to have a single property name that does both, but I don't think that's possible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-30T14:56:50.360", "Id": "10495", "ParentId": "2234", "Score": "5" } } ]
{ "AcceptedAnswerId": "10495", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T15:42:33.317", "Id": "2234", "Score": "15", "Tags": [ "c#", "asynchronous", "entity-framework" ], "Title": "What is better for Lazy-Loading Navigation Properties of detached Self-Tracking Entities through a WCF service?" }
2234
<p>This is a follow-up to the <a href="https://codereview.stackexchange.com/questions/2211/what-would-be-a-good-way-refactor-this-interpreter-written-in-c">question that I posted earlier regarding my interpreter</a>.</p> <p>After a lot of help, I refactored my code and added more functionality to it. Now, it allows users to declare functions like so</p> <pre><code>func function_name param1 param2 param3 . / param3 * param1 param2 </code></pre> <p>or like this</p> <pre><code>func to_radians deg . * deg / 3.14159 180 </code></pre> <p>and also like this</p> <pre><code>func sind theta . sin to_radians theta </code></pre> <p>As you can see, you would use a period (&quot;<code>.</code>&quot;) to tell the interpreter to stop taking in parameters and start reading the body of the function.</p> <p>On top of that, it can read from source code.</p> <p>Here's an example of such a source code:</p> <pre><code>; Variables def PI * 4 atan 1 ; Functions func to_rad deg . * deg / PI 180 func sind theta . sin to_rad theta ; Run the program sin to_rad 45 sind 45 </code></pre> <p>Which will then output</p> <blockquote> <p><code>0.707107</code></p> <p><code>0.707107</code></p> </blockquote> <p>If you have ever programmed using a Lisp-like programming language -- such as scheme -- you would notice that there are a lot of similarities with what I made. In fact, it <em>was</em> inspired by those programming languages.</p> <hr> <p>Anyways, there's one limitation behind the code for the interpreter: when it encounters an error from within the user's source code, it's programmed to crash completely. That's not a problem. I did that on purpose. It's <em>one</em> way indicates to the user that there was an error.</p> <p>Now, I want to implement a more appropriate error handler. But, before I do that, I would like to ensure that my code is easier to maintain.</p> <p>I have a hunch that I should separate my code into multiple files. But that's just one, and even that I need help on how I should approach it.</p> <p>What would be your suggestion?</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;cmath&gt; #include &lt;cstdlib&gt; // mmocny: I needed to add this to use atof #include &lt;functional&gt; using namespace std; //---------------------------------- class Variable { public: Variable(const string&amp; name, double val) : name_(name), val_(val) // mmocny: Use initializer lists { } // mmocny: get_* syntax is less common in C++ than in java etc. const string&amp; name() const { return name_; } // mmocny: Don't mark as inline (they already are, and its premature optimization) double val() const { return val_; } // mmocny: Again, don't mark as inline private: string name_; // mmocny: suggest renaming name_ or _name: Easier to spot member variables in method code, and no naming conflicts with methods double val_; }; //---------------------------------- class Func { public: Func(const string&amp; name, const vector&lt;string&gt;&amp; params, const string&amp; instr) : name_(name), params_(params), instr_(instr) { } const string&amp; name() const { return name_; } const vector&lt;string&gt;&amp; params() const { return params_; } const string&amp; body() const { return instr_; } private: string name_; vector&lt;string&gt; params_; string instr_; }; //---------------------------------- // mmocny: Replace print_* methods with operator&lt;&lt; so that other (non cout) streams can be used. // mmocny: Alternatively, define to_string()/str() methods which can also be piped out to different streams std::ostream &amp; operator&lt;&lt;(std::ostream &amp; out, Variable const &amp; v) { return out &lt;&lt; v.name() &lt;&lt; &quot;, &quot; &lt;&lt; v.val() &lt;&lt; endl; } std::ostream &amp; operator&lt;&lt;(std::ostream &amp; out, Func const &amp; f) { out &lt;&lt; &quot;Name: &quot; &lt;&lt; f.name() &lt;&lt; endl &lt;&lt; &quot;Params: &quot; &lt;&lt; endl; for (vector&lt;string&gt;::const_iterator it = f.params().begin(), end = f.params().end(); it != end; ++it) { out &lt;&lt; &quot; &quot; &lt;&lt; *it &lt;&lt; endl; } cout &lt;&lt; endl; cout &lt;&lt; &quot;Body: &quot; &lt;&lt; f.body(); } std::ostream &amp; operator&lt;&lt;(std::ostream &amp; out, vector&lt;Variable&gt; const &amp; v) { for (vector&lt;Variable&gt;::const_iterator it = v.begin(), end = v.end(); it != end; ++it ) // mmocny: Use iterators rather than index access { out &lt;&lt; *it &lt;&lt; endl; } return out; } std::ostream &amp; operator&lt;&lt;(std::ostream &amp; out, vector&lt;Func&gt; const &amp; v) { for (vector&lt;Func&gt;::const_iterator it = v.begin(), end = v.end(); it != end; ++it) { out &lt;&lt; *it &lt;&lt; endl; } return out; } //---------------------------------- class Interpreter { public: const vector&lt;Variable&gt;&amp; variables() const { return variables_; } const vector&lt;Func&gt;&amp; functions() const { return functions_; } // mmocny: replace istringstream with istream // mmocny: you only need to predeclare this one function double operate(const string&amp; op, istream&amp; in, vector&lt;Variable&gt;&amp; v); double operate(const string&amp; op, istream&amp; in); double get_func_variable(const string&amp; op, istream&amp; in, vector&lt;Variable&gt; v) { // mmocny: instead of using a vector&lt;Variable&gt; you should be using a map/unordered_map&lt;string,double&gt; and doing a key lookup here for (int size = v.size(), i = size - 1; i &gt;= 0; i--) { if (op == v[i].name()) return v[i].val(); } for (int size = functions_.size(), i = 0; i &lt; size; i++) { if (op == functions_[i].name()) { vector&lt;Variable&gt; copy = v; vector&lt;Variable&gt; params; for (int size_p = functions_[i].params().size(), j = 0; j &lt; size_p; j++) { string temp; in &gt;&gt; temp; params.push_back(Variable(functions_[i].params()[j], operate(temp, in, v))); } /*for (vector&lt;string&gt;::const_iterator it = functions_[i].params().begin(), end = functions_[i].params().end(); it != end; ++it) { string temp; in &gt;&gt; temp; params.push_back(Variable(*it, operate(temp, in, v))); }*/ for (int size_p = params.size(), j = 0; j &lt; size_p; j++) { copy.push_back(params[j]); } /*for (vector&lt;Variable&gt;::const_iterator it = params.begin(), end = params.end(); it != end; ++it) { copy.push_back(*it); }*/ istringstream iss(functions_[i].body()); string temp; iss &gt;&gt; temp; return operate(temp, iss, copy); } } // mmocny: what do you do if you don't find the variable? int char_to_int = op[0]; cout &lt;&lt; char_to_int &lt;&lt; endl; cout &lt;&lt; &quot;'&quot; &lt;&lt; op &lt;&lt; &quot;' is not recognized.&quot; &lt;&lt; endl; throw std::exception(); // mmocny: You should do something better than throw a generic exception() } double get_func_variable(const string&amp; op, istream&amp; in) { return get_func_variable(op, in, variables_); } //---------------------------------- bool is_number(const string&amp; op) { // mmocny: someone else already mentioned: what if op is empty? int char_to_int = op[0]; // mmocny: couple notes here: // 1) chars are actually numbers you can reference directly, and not need &quot;magic&quot; constants // 2) functions in the form &quot;if (...) return true; else return false;&quot; should just be reduced to &quot;return (...);&quot; // 3) is_number functionality already exists in libc as isdigit() // 4) long term, you are probably going to want to improve this function.. what about negative numbers? numbers in the form .02? etc.. //return (char_to_int &gt;= '0' &amp;&amp; char_to_int &lt;= '9'); return isdigit(char_to_int); } //---------------------------------- template&lt; class Operator &gt; double perform_action(istream&amp; in, Operator op, vector&lt;Variable&gt;&amp; v) { string left; in &gt;&gt; left; double result = operate(left, in, v); // mmocny: This is a big one: for correctness, you must calculate result of left BEFORE you read right string right; in &gt;&gt; right; return op(result, operate(right, in, v)); } template&lt; class Operator &gt; double perform_action(istream&amp; in, Operator op) { return perform_action(in, op, variables_); } //---------------------------------- void define_new_var(istream&amp; in) { string name; in &gt;&gt; name; string temp; in &gt;&gt; temp; double value = operate(temp, in); variables_.push_back(Variable(name, value)); } //---------------------------------- void define_new_func(istream&amp; in) { string name; in &gt;&gt; name; string temp; vector&lt;string&gt; params; do { in &gt;&gt; temp; if (temp == &quot;.&quot;) break; params.push_back(temp); } while (temp != &quot;.&quot;); string body = &quot;&quot;; while (in &gt;&gt; temp) { body += temp + &quot; &quot;; } Func fu(name, params, body); functions_.push_back(fu); } private: vector&lt;Variable&gt; variables_; vector&lt;Func&gt; functions_; }; //---------------------------------- double Interpreter::operate(const string&amp; op, istream&amp; in, vector&lt;Variable&gt;&amp; v) { double value; if (op == &quot;+&quot;) value = perform_action(in, plus&lt;double&gt;(), v); else if (op == &quot;-&quot;) value = perform_action(in, minus&lt;double&gt;(), v); else if(op == &quot;*&quot;) value = perform_action(in, multiplies&lt;double&gt;(), v); else if (op == &quot;/&quot;) value = perform_action(in, divides&lt;double&gt;(), v); /*else if (op == &quot;%&quot;) value = perform_action(in, modulus&lt;double&gt;());*/ else if (op == &quot;sin&quot;) { string temp; in &gt;&gt; temp; value = sin(operate(temp, in, v)); } else if (op == &quot;cos&quot;) { string temp; in &gt;&gt; temp; value = cos(operate(temp, in, v)); } else if (op == &quot;tan&quot;) { string temp; in &gt;&gt; temp; value = tan(operate(temp, in, v)); } else if (op == &quot;asin&quot;) { string temp; in &gt;&gt; temp; value = asin(operate(temp, in, v)); } else if (op == &quot;acos&quot;) { string temp; in &gt;&gt; temp; value = acos(operate(temp, in, v)); } else if (op == &quot;atan&quot;) { string temp; in &gt;&gt; temp; value = atan(operate(temp, in, v)); } else if (is_number(op)) value = atof(op.c_str()); // mmocny: consider using boost::lexical_cast&lt;&gt;, or strtod (maybe) else value = get_func_variable(op, in, v); return value; } double Interpreter::operate(const string&amp; op, istream&amp; in) { return operate(op, in, variables_); } //---------------------------------- void run_code(Interpreter&amp; interpret, const string&amp; op, istream&amp; in) { if (op == &quot;def&quot;) interpret.define_new_var(in); else if (op == &quot;func&quot;) interpret.define_new_func(in); else if (op[0] == ';' || op.empty()) return; else cout &lt;&lt; endl &lt;&lt; interpret.operate(op, in) &lt;&lt; endl; } //---------------------------------- bool is_all_blank(const string&amp; line) { for (int i = 0; i &lt; line.size(); i++) { if (line[i] != ' ') return false; } return true; } //---------------------------------- int main() { cout &lt;&lt; endl &lt;&lt; &quot;LePN Programming Language&quot; &lt;&lt; endl; Interpreter interpret; while (cin) { cout &lt;&lt; endl &lt;&lt; &quot;&gt; &quot;; string temp; getline(cin, temp); if (temp.empty()) // mmocny: This also handles the case of CTRL+D continue; istringstream iss(temp); string op; iss &gt;&gt; op; if (op == &quot;quit&quot;) break; else if (op == &quot;show_vars&quot;) std::cout &lt;&lt; interpret.variables() &lt;&lt; std::endl; else if (op == &quot;show_func&quot;) std::cout &lt;&lt; interpret.functions() &lt;&lt; std::endl; else if (op == &quot;open&quot;) { string filename; if (iss) { iss &gt;&gt; filename; } else { cin &gt;&gt; filename; } ifstream file(filename.c_str()); while (file &amp;&amp; !file.eof()) { string line; getline(file, line); istringstream temp_stream(line); if (!temp_stream || is_all_blank(line)) { continue; } temp_stream &gt;&gt; op; int char_to_int = op[0]; run_code(interpret, op, temp_stream); } } else run_code(interpret, op, iss); } } </code></pre>
[]
[ { "body": "<ol>\n<li><p>Some of the previous recommendation haven't yet been resolved.</p></li>\n<li><p><code>double get_func_variable(const string&amp; op, istream&amp; in, vector&lt;Variable&gt; v)</code></p>\n\n<ul>\n<li>you generate exception in end of functions, which is ok, but where are you catching it?</li>\n<li><p>how about <code>std::find_if</code> for this:</p>\n\n<pre><code>for (int size = v.size(), i = size - 1; i &gt;= 0; i--)\n{ \n if (op == v[i].name())\n return v[i].val();\n}\n</code></pre></li>\n</ul></li>\n<li><p>For functions</p>\n\n<pre><code>void define_new_var(istream&amp; in)\n</code></pre>\n\n<p>\nand</p>\n\n<pre><code>void define_new_func(istream&amp; in)\n</code></pre>\n\n<p>check variable of functions for exist(using std::find_if, write common function).</p></li>\n<li><p>I think that the architecture will be expanded and may make sense to implement the command pattern and factory pattern:</p>\n\n<pre><code>double Interpreter::operate(const string&amp; op, istream&amp; in, vector&lt;Variable&gt;&amp; v)\n</code></pre></li>\n<li><p>Use <code>std::find_if</code> for finding some objects in vector or list.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T20:59:12.220", "Id": "2241", "ParentId": "2236", "Score": "3" } }, { "body": "<p>If you're going to get serious on this project, here are some questions worth considering:</p>\n\n<ol>\n<li>Are you using version control? We all have our preferences here but the important thing is you're using <em>something</em>. It gives you a way to hit 'UNDO' in case you make a big oopsie.</li>\n<li>Are there any unit tests? If you're currently not unit testing I would strongly suggest you start doing that now before your interpreter gets bigger. I like to use google test but there are many other C++ testing frameworks to choose from. Unit testing gives you a way to better control entropy in your project and this becomes more important as your project grows.</li>\n<li>Is the code well separated into different appropriate source files? Just like you wouldn't stuff every sentence into one gigantic paragraph in an essay, you don't want to stuff all your class, functions and variables into one source. In C++ it's customary to put each defined class in its own respective header(.h) and implementation(.cpp) file.</li>\n</ol>\n\n<p>Now some specific comments regarding your presented code:</p>\n\n<ul>\n<li>There is no clear separation between the lexing stage, parsing stage and processing in your design which is the usual expected approach when writing a translator, compiler or interpreter etc. It seems like these stages are mixed in together in an ad-hoc fashion inside your interpreter class. This coupling and lack of clear separation in your code will make it harder to maintain later when you add more stuff to it.</li>\n<li>Typedef'ing <code>std::vector</code> usage to make it more container-agnostic. If you decide to change <code>std::vector</code> to a <code>std::map</code> later on you won't have to change it all over the place. Also consider using <code>std::back_insert_iterator</code> instead of directly <code>std::vector::push_back</code> to make it even more container-agnostic.</li>\n<li><p>This function can be expressed more directly:</p>\n\n<pre><code>bool is_all_blank(const string&amp; line)\n{\n // Shouldn't it check for other possible whitespace too? Like tab for example\n return line.find_first_not_of( \" \\t\" ) == string::npos;\n}\n</code></pre></li>\n<li><p>While skimming through your code I notice it's really bare of any comments. You might want to look into fixing that. </p></li>\n<li><p>One more point, when reorganizing your code into multiple source files <em>do not</em> use any <code>using namespace</code> directives in the header files. Reason being you don't want this header to pollute the namespace of the components that includes this header.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T01:09:11.470", "Id": "3606", "Score": "0", "body": "You asked three questions. For the first one, yes, I do have a source control system; I use git. For the second one: no; in fact I have never done unit-tests in my life, and I think I should look up some tutorials on that. For the third question: no, it's not separated into files, but I was planning on doing that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T21:42:00.287", "Id": "3788", "Score": "0", "body": "I'll echo the comment and unit test points. The unit tests will help you make sure you don't break things as you make changes. The comments will help you remember what you did when someone asks for a change 3 years from now." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T00:02:53.533", "Id": "2243", "ParentId": "2236", "Score": "5" } } ]
{ "AcceptedAnswerId": "2243", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T18:36:55.607", "Id": "2236", "Score": "5", "Tags": [ "c++", "interpreter" ], "Title": "Preparing interpreter for error-handling" }
2236
<p>Here's the issue. When I build an asp.net application I create a singleton to read the values from the web.config file so that the values are only read once and gives a slight speed increase to the app. I basically do the following :</p> <pre><code>/// &lt;summary&gt; /// Static class that handles the web.config reading. /// &lt;/summary&gt; public class SiteGlobal { /// &lt;summary&gt; /// Property that pulls the connectionstring value. /// &lt;/summary&gt; public static string ConnectionString { get; protected set;} /// &lt;summary&gt; /// Property that pulls the directory configuration value. /// &lt;/summary&gt; public static string Directory { get; protected set; } /// &lt;summary&gt; /// Static contructor for the SiteGlobal class. /// &lt;/summary&gt; static SiteGlobal() { ConnectionString = WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString; Directory = WebConfigurationManager.AppSettings["Directory"]; } } </code></pre> <p>Which I don't consider a bad optimization. (Suggestions for improvement are appreciated through.) </p> <p>Now though I'm trying to read from a ConfigurationSection that can contain multiple area's for example : </p> <pre><code>&lt;ApplicationArea&gt; &lt;test1&gt; &lt;add key="key value" value="value data"/&gt; &lt;/test1&gt; &lt;test2&gt; &lt;add key="key value1" value="value data2"/&gt; &lt;/test2&gt; &lt;/ApplicationArea&gt; </code></pre> <p>Where I can have multiple area's underneath ApplicationArea, such as test1 and test 2 above. The best I've been able to come up with for an optimization of this though is this :</p> <pre><code>public static string ApplicationArea(string skey, string skey2) { NameValueCollection nvc = WebConfigurationManager.GetSection("ApplicationArea/" + skey) as NameValueCollection; return nvc[skey2]; } </code></pre> <p>Which is not saving the data and rereads the web.config file every time it's accessed. Is there an easy way to optimize the reading of the sections? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T19:01:33.330", "Id": "3598", "Score": "2", "body": "The web.config is loaded into memory once per-request anyway - it isn't loaded and parsed every time you access a section via the `WebConfigurationManager`. What speed increases have you actually noticed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T19:10:58.343", "Id": "3599", "Score": "0", "body": "In fact, it might not even occur for each request, [according to MSDN](http://msdn.microsoft.com/en-us/library/ms178685.aspx): _'These settings are calculated once and then cached across subsequent requests. ASP.NET automatically watches for file changes and re-computes the cache when any of the configuration files change within that file's hierarchy. When the server receives a request for a particular URL, ASP.NET uses the hierarchy of configuration settings in the cache to find the requested resource.'_ So, you're just doubling up on memory consumption; and I'm not convinced it's faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T20:21:10.020", "Id": "3602", "Score": "0", "body": "So, my static optimizations were not needed and the reading of the sections should be fine. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T13:54:25.643", "Id": "3626", "Score": "0", "body": "@Mr. Disappointment: IIS does load web.config once and registers changes made directly to the web.config while the application is loaded. If there are changes, it will reload it. This only applies to the web.config file though. If you have an element in the web.config that references an external .config, changes in the external file will not register and the settings will remain static until the application pool is recycled." } ]
[ { "body": "<p>The web.config is loaded into memory once per-request anyway - it isn't loaded and parsed every time you access a section via the WebConfigurationManager. What speed increases have you actually noticed? </p>\n\n<p>In fact, it might not even occur for each request, <a href=\"http://msdn.microsoft.com/en-us/library/ms178685.aspx\">according to MSDN</a>: <em>'These settings are calculated once and then cached across subsequent requests. ASP.NET automatically watches for file changes and re-computes the cache when any of the configuration files change within that file's hierarchy. When the server receives a request for a particular URL, ASP.NET uses the hierarchy of configuration settings in the cache to find the requested resource.'</em> So, you're just doubling up on memory consumption; and I'm not convinced it's faster. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:02:47.443", "Id": "3628", "Score": "0", "body": "I posted Mr. Disappointment's comments as a community wiki answer to that others can see that the question was addressed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:18:25.707", "Id": "3634", "Score": "0", "body": "I had thought about doing so, just so it has some resolution; apologies for not getting around to it, and thanks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:01:50.313", "Id": "2258", "ParentId": "2237", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T18:37:09.080", "Id": "2237", "Score": "5", "Tags": [ "c#", "asp.net" ], "Title": "Optimizing the reading of web.config" }
2237
<p>I wrote a wrapper around boost-mpl and transformed it to an sql engine. It is a compile time sql thing, not related to normal databases. I have not finished it completely. I have some problem with the interface.</p> <p>A template meta program run in compile time. So input data always present in compile time that is why I organized the inputs to tables.</p> <p>Tables are simple:</p> <pre><code>#define DEF_COLUMN(name) struct Col##name {}; \ template&lt;typename T&gt; struct name \ { typedef typename mpl::pair&lt;Col##name, T&gt; type; }; struct TestTable1 { DEF_COLUMN(PrimaryKey) DEF_COLUMN(Storage) DEF_COLUMN(BaseType) typedef mpl::vector&lt;ColPrimaryKey, ColStorage, ColBaseType&gt; header; // sample table // PrimaryKey | Storage | BaseType // -----------+---------+----------- // CTypeA1 | int | CTypeABase // CTypeA2 | string | CTypeABase typedef mpl::vector&lt; mpl::map3&lt;PrimaryKey&lt;CTypeA1&gt;::type, Storage&lt;int&gt;::type, BaseType&lt;CTypeABase&gt;::type&gt;, mpl::map3&lt;PrimaryKey&lt;CTypeA2&gt;::type, Storage&lt;std::string&gt;::type, BaseType&lt;CTypeABase&gt;::type&gt; &gt; type; }; struct TestTable2 { DEF_COLUMN(Tag) DEF_COLUMN(Attribute) typedef mpl::vector&lt; mpl::map2&lt;Tag&lt;CTypeA1&gt;::type, Attribute&lt;CTypeB1&gt;::type&gt;, mpl::map2&lt;Tag&lt;CTypeA2&gt;::type, Attribute&lt;CTypeB1&gt;::type&gt;, mpl::map2&lt;Tag&lt;CTypeA2&gt;::type, Attribute&lt;CTypeB2&gt;::type&gt; &gt; type; }; </code></pre> <p>And you can make queries on it:</p> <pre><code>void TestQuery1() { typedef Select&lt; Columns&lt;MplFunction&lt;Column&lt;TestTable1::ColStorage&gt;, mpl::sizeof_&gt; &gt;, From&lt;TestTable1, Join&lt;TestTable2, Equal&lt;TestTable1::ColPrimaryKey, TestTable2::ColTag&gt; &gt; &gt; &gt; TResultSet; DEBUG_TYPE((TResultSet)); print_table&lt;TResultSet::type&gt;(); } </code></pre> <p>I have type debug macro and table print template helper.</p> <p>So the above prints:</p> <pre><code>TResultSet =&gt; Select&lt;Columns&lt;MplFunction&lt;Column&lt;TestTable1::ColStorage&gt;, boost::mpl::sizeof_&gt;, mpl_::na&gt;, From&lt;TestTable1, Join&lt;TestTable2, Equal&lt;TestTable1::ColPrimaryKey, TestTable2::ColTag&gt; &gt; &gt;, Where&lt;True&gt; &gt; +------------------------+ | TestTable1::ColStorage | +------------------------+ | mpl_::size_t&lt;8ul&gt; | | mpl_::size_t&lt;8ul&gt; | | mpl_::size_t&lt;4ul&gt; | +------------------------+ 3 rows in set </code></pre> <p>I have problem with the syntax, how can I improve this, to achive an easy to use meta query thing? I think I have to eliminate the Columns, Column thing from the </p> <pre><code>Select&lt;Columns&lt;MplFunction&lt;Column&lt; ... </code></pre> <p>expression. And I need good Row fetch things and others. Any idea? And where can I upload the source?</p> <p>So this gives back compile time types, not runtime values.</p> <pre><code>void TestQuery3() { typedef Select&lt; Columns&lt;Column&lt;TestTable1::ColStorage&gt; &gt;, From&lt;TestTable1&gt;, Where&lt; Equal&lt;TestTable1::ColPrimaryKey, CTypeA1&gt; &gt; &gt; TResultSet; DEBUG_TYPE((TResultSet)); print_table&lt;TResultSet::type&gt;(); // fetch one row typedef mpl::back&lt;TResultSet::type&gt;::type TResultRow; // get column ColStorage which is an int, TRes will be an int typedef mpl::at&lt;TResultRow, TestTable1::ColStorage&gt;::type TRes; // use the "int" type TRes testInteger = 9; // prints test value std::cout &lt;&lt; "testInteger:" &lt;&lt; testInteger &lt;&lt; std::endl; } </code></pre> <p>this prints:</p> <pre><code>TResultSet =&gt; Select&lt;Columns&lt;Column&lt;TestTable1::ColStorage&gt;, mpl_::na&gt;, From&lt;TestTable1, mpl_::na&gt;, Where&lt;Equal&lt;TestTable1::ColPrimaryKey, CTypeA1&gt; &gt; &gt; +------------------------+ | TestTable1::ColStorage | +------------------------+ | int | +------------------------+ 1 row in set testInteger:9 </code></pre>
[]
[ { "body": "<p>You my also want to have a look at how the Poco library achieves a similar thing using a Tuple class. From the <a href=\"http://www.appinf.com/docs/poco/00200-DataUserManual.html#11\" rel=\"nofollow\">docs</a>:</p>\n\n<pre><code>typedef Poco::Tuple&lt;std::string, std::string, int&gt; Person;\ntypedef std::vector&lt;Person&gt; People;\n\nPeople people;\npeople.push_back(Person(\"Bart Simpson\", \"Springfield\", 12));\npeople.push_back(Person(\"Lisa Simpson\", \"Springfield\", 10));\n\nStatement insert(session);\ninsert &lt;&lt; \"INSERT INTO Person VALUES(:name, :address, :age)\",\n use(people), now;\n\nStatement select(session);\nselect &lt;&lt; \"SELECT Name, Address, Age FROM Person\",\n into(people), now;\n\nfor (People::const_iterator it = people.begin(); it != people.end(); ++it)\n{\n std::cout &lt;&lt; \"Name: \" &lt;&lt; it-&gt;get&lt;0&gt;() &lt;&lt; \n \", Address: \" &lt;&lt; it-&gt;get&lt;1&gt;() &lt;&lt; \n \", Age: \" &lt;&lt; it-&gt;get&lt;2&gt;() &lt;&lt;std::endl;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T19:52:07.847", "Id": "3600", "Score": "0", "body": "Thanks, but this is run time. My meta sql gives back types, not runtime values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T19:58:47.107", "Id": "3601", "Score": "0", "body": "But I give you +1 because I did not know that library:)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T19:50:16.640", "Id": "2239", "ParentId": "2238", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T19:27:33.390", "Id": "2238", "Score": "5", "Tags": [ "c++", "sql" ], "Title": "C++ template meta sql" }
2238
<p>The subroutine below, GetDetailsQuarterly, accepts two dates. Then it writes out each quarter that falls within the date range. It also gives the first and last day of the quarter. I really don't like how the beginning and ending dates of each quarter are hardcoded. I don't believe this solution accounts for leap year as well. Could someone point me in the right direction to refactor this? Thanks in advance.</p> <p>GetDetailQuarterly:</p> <pre><code> Public Sub GetDetailsQuarterly(ByVal beginDate As Date, ByVal endDate As Date) Console.WriteLine("{0}&gt;&gt;&gt; date range is {1} - {2} {3}", Environment.NewLine, beginDate, endDate, Environment.NewLine) Dim incrementingStartDate As Date = beginDate Dim fy As New FiscalYear() While incrementingStartDate &lt;= endDate fy.qOneBegin = "1/1/" &amp; incrementingStartDate.Year fy.qOneEnd = "3/31/" &amp; incrementingStartDate.Year fy.qTwoBegin = "4/1/" &amp; incrementingStartDate.Year fy.qTwoEnd = "6/30/" &amp; incrementingStartDate.Year fy.qThreeBegin = "7/1/" &amp; incrementingStartDate.Year fy.qThreeEnd = "9/30/" &amp; incrementingStartDate.Year fy.qFourBegin = "10/1/" &amp; incrementingStartDate.Year fy.qFourEnd = "12/31/" &amp; incrementingStartDate.Year Select Case incrementingStartDate Case fy.qOneBegin To fy.qOneEnd fy.CurrentQuarter = 1 Case fy.qTwoBegin To fy.qTwoEnd fy.CurrentQuarter = 2 Case fy.qThreeBegin To fy.qThreeEnd fy.CurrentQuarter = 3 Case fy.qFourBegin To fy.qFourEnd fy.CurrentQuarter = 4 Case Else Console.WriteLine("out of range") End Select Console.WriteLine("your q{0}", fy.CurrentQuarter) fy.getCurrentQuarterRange() incrementingStartDate = incrementingStartDate.AddMonths(3) End While End Sub </code></pre> <p>FiscalYear Class:</p> <pre><code> Public Class FiscalYear Public Property qOneBegin() As Date Public Property qOneEnd() As Date Public Property qTwoBegin() As Date Public Property qTwoEnd() As Date Public Property qThreeBegin() As Date Public Property qThreeEnd() As Date Public Property qFourBegin() As Date Public Property qFourEnd() As Date Public Property CurrentQuarter As Integer Public Sub getCurrentQuarterRange() Select Case CurrentQuarter Case 1 Console.WriteLine("s: {0}, e: {1}", qOneBegin, qOneEnd) Case 2 Console.WriteLine("s: {0}, e: {1}", qTwoBegin, qTwoEnd) Case 3 Console.WriteLine("s: {0}, e: {1}", qThreeBegin, qThreeEnd) Case 4 Console.WriteLine("s: {0}, e: {1}", qFourBegin, qFourEnd) Case Else Console.WriteLine("out of range") End Select End Sub End Class </code></pre>
[]
[ { "body": "<p>I am a bit lost in terms of what you are actually trying to accomplish, but I can give some pointers.</p>\n\n<p>First, leap years do not particularly impact quarters unless you truly have some unique rules. Under normal behaviors, February 29 will be in the same quarter as February 28, and would solidly fall inside quarter 1 in your given scenario. </p>\n\n<p>Secondly, a quick way to figure out the quarter of a given date (if your quarter system starts at January 1) is the following formula </p>\n\n<pre><code>Dim currentQuarter as Integer = currentDateTime.Month \\ 3 + 1\n</code></pre>\n\n<p>Similarly, you can perform operations to arrive at quarter beginning and ending dates.</p>\n\n<pre><code>Dim quarterStart = new DateTime(currentDateTime.Year, 3 * (currentQuarter - 1) + 1, 1)\nDim quarterEnd = quarterStart.AddMonths(3).AddSeconds(-1)\n</code></pre>\n\n<p>For example, using today as the base, you could test the code </p>\n\n<pre><code>Dim currentDateTime = DateTime.Now\n\nDim currentQuarter = currentDateTime.Month \\ 3 + 1\nDim quarterStart = new DateTime(currentDateTime.Year, 3 * (currentQuarter - 1) + 1, 1)\nDim quarterEnd = quarterStart.AddMonths(3).AddSeconds(-1)\n\nConsole.WriteLine(currentQuarter)\nConsole.WriteLine(quarterStart)\nConsole.WriteLine(quarterEnd)\n</code></pre>\n\n<p>And see these results </p>\n\n<pre><code>2\n4/1/2011 12:00:00 AM\n6/30/2011 11:59:59 PM\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T12:38:46.063", "Id": "3615", "Score": "0", "body": "Anthony, This is exactly what I was looking for. Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:37:04.450", "Id": "3640", "Score": "0", "body": "How would one accommodated a date range that spans more than one year? For example, 12/1/2010 - 2/1/2011." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T17:36:25.337", "Id": "3641", "Score": "0", "body": "@rross, can your clarify? Also, your followup *might* end up being more suitable on StackOverflow directly." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T21:00:55.273", "Id": "2242", "ParentId": "2240", "Score": "4" } } ]
{ "AcceptedAnswerId": "2242", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-04T20:27:08.403", "Id": "2240", "Score": "3", "Tags": [ ".net", "classes", "object-oriented", "vb.net" ], "Title": "Refactor a subroutine that divides date range into quarters." }
2240
<p>Can you please help me split this method to reuse the repeating code?</p> <p>Any advice/comments on the code are welcome.</p> <pre><code>//This method will return Dictionary object having key/value pair of keywords and URLs. //Keywords are single word or bunch of words from db. //Value in dictionary is URLs against each key (keyword). //Code starts from here. private static Dictionary&lt;string, string&gt; GetKeywordsAndEntityWithURL(int eventTypeId, string entityName) { // Get initial url from configuration file. string basewebUrl = CommonMethods.GetAppSettingsValue("Baseweb"); // Get all keywords from db, from KeyWords table. KeywordsCollection keyWords = KeywordsEntity.GetKeywords(null, eventTypeId); // This text will be concatenated with entityname. // Purpose of this is to avoid replacement of EntityName again in find/replace. string dummyText = "TemporaryText"; // This object will be used to create key/value pair of keys and URLs. Dictionary&lt;string, string&gt; keyWordsWithURLs = new Dictionary&lt;string, string&gt;(); // There are two types of keywords in db, Singular and Plural. Get each and create key/value using them. foreach (KeywordsEntity keyWord in keyWords) { string singularKeyword = keyWord.Keyword; // Keywords are like 'stag do' in db we need to replace white space // with hyphen to use this in URLs. singularKeyword = singularKeyword.Replace(' ', '-'); // This key is like 'stag do London'. string singularKey = string.Empty; singularKey = string.Format("{0} {1}", keyWord.Keyword.ToString(), entityName); // Concat entityName (London) with dummytext. entityName = entityName + dummyText; // Text of URL e.g. stag do London string urlText = keyWord.Keyword + " " + entityName; // This value is like initial url (whatever it is in config file)/stag-do/london string singularValue = string.Empty; singularValue = string.Format("&lt;a style='text-decoration:underline;' href='" + basewebUrl + "/{0}/{1}'&gt;{2}&lt;/a&gt;", singularKeyword, entityName, urlText); // Add key/value in dictionaly. keyWordsWithURLs.Add(singularKey, singularValue); // Plural keywords are like 'stag dos' in db we need to replace space with hyphen for URLs. string pluralKeyword = keyWord.PluralKeyword; pluralKeyword = pluralKeyword.Replace(' ', '-'); // This key would be 'stag dos london' string pluralKey = string.Empty; pluralKey = string.Format("{0} {1}", keyWord.PluralKeyword.ToString(), entityName); // URL would be, initial url(whatever in config file)/ stag-dos/london string pluralValue = string.Empty; pluralValue = string.Format("&lt;a style='text-decoration:underline;' href='" + basewebUrl + "/{0}/{1}'&gt;{2}&lt;/a&gt;", pluralKeyword, entityName, urlText); // Add key/value in dictionary. keyWordsWithURLs.Add(pluralKey, pluralValue); // Singular Key = London stag do singularKey = string.Format("{0} {1}", entityName, keyWord.Keyword.ToString()); // Text of anchor e.g. London stag do. urlText = entityName + dummyText + " " + keyWord.Keyword; // Singular Value = /stag-do/london singularValue = string.Format("&lt;a style='text-decoration:underline;' href='" + basewebUrl + "/{0}/{1}'&gt;{2}&lt;/a&gt;", singularKeyword, entityName, urlText); keyWordsWithURLs.Add(singularKey, singularValue); // Plural Key = London stag dos pluralKey = string.Format("{0} {1}", entityName, keyWord.PluralKeyword.ToString()); // Plural Key = /stag-dos/lonon pluralValue = string.Format("&lt;a style='text-decoration:underline;' href='" + basewebUrl + "/{0}/{1}'&gt;{2}&lt;/a&gt;", pluralKeyword, entityName, urlText); // Add key/value pair in dictionary. keyWordsWithURLs.Add(pluralKey, pluralValue); urlText = keyWord.Keyword + " in " + entityName + dummyText; singularKey = string.Format("{0} {1} {2}", keyWord.Keyword.ToString(), "in", entityName); singularValue = string.Format("&lt;a style='text-decoration:underline;' href='" + basewebUrl + "/{0}/{1}'&gt;{2}&lt;/a&gt;", singularKeyword, entityName, urlText); // Add key/value in dictionaly. keyWordsWithURLs.Add(singularKey, singularValue); pluralKey = string.Format("{0} {1} {2}", keyWord.PluralKeyword.ToString(), "in", entityName); pluralValue = string.Format("&lt;a style='text-decoration:underline;' href='" + basewebUrl + "/{0}/{1}'&gt;{2}&lt;/a&gt;", pluralKeyword, entityName, urlText); // Add key/value in dictionary. keyWordsWithURLs.Add(pluralKey, pluralValue); if (keyWord.IsDefault) { pluralKeyword = keyWord.PluralKeyword.Replace(' ', '-'); pluralKey = string.Format("{0}", entityName); pluralValue = string.Format("&lt;a style='text-decoration:underline;' href='" + basewebUrl + "/{0}/{1}'&gt;{2}&lt;/a&gt;", pluralKeyword, entityName, entityName); keyWordsWithURLs.Add(pluralKey, pluralValue); } } return keyWordsWithURLs; } </code></pre> <p>If you need the full class, please write a comment. I will upload it.</p>
[]
[ { "body": "<p>I would probably start by cleaning up the method before trying to extract anything as it will make it easier to see where to draw the line.</p>\n\n<ul>\n<li><p>There are a couple of places where you define a variable with an initial value and then override that value on the next line (singularKeyword, singularKey)</p>\n\n<pre><code>string singularKeyword = keyWord.Keyword.singularKeyword.Replace(' ', '-');\nstring singularKey = string.Format(\"{0} {1}\", keyWord.Keyword.ToString(), entityName);\n</code></pre></li>\n<li><p>You shouldn't need the call to ToString in the above line either as string.Format() will do it for you.</p></li>\n<li><p>Any time you find yourself appending to a string in a loop, you should consider if using StringBuilder would be better.</p></li>\n<li><p>I generally prefer not to modify arguments, particularly in such a large method as it tends to confuse it's meaning.</p></li>\n<li><p>Why pass a string literal into string.Format instead of including it in the format string?</p>\n\n<pre><code>singularKey = string.Format(\"{0} in {1}\", keyWord.Keyword.ToString(), entityName);\n</code></pre></li>\n<li><p>I noticed that in several places you append basewebUrl to directly the format string instead of passing it in as another arg?</p></li>\n<li><p>The whole string.Format call in this following line seems a bit redundant.</p>\n\n<pre><code>pluralKey = string.Format(\"{0}\", entityName);\n</code></pre>\n\n<p>Why not just set pluralKey to entityName.</p>\n\n<pre><code>pluralKey = entityName;\n</code></pre></li>\n<li><p>pluralKey is set but never used, you only use pluralKeyword.</p></li>\n<li><p>I'm probably going to get punished for saying this, but I think you may have overdone some of the comments.</p>\n\n<p>eg.</p>\n\n<pre><code>//Code starts from here.\n\n// Add key/value in dictionary.\n</code></pre>\n\n<p>Personally I find this sort of commenting more distracting than helpful. :)</p></li>\n</ul>\n\n<p>The following look wrong to me, but I'm not entirely sure since it should show up quite obviously during functional testing.</p>\n\n<ul>\n<li><p>Each iteration appends another copy of dummyText to entityName.</p></li>\n<li><p>If appending to entityName is intended, is it also intended to happen between its first and second use within the loop?</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T12:41:01.477", "Id": "3616", "Score": "1", "body": "Prefer StringWriter to StringBuilder - It uses a string builder under the covers, but your code is now writing to a TextWriter, far more natural, and is interchangeable with all other TextWriters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T12:46:37.543", "Id": "3617", "Score": "0", "body": "@Binary Worrier: either will work, if it will not be exposed publicly and I don't need the ability to swap in other `TextWriter`s then I generally tend towards using StringBuilder for the more convenient append methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T13:34:52.203", "Id": "3625", "Score": "0", "body": "Indeed they will. I find the TextWriter write methods more convenient. Each to his own I suppose :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:30:35.080", "Id": "3638", "Score": "0", "body": "sparing time for my code review is so kind of you. I am really thankful. I am going to change my code as you suggested. One question, should I try to spend time on refactoring this method or it is ok? If so then any hint?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T02:50:29.613", "Id": "3650", "Score": "0", "body": "@Muhammad: I find that cleaning up code like this tends to be an iterative process, as you take each step the next becomes clearer. I would find it hard to see where to go after these steps until I see the result. I suspect you would be able to extract methods to add plural and singular values to the dictionary, but the details are not clear yet." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T11:41:51.653", "Id": "2252", "ParentId": "2246", "Score": "3" } } ]
{ "AcceptedAnswerId": "2252", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T06:09:27.603", "Id": "2246", "Score": "5", "Tags": [ "c#", "hash-map" ], "Title": "Return Dictionary object having key/value pair of keywords and URLs" }
2246
<h2>Description</h2> <p>Structured Query Language (SQL) is the most common language to use for interacting with relational databases. However, over the years, database vendors have implemented extensions of SQL to provide more functionality as well as simplify queries. Because most database systems are not fully compliant with the ANSI standards, and offer features not specified by ANSI, SQL is usually non-portable - syntax that works on one vendor does not necessarily work on another.</p> <h2>Tag Guidelines</h2> <p>This tag should be used for general SQL programming language questions. Be sure to also tag questions with for the specific database system(s) that you are using, so that reviews can use the appropriate SQL dialect and feature set. Database product tags include:</p> <ul> <li>Microsoft SQL Server: <a href="/questions/tagged/sql-server" class="post-tag" title="show questions tagged &#39;sql-server&#39;" rel="tag">sql-server</a> (<a href="/questions/tagged/t-sql" class="post-tag" title="show questions tagged &#39;t-sql&#39;" rel="tag">t-sql</a> for its SQL dialect)</li> <li>MySQL and its derivatives: <a href="/questions/tagged/mysql" class="post-tag" title="show questions tagged &#39;mysql&#39;" rel="tag">mysql</a></li> <li>Oracle: <a href="/questions/tagged/oracle" class="post-tag" title="show questions tagged &#39;oracle&#39;" rel="tag">oracle</a> (<a href="/questions/tagged/plsql" class="post-tag" title="show questions tagged &#39;plsql&#39;" rel="tag">plsql</a> for its extension language)</li> <li>PostgreSQL: <a href="/questions/tagged/postgresql" class="post-tag" title="show questions tagged &#39;postgresql&#39;" rel="tag">postgresql</a> (<a href="/questions/tagged/plpgsql" class="post-tag" title="show questions tagged &#39;plpgsql&#39;" rel="tag">plpgsql</a> for its extension language)</li> <li>SQLite: <a href="/questions/tagged/sqlite" class="post-tag" title="show questions tagged &#39;sqlite&#39;" rel="tag">sqlite</a></li> </ul> <h2>Question Guidelines</h2> <p>If you request a code review for an SQL query,</p> <ul> <li>Provide some <strong>context</strong> about what your query is trying to accomplish. <ul> <li>Does it run as an offline batch job on a reporting database? Or does it run on your primary database, and the user expects an immediate response?</li> <li>Does the code execute the query in one shot, or does it execute the query many times in a loop?</li> <li>Are there any tables where the number of rows could be a concern?</li> </ul></li> <li>Include sufficient information about your database <strong>schema</strong> (table definitions)</li> <li>If query performance is a concern, <ul> <li>Ensure that <a href="http://use-the-index-luke.com" rel="nofollow noreferrer"><strong>indexes</strong></a> are in place, and mention them when describing the schema.</li> <li>Include the output from executing the statement <strong><code>EXPLAIN SELECT</code></strong>.</li> </ul></li> </ul> <h3>Other Sites</h3> <p>SQL questions may also be appropriate on <a href="https://dba.stackexchange.com">Database Administrators</a> <em>if they are <a href="https://dba.stackexchange.com/help/on-topic">not beginner questions</a></em>. Questions about schema design would probably be best suited to <a href="https://softwareengineering.stackexchange.com/questions/tagged/database-design">Programmers SE</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-05-05T08:16:59.207", "Id": "2247", "Score": "0", "Tags": null, "Title": null }
2247
Structured Query Language is a language for interacting with relational databases. Read the tag wiki's guidelines for requesting SQL reviews: 1) Provide context, 2) Include the schema, 3) If asking about performance, include indexes and the output of EXPLAIN SELECT.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T08:16:59.207", "Id": "2248", "Score": "0", "Tags": null, "Title": null }
2248
<p>I'm learning Haskell at the moment, and have just written my first useful module - a parser fo INI files. I used Parsec. I'd like to know what can be improved here - or maybe I did some things completely wrong and there is a better way. Thanks.</p> <pre><code>module IniFile (iniFileToMap) where import Text.ParserCombinators.Parsec import qualified Data.Map as Map import Char parseIniFile :: Parser ([(String, [(String, String)])]) parseSection :: Parser (String, [(String, String)]) parseSectionHeader :: Parser String parseNameValue :: Parser (String, String) parseComment :: Parser () parseNormalValue :: Parser String parseQuotedValue :: Parser String parseValue :: Parser String parseName :: Parser String parseInsideQuotes :: Parser String parseCmtOrSpace :: Parser () iniFileToMap :: FilePath -&gt; IO (Map.Map String (Map.Map String String)) parseCmtOrSpace = do{ spaces; skipMany parseComment; } parseInsideQuotes = many (noneOf "\"") parseQuotedValue = between (char '"') (char '"') parseInsideQuotes parseNormalValue = many1 (satisfy (\c -&gt; isPrint c &amp;&amp; not (isSpace c))) parseValue = parseQuotedValue &lt;|&gt; parseNormalValue parseName = many1 (satisfy (\c -&gt; isAlpha c || isDigit c || c == '_' || c == '.')); parseComment = do{ skipMany1 (char ';'); skipMany (noneOf "\n"); spaces; } parseNameValue = do{ name &lt;- parseName; between (skipMany (oneOf " \t")) (skipMany (oneOf " \t")) (char '='); value &lt;- parseValue; return (name, value); } parseSectionHeader = do{ name &lt;- between (char '[') (char ']') parseName; return name; } parseSection = do{ name &lt;- between parseCmtOrSpace parseCmtOrSpace parseSectionHeader; values &lt;- endBy1 (parseNameValue) (parseCmtOrSpace); return (name, values); } parseIniFile = do{ result &lt;- many1 (parseSection); return result; } list2Map list = Map.fromList (map (\e -&gt; (fst e, Map.fromList (snd e))) list) iniFileToMap path = do{ result &lt;- parseFromFile parseIniFile path; case (result) of Left err -&gt; error (show err) Right xs -&gt; return (list2Map(xs)); } </code></pre>
[]
[ { "body": "<p>The first thing I noticed is that you have grouped all the type signatures together, away from the function bodies. This seems very strange to me. It's way more common (and as far as I'm concerned also way more readable) to have a value's type directly before its definition.</p>\n\n<p>The second thing I noticed were all the braces and semicolons. Unless you have a specific reason to use them, I'd strongly recommend making use of Haskell's significant indentation instead. Much less visual noise. I'm especially confused by the semicolon at the end of <code>parseName</code>'s definition as <code>parseName</code> doesn't use <code>do</code>-notation and you didn't use a semicolon on any other definition which didn't use <code>do</code>.</p>\n\n<hr>\n\n<p>You sometimes surround variables with parentheses (e.g. in <code>values &lt;- endBy1 (parseNameValue) (parseCmtOrSpace)</code>, but not in the line <code>name &lt;- between parseCmtOrSpace ...</code> directly above it). I can't see any system to when you do this and when you don't, so it just seems random and inconsistent. So I'd recommend to get rid of the needless parentheses.</p>\n\n<p>Speaking of parentheses, you might also want to get rid of some more parentheses by sprinkling a couple of <code>$</code> signs in your code, to give it a more \"haskellish\" feel.</p>\n\n<hr>\n\n<pre><code>parseSectionHeader = do{\n name &lt;- between (char '[') (char ']') parseName;\n return name;\n}\n\nparseIniFile = do{\n result &lt;- many1 (parseSection);\n return result;\n}\n</code></pre>\n\n<p>Whenever you have something of the form:</p>\n\n<pre><code>foo &lt;- bar\nreturn foo\n</code></pre>\n\n<p>You can simply just write <code>bar</code>. I.e.:</p>\n\n<pre><code>parseSectionHeader = between (char '[') (char ']') parseName\n\nparseIniFile = many1 parseSection\n</code></pre>\n\n<hr>\n\n<pre><code>iniFileToMap path = do{\n result &lt;- parseFromFile parseIniFile path;\n case (result) of\n Left err -&gt; error (show err)\n Right xs -&gt; return (list2Map(xs));\n}\n</code></pre>\n\n<p>Here the indentation is off - <code>case</code> should not be indented further than <code>result &lt;-</code>. It should be:</p>\n\n<pre><code>iniFileToMap path = do\n result &lt;- parseFromFile parseIniFile path\n case result of\n Left err -&gt; error $ show err\n Right xs -&gt; return $ list2Map xs\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T16:34:49.157", "Id": "2286", "ParentId": "2253", "Score": "6" } }, { "body": "<p><strong>Formatting/Conventions</strong></p>\n\n<p>Firstly, the usual convention is to alias Data.Map as M. Usually qualified imports are one letter, unless you need two because of a collision.</p>\n\n<p>Don't use braces except for record syntax.</p>\n\n<p>Don't use semicolons.</p>\n\n<p><strong>Monads</strong></p>\n\n<p>Alot of your do notation doesn't need do notation. To add to sepp2k's examples, we also have stuff like:</p>\n\n<pre><code>parseCmtOrSpace = do\n spaces\n skipMany parseComment\n</code></pre>\n\n<p>which should be written much more nicely as</p>\n\n<pre><code>parseCmtOrSpace = spaces &gt;&gt; skipMany parseComment\n</code></pre>\n\n<p>since do notation is usually not necessary for a two line do.</p>\n\n<p>As another example of cleaning up do notation: (This one is significantly more to personal case than my other example. However it also makes some other changes that you should look at, even if you want to keep your monadic do notation, such as refactoring out the tabs)</p>\n\n<pre><code>parseNameValue = do\n name &lt;- parseName\n between (skipMany (oneOf \" \\t\")) (skipMany (oneOf \" \\t\")) (char '=')\n value &lt;- parseValue\n return (name, value)\n</code></pre>\n\n<p>We can instead write: (I apologize if the following is incorrect, I don't have a compiler available)</p>\n\n<pre><code>parseNameValue = liftM3 g parseName eq parseValue\n where eq = between ts ts $ char '='\n ts = skipMany $ oneOf \" \\t\"\n g x _ y = (x, y)\n</code></pre>\n\n<p>We can do the same for <code>parseSection</code>:</p>\n\n<pre><code>parseSection = do\n name &lt;- between parseCmtOrSpace parseCmtOrSpace parseSectionHeader\n values &lt;- endBy1 (parseNameValue) (parseCmtOrSpace)\n return (name, values)\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>parseSection = liftM2 g names values\n where names = between parseCmtOrSpace parseCmtOrSpace parseSectionHeader\n values = endBy1 parseNameValue parseCmtOrSpace\n g x y = (x, y)\n</code></pre>\n\n<p><strong>Parsec</strong></p>\n\n<p>You should define a way to get an <code>Either ParseError (M.Map String String)</code> instead of erroring in the library. Erroring should be left to the client. Although you may want to provide one that provides an <code>Either</code>, and one function that errors automatically.</p>\n\n<p>It seems to be convention that the monads that build up the parser should not begin with parse. We see this in the Parsec library (its <code>char</code>, not <code>parseChar</code>). The functions don't parse; they return data that can be used for parsing. At the very least do <code>nameValueParser</code>, but theres nothing wrong with just <code>nameValue</code>. Just don't export the functions and there won't be any namespacing issues most of the time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-26T06:18:25.463", "Id": "4113", "Score": "0", "body": "You can create stunningly readable Parsec code by using its Applicative instance. For example, `parseNameValue` then becomes\n\n `parseNameValue = (,) <$> parseName <*> (ws *> char '=' <* ws) *> parseValue`\n\n(where `ws = skipMany $ oneOf \" \\t\"`)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-07T12:37:50.597", "Id": "2299", "ParentId": "2253", "Score": "2" } } ]
{ "AcceptedAnswerId": "2286", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T12:29:02.973", "Id": "2253", "Score": "6", "Tags": [ "haskell", "parsec" ], "Title": "INI File Parser in Haskell" }
2253
<p>I would like to write the following piece of code cleaner and more efficient, any comments will be greatly appreciated:</p> <pre><code>Dim dt As DataTable = SomeDataTable For Each dr As DataRow In dt.Rows Dim myColumn As String = dr("column").Trim().ToUpper() For Each group As String In collection If (group.Trim().ToUpper() = myColumn) Then 'Add some logic here End If Next` </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T11:53:31.270", "Id": "3619", "Score": "1", "body": "Unrelated, but don't use ToUpper() for case-insensitive string compares unless you're positive there will never be localized versions of your application (see: http://www.mattryall.net/blog/2009/02/the-infamous-turkish-locale-bug)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T12:06:11.283", "Id": "3620", "Score": "0", "body": "This is not C# code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T12:08:26.167", "Id": "3621", "Score": "0", "body": "I am not a BASIC speaker, but I feel the last 4 lines do nothing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T12:23:07.267", "Id": "3622", "Score": "0", "body": "@M.Sameer - Thanks for changing it to VB,NET\n@Ingo - I updated the example to be more descriptive" } ]
[ { "body": "<p>There are two concerns with the code presented. If you can guarantee that you won't ever need localization and that the strings in <code>collection</code> will ALWAYS be upper case then you could use something like this:</p>\n\n<pre><code>Dim dt As DataTable = SomeDataTable\n\nFor Each dr As DataRow In dt.Rows\n 'I always recommend explicitly calling .ToString() first\n 'In response to @Mr. Disappointment's comment - he is right\n 'Null check this first\n If Not dr.IsNull(\"column\") Then \n Dim myColumn As String = dr(\"column\").ToString().ToUpper().Trim()\n\n If collection.Contains(myColumn) Then\n 'Do your stuff here\n End If\n End If\nNext\n</code></pre>\n\n<p>However, if these things are not guaranteed, then you are better off foregoing <code>.Contains</code> and using your own for loop (which is what <code>.Contains</code> will end up using anyway):</p>\n\n<pre><code>Dim dt As DataTable = SomeDataTable\n</code></pre>\n\n<p>There are two concerns with the code presented. If you can guarantee that you won't ever need localization and that the strings in <code>collection</code> will ALWAYS be upper case then you could use something like this:</p>\n\n<pre><code>Dim dt As DataTable = SomeDataTable\n\nFor Each dr As DataRow In dt.Rows\n 'I always recommend explicitly calling .ToString() first\n 'In response to @Mr. Disappointment's comment - he is right\n 'Null check this first\n If Not dr.IsNull(\"column\") Then \n Dim myColumn As String = dr(\"column\").ToString().Trim()\n\n For each group as String in collection\n If group.Equals(myColumn, StringComparison.OrdinalIgnoreCase) Then\n 'Do your stuff here\n End If\n Next\n End If\nNext\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:02:29.033", "Id": "3627", "Score": "0", "body": "_'always recommend explicitly calling .ToString() first'_: Without checking for a `null` reference? Things go BANG! that way. You can use `dr.IsNull(\"column\")` to check." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:08:50.483", "Id": "3629", "Score": "0", "body": "@Mr. Disappointment: Tru dat. In my own code I would never use tables in this manner so my null checks would be handled differently, but you're absolutely right. A null check is highly advisable here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:11:26.893", "Id": "3630", "Score": "0", "body": "@Mr. Disappointment: Edit/credit added." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:12:49.613", "Id": "3631", "Score": "0", "body": "@JoelEtherton: A check for `null` is required / highly advisable in **any** case where a `NullReferenceException` might occur. To be fair, we're not talking about your code, but rather code you're offering to somebody as an improvement to their own - if you have thoughts on the issue then present them, please don't omit them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:16:05.430", "Id": "3632", "Score": "0", "body": "@JoelEtherton: Better. Now just declare the `String` variable once outside of the loop and re-use it. ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:17:35.250", "Id": "3633", "Score": "0", "body": "@Mr. Disappointment: Ok, seriously the tone of your last comment is not appreciated. I was agreeing with your comment, and I adjusted my answer in line with that. In my original answer I hadn't considered null checks there because that's not where I handle those kinds of things in my code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:19:28.540", "Id": "3635", "Score": "0", "body": "@Mr. Disappointment: In this case, the scope of the variable is highly irrelevant. The difference in reusing the variable vs re-dimming it in this case is negligible. If you want to take optimization to that level, you should recommend usage of the `StringBuilder` class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:25:51.703", "Id": "3637", "Score": "0", "body": "@JoelEtherton: My concern isn't really for optimising in terms of speed, but productivity and readability - even this is negligible and hence my -wink- to convey such as somewhat tongue-in-cheek." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T12:26:28.497", "Id": "2255", "ParentId": "2254", "Score": "1" } }, { "body": "<p>I'm not a VB.Net developer, but if I were writing this in C# I would use the Contains method on your collection. I'm assuming that your collection is a list of strings in this case.</p>\n\n<p>I've included what the code might look like in VB.Net below. I give no guarantees that it works though. :)</p>\n\n<pre><code>Dim dt As DataTable = SomeDataTable\n\nFor Each dr As DataRow In dt.Rows\n Dim myColumn As String = dr(\"column\").ToString().Trim()\n\n If collection.Contains(myColumn, StringComparer.OrdinalIgnoreCase) Then\n 'Do your stuff here\n End If\nNext\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T13:27:32.563", "Id": "3623", "Score": "0", "body": "+1 but to use Contains in this fashion (works in 4.0 only) it needs to be `StringComparer.OrdinalIgnoreCase`. `StringComparison` will fail the overload." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T13:29:46.920", "Id": "3624", "Score": "0", "body": "@Joel Etherton, ah I missed that when I was typing it out. Thanks for catching it. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T13:21:55.613", "Id": "2256", "ParentId": "2254", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T11:37:16.133", "Id": "2254", "Score": "2", "Tags": [ "vb.net", "strings" ], "Title": "Iterate comparison - How can I write this better?" }
2254
<p>How to make this code better?</p> <pre><code>if (Program.Data.DataBase.TryOpenDataBase()) { bool result; DataBase= new Program.Data.DataBase(out result); if (!result) { if (Program.DataBase!= null) Program.DataBase.Dispose(); Program.DataBase= null; Log.WriteERROR("Can not open database"); Application.Exit(); return; } else { Log.WriteERROR("Can not open database"); Application.Exit(); return; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:22:45.773", "Id": "3636", "Score": "1", "body": "There's a lot of stuff here that appears to be proprietary and has no real meaning in a usable context. Are you using MSSQL, MySQL, Oracle? What does `TryOpenDataBase()` look like? What is `DataBase`?" } ]
[ { "body": "<p>I would remove the out parameter from the constructor. It is really confusing to read. Maybe create a function that throws an exception instead. If the database implements IDisposable you can use a using block instead.</p>\n\n<p><strong>Edit -</strong> You have some duplicate code as well:</p>\n\n<pre><code>Log.WriteERROR(\"Can not open database\");\nApplication.Exit();\nreturn;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T22:23:32.027", "Id": "2266", "ParentId": "2257", "Score": "4" } }, { "body": "<p>Generally you shouldn't return any error codes, use exceptions and try/catch blocks.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-26T20:55:06.090", "Id": "4142", "Score": "0", "body": "To be clear, returning the error code doesn't just have be the return value of the method, it could be an out parameter. This is still usually a bad thing." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T17:55:30.557", "Id": "2313", "ParentId": "2257", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:00:11.253", "Id": "2257", "Score": "4", "Tags": [ "c#", "exception-handling" ], "Title": "Open database and hande errors" }
2257
<p>I work as a C# developer at a company that doesn't use best practices at all. We're on .NET 3.5 but most code is written in a .NET 1.1 style (e.g. almost all the logic is in the code behind of the ASPX page, everything uses untyped DataSets instead of returning objects, makes gratuitous use of Session and QueryString to pass data, very little architectural patterns). I have spent a couple of years learning best practices by reading blogs and watching screencasts from the top echelon of .Net developers. </p> <p>I was recently tasked with creating a new feature on our in-house ERP system that writes data from XML to a PDF for display. It was suggested that we might want various types of PDFs in the future, so the framework should be flexible. I took the opportunity to apply proper design patterns and a DDD-like approach to the code, with the idea being to demonstrate a "better way" of doing things to my peers. My code was subsequently rejected in a "code review" by the lead developer/development manager as being "too complicated" compared to simply writing all the logic in a single class or in the code-behind (what my other co-workers would have done had they been given the project instead). I managed to get the code passed anyways as they didn't want me to "waste time" going back and changing it (they consider refactoring a waste of time that adds no business value), but it got me thinking if the code really is too complex; I appear to be following all of the best practices, I am following (I think) all of the SOLID principles, I am using proper design patterns and OOP software engineering techniques.</p> <p>Here is a simplified version of the classes (may or may not be 100% compilable as it's a stripped down version; you should get the idea though):</p> <pre><code>// Repositories public interface IRepository { } public interface IXmlRepository : IRepository { XmlDocument GetXml(); } // Repositories.Impl public abstract class BillingXmlRepository : IXmlRepository { protected long quoteID; public BillingXmlRepository(long quoteID) { this.quoteID = quoteID; } public abstract XmlDocument GetXml(); } public sealed class XmlInvoiceRepository : BillingXmlRepository { public XmlInvoiceRepository(long quoteID) : base(quoteID) { } public override XmlDocument GetXml() { // XML retrival here... } } // DataAggregation pubilc interface IAggregatableData&lt;T&gt; { T GetData(); } public abstract class DataAggregator&lt;T&gt; : IAggregatableData&lt;T&gt; { public abstract T GetData(); protected abstract ICollection&lt;IRepository&gt; GetAllRequiredRepositories(); } public abstract class XmlDataAggregator : DataAggregator&lt;XmlDocument&gt; { public override XmlDocument GetData() { XmlDocument root = new XmlDocument(); foreach (IRepository repository in this.GetAllRequiredRepositories()) { XmlDocument xml = (repository as IXmlRepository).GetXml(); XmlDocumentFragment fragment = root.CreateDocumentFragment(); fragment.InnerXml = xml.InnerXml; root.DocumentElement.AppendChild(fragment); } return root; } } public sealed class BillingDataAggregator : XmlDataAggregator { private long quoteID; public BillingDataAggregator(long quoteID) { this.quoteID = quoteID; } protected override void ICollection&lt;IRepository&gt; GetAllRequiredRepositories() { return new List&lt;IRepository&gt; { new XmlBillingRepository(this.quoteID); } } } // Mappers to map raw XML to classes public interface IMappable&lt;T, K&gt; { T Map(K rawData); } public interface IXmlMappable&lt;T&gt; : IMappable&lt;T, XmlDocument&gt; { } public sealed class BillingXmlMapper : IXmlMappable&lt;BillingInfo&gt; { public BillingInfo Map(XmlDocument rawData) { // LINQ code to traverse the XML and map it into a BillingInfo DTO } } // Entities public sealed class BillingInfo { // simple properties } // Consumer example XmlDataAggregator aggregator = new BillingDataAggregator(1234); var xml = aggregator.GetData(); var mapper = new BillingXmlMapper(); BillingInfo info = mapper.Map(xml); </code></pre> <p>Am I on the right track as far as following the best way to write modular code? I can't bring myself to ignore good practices and write all the code in code-behind files or the like.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T08:39:18.513", "Id": "48131", "Score": "0", "body": "Did you show your peers any unit tests that you were able to write as a result of segregating the interfaces? That might have gone some way towards convincing them" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T14:56:28.483", "Id": "48169", "Score": "0", "body": "It's a moot point now as I was fired from this job in July '12 for applying design patterns to the code and trying to help my peers improve, but we had no unit tests of any kind at the company and testing was seen as a waste of time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T18:32:42.050", "Id": "48200", "Score": "0", "body": "Sorry to hear that, I didn't realise this question was so old. I hope you're in a more inspiring environment now." } ]
[ { "body": "<p>The interfaces might be a little overkill, but they're not necessarily a bad idea. This is how the code is meant to be written. If it's too complicated for the lead and potentially the rest of the team, then perhaps the company needs a new team. I have to architect things with our junior developers in mind with respect to our applications, but on our team we always establish the needs of the project against the resources available to train up our juniors to be able to handle certain things.</p>\n\n<p>That being said, we do have a few people here who just \"bang stuff out\", and then they end up having to maintain it because they've failed to follow industry standards so the rest of us have to re-engineer it their way before we can troubleshoot.</p>\n\n<p>My advice to you is to continue to lead by example doing things according to industry standards, but don't become a maverick bucking every trend set by those above you. You could end up coding yourself out of a job. Continue keeping up with best practice and current trends, continue to rally for these things, but don't just begin implementing things because you think they're the right way. Your description of this situation sounds like you handled it just right. They asked you to do something, and you did it according to best practices and industry standards. If they had other requirements, they should have included those instructions up front.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T15:04:38.733", "Id": "2261", "ParentId": "2259", "Score": "3" } }, { "body": "<p>I think you are complicating it a bit too much.</p>\n\n<p>The first question that pops into my head is, \"Why so much inheritance?\" Why inherit IXmlRepository from IRepository? What's the point? </p>\n\n<p>I'd also take issue with calling that a \"Repository\" - I think that is one of the most overused terms in architecture at the moment. Read Evans' DDD or Fowler's site and tell me if you really think that class qualifies under a definition of \"Repository\". And then convince me that no one will get confused between that and some other type of \"Repository\" that exists in your project. (just going from my experiences here)</p>\n\n<p>Also regarding inheritance, why the abstract DataAggregator? I understand you've cut down from the actual code, but from what I can see here it is again a totally pointless construct.</p>\n\n<p>Another one: you have an inheritance chain that is XmlInvoiceRepository -> BillingRepository -> IXmlRepository -> IRepository. Huh? Why on earth is XmlInvoiceRepository inherited from BillingRepository? Hopefully not just because Invoices are part of Billing in someone's conceptual model. </p>\n\n<p>Is there some reason XmlInvoiceRepository -> IXmlRepository wouldn't be enough?</p>\n\n<p>Also, you're throwing a lot of <code>sealed</code>'s in there. Why? Are there clear reasons for that choice, or is it more just for good measure? If the latter, get rid of it. Be as simple as possible and no simpler.</p>\n\n<p>Also, do you really need two interfaces to represent a function that can map from an XmlDocument to a generic type? How many places is that really getting used. Same question with your DataAggregator, how many different places is that really getting used.</p>\n\n<p>Your usage example is right on. That's what you should aim for. Short, concise, clear, to the point. The operations are occurring on the same level of abstraction.</p>\n\n<p>I would just say that you seem to be unnecessarily creating a bit too many artifacts in the process that don't appear to provide any actual value.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T19:50:35.857", "Id": "3643", "Score": "0", "body": "You're right, and after I posted this I consolidated it a little bit; for instance I only have the IXmlRepository<T>, not an IRepository and then an IXmlRepository that doesn't do anything except say I'm using an XmlDocument. I made some other changes I can't remember (rather, I can't remember what I obfuscated for the code snippet here :p). The `sealed` is something that I only recently started after reading something from the Java world about when to use `final` on classes." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T19:40:04.357", "Id": "2263", "ParentId": "2259", "Score": "5" } }, { "body": "<p>I agree with qes on all points but in summary you've just taken the Interface Segregation principle a little too far. But the most important point I want to get across is consider a career move. You've demonstrated a willingness to learn so don't hang around in a team that's not willing to assist you in this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T19:37:59.903", "Id": "2411", "ParentId": "2259", "Score": "4" } }, { "body": "<p>I think that DDD might be a little too much for such a small task. You don'treally need a repository to hold a in memory collection of data since you are not dealing with a datastore per say, only transfering data from one output to another.</p>\n\n<p>You could use the OOP design patterns for this for sure, look at the seperation of concerns and use IoC if you like and strategy pattern to encapsulate some algorithms, just don't go overboard and apply too many design patterns. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T08:45:46.963", "Id": "48132", "Score": "0", "body": "+1 for *\"DDD might be a little too much for such a small task.\"*. However there's really no sign of DDD in the example anyway... (having a class called \"Repository\" doesn't make it DDD)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T00:56:01.010", "Id": "30282", "ParentId": "2259", "Score": "2" } } ]
{ "AcceptedAnswerId": "2263", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:26:42.713", "Id": "2259", "Score": "5", "Tags": [ "c#", "design-patterns", "xml" ], "Title": "Is this architecture overly complex or following best practices?" }
2259
<p>Note: This was originally posted at <a href="https://stackoverflow.com/questions/5883475/javascript-closure-code-trivia-to-keep-the-event-handler-separate">SO</a>, and as per the recommendation moving to this form. </p> <p>In my effort to learn JS on the backdrop of SVG development, I got lot of help from <a href="https://stackoverflow.com/questions/5874041/javascript-closure">SO</a> so far. The answer to previous query was the best to understand closure; its usage and caveats in very short time. While continuing on the same line, I was trying to breakdown the below function so that it is more readable and easy to expand. It was part of an answer given by @<a href="https://stackoverflow.com/questions/4850821/svg-coordinates-with-transform-matrix">Phrogz</a>. I could not think a way to keep the onmove closure outside the loop.</p> <p>If someone can help me with a pseudo code/skeleton of how can it be done without too many variable to retain the state (like button click state while moving etc), it would clarify many of my doubts regarding how the closure can be assigned etc. You may also break the function into 3 event handlers (mousedown, mousemove, mouseup). I could not think a way to do this while keeping the context (mousemove only triggers when the mouse is down, as it is within the closure).</p> <p>I use jQuery typically in my projects, so if that helps to make the above code more maintainable, that would help too.</p> <pre><code>for (var a=svg.querySelectorAll('.drag'),i=0,len=a.length;i&lt;len;++i){ (function(el){ var onmove; // make inner closure available for unregistration el.addEventListener('mousedown',function(e){ el.parentNode.appendChild(el); // move to top var x = el.tagName=='circle' ? 'cx' : 'x'; var y = el.tagName=='circle' ? 'cy' : 'y'; var mouseStart = cursorPoint(e); var elementStart = { x:el[x].animVal.value, y:el[y].animVal.value }; onmove = function(e){ var current = cursorPoint(e); pt.x = current.x - mouseStart.x; pt.y = current.y - mouseStart.y; console.log("pt.x:" + pt.x + "pt.y:" + pt.y); var m = el.getTransformToElement(svg).inverse(); m.e = m.f = 0; pt = pt.matrixTransform(m); el.setAttribute(x,elementStart.x+pt.x); el.setAttribute(y,elementStart.y+pt.y); var dragEvent = document.createEvent("Event"); dragEvent.initEvent("dragged", true, true); el.dispatchEvent(dragEvent); }; document.body.addEventListener('mousemove',onmove,false); },false); document.body.addEventListener('mouseup',function(){ document.body.removeEventListener('mousemove',onmove,false); },false); })(a[i]); } </code></pre>
[]
[ { "body": "<ol>\n<li>Add more spaces.</li>\n<li>Use more named functions. (wrap the whole thing in an anonimous wrapper if you're worried about name space conflicts).</li>\n<li>When you do use lamdas give them names (it makes the code easier to read and you don't get showing up in the error log. </li>\n<li>Declare variables in higher functions to take advantage of closures. eg x, y, elementStart and mouseStart.</li>\n<li>camelCase.</li>\n<li>Use === unless you explicitly want to force casting.</li>\n<li>Don't make functions in a loop.</li>\n</ol>\n\n<p><a href=\"http://codr.cc/s/03c0d0af/js\" rel=\"nofollow\">http://codr.cc/s/03c0d0af/js</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-07T17:17:58.980", "Id": "2301", "ParentId": "2260", "Score": "2" } }, { "body": "<p>The function in a loop thing:</p>\n\n<pre><code>function innerStuff(el) {\n var onmove; // make inner closure available for unregistration\n el.addEventListener('mousedown',function(e){\n // ... etc etc\n }\n}\n\nfor (var a=svg.querySelectorAll('.drag'),i=0,len=a.length;i&lt;len;++i){\n innerStuff(a[i]);\n}\n</code></pre>\n\n<p>This will mean the variables are inside the <code>innerStuff()</code> function and you are not creating a new function every time. <em>(don't use that name ... make your own descriptive one.)</em> </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T05:28:39.387", "Id": "35805", "ParentId": "2260", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:37:19.507", "Id": "2260", "Score": "4", "Tags": [ "javascript", "jquery", "closure" ], "Title": "JavaScript closure: code trivia to keep the event handler separate" }
2260
<p>I have a representation for each <a href="http://en.wikipedia.org/wiki/Tetris#Colors_of_tetrominoes" rel="nofollow">initial shape</a> as an <code>Enum</code> with points and another for each rotated shape in the same <code>Enum</code>.</p> <p>Here is an example of the latter <code>Enum</code>:</p> <pre><code>// // * * // * // * J_SHAPE_SOUTH(new Point[] { new Point(2, 0), new Point(2, 1), new Point(2, 2), new Point(3, 2) }), // // * * // * // * L_SHAPE_SOUTH(new Point[] { new Point(1, 2), new Point(2, 0), new Point(2, 1), new Point(2, 2) }); </code></pre> <p>I was then wondering whether to move the rotated shapes into individual <code>Enum</code>s, say <code>RotatedJShape</code>, or simply keep <em>all</em> the rotated shapes in the same <code>Enu</code>m. My concern is that some shapes like the I-shape only has one rotated condition, so it seems pointless to have an <code>Enum</code> for that shape.</p> <p>What would be the most suitable approach in my case in terms of scalability and code correctness?</p>
[]
[ { "body": "<p>How are you rotating them now? Would it make more sense to change from an enum to a class with a Rotate method instead?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T06:55:46.180", "Id": "3656", "Score": "0", "body": "Swapping through the list of rotated pieces. I wanted an easy approach, that's why I did it this way. Rotating would require a somewhat complex logic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-07T15:09:40.567", "Id": "3673", "Score": "3", "body": "@Whirlwin: I believe 'complex' is somewhat exaggerating. :) Besides you asked for a scalable approach. If you ever want to support other blocks, this is the most scalable." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T22:34:42.860", "Id": "2267", "ParentId": "2265", "Score": "5" } }, { "body": "<p>Ages ago I did a Tetris clone, and my idea for a data structure was this:</p>\n\n<p>A circular linked list of matrices.</p>\n\n<p>How do you rotate? Walk the list...</p>\n\n<p>You can have a single array of these lists (one per each block type), and your game logic's notion of the \"current piece\" is a reference to something inside that table. That way the game logic can have no knowledge of the different shapes, and you declare a small array that defines what the shapes are.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T02:02:02.367", "Id": "2273", "ParentId": "2265", "Score": "9" } }, { "body": "<p>Have an enum like you do for the pieces. </p>\n\n<p>That is okay.</p>\n\n<p>Points is more work than you need to do.</p>\n\n<p>The piece in play is an instance, with a reference to the original enum.</p>\n\n<pre><code>class FallingBlock {\n BlockEnum originalBlock;\n Point location;\n Shape shapeToDraw; // a copy of the original shape so you can manipulate it.\n}\n</code></pre>\n\n<p>The shape instance can be rotated, scaled etc.. Java2D is quite helpful.\nYou could do it all with AffineTransforms upon original shapes , and not have an original shape and a copy but this way is less complicated.\nAnd you can have arbitrarily complicated shapes!\nYou keep the original for the points value, and so you can display it in a \"current block\" pane.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T00:22:21.047", "Id": "2447", "ParentId": "2265", "Score": "2" } } ]
{ "AcceptedAnswerId": "2273", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T21:59:03.937", "Id": "2265", "Score": "6", "Tags": [ "java", "design-patterns" ], "Title": "Tetris clone in Java" }
2265
<p>Over on <a href="https://stackoverflow.com/questions/5904425/what-is-difference-between-protected-and-private-derivation-in-c">StackOverflow</a>, I was asked if I could come up with an example where private inheritance would be preferred to composition (in C++). The following is the situation I described, and I was wondering which implementation you would prefer. Most of the references I've found to private inheritance are poor uses, and I agree that it is rarely useful.</p> <p>Let's say you have a class <code>Foo</code> that should be immutable, but it's rather complicated to set up (maybe you're reading settings from a file), so you decide to create a separate class <code>FooBuilder</code> to set up your <code>Foo</code> objects for you. My solution (using private inheritance) is to declare an abstract interface:</p> <pre><code>class MutableFoo { public: virtual void setValue(int n) = 0; virtual void setSomethingElse(string s) = 0; }; </code></pre> <p>And my original <code>Foo</code> class:</p> <pre><code>class Foo : private MutableFoo { public: Foo(FooBuilder builder) { builder.build(this); } int value() const { return myValue; } string somethingElse() const { return mySomethingElse; } private: void setValue(int n) { myValue = n; } void setSomethingElse(string s) { mySomethingElse = s; } int myValue; string mySomethingElse; }; </code></pre> <p>And the <code>FooBuilder</code>:</p> <pre><code>class FooBuilder { public: FooBuilder(string fileWithSettings); void build(MutableFoo *fooToBuild); }; </code></pre> <p>Now I can create read-only <code>Foo</code> objects without declaring them all to be <code>const</code>:</p> <pre><code>Foo aFoo(FooBuilder(aFileWithSettings)); </code></pre> <p>A similar implementation using composition might look something like this:</p> <pre><code>class Foo { public: Foo(FooData d); int value() const { return data.value(); } string somethingElse() const { return data.somethingElse(); } private: FooData data; }; class FooData { public: int value() const { return myValue; } int somethingElse() const { return mySomethingElse; } void setValue(int n) { myValue = n; } void setSomethingElse(string s) { mySomethingElse = s; } private: int myValue; string mySomethingElse; }; class FooBuilder { public: FooBuilder(string fileWithSettings); FooData getData() const; }; Foo aFoo(FooBuilder(aFileWithSettings).getData()); </code></pre> <p>I don't see much difference between these implementations as far as coupling is concerned (which is the complaint I see most frequently leveled against inheritance vs. composition). In fact, the version using inheritance may have less coupling, as both <code>Foo</code> and <code>FooBuilder</code> depend on an abstract interface (<code>MutableFoo</code>) instead of a concrete class <code>FooData</code>. Also, if we have lots of methods, the composition version will end up with lots of simple delegations, which is tedious if nothing else.</p> <p>Which do you prefer? Have I found a reasonable use for private inheritance? Have you found other reasonable uses?</p> <p>And finally, has <em>anyone</em> ever found a legitimate use for protected inheritance? :-P</p>
[]
[ { "body": "<p>Herb Sutter in his book 'Exceptional C++', Item 24 (Uses and Abuses of Inheritance), discusses the issue, and cites the following reasons for using private inheritance (instead of containment):</p>\n\n<ul>\n<li>Override a virtual function</li>\n<li>Access to a protected member</li>\n<li>Construct the used object before, or destroy it after, another base sub-object</li>\n<li>Share a common virtual base class or override the construction of a virtual base class</li>\n<li>We benefit substantially from the empty base class optimization</li>\n<li>We need \"controlled polymorphism\" - LSP IS-A, but in certain code only</li>\n</ul>\n\n<p>If one of these situations applies, then you must use private inheritance. Otherwise, containment is preferred.</p>\n\n<p>The last of these reasons is cited as a possible reason for protected inheritance.</p>\n\n<p>He also comments:</p>\n\n<blockquote>\n <p>That's as complete a list as I can make of the reasons to use non-public inheritance. (In fact, just one additional point would make this a complete list of all reasons to use any kind of inheritance: We need public inheritance to express IS-A. [...])</p>\n</blockquote>\n\n<p>The item occupies 8 pages.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T05:06:02.360", "Id": "2306", "ParentId": "2268", "Score": "3" } }, { "body": "<p>Your second case isn't really using composition. In my view composition requires that I'm making use of usually a few distinct object each of which has internal logic. Your FooData class has no logic. You are really implementing the parameter object pattern. </p>\n\n<p>FooData basically consists of an object which holds all of the arguments that you would usually pass to a constructor. You are using FooData because there are too many parameters to configure. But as long as the object does nothing but hold argument you should implement it as a struct without getters/setters. </p>\n\n<p>If you do that, I think your second case wins over the first case. It is simpler and doesn't make use of any unusual techniques. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T00:58:09.773", "Id": "2318", "ParentId": "2268", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T23:08:54.410", "Id": "2268", "Score": "8", "Tags": [ "c++" ], "Title": "Composition or Private Inheritance for Implementing Builder?" }
2268
<p>I've got a method that parses a file. I take all the words and add them to a <code>SortedSet</code>. Every word contains a list of <code>Lines</code> that contain said word. Words are not strings but a class I created:</p> <pre><code>class Word : IComparable&lt;Word&gt; { public Word() { Lines = new List&lt;Line&gt;(); } public string WordStr { get; set; } public List&lt;Line&gt; Lines { get; set; } public int CompareTo(Word other) { return string.Compare(this.WordStr, other.WordStr, StringComparison.OrdinalIgnoreCase); } } </code></pre> <p>And the method that parses the file (I suspect I am not doing something properly here):</p> <pre><code>private void AddFile(string path) { Regex regex = new Regex("[^A-Za-z0-9\\s\\']"); FileInfo fi = new FileInfo(path); if (!fi.Exists || Files.Contains(path.ToLower())) //File does not exist or file already indexed { return; } Files.Add(path.ToLower()); StreamReader sr = new StreamReader(path); string file = sr.ReadToEnd(); string saniFile = regex.Replace(file, ""); string[] saniLines = saniFile.Split(new char[]{'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries); int lineNo = 1; foreach (var l in saniLines) { Line line = new Line(l, path, lineNo); string[] words = l.Split(' '); foreach (var word in words) { Word w = new Word(); w.WordStr = word; if (Words.Contains(w, new WordComparer())) //Set already contains the word { Word wordToAdd = (from wors in Words where wors.WordStr.ToLower() == w.WordStr.ToLower() select wors).First(); if (!wordToAdd.Lines.Contains(line)) wordToAdd.Lines.Add(line); } else { w.Lines.Add(line); Words.Add(w); } } lineNo++; } } </code></pre> <p>I have the exact same functionality working in C++ and it's orders of magnitudes faster. So is there something I am doing incorrectly? What if I used a <code>SortedDictionary</code> instead of a <code>SortedSet</code> for the words? Then the key could be the string that is the word and the value would be the list of lines that contain that word. </p> <p>For reference, a 618KB text file takes a few seconds to parse and index in C++. It's taking me minutes to do it in C#.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T02:10:40.870", "Id": "3646", "Score": "0", "body": "I would change the `foreach` to a `for` if you can. I was trying to do a lot of small things really fast (few thousand in less than a second) and `foreach` added a great deal of overhead (causing it to run more than 1 second). I don't know if that would apply in a longer running situation. But I do know in general, `for` will be faster than `foreach`. I've seen benchmarks on SO where it's upwards of 5x faster in some situations." } ]
[ { "body": "<p>Your best bet is to not speculate or make assumptions when it comes to performance. Grab a profiler and get some real data so you can make the correct decisions based on that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T01:09:12.107", "Id": "3645", "Score": "0", "body": "Unfortunately, I'm not sure of how to \"grab a profiler\". I was really hoping someone could see something that could be improved." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T05:41:43.980", "Id": "3655", "Score": "1", "body": "@Pete: Google is your friend." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T16:50:04.013", "Id": "3661", "Score": "0", "body": "JetBrains (ReSharper guys) make one here: http://www.jetbrains.com/profiler/ Also - Visual Studio 2010 Premium has one built in." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T00:04:12.113", "Id": "2272", "ParentId": "2269", "Score": "3" } }, { "body": "<p>Your instincts are basically right that maybe a dictionary of some sort could help. Let's look at some key lines of your code. </p>\n\n<pre><code>foreach (var l in saniLines)\n{\n Line line = new Line(l, path, lineNo);\n string[] words = l.Split(' ');\n foreach (var word in words)\n {\n Word w = new Word();\n w.WordStr = word;\n\n if (Words.Contains(w, new WordComparer())) //Set already contains the word\n {\n Word wordToAdd = (from wors in Words where wors.WordStr.ToLower() == w.WordStr.ToLower() select wors).First();\n if (!wordToAdd.Lines.Contains(line))\n wordToAdd.Lines.Add(line);\n</code></pre>\n\n<p>I see 5 nested loops here. If you step through the code, you'll see them, too. The outer 2 are obvious, you've coded them explicitly. But stepping through the code will reveal the looping being done at <code>Words.Contains</code>. The Linq query is also an abstracted loop. And <code>wordToAdd.Lines.Contains</code> is also going to be a loop. You're going to pay a high price for these. </p>\n\n<p>Profiling will always help. But I would suggest perhaps changing <code>Words</code> to some sort of <code>IDictionary&lt;string, Word&gt;</code>, where you can replace </p>\n\n<pre><code>if (Words.Contains(w, new WordComparer())) //Set already contains the word\n{\n Word wordToAdd = (from wors in Words where wors.WordStr.ToLower() == w.WordStr.ToLower() select wors).First();\n</code></pre>\n\n<p>With something more like </p>\n\n<pre><code>if (Words.ContainsKey(w.WordStr))\n{\n Word wordToAdd = Words[w.WordStr];\n // ...\n}\n</code></pre>\n\n<p>And you could also change <code>Lines</code> into a <code>HashSet&lt;Line&gt;</code> instead of a list. That should improve the performance of </p>\n\n<pre><code>if (!wordToAdd.Lines.Contains(line))\n wordToAdd.Lines.Add(line);\n</code></pre>\n\n<p>In fact, <code>HashSet&lt;T&gt;.Add(T val)</code> could be used by itself, without the call to <code>Contains</code>, as <code>Add</code> returns a <code>bool</code> indicating if the addition could be performed. If a matching value is already in the set, it simply returns <code>false</code> without modifying its contents.</p>\n\n<p>Try these changes, measure the performance before and after and see where you are. </p>\n\n<p>Unrelated, but I also recommend that you wrap your <code>StreamReader</code> in a <code>using () { }</code> block so that the resource is properly disposed when you're through with it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T03:18:44.347", "Id": "3652", "Score": "0", "body": "Wow, thank you so much. The same file actually indexes almost instantly now (after implementing your two changes)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T03:21:20.710", "Id": "3653", "Score": "0", "body": "@Pete, that's a pretty good boost! Glad to help." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T02:59:53.497", "Id": "2274", "ParentId": "2269", "Score": "14" } } ]
{ "AcceptedAnswerId": "2274", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T23:20:49.543", "Id": "2269", "Score": "7", "Tags": [ "c#", "performance", "parsing" ], "Title": "Slow-running File parser" }
2269
<p>Readability is a subjective parameter used to measure an aspect of code quality. It is based on the assumption that code should be easily comprehensible by humans, both in its form and in its meaning. </p> <p>To improve code readability, the following is usually considered:</p> <ul> <li><p>The code is written such that a person with poorer programming skills will be able to understand what is written.</p></li> <li><p>Adding descriptive comments to explain every step of the way. </p></li> <li><p>Using proper indentation and white spaces.</p></li> <li><p>Choosing object\variable names that describe their purposes.</p></li> <li><p>Referencing the algorithm and the responsible authors.</p></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T23:58:16.970", "Id": "2270", "Score": "0", "Tags": null, "Title": null }
2270
<p>I have written a simple web-scraper in Common Lisp, &amp; would greatly appreciate any feedback:</p> <pre><code>(defpackage :myfitnessdata (:use :common-lisp) (:export #:main)) (in-package :myfitnessdata) (require :sb-posix) (load (merge-pathnames "quicklisp/setup.lisp" (user-homedir-pathname))) (ql:quickload '("drakma" "closure-html" "cxml-stp" "net-telent-date")) (defun show-usage () (format t "MyFitnessData - a CSV web scraper for the MyFitnessPal website.~%") ;; snip (format t "'c:\\Users\\bob\\weights.csv', overwriting it if it exists.~%")) (defun login (username password) "Logs in to www.myfitnesspal.com. Returns a cookie-jar containing authentication details." (let ((cookie-jar (make-instance 'drakma:cookie-jar))) (drakma:http-request "http://www.myfitnesspal.com/account/login" :method :post :parameters `(("username" . ,username) ("password" . ,password)) :cookie-jar cookie-jar) cookie-jar)) (defun logged-in? (cookie-jar) "Returns true if a cookie-jar contains login information for www.myfitnesspal.com, and nil otherwise." (let ((logged-in? nil)) (loop for cookie in (drakma:cookie-jar-cookies cookie-jar) do (if (and (equal (drakma:cookie-name cookie) "known_user") (equal (drakma:cookie-domain cookie) "www.myfitnesspal.com") (drakma:cookie-value cookie)) (setq logged-in? t))) logged-in?)) (defun get-page (page-num cookie-jar) "Downloads a potentially invalid HTML page containing data to scrape. Returns a string containing the HTML." (let ((url (concatenate 'string "http://www.myfitnesspal.com/measurements/edit?type=1&amp;page=" (write-to-string page-num)))) (let ((body (drakma:http-request url :cookie-jar cookie-jar))) (if (search "No measurements found." body) nil body)))) (defun scrape-body (body) "Scrapes data from a potentially invalid HTML document, returning a list of lists of values." (let ((valid-xhtml (chtml:parse body (cxml:make-string-sink)))) (let ((xhtml-tree (chtml:parse valid-xhtml (cxml-stp:make-builder)))) (scrape-xhtml xhtml-tree)))) (defun scrape-xhtml (xhtml-tree) "Scrapes data from an XHTML tree, returning a list of lists of values." (let ((results nil)) (stp:do-recursively (element xhtml-tree) (when (and (typep element 'stp:element) (equal (stp:local-name element) "tr")) (if (scrape-row element) (setq results (append results (list (scrape-row element))))))) results)) (defun scrape-row (row) "Scrapes data from a table row into a list of values." (if (equal 4 (stp:number-of-children row)) (let ((measurement-type (nth-child-data 0 row)) (measurement-date (nth-child-data 1 row)) (measurement-value (nth-child-data 2 row))) (if (not (equal measurement-type "Measurement")) (list measurement-date measurement-value))))) (defun nth-child-data (number row) (stp:data (stp:nth-child 0 (stp:nth-child number row)))) (defun recursive-scrape-page (page-num cookie-jar) "Recursively scrapes data from a page and all successive pages. Returns a list of lists of values." (let ((body (get-page page-num cookie-jar))) (if body (append (scrape-body body) (recursive-scrape-page (+ 1 page-num) cookie-jar))))) (defun show-login-failure () (format t "Login failed.~%")) (defun write-csv (data csv-pathname) "Takes a list of lists of values, converts them to CSV, and writes them to a file." (with-open-file (stream csv-pathname :direction :output :if-exists :overwrite :if-does-not-exist :create) (format stream (make-csv data)))) (defun separate-values (value-list) "Takes a list of values, and returns a string containing a CSV row that represents the values." (format nil "~{~A~^,~}" value-list)) (defun make-csv (list) "Takes a list of lists of values, and returns a string containing a CSV file representing each top-level list as a row." (let ((csv "") (sorted-list (sort list #'first-column-as-date-ascending))) (mapcar (lambda (row) (setq csv (concatenate 'string csv (separate-values row) (format nil "~%")))) sorted-list) csv)) (defun first-column-as-date-ascending (first-row second-row) "Compares two rows by their first column, which is parsed as a time." (&lt; (net.telent.date:parse-time (car first-row)) (net.telent.date:parse-time (car second-row)))) (defun scrape (username password csv-pathname) "Attempts to log in, and if successful scrapes all data to the file specified by csv-pathname." (let ((cookie-jar (login username password))) (if (logged-in? cookie-jar) (write-csv (recursive-scrape-page 1 cookie-jar) csv-pathname) (show-login-failure)))) (defun main (args) "The entry point for the application when compiled with buildapp." (if (= (length args) 4) (let ((username (nth 1 args)) (password (nth 2 args)) (csv-pathname (nth 3 args))) (scrape username password csv-pathname)) (show-usage))) </code></pre> <p>There are several areas I'm unsure about, &amp; would particularly appreciate feedback on:</p> <ul> <li>use of let &amp; setq (I've got this wrong <a href="https://codereview.stackexchange.com/questions/2135/simple-octal-reader-macro-in-common-lisp">in the past</a>)</li> <li>structure, naming &amp; comments (as a Lisper, would you like to inherit this codebase?)</li> </ul> <p>The entire app is <a href="https://github.com/duncan-bayne/myfitnessdata/" rel="nofollow noreferrer">here on GitHub</a> if you're interested.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T16:19:09.227", "Id": "3660", "Score": "0", "body": "I always feel interested in every CL projects . Hey thank to your codebase, now I know how to use defpackage :D" } ]
[ { "body": "<p>You might want to take a look at defining <code>asdf</code> systems instead of using <code>quicklisp</code> to load dependencies internally.</p>\n\n<p>The standard way of doing this is to set up an <code>asd</code> file. <a href=\"http://tychoish.com/rhizome/using-asdf-install-with-sbcl/\" rel=\"nofollow\">Here's</a> a decent walk-through of that process. It's more verbose than <code>ql:quickload</code>, but it lets people who don't have quicklisp use your package regardless.</p>\n\n<p>On second thought, screw those guys, keep it up.</p>\n\n<hr>\n\n<pre><code>(defun logged-in? (cookie-jar) \n \"Returns true if a cookie-jar contains login information for www.myfitnesspal.com, and nil otherwise.\"\n (let ((logged-in? nil))\n (loop for cookie in (drakma:cookie-jar-cookies cookie-jar) do\n (if (and (equal (drakma:cookie-name cookie) \"known_user\")\n (equal (drakma:cookie-domain cookie) \"www.myfitnesspal.com\")\n (drakma:cookie-value cookie))\n (setq logged-in? t)))\n logged-in?))\n</code></pre>\n\n<p>There's actually a <code>loop</code> shorthand for \"make sure each member of <code>list</code> satisfies <code>predicate</code>\". The above function can be written as</p>\n\n<pre><code>(defun logged-in? (cookie-jar) \n \"Returns true if a cookie-jar contains login information for www.myfitnesspal.com, and nil otherwise.\"\n (loop for cookie in (drakma:cookie-jar-cookies cookie-jar)\n always (and (equal (drakma:cookie-name cookie) \"known_user\")\n (equal (drakma:cookie-domain cookie) \"www.myfitnesspal.com\"))))\n</code></pre>\n\n<hr>\n\n<p><code>foo?</code> is the Scheme convention for predicates. The common CL conventions are <code>foop</code> or <code>foo-p</code>. Personally, I prefer <code>foo?</code> too, just be aware that it's not standard.</p>\n\n<hr>\n\n<pre><code>...\n(sorted-list (sort list #'first-column-as-date-ascending)))\n...\n</code></pre>\n\n<p>This can get you into trouble. The Common Lisp <code>sort</code> should really be named <code>sort!</code>, because it's destructive (so <code>sorted-list</code> will now contain a sorted list, but <code>list</code> won't still be the unsorted list, and isn't guaranteed to be the complete sequence anymore). If you might use <code>list</code> again later, instead do</p>\n\n<pre><code>...\n(sorted-list (sort (copy-list list) #'first-column-as-date-ascending)))\n...\n</code></pre>\n\n<hr>\n\n<pre><code>(if (search \"No measurements found.\" body)\n nil\n body)\n</code></pre>\n\n<p>Can be written as </p>\n\n<pre><code>(unless (search \"No measurements found.\" body) body)\n</code></pre>\n\n<hr>\n\n<p><strong>EDIT:</strong> </p>\n\n<p><code>format</code> can accept nested iterations in the directive, so you can eliminate <code>separate-values</code> by writing <code>make-csv</code> as</p>\n\n<pre><code>(defun make-csv (list)\n \"Takes a list of lists of values, and returns a string containing a CSV file representing each top-level list as a row.\"\n (let ((sorted-list (sort list #'first-column-as-date-ascending)))\n (format nil \"~{~{~A~^,~}~^~%~}\" sorted-list)))\n</code></pre>\n\n<p>You could eliminate <code>make-csv</code> entirely by putting the above sort+directive directly into <code>write-csv</code> (this would also save you a trip through the CSV string, which may or may not make a significant difference).</p>\n\n<hr>\n\n<p><code>recursive-scrape-page</code> can be simplified down to</p>\n\n<pre><code>(defun scrape-page (page-num cookie-jar)\n (loop for i from page-num \n if (get-page i cookie-jar) collect it into pg\n else return pg))\n</code></pre>\n\n<p>As a rule, Common Lisp doesn't guarantee tail-calls the way Scheme does, so it's generally a better idea to use a <code>loop</code> than raw recursion. SBCL does support some tail calls, but it isn't guaranteed (though this situation looks simple enough that it just might; do some profiling and compare).</p>\n\n<p>You should be able to simplify <code>scrape-xhtml</code> in a similar way to eliminate <code>(let ((results nil))</code>.</p>\n\n<p>Note that I haven't tested or profiled any of this since I don't have a \"MyFitnessPal\" account. Check that it works first.</p>\n\n<hr>\n\n<p>EDIT the Second:</p>\n\n<pre><code> ...\n (let ((valid-xhtml (chtml:parse body (cxml:make-string-sink))))\n (let ((xhtml-tree (chtml:parse valid-xhtml (cxml-stp:make-builder))))\n ...\n</code></pre>\n\n<p>You use this nested let idiom in a couple of places. I assume this is just because the value of <code>xhtml-tree</code> depends on the value of <code>valid-html</code>. In this case, you can instead write</p>\n\n<pre><code> ...\n (let* ((valid-xhtml (chtml:parse body (cxml:make-string-sink)))\n (xhtml-tree (chtml:parse valid-xhtml (cxml-stp:make-builder))))\n ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T19:00:42.790", "Id": "2293", "ParentId": "2277", "Score": "6" } }, { "body": "<p>Be careful to indent your code properly to make it more readable. For instance:</p>\n\n<pre><code>(let ((cookie-jar (login username password)))\n (if (logged-in? cookie-jar)\n (write-csv (recursive-scrape-page 1 cookie-jar) csv-pathname)\n (show-login-failure)))\n</code></pre>\n\n<p>That piece of code could by the way possibly be improved by an idiomatic <code>WITH-VALID-LOGIN</code> macro (if you want to practice). It could become...</p>\n\n<pre><code>(with-valid-login (cookie-jar username password)\n (write-csv (recursive-scrape-page 1 cookie-jar) csv-pathname))\n</code></pre>\n\n<p>...with a macro definition like:</p>\n\n<pre><code>(defmacro with-valid-login ((jar user password) &amp;body body)\n `(let ((,jar (login ,user ,password)))\n (if (logged-in? ,jar)\n (progn ,@body)\n (show-login-failure))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2016-01-12T07:41:18.313", "Id": "116533", "ParentId": "2277", "Score": "3" } } ]
{ "AcceptedAnswerId": "2293", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T09:33:26.050", "Id": "2277", "Score": "6", "Tags": [ "common-lisp" ], "Title": "Simple web-scraper in Common Lisp (SBCL)" }
2277
<p>As a Python newbie, I have coded this binary tree as best as I could to follow Python idioms. However, I know it is still very verbose and not up to standard. I would like Python experts to tear this apart and identify its weaknesses. </p> <pre><code>class TreeNode(object): """ applicable to all tree nodes including root node """ def __init__(self, value, left=None, right=None,root=False): self.value = value TreeNode.check(left) TreeNode.check(right) self.left = left self.right = right self.root = root def inorder(self): s = list() if not self.left: s.append('') else: s.append(self.left.inorder()) s.append(str(self.value)) if not self.right: s.append('') else: s.append(self.right.inorder()) return ' '.join(s).strip() # returns True if success, False otherwise def insert( self, new_value ): # TODO ?? what happens if we are inserting strings if not new_value and new_value != 0: return False if new_value == self.value: return False # need to find the right location in terms of binary tree ordering if new_value &lt; self.value: if not self.left: self.left = TreeNode(new_value) return True else: return self.left.insert( new_value ) elif new_value &gt; self.value: if not self.right: self.right = TreeNode(new_value) return True return self.right.insert( new_value ) return False @staticmethod def check(node): if not node: return if not isinstance(node, TreeNode): raise TypeError('only instances of TreeNode are allowed') def __repr__(self): return '(' + repr(self.left) + ',' + \ str(self.value) + ',' + repr(self.right) + ')' </code></pre>
[]
[ { "body": "<p>Firstly, the official python style guide recommends 4-space indentation, and you are using 2. (No big deal but following the style guide is helpful)</p>\n\n<pre><code>class TreeNode(object):\n \"\"\" applicable to all tree nodes including root node \"\"\"\n def __init__(self, value, left=None, right=None,root=False):\n</code></pre>\n\n<p>Your code never passes a left/right parameter. There are also doesn't seem to be a good reason why you would pass left/right parameters in the construction of the tree. I assume you would use this class by constructing an empty tree and inserting values into it, not by composing trees. As a result, I suggest eliminating left/right.</p>\n\n<p>Also, you have a root parameter which is never used. It looks like something that you should eliminate. </p>\n\n<p>Additionally, you cannot create an empty tree with this method.</p>\n\n<pre><code> self.value = value \n TreeNode.check(left)\n TreeNode.check(right)\n self.left = left\n self.right = right\n self.root = root\n\n def inorder(self):\n s = list()\n</code></pre>\n\n<p>Use s = [], also don't use single letter variable names. </p>\n\n<pre><code> if not self.left:\n</code></pre>\n\n<p>When checking for None, recommened practice is to do it like: if self.left is None:</p>\n\n<pre><code> s.append('') \n else:\n s.append(self.left.inorder())\n\n s.append(str(self.value))\n\n if not self.right:\n s.append('')\n else:\n s.append(self.right.inorder())\n\n return ' '.join(s).strip()\n</code></pre>\n\n<p>The fact that you are trying to construct a string is kinda wierd. I'd expect this method to produce either an iterator or a list containing all the elements. </p>\n\n<pre><code> # returns True if success, False otherwise \n def insert( self, new_value ):\n # TODO ?? what happens if we are inserting strings\n if not new_value and new_value != 0:\n return False\n</code></pre>\n\n<p>This is why you should \"is None\"</p>\n\n<pre><code> if new_value == self.value:\n return False\n\n # need to find the right location in terms of binary tree ordering\n if new_value &lt; self.value:\n if not self.left:\n self.left = TreeNode(new_value) \n return True\n else:\n return self.left.insert( new_value )\n elif new_value &gt; self.value:\n</code></pre>\n\n<p>You've already established that this expression must be true, just use else</p>\n\n<pre><code> if not self.right:\n self.right = TreeNode(new_value)\n return True\n return self.right.insert( new_value )\n</code></pre>\n\n<p>The previous branch had this inside an else. You should at least be consistent between branches</p>\n\n<pre><code> return False\n\n @staticmethod \n def check(node):\n if not node:\n return\n if not isinstance(node, TreeNode):\n raise TypeError('only instances of TreeNode are allowed')\n</code></pre>\n\n<p>Explicitly checking types is frowned upon. All you manage is converting an AttributeError into a TypeError. However, a check method could usefully verify the invariants of a data structure. (Just only do it while debugging). </p>\n\n<pre><code> def __repr__(self):\n return '(' + repr(self.left) + ',' + \\\n str(self.value) + ',' + repr(self.right) + ')'\n</code></pre>\n\n<p>TreeNode seems to be a collection class, one that holds elements. The internal structure shouldn't matter to the world. However, repr spills the internal structure for the world to see. I'd suggest calling inorder to produce all of the elements inside the string and show that. Also repr's value should make it clear what class is being repr, by including \"TreeMap\" somewhere in its output.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-07T20:58:27.117", "Id": "3676", "Score": "0", "body": "Whats wrong with single letter variable names? Especially for something so used as the `s` in this case. Do you dislike `i` as well?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-07T21:31:47.397", "Id": "3677", "Score": "0", "body": "Single letter variable names are acceptable if the abbreviation is common. Otherwise it just makes the code harder to read. s doesn't strike me as a common abbreviation for what you are doing. Of course, that's subjective, so if you find it common enough, that's ok." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-07T21:33:34.243", "Id": "3678", "Score": "0", "body": "My own policy is to almost entirely avoid single letter variable names. Python features properly used eliminate many of the variables which would typically be candidates for such short names. I always use longer names to make sure I don't slip into being lazy and stop looking for a better way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T06:28:06.763", "Id": "3681", "Score": "0", "body": "There are tons of code written by supposedly expert pythonista which uses `isinstance`. When is it kosher to use it ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T13:56:34.920", "Id": "3683", "Score": "0", "body": "@Jacques, that question is much too large to answer here. You should probably open another question on that. Short answer: everything always depends." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T12:35:48.017", "Id": "2282", "ParentId": "2280", "Score": "6" } } ]
{ "AcceptedAnswerId": "2282", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T10:06:26.743", "Id": "2280", "Score": "9", "Tags": [ "python", "beginner", "tree" ], "Title": "Binary tree in Python" }
2280
<p>I've got a list with about 120 items in IE and I have some items I want to activate. I compare, build and randomize some Arrays on the fly. The for loop in the <code>run()</code> function is really slow, and i tried to add a <code>setTimeout()</code>, like i've read somewhere on stackoverflow.</p> <p>It does not seem to improve the performance, and if the requested list of items to be activated is too large, IE starts to give the slow script error.</p> <p>Can i optimize this to something that'll work?</p> <pre><code>for(index = 0; index &lt; 120; index++){ wrapper.tempSlot.push(index); } Array.prototype.shuffle = function shuffle(){ var tempSlot; var randomNumber; for(var i =0; i != this.length; i++){ randomNumber = Math.floor(Math.random() * this.length); tempSlot = this[i]; this[i] = this[randomNumber]; this[randomNumber] = tempSlot; } } Array.prototype.compare = function(testArr) { if (this.length != testArr.length) return false; for (var i = 0; i &lt; testArr.length; i++) { if (this[i].compare) { if (!this[i].compare(testArr[i])) return false; } if (this[i] !== testArr[i]) return false; } return true; } function checkAgainstEl(val){ val = $($item.select).eq(val).data('personid') return val in oc([array, with, to, be, activated, numbers]); } var index = 0; var length = wall.globals.highlight.selection.length; var run = function(){ for(;index &lt; length; index++){ wrapper.tempSlot.shuffle(); var pop = wrapper.tempSlot.pop(); var value = wall.globals.highlight.selection[index]; var newItem = $('#wallItem' + value); wrapper.objectsStr = wrapper.objectsStr + '#wallItem' + value + ', '; while(checkAgainstEl(pop)){ wrapper.tempSlot.shuffle() pop = wrapper.tempSlot.pop(); } beforeItem = $($item.select).eq(pop); newItem.insertBefore(beforeItem); $($container.select).append(beforeItem); if (index + 1 &lt; length &amp;&amp; index % 5 == 0) { setTimeout(run, 25); } } } run(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T13:57:19.827", "Id": "3659", "Score": "0", "body": "I haven't looked at it too deeply, but just on the surface it looks like you're ultimately nesting 3 loops, each with a minimum of 120 members. This becomes 1,728,000 operations. it also looks like compare calls itself in yet another nest. My suspicion is that this is where your slowness is being introduced." } ]
[ { "body": "<ol>\n<li><p>Interacting with the DOM is one of the slowest operations in JavaScript. I'd suggest selecting all your elements before the loop, then referring to the cached elements inside.</p></li>\n<li><p>On the same token, do not perform any DOM manipulation in a loop if you can help it. Since it doesn't look like you can, another approach is to detach all DOM elements you're going to rearrange before the loop, perform the manipulation inside the loop, then re-attach them to the DOM at the end.</p></li>\n<li><p>A reverse <code>while</code> loop would be faster than the <code>for</code>.</p></li>\n<li><p>If you're using a version of jQuery prior to 1.6, the <code>.data()</code> method carries a lot of overhead. In <code>checkAgainstEl()</code>, use <code>$.data($($item.select).get(val), 'personId')</code> instead.</p></li>\n<li><p>It looks like you're re-wrapping jQuery objects in new jQuery objects unnecessarily, and in multiple places. Like in #4. I'm assuming variables prefixed with a <code>$</code> are jQuery objects; if they are, no need to wrap them in <code>$()</code> again.</p></li>\n</ol>\n\n<p>Your biggest problem is the DOM interaction inside a loop. Cut that out any way you can and you'll be golden.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T20:45:31.847", "Id": "2295", "ParentId": "2283", "Score": "5" } } ]
{ "AcceptedAnswerId": "2295", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T13:37:15.867", "Id": "2283", "Score": "4", "Tags": [ "javascript", "performance", "jquery", "shuffle" ], "Title": "Activating items in some randomized arrays" }
2283
<p>I noticed a pattern in some elisp modes I was putting together:</p> <pre><code>(let ((map (make-sparse-keymap))) (define-key map KEY 'FN) ... (setq FOO map)) </code></pre> <p>so I wrote up the following macro</p> <pre><code>(defmacro def-sparse-map (name &amp;rest key/fn-list) `(let ((map (make-sparse-keymap))) ,@(loop for (key fn) on key/fn-list by #'cddr collecting `(define-key map ,key ',fn)) (setq ,name map))) </code></pre> <p>which lets me write</p> <pre><code>(def-sparse-map FOO KEY FN ...) </code></pre> <p>instead. All comments welcome, but some specific questions are </p> <ul> <li>Can this be done more cleanly (and more generally, is it acceptable practice to use the ported CL functions when defining Elisp modes)? </li> <li>Are there some issues I'm not seeing with that use of <code>let</code>/<code>setq</code>? </li> <li>Is it worth it writing up an elisp <a href="http://gbbopen.org/hyperdoc/ref-with-gensyms.html" rel="nofollow"><code>with-gensyms</code></a> to keep <code>map</code> from being bound externally?</li> </ul> <p>and most importantly</p> <ul> <li>Is there an Elisp primitive that does the same thing, or close to it?</li> </ul>
[]
[ { "body": "<h3>General notes</h3>\n\n<ul>\n<li>Standard modes are not supposed to use <code>cl</code>. This, in practice, leads to more code duplication than it saves memory (a lot of third-party modes or user init files use <code>cl</code> anyway). So don't worry about using it unless you're really intent on having your package integrated into GNU Emacs.</li>\n<li>Yes, using the <code>map</code> symbol in this way will interfere a use of <code>map</code> outside your macro. That's what <code>gensym</code> is for.</li>\n</ul>\n\n<h3>My approach</h3>\n\n<p>You don't need a complex macro here.</p>\n\n<pre><code>(defun inaimathi-make-keymap (&amp;rest bindings)\n \"Make a sparse keymap containing the specified bindings\"\n (let ((map (make-sparse-keymap)))\n (while (consp bindings)\n (define-key map (car bindings) (car (cdr bindings)))\n (setq bindings (cdr (cdr bindings))))\n map))\n(defmacro inaimathi-defmap (symbol docstring &amp;rest bindings)\n \"Define a keymap called SYMBOL, with a DOCSTRING.\nPopulate the keymap with BINDINGS by building it with `inaimathi-make-keymap'\"\n `(progn\n (defvar ,symbol nil ,docstring)\n (setq map (inaimathi-make-keymap . ,bindings))))\n(inaimathi-defmap some-map \"Keymap for some mode.\"\n \"\\C-c\\C-a\" 'do-something\n \"\\C-c\\C-z\" 'do-something-else)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T00:31:22.377", "Id": "3635", "ParentId": "2284", "Score": "3" } }, { "body": "<p>Let the macro define the keymap, whether or not you provide it the bindings at the time of creation.</p>\n\n<pre><code>(defmacro new-map (mapname &amp;optional doc-string bindings)\n \"Define keymap MAPNAME, with optional DOC-STRING and BINDINGS.\"\n (let ((map (make-sparse-keymap)))\n (dolist (key.cmd bindings)\n (define-key map (car key.cmd) (cdr key.cmd)))\n `(defvar ,mapname ',map ',doc-string)))\n</code></pre>\n\n<p>Use example:</p>\n\n<pre><code>(new-map my-map \"My map.\" ((\"\\C-cf\" . forward-char)\n (\"\\C-cb\" . backward-char)))\n</code></pre>\n\n<p>Better: make adding the bindings to a map a separate function, <code>add-bindings</code>:</p>\n\n<pre><code>(defun add-bindings (keymap bindings)\n \"Add BINDINGS to KEYMAP\"\n (dolist (key.cmd bindings)\n (define-key keymap (car key.cmd) (cdr key.cmd))))\n\n(defmacro new-map (mapname &amp;optional doc-string bindings)\n \"Define keymap MAPNAME, with optional DOC-STRING and BINDINGS.\"\n (let ((map (make-sparse-keymap)))\n (add-bindings keymap bindings)\n `(defvar ,mapname ',map ',doc-string)))\n</code></pre>\n\n<p>That way a program can separate creating the map from adding bindings to it (e.g., any number of times).</p>\n\n<p>Use example:</p>\n\n<pre><code>(new-map my-map \"My map.\") ; Create the map\n(add-bindings my-map '((\"\\C-cf\" . forward-char) ; Add some bindings\n (\"\\C-cb\" . backward-char)))\n...\n(add-bindings my-map '((\"\\C-ca\" . backwardward-sentence) ; Add more bindings\n (\"\\C-ce\" . forward-sentence)\n</code></pre>\n\n<p>Define removing some bindings the same way.</p>\n\n<pre><code>(defun remove-bindings (keymap keys)\n \"Remove bindings for KEYS from KEYMAP.\"\n (dolist (key keys) (define-key keymap key nil)))\n</code></pre>\n\n<p>Use example: </p>\n\n<pre><code>(remove-bindings my-map '(\"\\C-cb\"))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T04:30:02.900", "Id": "33567", "ParentId": "2284", "Score": "0" } } ]
{ "AcceptedAnswerId": "3635", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T16:07:36.827", "Id": "2284", "Score": "4", "Tags": [ "elisp", "macros" ], "Title": "Keys in mode maps" }
2284
<p>I'm a hacker, not a trained engineer. I ask/answer specific questions on StackOverflow and am pretty confident in my ability to get the browser to do what I want, I thought I could benefit a great deal from a code review- hopefully I'm in the right place.</p> <p>Please tear down my bright-eyed naivetie with cutting comments on code style, design, etc if I am and let me know if this isn't what this site is for. </p> <p>This is a filter class that hides and shows long lists of content in container divs based on the content meta data. A sample content div:</p> <pre><code>&lt;div class="todd.packer StreamContent" data-username="todd.packer" data-topic_id="13" data-post_id="1394"&gt; ... &lt;/div&gt; </code></pre> <p>The class itself (relies on JQuery):</p> <pre><code>function StreamFilter(_containerId, _testAttribute, _targetStyleClass, _applyStyleClass, _testFor){ return{ active : false, filterHash : {}, testFor : _testFor, CONTAINER_ID : _containerId, TEST_ATTRIBUTE : _testAttribute, TARGET_STYLE_CLASS : _targetStyleClass, APPLY_STYLE_CLASS : _applyStyleClass, on : function(){ this.active = true; this.enforce(); }, off : function(){ this.clear(); this.active = false; this.unenforce(); }, clear : function(){ this.filterHash = {}; }, add_key : function(_key){ // messages with matching metadata will be displayed this.filterHash[_key] = true; }, filter_only : function(_key){ this.clear(); this.add_key(_key); this.on(); }, test : function(_key){ return(this.filterHash[_key]); }, render : function(_$object){ if(this.active &amp;&amp; ((this.test(_$object.attr(this.TEST_ATTRIBUTE)) === true) === this.testFor)){ _$object.addClass(this.APPLY_STYLE_CLASS); } return _$object; }, enforce : function(){ var i; // possible performance problems $("#" + this.CONTAINER_ID + " ." + this.TARGET_STYLE_CLASS).addClass(this.APPLY_STYLE_CLASS); //first hide everything... for(i in this.filterHash){ // For each attribute and value in add_key, remove the hidden class $("[" + this.TEST_ATTRIBUTE + "='" + i + "']").removeClass(this.APPLY_STYLE_CLASS); } }, unenforce : function(){ $("#" + this.CONTAINER_ID + " ." + this.TARGET_STYLE_CLASS).removeClass(this.APPLY_STYLE_CLASS); } }; } </code></pre>
[]
[ { "body": "<p>The usefulness of creating a class is that you can have private variables.</p>\n\n<p>Simply placing every thing in an object defeats that point. Instead you should define everything in the protected part of the function and simply expose an external API with the return.</p>\n\n<p><a href=\"http://codr.cc/s/9b31baa5/js\" rel=\"nofollow\">http://codr.cc/s/9b31baa5/js</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-07T17:54:25.813", "Id": "2302", "ParentId": "2287", "Score": "2" } } ]
{ "AcceptedAnswerId": "2302", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T16:48:20.973", "Id": "2287", "Score": "2", "Tags": [ "javascript", "jquery", "classes" ], "Title": "Javascript filter class to hide and show content on data-attributes" }
2287
<p>Could someone review the following code?</p> <pre><code>class PigLatin attr_accessor :phrase ending = "ay" def initialize the_phrase @phrase = the_phrase end def translate translated_phrase = String.new words = @phrase.split words.each do |word| puts word if vowel_is_first word translated_phrase += translate_with_vowel(word) else translated_phrase += translate_with_consonant(word) end end clean_up translated_phrase end def vowel_is_first test_word true if test_word[0] =~ /aeiou/ #will this make false since 0?? false end def translate_with_vowel word word + "-" + ending + " " end def translate_with_consonant word return word + "-way " if word.size &lt;= 2 split_location = word =~ /a|e|i|o|u/ word_array_length = word.size - 1 first_segment = word[split_location,word_array_length] second_segment = "-" + word[0,split_location-1] + word[split_location-1] + "ay" + " " first_segment + second_segment end def clean_up to_be_cleaned to_be_cleaned = to_be_cleaned[0..to_be_cleaned.size-2] to_be_cleaned.capitalize end end </code></pre> <p>I'm sure it could use some work as I'm just getting going in Ruby, so anything and everything would be helpful. The clean-up function, I think, could especially use work. It gets the job done, but w/o it there is always a space at the end, and <code>str.strip</code> wasn't getting the job done.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T19:41:09.987", "Id": "3666", "Score": "0", "body": "Oh and btw: `0` is \"truthy\" in ruby, so `=~` returning `0` will not lead to problems in an `if`." } ]
[ { "body": "<p>First of all there are two mistakes in the code:</p>\n\n<ol>\n<li><code>ending = \"ay\"</code> is a local variable only visible directly in the class body, not inside of the <code>def</code>s. For this reason <code>translate_with_vowel</code> will throw a NameError when it is called. You should make it a constant, so it'll be visible everywhere.</li>\n<li>The reason that you did not notice the first mistake is that <code>translate_with_vowel</code> is never called because <code>vowel_is_first</code> will always return <code>false</code>. You should use <code>if ... else ... end</code> instead of the inline <code>if</code>. The reason that it doesn't work the way you wrote it is that since <code>true if test_word[0] =~ /aeiou/</code> is not the last expression in the method, so its return value simply gets discarded and it doesn't have any side-effects.</li>\n</ol>\n\n<hr>\n\n<p>From a design perspective, I'm a bit doubtful that having a <code>PigLatin</code> object for each string you want to translate is really a good idea. Each <code>PigLatin</code> object has one instance variable, which is set in initialize and used by exactly one method (<code>translate</code>). All other methods only depend on their arguments and not on the state of the object. So from a programmer's point of view, having the string encapsulated in an object buys you nothing over taking it as an argument to <code>translate</code>.</p>\n\n<p>From the user's point of view it also makes the API more cumbersome than it needs to be. There's no reason to prefer <code>PigLatin.new(string).translate</code> over <code>PigLatin.translate(string)</code> if there's no reason why I'd ever call more than one method on an object, there really is no reason for the object to exist at all.</p>\n\n<p>If the translation was parametrized by some configuration options, it would make sense to have a class which is instantiated with the options and a <code>translate</code> method which takes the string, like this:</p>\n\n<pre><code>pig_latin = Translator.new(:input =&gt; :english, :output =&gt; :pig_latin)\nstring1 = pig_latin.translate(\"Hello World\")\nstring2 = pig_latin.translate(\"Goodbye World\")\n</code></pre>\n\n<p>However since in this case there are no options, I'd recommend using a <code>PigLatin</code> module and defining all the methods as <code>module_function</code>s. This way the usage would be <code>PigLatin.translate(\"Hello World\")</code> or <code>include PigLatin; translate(\"Hello World\")</code>.</p>\n\n<p>Also since there's no reason why a user should ever call any of your methods except <code>translate</code>, the other methods should probably be private.</p>\n\n<hr>\n\n<pre><code> def translate\n translated_phrase = String.new\n words = @phrase.split\n words.each do |word|\n puts word\n if vowel_is_first word\n translated_phrase += translate_with_vowel(word)\n else\n translated_phrase += translate_with_consonant(word)\n end\n end\n\n clean_up translated_phrase\n end\n</code></pre>\n\n<p>I assume the <code>puts</code> is just an old debug statement you forgot to remove. If it isn't, be advised that mixing IO with logic is usually bad design. If it is, a little tip: If you use <code>p</code> instead of <code>puts</code> for debug statements, you will get output which is more useful because you can see whether the object has the type you expect and, in case of strings, whether it contains any unprintable meta characters.</p>\n\n<p><code>String.new</code> is just a more verbose way to say <code>\"\"</code>, so you should use that instead. However instead of appending to an empty string in an <code>each</code> loop, I'd rather use <code>map</code> and <code>join</code>. <code>join</code> will also take care of inserting spaces between the elements for you (if you tell it to, that is), so you don't need to add those spaces yourself in the <code>translate_</code> methods and you don't have to remove the space at the end.</p>\n\n<p>So I'd write <code>translate</code> like this:</p>\n\n<pre><code> def translate(string)\n words = @phrase.split\n translated_words = words.map do |word|\n if vowel_is_first word\n translate_with_vowel(word)\n else\n translate_with_consonant(word)\n end\n end\n translated_phrase = translated_words.join(\" \")\n translated_phrase.capitalize\n end\n</code></pre>\n\n<p>You can also define another helper method <code>translate_word</code> which contains the above <code>if</code> statement and then simplify the above to <code>translated_words = words.map(&amp;:translate_word)</code>.</p>\n\n<hr>\n\n<pre><code> def translate_with_consonant word\n return word + \"-way \" if word.size &lt;= 2\n split_location = word =~ /a|e|i|o|u/\n word_array_length = word.size - 1\n\n first_segment = word[split_location,word_array_length]\n second_segment = \"-\" + word[0,split_location-1] + word[split_location-1] + \"ay\" + \" \"\n\n first_segment + second_segment\n end\n</code></pre>\n\n<p>The whole <code>split_location</code> is overly complicated. Just use <code>String#split</code> (which accepts an integer as a second argument, which you can use to tell it that you only want to split the string into two parts). You may also want to use string interpolation instead of concatenation. And as I said earlier, you can get rid of the <code>+ \" \"</code> as that's now handled by <code>join</code>.</p>\n\n<p>I'd write it like this:</p>\n\n<pre><code> def translate_with_consonant word\n return word + \"-way \" if word.size &lt;= 2\n second_segment, first_segement = word.split(/a|e|i|o|u/, 2)\n\n \"#{ first_segment }-#{ second_segment }ay\"\n end\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-10T18:05:16.317", "Id": "169559", "Score": "0", "body": "I like your code at the end. I wasn't aware that [String#split](http://ruby-doc.org/core-2.2.0/String.html#method-i-split) had an optional `limit` argument. That's good to know. I can see how it could be very useful. Note there's a typo in your code: ethay irstfay `irstfay_egementsay` ouldshay ebay `irstfay_egmentsay`. Hmmm. I wonder if a popular online auction was originally to be called \"be\", but got changed in translation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T19:23:11.463", "Id": "2294", "ParentId": "2290", "Score": "8" } } ]
{ "AcceptedAnswerId": "2294", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T17:26:29.083", "Id": "2290", "Score": "7", "Tags": [ "ruby", "pig-latin" ], "Title": "Pig Latin Translator" }
2290
<p>I am trying to update my server to let it know that the user had some activity in the past 15 minutes. In order to do that, I made this implementation:</p> <pre><code>var page = { updated: false, change_state: function(e) { var self = this; if(!this.updated){ debugConsole.log('Moved mouse'); setTimeout(function(){ self.updated = false; }, // 10000); //10 seconds 120000); //2 minutes this.updated = true; $.ajax({ url: 'comet/update.php', success: function(data){ debugConsole.log('Moved mouse at: ' + data); } }) } }, mouse_click: function(e) { this.updated = false; } } $("*").live('mousemove',function(e){ e.stopPropagation(); page.change_state(e); }); $("*").live('click',function(e){ page.mouse_click(e); }); </code></pre> <p>I made it so that it only takes effect after 2 minutes from the last action, unless the last action was a click.</p> <p>Is this the best way of doing it?</p>
[]
[ { "body": "<p>I wouldn't recommend using $(\"*\").live, you only need the events on the document body, so long as they are allowed to properly bubble.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T18:40:41.140", "Id": "3663", "Score": "0", "body": "How do i make the `properly bubble`? this page is live so the dom is changing all of the time" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T18:55:18.103", "Id": "3664", "Score": "0", "body": "@Neal — Events bubble unless they are specifically prevented from doing so. You should be able to use `$(document.body).bind` instead of `$(\"*\").live` (and you will see much better performance if you do)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T18:58:42.300", "Id": "3665", "Score": "0", "body": "@BenBlank, how do i use `document.bind`?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T18:39:50.037", "Id": "2292", "ParentId": "2291", "Score": "2" } }, { "body": "<p>I wouldn't alert the server every time the mouse moves. Instead I'd just make a note of the time. For letting the server know I'd set up an interval that tells the server if the user has been active recently.</p>\n\n<pre><code>var page = {\n lastUpdated: (new Date).getTime(),\n mouse_move: function(e) {\n this.lastUpdated = (new Date).getTime();\n },\n mouse_click: function(e) {\n this.lastUpdated = (new Date).getTime();\n },\n checkForLife: function () {\n if( page.lastUpdated + 15 * 60 * 1000 &gt; (new Date).getTime() ) {\n $.post('comet/update.php',{status: 'alive'});\n } else {\n $.post('comet/update.php',{status: 'dead'});\n }\n }\n}\n$(\"body\").mousemove( page.mouse_move );\n$(\"body\").click( page.mouse_click );\nsetInterval( page.checkForLife, 2 * 60 * 1000 );\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T05:11:03.327", "Id": "3679", "Score": "0", "body": "how is this different than what i have?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T07:34:55.440", "Id": "3682", "Score": "0", "body": "1: The event binding are only on the body. 2: The server interaction is handled in a separate `setInterval`, not an event." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T18:58:07.527", "Id": "3687", "Score": "0", "body": "yes but it happens every `x` seconds as opposed to hen they do the action, why would i want that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T19:11:08.573", "Id": "3688", "Score": "0", "body": "1: the posting loop also lets the server know the user is idle. 2: the posting loop is evenly rate limited to balance server load." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T23:57:23.403", "Id": "3691", "Score": "0", "body": "yes, but i dont want to send a message if no action was taken, this app may be for many users, and i dont want a high server hit" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-07T02:02:28.853", "Id": "2298", "ParentId": "2291", "Score": "1" } }, { "body": "<p>The <code>.live()</code> has been deprecated since jQuery 1.7 we use the <code>.on()</code> method now:</p>\n\n<pre><code>$(\"*\").on('mousemove',function(e){\n e.stopPropagation();\n page.change_state(e); \n});\n\n$(\"*\").on('click',function(e){\n page.mouse_click(e); \n});\n</code></pre>\n\n<p>Also I wouldn't recommend attaching an event handler to that global element.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T15:07:18.897", "Id": "23960", "ParentId": "2291", "Score": "1" } } ]
{ "AcceptedAnswerId": "2292", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T17:53:27.853", "Id": "2291", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Checking user mouse movement" }
2291
<pre><code>import random import rlereader class Board: """Handles the status of all cells.""" def __init__(self, size): self.size = size self.grid = self.make_blank_grid() self.furthest_col = 0 self.furthest_row = 0 def run_turns(self, num_turns): """Run a the simulator for a number of turns.""" while num_turns &gt; 0: self.run_turn() num_turns -= 1 def run_turn(self): """Run a single turn of the simulator.""" new_grid = self.make_blank_grid() for row in range(0, self.size): for col in range(0, self.size): new_grid[row][col] = self.get_cell_life(row, col) self.grid = new_grid def toggle_cell(self, row, col): """Toggle the dead or alive status of a single cell.""" self.grid[row][col] = not self.grid[row][col] def check_furthest(self, row, col): """Check the furthest processed cell against this one and update if we near the edge.""" if row + 1 &gt;= self.furthest_row: self.furthest_row = row + 2 if col + 1 &gt;= self.furthest_col: self.furthest_col = col + 2 def get_cell_life(self, row, col): """Return whether a given cell should become dead or alive. This may update the processed cell boundaries if neccessary.""" living_neighbours = self.count_living_neighbours(row, col) if self.grid[row][col]: if living_neighbours in [2, 3]: return True else: self.check_furthest(row, col) return False else: if living_neighbours == 3: self.check_furthest(row, col) return True return False def check_cell(self, row, col): """Return whether the cell is dead or alive for the current generation.""" if row &lt; 0: row = self.size - 1 if row &gt; self.size - 1: row = 0 if col &lt; 0: col = self.size - 1 if col &gt; self.size - 1: col = 0 return self.grid[row][col] def count_living_neighbours(self, row, col): """Find how many neighnours of a given cell are alive.""" active_count = 0 to_check = [ (row - 1, col - 1), # Top left (row - 1, col), # Top (row - 1, col + 1), # Top right (row, col - 1), # Left (row, col + 1), # Right (row + 1, col - 1), # Bottom left (row + 1, col), # Bottom (row + 1, col + 1) # Bottom Right ] for crow, ccol in to_check: if self.check_cell(crow, ccol): active_count += 1 return active_count def make_blank_grid(self): """Returns a blank grid for future use.""" grid = [] for row in range(0, self.size): grid.append([]) for col in range(0, self.size): grid[row].append([]) grid[row][col] = False return grid def load_rle_into_grid(self, rle): """Loads a RLE representation of a playing field into the grid. rle should be a file like object.""" reader = rlereader.GRLEReader() data = reader.read_rle(rle) # Returns an uncompressed series of tokens from an rle file. The rle file is opened elsewhere than this package. self.blank_grid() current_token = 0 current_row = 0 current_col = 0 while True: try: token = data[current_token] except IndexError: break # Out of tokens if type(token) == rlereader.EOFToken: break if token.value in ['b', 'o']: # 'o' = alive' 'b' = dead self.grid[current_row][current_col] = (token.value == 'o') current_col += 1 if current_col &gt; self.size - 1: print('Too wide an import, cancelling import.') break if current_col &gt;= self.furthest_col: self.furthest_col = current_col + 2 if token.value == '$': # $ indicates end of line. current_row += 1 if current_row &gt; self.size - 1: print('Too high an import, cancelling import.') break current_col = 0 if current_row &gt; self.furthest_row: self.furthest_row = current_row + 2 current_token += 1 def randomise_grid(self): """Change every cell in a grid to random dead or alive state.""" for row in range(0, self.size): for col in range(0, self.size): self.grid[row][col] = random.choice([True, False]) self.furthest_row = self.size - 1 self.furthest_col = self.size - 1 def blank_grid(self): """Replace the current grid with a blank grid.""" self.grid = self.make_blank_grid() </code></pre> <p>This is the business end of a Python Game Of Life simulator I wrote. Can I get some opinions of it? (I hope it's not too much, I cut out all the GUI code and rlereader because they're not too relevant. blank_grid, randomise_grid and toggle_cell are all only called from the UI code.</p>
[]
[ { "body": "<pre><code>import random\n\nimport rlereader\n\nclass Board:\n \"\"\"Handles the status of all cells.\"\"\"\n\n def __init__(self, size):\n self.size = size\n self.grid = self.make_blank_grid()\n self.furthest_col = 0\n self.furthest_row = 0\n\n def run_turns(self, num_turns):\n \"\"\"Run a the simulator for a number of turns.\"\"\"\n while num_turns &gt; 0:\n</code></pre>\n\n<p>Use a <code>for turn in range(num_terms)</code> loop instead of a while loop</p>\n\n<pre><code> self.run_turn()\n num_turns -= 1\n\n def run_turn(self):\n \"\"\"Run a single turn of the simulator.\"\"\"\n new_grid = self.make_blank_grid()\n for row in range(0, self.size):\n</code></pre>\n\n<p>Just use range(self.size), the 0 is not needed.</p>\n\n<pre><code> for col in range(0, self.size):\n new_grid[row][col] = self.get_cell_life(row, col)\n\n self.grid = new_grid\n\n def toggle_cell(self, row, col):\n \"\"\"Toggle the dead or alive status of a single cell.\"\"\"\n self.grid[row][col] = not self.grid[row][col]\n\n def check_furthest(self, row, col):\n \"\"\"Check the furthest processed cell against this one and update if we\nnear the edge.\"\"\"\n if row + 1 &gt;= self.furthest_row:\n self.furthest_row = row + 2\n if col + 1 &gt;= self.furthest_col:\n self.furthest_col = col + 2\n</code></pre>\n\n<p>Write it like this instead:</p>\n\n<pre><code> self.furthest_row = max(self.furthest_row, row + 2)\n self.furthest_col = max(self.furthest_col, col + 2)\n</code></pre>\n\n<p>Also, the function updates rather then checks the furthest, a better name would be update_furthest</p>\n\n<p>I don't know why you are adding 2 here, a comment explaining that would be helpful</p>\n\n<pre><code> def get_cell_life(self, row, col):\n \"\"\"Return whether a given cell should become dead or alive.\n\nThis may update the processed cell boundaries if neccessary.\"\"\"\n living_neighbours = self.count_living_neighbours(row, col)\n if self.grid[row][col]:\n if living_neighbours in [2, 3]:\n return True\n else:\n self.check_furthest(row, col)\n return False\n else:\n if living_neighbours == 3:\n self.check_furthest(row, col)\n return True\n return False\n</code></pre>\n\n<p>Write it like this instead:</p>\n\n<pre><code> living_neighbours = self.count_living_neighbours(row, col)\n if self.grid[row][cell]:\n new_value = living_neighbors in [2,3]\n else:\n new_value = living_neighbors == 3\n\n if new_value != self.grid[row][cell]:\n self.check_furthest(row, cell)\n\n return new_value\n</code></pre>\n\n<p>This way we separate the furthest updating from the decision of the new value of the cell. It might also be a good idea to move the furthest updating to run_turn</p>\n\n<pre><code> def check_cell(self, row, col):\n \"\"\"Return whether the cell is dead or alive for the current\ngeneration.\"\"\"\n if row &lt; 0:\n row = self.size - 1\n if row &gt; self.size - 1:\n row = 0\n\n if col &lt; 0:\n col = self.size - 1\n if col &gt; self.size - 1:\n col = 0\n\n\n return self.grid[row][col]\n</code></pre>\n\n<p>Use modulous instead of all those ifs</p>\n\n<pre><code> def check_cell(self, row, col):\n return self.grid[row % self.size][col % self.size]\n</code></pre>\n\n<p>The % divides with remainder which gives exactly the wrap around feature you want.</p>\n\n<pre><code> def count_living_neighbours(self, row, col):\n \"\"\"Find how many neighnours of a given cell are alive.\"\"\"\n active_count = 0\n to_check = [\n (row - 1, col - 1), # Top left\n (row - 1, col), # Top\n (row - 1, col + 1), # Top right\n (row, col - 1), # Left\n (row, col + 1), # Right\n (row + 1, col - 1), # Bottom left\n (row + 1, col), # Bottom\n (row + 1, col + 1) # Bottom Right\n ]\n\n for crow, ccol in to_check:\n if self.check_cell(crow, ccol):\n active_count += 1\n\n return active_count\n</code></pre>\n\n<p>You can simplify the function by replacing it with:</p>\n\n<pre><code> return sum(self.check_cell(row, col) for row, col in to_check)\n</code></pre>\n\n<p>I recommend moving to_check to a global constant.</p>\n\n<pre><code> def make_blank_grid(self):\n \"\"\"Returns a blank grid for future use.\"\"\"\n grid = []\n for row in range(0, self.size):\n grid.append([])\n for col in range(0, self.size):\n grid[row].append([])\n grid[row][col] = False\n return grid\n</code></pre>\n\n<p>Write it like this instead:</p>\n\n<pre><code> def make_blank_grid(self):\n \"\"\"Returns a blank grid for future use.\"\"\"\n grid = []\n for row in range(0, self.size):\n grid.append([False] * self.size)\n return grid\n</code></pre>\n\n<p>The multiply produces a new list which is the original list repeated. But only use it on immutable values like numbers and bools. Don't use on anything that can be modified like other lists.</p>\n\n<pre><code> def load_rle_into_grid(self, rle):\n \"\"\"Loads a RLE representation of a playing field into the grid.\n\nrle should be a file like object.\"\"\"\n reader = rlereader.GRLEReader()\n data = reader.read_rle(rle) # Returns an uncompressed series of tokens from an rle file. The rle file is opened elsewhere than this package.\n\n self.blank_grid()\n\n current_token = 0\n\n current_row = 0\n current_col = 0\n while True:\n try:\n token = data[current_token]\n except IndexError:\n break # Out of tokens\n</code></pre>\n\n<p>Use <code>for token in data</code> instead of the while loop. For loops are almost always better then while loops.</p>\n\n<pre><code> if type(token) == rlereader.EOFToken:\n break\n</code></pre>\n\n<p>Breaking out because of either an EOFToken or running out of tokens is strange. You should probably only have to break in case or the other not both. Also, checking the types of variables is discouraged. You shouldn't need to do that. Is rlereader your code or something else?</p>\n\n<pre><code> if token.value in ['b', 'o']: # 'o' = alive' 'b' = dead\n self.grid[current_row][current_col] = (token.value == 'o')\n current_col += 1\n if current_col &gt; self.size - 1:\n print('Too wide an import, cancelling import.')\n break\n</code></pre>\n\n<p>When something goes wrong, its best to throw an exception, not print a message and continue on your merry way.</p>\n\n<pre><code> if current_col &gt;= self.furthest_col:\n self.furthest_col = current_col + 2\n</code></pre>\n\n<p>Use you check_furthest method, so as not to duplicate logic.</p>\n\n<pre><code> if token.value == '$': # $ indicates end of line.\n current_row += 1\n if current_row &gt; self.size - 1:\n print('Too high an import, cancelling import.')\n break\n current_col = 0\n if current_row &gt; self.furthest_row:\n self.furthest_row = current_row + 2\n\n current_token += 1\n\n def randomise_grid(self):\n \"\"\"Change every cell in a grid to random dead or alive state.\"\"\"\n for row in range(0, self.size):\n for col in range(0, self.size):\n self.grid[row][col] = random.choice([True, False])\n\n self.furthest_row = self.size - 1\n self.furthest_col = self.size - 1\n\n def blank_grid(self):\n \"\"\"Replace the current grid with a blank grid.\"\"\"\n self.grid = self.make_blank_grid() \n</code></pre>\n\n<p>One additional thing to consider would be using numpy. Numpy is a python library that provides a multi-dimensional array type. Its more natural to work with then lists of lists. It also provides vector operations, which allow you to perform the same operation against all the element in the array very efficiently and with less code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-07T20:20:58.233", "Id": "2304", "ParentId": "2303", "Score": "4" } } ]
{ "AcceptedAnswerId": "2304", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-07T18:35:57.523", "Id": "2303", "Score": "10", "Tags": [ "python", "game-of-life" ], "Title": "Python implementation of a wrapped Conway's Game Of Life board" }
2303
<p>I need to extend the default <code>TextWriterTraceListener</code> class to include timestamps with each message on same line and file rotation. I can't seem to find any way of doing it with <code>TraceListener</code> configuration.</p> <p>Can you please review it and let me know any flaws to be used in a multi-threaded application?</p> <pre><code>using System; using System.Collections.Generic; using System.IO; using System.Diagnostics; using System.Text; namespace ConsoleApplication1 { public class MyTextWriterTraceListener : TextWriterTraceListener { public MyTextWriterTraceListener(System.IO.Stream stream) : base(stream) { } public MyTextWriterTraceListener(System.IO.Stream stream, string name) : base(stream, name) { } public MyTextWriterTraceListener(string FileName, string name) : base(FileName, name) { RotateLogFiles(FileName); } public MyTextWriterTraceListener(string FileName) : base(FileName) { RotateLogFiles(FileName); } public MyTextWriterTraceListener(System.IO.TextWriter writer, string name) : base(writer, name) { } public MyTextWriterTraceListener(System.IO.TextWriter writer) : base(writer) { } public override void Write(string Msg) { base.Write(Msg); base.Flush(); } public override void WriteLine(string Msg) { base.WriteLine(LinePrefix() + Msg); base.Flush(); } private void RotateLogFiles(string FileName) { FileInfo TheFileInfo = new FileInfo(FileName); if (TheFileInfo.Exists == false) return; if (TheFileInfo.LastWriteTime.Date &lt; DateTime.Today) { TheFileInfo.MoveTo(string.Format(@"{0}\{1}_{2}{}", TheFileInfo.DirectoryName, TheFileInfo.Name, TheFileInfo.LastWriteTime.ToString(), TheFileInfo.Extension)); } } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private string LinePrefix() { DateTime Now = DateTime.Now; return string.Format("{0} : ", Now.ToString("dd-MMM-yyyy HH:mm:ss")); } } } </code></pre>
[]
[ { "body": "<p>In my opinion the code is ok.</p>\n\n<p>there may be some minor issues</p>\n\n<ul>\n<li>Rotate-logfile is only called in the constructor of MyTextWriterTraceListener. So if you are tracing long running applications (i.e. a service) the logfile is not rotated at all.</li>\n<li>The LinePrefix with dateTime is only called in writeline. If you are constructing the line with several Write-statements the prefix might go to the wrong place.</li>\n<li>the formatig of RotateLogFiles removes the fileextenstion <code>string.Format(@\"{0}\\{1}_{2}{}\"</code> the last argument {} should be {3}. I prefer to use Path.Combine methods that also verifies validity of filenames instead of string.Format. </li>\n</ul>\n\n<p>I personally prefer to use log4net for logging, that already supports your hommade features (DateTime-Prefix, FileName-Rotation)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T10:15:15.380", "Id": "2308", "ParentId": "2305", "Score": "2" } }, { "body": "<h2>Possible issues</h2>\n\n<p><strong>1</strong> Follow a style guideline. It is common convention to camel case local variable names. </p>\n\n<p><code>var theFile = new FileInfo(...)</code> instead of <code>var TheFile = new FileInfo(...)</code>. </p>\n\n<p>Format your file equally (i.e. either all methods are separated by a blank line or none).</p>\n\n<p><strong>2</strong> Keep lines short and use more variables to get better readability and easier debugging:</p>\n\n<pre><code>var newPath = Path.Combine(file.DirectoryName, file.Name, file.LastWriteTime.ToString(), file.Extension)\nfile.MoveTo(newPath);\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>TheFileInfo.MoveTo(string.Format(@\"{0}\\{1}_{2}{}\", TheFileInfo.DirectoryName, TheFileInfo.Name, TheFileInfo.LastWriteTime.ToString(), TheFileInfo.Extension));\n</code></pre>\n\n<p><strong>3</strong> Use meaningful names. </p>\n\n<p><code>RollingTextWriterTraceListener</code> instead of <code>MyTextWriterTraceListener</code></p>\n\n<p><code>[MethodImpl(MethodImplOptions.NoInlining)]</code> instead of <code>[System[...]NoInlining)]</code></p>\n\n<p>What do you do if you need an other implementation - <code>MyOtherTextWriterTraceListener</code>?\nThe same applies to <code>TheFileInfo</code>, <code>ConsoleApplication1</code>.</p>\n\n<p><strong>4</strong> Remove redundant qualifiers to remove clutter.</p>\n\n<pre><code>public MyTextWriterTraceListener(Stream stream) : base(stream) { }\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>public MyTextWriterTraceListener(System.IO.Stream stream) : base(stream) { }\n</code></pre>\n\n<p><code>var file = new FileInfo(...)</code> instead <code>FileInfo file = new FileInfo(...)</code></p>\n\n<p><strong>5</strong> Are you sure you need the <code>[MethodImpl(MethodImplOptions.NoInlining)]</code> attribute?</p>\n\n<h2>What I like</h2>\n\n<p><strong>1</strong> <code>if (TheFileInfo.Exists == false) return;</code></p>\n\n<p>because the return statement reduces nesting (see arrow head anti pattern) and <code>== false</code> because its more obvious and than <code>!TheFileInfo.Exists</code>. A lonely <code>!</code> can quick be overseen. I would recommend the same procedure for the following if statement, too:</p>\n\n<pre><code>if (TheFileInfo.LastWriteTime.Date &gt;= DateTime.Today) return;\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>if (TheFileInfo.LastWriteTime.Date &lt; DateTime.Today) { ... }\n</code></pre>\n\n<h2>General recommendations</h2>\n\n<p><strong>1</strong> As k3b mentioned I would recommend using log4net, too. It has more flexibility you will ever need and you can configure it via config file which means you can change your logging output without recompiling.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T21:53:07.017", "Id": "2333", "ParentId": "2305", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T02:10:52.180", "Id": "2305", "Score": "4", "Tags": [ "c#" ], "Title": "TextWriterTraceListener class" }
2305
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-18.html" rel="nofollow">SICP</a>:</p> <blockquote> <p><strong>Exercise 2.84</strong></p> <p>Using the raise operation of exercise 2.83, modify the apply-generic procedure so that it coerces its arguments to have the same type by the method of successive raising, as discussed in this section. You will need to devise a way to test which of two types is higher in the tower. Do this in a manner that is ``compatible'' with the rest of the system and will not lead to problems in adding new levels to the tower.</p> </blockquote> <p>I wrote the following solution. In particular, please pay attention to the make-all-typematch function, and apply-generic. </p> <pre><code>(define (make-all-typematch . args) (define (typematch obj1 obj2) (cond ((eq? (type-tag obj1) (type-tag obj2)) obj1) ((and (not (can-raise? obj1)) (not (can-raise? obj2))) '()) ((higher? obj2 obj1) (and (can-raise? obj1) (typematch (raise obj1) obj2))) (else (and (can-raise? obj2) (typematch obj1 (raise obj2)))))) (define (least-common-type first second . rest) (let ((matched-obj (typematch first second))) (if (not (null? matched-obj)) (if (null? rest) (type-tag matched-obj) (apply least-common-type (cons matched-obj rest))) '()))) (define (raise-to-type the-type arg) (if (eq? (type-tag arg) the-type) arg (raise-to-type the-type (raise arg)))) (define (iter result the-type args) (if (null? args) result (iter (cons (raise-to-type the-type (car args)) result) the-type (cdr args)))) (let ((lct (apply least-common-type args))) (if (null? lct) (error "Can't make these objects agree:" args) (iter '() lct args)))) (define (apply-generic op . args) (define (all-same? head . rest) (if (null? rest) true (and (eq? head (car rest)) (apply all-same? rest)))) (let ((type-tags (map type-tag args))) (let ((proc (get op type-tags))) (if proc (apply proc (map contents args)) (if (and (&gt; (length type-tags) 1) (apply all-same? type-tags)) (error "No method for these types -- APPLY-GENERIC" (list op type-tags)) (apply apply-generic op (apply make-all-typematch args))))))) (define (add x y) (apply-generic 'add x y)) (define (sub x y) (apply-generic 'sub x y)) (define (mul x y) (apply-generic 'mul x y)) (define (div x y) (apply-generic 'div x y)) (define (equ? x y) (apply-generic 'equ? x y)) (define (=zero? x) (apply-generic '=zero? x)) (define (raise x) (apply-generic 'raise x)) (define (can-raise? x) (if (with-handlers ([exn:fail? (lambda (exn) false)]) (raise x)) true false)) (define (can-be-raised-to? type x) (or (eq? (type-tag x) type) (and (can-raise? x) (can-be-raised-to? type (raise x))))) (define (higher? x y) (can-be-raised-to? (type-tag x) y)) (define (square x) (* x x)) (define (attach-tag type-tag contents) (if (or (symbol? contents) (number? contents)) contents (cons type-tag contents))) (define (type-tag datum) (cond ((pair? datum) (car datum)) ((exact? datum) 'scheme-number) ((inexact? datum) 'scheme-real) ((symbol? datum) 'scheme-symbol) (else (error "Bad tagged datum -- TYPE-TAG" datum)))) (define (contents datum) (cond ((pair? datum) (cdr datum)) ((or (number? datum) (symbol? datum)) datum) (else (error "Bad tagged datum -- CONTENTS" datum)))) (define fn-registry '()) (define (get op param-types) (define (rec entry . rest) (define (all-equal a b) (if (symbol? a) (eq? a b) (and (= (length a) (length b)) (let loop ((x a) (y b)) (or (null? x) (and (eq? (car x) (car y)) (loop (cdr x) (cdr y)))))))) (let ((op-entry (car entry)) (param-types-entry (cadr entry)) (function-entry (caddr entry))) (if (and (eq? op-entry op) (all-equal param-types-entry param-types)) function-entry (if (null? rest) false (apply rec rest))))) (apply rec fn-registry)) (define (put op param-types fn) (set! fn-registry (cons (list op param-types fn) fn-registry))) (define (install-scheme-number-package) (define (tag x) (attach-tag 'scheme-number x)) (put 'add '(scheme-number scheme-number) (lambda (x y) (tag (+ x y)))) (put 'sub '(scheme-number scheme-number) (lambda (x y) (tag (- x y)))) (put 'mul '(scheme-number scheme-number) (lambda (x y) (tag (* x y)))) (put 'div '(scheme-number scheme-number) (lambda (x y) (tag (/ x y)))) (put 'make '(scheme-number) (lambda (x) (tag x))) (put 'equ? '(scheme-number scheme-number) =) (put '=zero? '(scheme-number) zero?) (put 'raise '(scheme-number) (lambda (x) (if (integer? x) (make-rational x 1) (make-real x)))) 'done) (define (make-scheme-number n) ((get 'make 'scheme-number) n)) (define (install-real-number-package) (define (tag x) (attach-tag 'scheme-real x)) (put 'add '(scheme-real scheme-real) (lambda (x y) (tag (+ x y)))) (put 'sub '(scheme-real scheme-real) (lambda (x y) (tag (- x y)))) (put 'mul '(scheme-real scheme-real) (lambda (x y) (tag (* x y)))) (put 'div '(scheme-real scheme-real) (lambda (x y) (tag (/ x y)))) (put 'make '(scheme-real) (lambda (x) (tag x))) (put 'equ? '(scheme-real scheme-real) =) (put '=zero? '(scheme-real) zero?) (put 'raise '(scheme-real) (lambda (x) (make-complex-from-real-imag x 0))) 'done) (define (make-real n) ((get 'make '(scheme-real)) n)) (define (install-rational-package) ;; internal procedures (define (numer x) (car x)) (define (denom x) (cdr x)) (define (make-rat n d) (let ((g (gcd n d))) (cons (/ n g) (/ d g)))) (define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (sub-rat x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mul-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (define (div-rat x y) (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) (define (equ?-rat x y) (and (= (numer x) (numer y)) (= (denom x) (denom y)))) (define (=zero?-rat x) (zero? (numer x))) ;; interface to rest of the system (define (tag x) (attach-tag 'rational x)) (put 'add '(rational rational) (lambda (x y) (tag (add-rat x y)))) (put 'sub '(rational rational) (lambda (x y) (tag (sub-rat x y)))) (put 'mul '(rational rational) (lambda (x y) (tag (mul-rat x y)))) (put 'div '(rational rational) (lambda (x y) (tag (div-rat x y)))) (put 'equ? '(rational rational) equ?-rat) (put '=zero? '(rational) =zero?-rat) (put 'raise '(rational) (lambda (n) (make-real (exact-&gt;inexact (/ (numer n) (denom n)))))) (put 'make '(rational) (lambda (n d) (tag (make-rat n d)))) 'done) (define (make-rational n d) ((get 'make '(rational)) n d)) (define (real-part z) (apply-generic 'real-part z)) (define (imag-part z) (apply-generic 'imag-part z)) (define (magnitude z) (apply-generic 'magnitude z)) (define (angle z) (apply-generic 'angle z)) (define (install-complex-package) ;; imported procedures from rectangular and polar packages (define (make-from-real-imag x y) ((get 'make-from-real-imag 'rectangular) x y)) (define (make-from-mag-ang r a) ((get 'make-from-mag-ang 'polar) r a)) ;; internal procedures (define (add-complex z1 z2) (make-from-real-imag (+ (real-part z1) (real-part z2)) (+ (imag-part z1) (imag-part z2)))) (define (sub-complex z1 z2) (make-from-real-imag (- (real-part z1) (real-part z2)) (- (imag-part z1) (imag-part z2)))) (define (mul-complex z1 z2) (make-from-mag-ang (* (magnitude z1) (magnitude z2)) (+ (angle z1) (angle z2)))) (define (div-complex z1 z2) (make-from-mag-ang (/ (magnitude z1) (magnitude z2)) (- (angle z1) (angle z2)))) (define (equ?-complex z1 z2) (and (= (real-part z1) (real-part z2)) (= (imag-part z1) (imag-part z2)))) (define (=zero?-complex z) (and (zero? (real-part z)) (zero? (imag-part z)))) ;; interface to rest of the system (define (tag z) (attach-tag 'complex z)) (put 'add '(complex complex) (lambda (z1 z2) (tag (add-complex z1 z2)))) (put 'sub '(complex complex) (lambda (z1 z2) (tag (sub-complex z1 z2)))) (put 'mul '(complex complex) (lambda (z1 z2) (tag (mul-complex z1 z2)))) (put 'div '(complex complex) (lambda (z1 z2) (tag (div-complex z1 z2)))) (put 'make-from-real-imag 'complex (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'complex (lambda (r a) (tag (make-from-mag-ang r a)))) (put 'equ? '(complex complex) equ?-complex) (put '=zero? '(complex) =zero?-complex) 'done) (define (install-polar-package) ;; internal procedures (define (magnitude z) (car z)) (define (angle z) (cdr z)) (define (make-from-mag-ang r a) (cons r a)) (define (real-part z) (* (magnitude z) (cos (angle z)))) (define (imag-part z) (* (magnitude z) (sin (angle z)))) (define (make-from-real-imag x y) (cons (sqrt (+ (square x) (square y))) (atan y x))) (define (equ? x y) (and (= (magnitude x) (magnitude y)) (= (angle x) (angle y)))) (define (=zero? x) (zero? (magnitude x))) ;; interface to the rest of the system (define (tag x) (attach-tag 'polar x)) (put 'real-part '(polar) real-part) (put 'imag-part '(polar) imag-part) (put 'magnitude '(polar) magnitude) (put 'angle '(polar) angle) (put 'equ? '(polar polar) equ?) (put '=zero? '(polar) =zero?) (put 'make-from-real-imag 'polar (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'polar (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) (define (install-rectangular-package) ;; internal procedures (define (real-part z) (car z)) (define (imag-part z) (cdr z)) (define (make-from-real-imag x y) (cons x y)) (define (magnitude z) (sqrt (+ (square (real-part z)) (square (imag-part z))))) (define (angle z) (atan (imag-part z) (real-part z))) (define (make-from-mag-ang r a) (cons (* r (cos a)) (* r (sin a)))) (define (equ? x y) (and (= (real-part x) (real-part y)) (= (imag-part x) (imag-part y)))) (define (=zero? x) (and (zero? (real-part x)) (zero? (imag-part x)))) ;; interface to the rest of the system (define (tag x) (attach-tag 'rectangular x)) (put 'real-part '(rectangular) real-part) (put 'imag-part '(rectangular) imag-part) (put 'magnitude '(rectangular) magnitude) (put 'angle '(rectangular) angle) (put 'equ? '(rectangular rectangular) equ?) (put '=zero? '(rectangular) =zero?) (put 'make-from-real-imag 'rectangular (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'rectangular (lambda (r a) (tag (make-from-mag-ang r a)))) 'done) (define (make-complex-from-real-imag x y) ((get 'make-from-real-imag 'complex) x y)) (define (make-complex-from-mag-ang r a) ((get 'make-from-mag-ang 'complex) r a)) (install-rational-package) (install-scheme-number-package) (install-complex-package) (install-polar-package) (install-rectangular-package) (install-real-number-package) </code></pre> <p>I'm certain that there is a better way to solve this problem. How can I improve my solution?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T07:00:26.083", "Id": "2307", "Score": "1", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Coercion of arguments using successive raising" }
2307
<p>I'm posting my PHP code for sessions using MySQL. Please tell me if there are any errors, if it can be optimized, or if security can be enhanced.</p> <ul> <li>Host: localhost</li> <li>User: root</li> <li>Password: ""</li> <li>Database: pro</li> </ul> <p>Table structure:</p> <blockquote> <p>SessionID [pk] - Data - DateTouched</p> </blockquote> <pre><code>&lt;?php function open($sess_id, $sess_name) { return true; } function close() { return true; } function read($sess_id) { $con = mysqli_connect("localhost", "root", "","pro"); $stmt = mysqli_prepare($con,"SELECT Data FROM sessions WHERE SessionID = ?"); mysqli_stmt_bind_param($stmt,"s",$sess_id); mysqli_stmt_execute($stmt); mysqli_stmt_bind_result($stmt,$data); mysqli_stmt_fetch($stmt); mysqli_stmt_close($stmt); $CurrentTime = date('Y-m-d H:i:s'); if (!isset($data)) { $stmt = mysqli_prepare($con,"INSERT INTO sessions (SessionID, DateTouched) VALUES (?,?)"); mysqli_stmt_bind_param($stmt,"ss",$sess_id,$CurrentTime); mysqli_stmt_execute($stmt); mysqli_stmt_close($stmt); return false; } else { $stmt = mysqli_prepare($con,"UPDATE sessions SET DateTouched = ? WHERE SessionID = ?"); mysqli_stmt_bind_param($stmt,"ss",$CurrentTime,$sess_id); mysqli_stmt_execute($stmt); mysqli_stmt_close($stmt); return $data; } } function write($sess_id, $data) { $con = mysqli_connect("localhost", "root", "","pro"); $CurrentTime = date('Y-m-d H:i:s'); $stmt = mysqli_prepare($con,"UPDATE sessions SET Data= ?,DateTouched=? WHERE SessionID=?"); mysqli_stmt_bind_param($stmt,"sss",$data,$CurrentTime,$sess_id); mysqli_stmt_execute($stmt); return true; } function destroy($sess_id) { $con = mysqli_connect("localhost", "root", "","pro"); $stmt = mysqli_prepare($con,"DELETE FROM sessions WHERE SessionID = ?"); mysqli_stmt_bind_param($stmt,"s",$sess_id); mysqli_stmt_execute($stmt); return true; } function gc($sess_maxlifetime) { $con = mysqli_connect("localhost", "root", "","pro"); $stmt = mysqli_prepare($con,"Delete from sessions where TIMESTAMPDIFF (Second ,DateTouched,now())&gt;=?"); mysqli_stmt_bind_param($stmt,"s",$sess_maxlifetime); mysqli_stmt_execute($stmt); return true; } session_set_save_handler("open", "close", "read", "write", "destroy", "gc"); session_name('Session'); session_start(); ?&gt; </code></pre>
[]
[ { "body": "<p>Your <code>open</code> and <code>close</code> functions don't do anything. You <em>could</em> use them to connect &amp; disconnect from the database. That way, an error in the connection won't be a read or write error, but will be an error in <code>open</code>. That may later help diagnosing such errors. It also means less duplicated code and it may mean fewer connections to the database (which might speed up things a bit).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T17:59:07.700", "Id": "3686", "Score": "0", "body": "good idea ronald, anything else you will suggest ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T14:21:00.073", "Id": "3702", "Score": "1", "body": "@Sourav Well, personally I'd put all of it in a class so I could carry the connection around in an object..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T14:23:12.100", "Id": "3703", "Score": "0", "body": "anything for security or increasing performance ?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T16:08:29.890", "Id": "2311", "ParentId": "2310", "Score": "2" } }, { "body": "<p>Especially in ajaxy environments, a lot of different request can be opened to your server. In their current implementation there is no check or lock for that, which means that setting a session variable somewhere can be undone by a session save in another request.</p>\n\n<ol>\n<li>Request A open</li>\n<li>Request B open</li>\n<li>A changes data</li>\n<li>A exist &amp; saves</li>\n<li>B exists &amp; saves <strong>stale data</strong></li>\n</ol>\n\n<p>I'd recommand either doing an <code>SELECT ..... FOR UPDATE</code> or checking last-opened-time with last-changed-time in the database.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T02:30:24.330", "Id": "4404", "Score": "0", "body": "plz explain a little bit more !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T18:04:37.823", "Id": "4416", "Score": "0", "body": "What do you need more explanation of? You can see PHP's file-based session solution in action by creating a file with `<?php session_start();sleep(60);?>`, and while that is loading, try to open any other page with a `session_start()` in it: it won't load any further beyond the blocking `session_start()` until the other request is finished. Doing a `SELECT .... FOR UPDATE` is pretty much the same thing, only it locks a row in the database (i.e. it cannot be selected until the connection having the lock either releases it or exits)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T18:09:17.270", "Id": "4417", "Score": "0", "body": "If you do so, make the `gc` a cronjob rather then in the code of a request itself: the `gc` handler will also block until the lock on that row is released. To avoid something like that, you could store a token (not a timestamp, microseconds do count) in the row in the database and only allow writing if the token has stayed the same, but that would mean 2 simultaneous requests (that are not blocked in this manner) could want to write different changes to the session in the database. You'll have to think of something clever in your application to handle that if you support concurrent requests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T02:55:58.390", "Id": "4423", "Score": "0", "body": "but InnoDB only the row gets locked not the table (as in MyISAM), and as a user should only have a single session then i dont think it's problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-09T08:28:26.810", "Id": "4428", "Score": "0", "body": "Yes, but the `gc` needs access to all rows afaik..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T00:45:19.750", "Id": "2862", "ParentId": "2310", "Score": "1" } } ]
{ "AcceptedAnswerId": "2311", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T14:32:01.737", "Id": "2310", "Score": "3", "Tags": [ "php", "mysql", "session" ], "Title": "Session in database" }
2310
<p>I'm a beginner-intermediate C++ programmer, and I never used or understood C input &amp; validation. I just always used C++ streams.</p> <p>Anyway, I just want code critique, as I have never used the C input functions (I admit, I have used and like <code>printf()</code>! I even made my own <code>sprintf()</code>, compatible with the C++ string class.)</p> <p>I hope my code is good. I tend to get code to work properly, completely ignoring formatting and performance, then later once it works I make it look and run nicely.</p> <p><strong>caesar.c</strong></p> <pre><code>#include &lt;string.h&gt; /* for strlen() */ #include "caesar.h" char *getCipherText(char *src, int key) { int len = strlen(src); int i = 0; int ch = 0; /* Loop over each char in src */ for (i = 0; i &lt; len; i++) { ch = (int)src[i]; /* Convert the char to int to prevent many uneccecary casts */ if (ch &gt;= 65 &amp;&amp; ch &lt;= 90) { /* If the char is uppercase */ ch += key; /* add the key */ if (ch &gt; 90) ch -= 26; /* if the char is higher than the highest uppercase char, sub 26 */ if (ch &lt; 65) ch += 26; /* if the char is lower than the lowest uppercase char, add 26 */ src[i] = (char)ch; /* set the current char in src to the char value of ch */ } else if (ch &gt;= 97 &amp;&amp; ch &lt;= 122) { /* else if it's lowercase */ ch += key; /* add the key */ if (ch &gt; 122) ch -= 26; /* if the char is higher than the highest lowercase char, sub 26 */ if (ch &lt; 97) ch += 26; /* if the char is lower than the lowest lowercase char, add 26 */ src[i] = (char)ch; /* set the current char in src to the char value of ch */ } /* an else case is not needed, since we are modifying the original. */ } /* Return a pointer to the char array passed to us */ return src; } char *getPlainText(char *src, int key) { /* Since getCipherText adds the key to each char, adding a negative key * is equivalent to subtracting a positive key. Easier than re-implementing. */ return getCipherText(src, -key); } </code></pre> <p><strong>caesar.h</strong></p> <pre><code>char *getCipherText(char *src, int key); char *getPlainText(char *src, int key); </code></pre> <p><strong>main.c</strong></p> <pre><code>#include &lt;stdio.h&gt; /* for printf(), sscanf(), fgetc() and fgets() */ #include &lt;stdlib.h&gt; /* for malloc() and free() */ #include &lt;string.h&gt; /* for strlen() */ #include "caesar.h" /* Size of text buffer to read into */ #define BUFS 1024 /* Size of buffer for reading misc. items, i.e. for the get_int() function */ #define TBUFS 128 /* Get char, no new lines */ int getc_nnl() { int ch = '\n'; /* While ch is a newline or carriage return, read another char */ while (ch == '\n' || ch == '\r') ch = fgetc(stdin); /* Return the char, promoted to an integer */ return ch; } /* Get an integer */ int get_int() { char *s = (char*)malloc(TBUFS); s[0] = '\0'; int i = 0; /* Read a string, and later parse the int in case there are no ints to read */ while (strlen(s) &lt;= 1) fgets(s, TBUFS, stdin); /* Parse the int. Using sscanf because scanf on stdin leaves the file caret at a unknown position. */ sscanf(s, "%d", &amp;i); /* Return the int - if sscanf found nothing, it's already 0 */ return i; } int main(int argc, char *argv[]) { char *text = NULL; int key = 0; int ch = 0; while(1) { /* Forever loop, until we break; out */ /* Prompt for an option */ printf("Encrypt, Decrypt, or Quit? (e/d/q) "); ch = getc_nnl(); /* Make sure they gave us a valid option - if not, keep prompting! */ while (ch != 'e' &amp;&amp; ch != 'E' &amp;&amp; ch != 'd' &amp;&amp; ch != 'D' &amp;&amp; ch != 'q' &amp;&amp; ch != 'Q') { printf("Invalid option. Encrypt, Decrypt, or Quit? (e/d/q) "); ch = getc_nnl(); } /* If the user wants to quit... */ if (ch == 'q' || ch == 'Q') break; /* ...then break out of the loop */ /* Allocate buffer for text (I set text[0] to a null-terminator due to later strlen() calls) */ text = (char*)malloc(BUFS); text[0] = '\0'; /* Get the text to encrypt - If user entered nothing, * or fgets() is reading only a newline (from the fgetc calls), keep reading. */ printf("Please enter your text: "); while (strlen(text) &lt;= 1) fgets(text, BUFS, stdin); /* Get the integer key to encrypt/decrypt with. If it's invalid, keep prompting! :) */ printf("Ok, now what key should I use? (1 - 25) "); key = get_int(); while (key &lt; 1 || key &gt; 25) { printf("Invalid key. Please enter a number between 1 and 25: "); key = get_int(); } /* Ok, we have our data - now, did they say encrypt or decrypt? */ if (ch == 'e' || ch == 'E') { /* Encrypt, and print the result */ getCipherText(text, key); printf("Ok. Here's your encrypted text: %s\n", text); } else if (ch == 'd' || ch == 'D') { /* Decrypt, and print the result */ getPlainText(text, key); printf("Ok. Here's your decrypted text: %s\n", text); } /* Free our malloc, so we don't have a memory overrun */ free(text); } return 0; } </code></pre>
[]
[ { "body": "<ul>\n<li>after <code>malloc</code> check result to NULL</li>\n<li>getCipherText check <code>src</code> to NULL, if <code>strlen</code> get NULL string it crushed.</li>\n<li>function <code>get_int</code> free <code>s</code> string before return result</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T21:53:37.193", "Id": "2316", "ParentId": "2314", "Score": "3" } }, { "body": "<pre><code>/* Loop over each char in src */\nfor (i = 0; i &lt; len; i++) {\n</code></pre>\n\n<p>To some C programmers, writing string manipulation like this is like speaking in a foreign accent. Consider this:</p>\n\n<pre><code>while (*src)\n{\n // TODO: do something with *src\n\n src++;\n}\n</code></pre>\n\n<p>Moreover, the way you've written it you're looping through all chars twice. (<code>strlen</code> will loop through all chars to find the length, and then you'll loop through again to perform the cypher.) The code above loops through exactly once.</p>\n\n<pre><code>ch = (int)src[i]; /* Convert the char to int to prevent many uneccecary casts */\n</code></pre>\n\n<p>I'm not sure what is meant by this comment, or where the confusion lies. I'd say do it without casts if you can. (It looks like you can.)</p>\n\n<pre><code>if (ch &gt;= 65 &amp;&amp; ch &lt;= 90) { /* If the char is uppercase */\n</code></pre>\n\n<p>Are you hardcoding ASCII? That's a little weird. You can do <code>ch &gt;= 'A'</code> etc. Better yet, <code>isupper</code> from <code>ctype.h</code>.</p>\n\n<pre><code>while (strlen(s) &lt;= 1) \n fgets(s, TBUFS, stdin);\n</code></pre>\n\n<p>This looks very weird. First of all <code>strlen(s) &lt;= 1</code> should produce a result equivalent to <code>!s[0] || !s[1]</code>, except that <code>strlen</code> will traverse the entire string, which is bad. But overall the \"while length of string is &lt;= 1\" approach is a bit confusing... I think cleaner code would call <code>fgets</code> first, then observe the result.</p>\n\n<p><b>Update, having glanced at the code again:</b> Also, your buffer sizes are small and fixed-size. At those sizes it's probably more sensible to make them stack-allocated arrays instead of calling <code>malloc</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T17:00:06.060", "Id": "3708", "Score": "0", "body": "Wow, thanks a ton. I am new to C-style programming, having used the C++ `string` class whenever I could. And I am taking your comment about making my pointers \"stack-allocated arrays\" to mean use `char bla[TBUFS];` rather than `char *bla = (char*)malloc(TBUFS);` ? ----- I will work on my code, as per your [really good] suggestions, and will update the code on my OP. Thanks!!!! (And especially thanks for explaining why you suggested each thing! :) )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T17:38:26.353", "Id": "3709", "Score": "0", "body": "Updated the code on my OP - did I properly implement what you meant in the getCipherText() function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T00:08:53.133", "Id": "3715", "Score": "0", "body": "@FurryHead Yes, the edits you have made address some of my points, particularly about `while(*src++)` and the fixed-size buffers." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T01:13:05.467", "Id": "2319", "ParentId": "2314", "Score": "7" } }, { "body": "<p>I think I'd change a few things. First of all, I would generally <em>avoid</em> making the program interactive. At least for me, a program like this that fundamentally carries out a single operation should (by strong preference) let me enter everything necessary on the command line. If you insist, you can allow interactive use as well, but <em>don't</em> force me to respond to your prompts instead of entering data as I see fit, and don't stop me from creating scripts and such to handle such things with even less work if I choose to.</p>\n\n<p>Second, I think I'd segment the problem into functions slightly differently. At the bottom level, I'd have a function that just takes one input character, and returns one encoded/decoded character:</p>\n\n<pre><code>int cipher(int ch, int key) { \n if (islower(ch)) return (ch-'a' + key) % 26 + 'a';\n if (isupper(ch)) return (ch-'A' + key) % 26 + 'A';\n return ch;\n}\n</code></pre>\n\n<p>Then, if you really want to deal in strings, as a layer on top of that, I'd have something that knows how to deal with strings of characters:</p>\n\n<pre><code>void encode(char *s, int key) { \n while (*s)\n *s = cipher(*s++, key);\n}\n\nvoid decode(char *s, int key) { \n while (*s) \n *s = cipher(*s++, -key);\n}\n</code></pre>\n\n<p>Then, as the top layer enough to open files, and act as a filter:</p>\n\n<pre><code>int main(int argc, char **argv) { \n char buffer[256];\n // skipping error checking for now.\n int key = atoi(argv[1]);\n\n while (fgets(buffer, 256, stdin))\n if (tolower(argv[2][0] == 'd')\n puts(decode(buffer));\n else\n puts(encode(buffer));\n return 0;\n}\n</code></pre>\n\n<p>Or, if you don't mind a tiny bit of trickiness:</p>\n\n<pre><code>typedef int (*func)(int);\n\nfunc f = tolower(argv[2][0]) == 'd' ?\n decode : \n encode;\n\nwhile (fgets(buffer, 256, stdin))\n puts(f(buffer));\n</code></pre>\n\n<p>Alternatively, you can ignore using strings at all, and just deal in single characters throughout:</p>\n\n<pre><code>int encode(int ch, int key) { \n if (islower(ch)) ch = (ch-'a' + key) % 26 + 'a';\n else if (isupper(ch)) ch = (ch-'A' + key) % 26 + 'A';\n return ch;\n}\n\nint decode(int ch, int key) { \n return encode(ch, -key);\n}\n\nint main(int argc, char **argv) { \n int ch;\n int key = atoi(argv[1]);\n\n int (*f)(int) = argv[2][0] == 'd' ?\n decode :\n encode;\n\n while (EOF != (ch=getchar()))\n putchar(f(ch));\n\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T02:09:21.387", "Id": "3751", "Score": "0", "body": "Wow, thank you so much! I edited your encode() function, as it did not handle a negative key being passed (i.e. -2 being passed when the char is 'A') and added error checking (atoi() returns 0 if there is no valid number) ----- Thanks a ton, though!! You drastically reduced my code size, while adding more features! Woo! (EDIT: Also, I updated the code on my OP -- Thanks again!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T02:14:41.237", "Id": "3752", "Score": "1", "body": "@FurryHead: sure -- it's always a bit tricky dealing with (what looks like) homework. I try to nudge in what I think is a reasonable direction, but still leave at least a little for you (the OP generally) to think about/deal with. It's good to see somebody really thinking and running with it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T14:43:21.200", "Id": "3764", "Score": "1", "body": "Actually, it's not homework. Programming is just a hobby of mine, and I try to learn things thoroughly. (And I try to eliminate _every_ bug I can - I really, really, *really* hate buggy programs!) I've used several languages, just to see what they're like, but I've never used a language without objects/classes. (Until now; using C ) I can't imagine how I will manage without Objects! LOL... Anyway, thanks again - I really appreciate the help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T15:11:44.963", "Id": "3765", "Score": "0", "body": "@FurryHead: The fact that it's self-assigned doesn't mean it isn't homework! :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T01:51:50.630", "Id": "13036", "Score": "0", "body": "Bad trickiness. Just use `if (argv[2][0] == 'd') key = 26-key;`, and lost the decode function entirely." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T21:23:55.810", "Id": "2354", "ParentId": "2314", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T20:42:37.177", "Id": "2314", "Score": "10", "Tags": [ "c", "beginner", "caesar-cipher" ], "Title": "Caesar Cipher program in C" }
2314
<p>I've just written this Twisted resource base class for serving files. It's part of a larger application, this is just for serving its images, JavaScript files, etc.</p> <p>Is it okay? I wonder if checking for <code>..</code> in the path is enough -- all the files that exist in <code>self.directory</code> are intended to be served, to anyone, so this should be all that's needed, I think. Should these it be a Unicode string? Should they all be Unicode strings?</p> <p>Will <code>return open(file).read()</code> be enough? I would think the resource would be closed when the function goes out of scope, but I'm not completely sure.</p> <pre><code>""" Base class for resources serving files to the browser. This doesn't use the `Page` class because it doesn't need to set up templates or anything, just serve the file. """ from twisted.web.resource import Resource import os.path class File(Resource): """ Serves a certain type of file from the server. It could be images, javascript, etc. It serves files from a single directory which have a single extension. members: content_type -- the HTTP content type of the files to be served directory -- the local directory the files are stored in extension -- the extension which the files are saved with. """ content_type = None directory = None extension = None def render_GET(self, request): """ Serve the requested file. Makes sure the file exists and the request doesn't contain '..' to escape the file directory. """ file = request.path.strip("/") file = file.split("/", 1)[1] file = "{directory}/{filepath}.{extension}".format( directory=self.directory, filepath=file, extension=self.extension) request.responseHeaders.setRawHeaders("content-type", [self.content_type]) if ".." in file: request.setResponseCode(400) return "" if not os.path.isfile(file): request.setResponseCode(404) return "" return open(file).read() </code></pre>
[]
[ { "body": "<p>Firstly, don't try to think of everything that could go wrong. Instead, check for what you know to be valid.</p>\n\n<pre><code>import re\ndirectory, filename = re.match('/([A-Za-z0-9]+)/([A-Za-z0-9]+)/?', alpha).groups()\n</code></pre>\n\n<p>By using this method to extract the directory and filename, we can be sure that directory and filename contain nothing except letters and numbers which are perfectly safe.</p>\n\n<p>Its also best to use <code>os.path.join</code> to produce folder paths rather then string formatting to put them together. </p>\n\n<pre><code> return open(file).read()\n</code></pre>\n\n<p>This works, but not if you try and run on IronPython/Jython/PyPy. CPython depends on reference counting which will cause the file to be closed as soon as it returns. A better version is probably:</p>\n\n<pre><code>with open(file) as source:\n return source.read()\n</code></pre>\n\n<p>This is guaranteed to close the file even without reference counting.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-18T17:51:26.207", "Id": "333769", "Score": "0", "body": "The regex for directory and filename isn't very good. Many, many valid directory and filenames would be treated as invalid." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-18T23:31:05.330", "Id": "333830", "Score": "0", "body": "@jwg, yes, but that's my point. Its better to reject good filenames than to fail to reject bad ones. If all you need are alphanumeric names, then you don't need to go the extra mile to handle other characters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-19T07:57:55.857", "Id": "333871", "Score": "0", "body": "Rejecting anything with a `.` or `_` is clearly broken." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T22:19:48.987", "Id": "2317", "ParentId": "2315", "Score": "2" } } ]
{ "AcceptedAnswerId": "2317", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T20:58:38.770", "Id": "2315", "Score": "4", "Tags": [ "python", "twisted" ], "Title": "File-serving Twisted resource" }
2315
<p>I am new to the world of coding, PHP as well as XHTML. As my first stab at object oriented coding, I put together a basic registration form that is meant to serve as a means to collect user details.</p> <p><strong>What this form does not do is the following;</strong></p> <ul> <li>Capture information is a file or database as I have not yet gained enough experience about databases, sessions, cookies or files. </li> <li>I looked at using onchange to populate the days dropdown menu dynamically but despise the form reloading and hence avoided doing so. I am aware I can use AJAX however considering my lack of knowledge, I was hoping someone could advise other alternatives apart from Javascript.</li> <li>Sanitize the data using htmlentities or htmlspecialchars. </li> </ul> <p><strong>What I would like</strong></p> <ul> <li>I would appreciate any constructive criticisms, what I can improve on, what I could have done better</li> </ul> <p><strong>XHTML Code</strong></p> <pre><code>&lt;?php require_once('includes/base.php'); require_once('functions.php'); ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;meta name="keywords" content="" /&gt; &lt;meta name="description" content= "" /&gt; &lt;meta name="author" content="" /&gt; &lt;title&gt;Event Details&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="web.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Details&lt;/h1&gt; &lt;p&gt;Please provide us with your details so that we can confirm your booking&lt;/p&gt; &lt;div&gt; &lt;?php $eventform = new eventform(); $eventform -&gt; validateform(); ?&gt; &lt;fieldset&gt; &lt;legend&gt;Your details&lt;/legend&gt; &lt;form name="eventdetails" method="post" action="event.php"&gt; &lt;label for="fname"&gt;First Name&lt;/label&gt; &lt;input type="text" name="fname" value="&lt;?php echo isset($_POST['fname']) ? $_POST['fname'] : ''; ?&gt;" tabindex="1" id="fname" /&gt; &lt;label for="lname"&gt;Last Name&lt;/label&gt; &lt;input type="text" name="lname" value="&lt;?php echo isset($_POST['lname']) ? $_POST['lname'] : ''; ?&gt;" tabindex="2" id="lname" /&gt; &lt;label for="email"&gt;Email&lt;/label&gt; &lt;input type="text" name="email" value="&lt;?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?&gt;" tabindex="3" id="email" /&gt; &lt;label for="cuisine"&gt;Cuisine&lt;/label&gt; &lt;?php $eventform = new eventform(); $eventform -&gt; radiobuttons('cuisine'); ?&gt; &lt;label for="eventperiod"&gt;Please select an event day&lt;/label&gt; &lt;?php $eventform = new eventform(); ?&gt; &lt;select name="eventmonth" tabindex="8" id="eventmonth"&gt; &lt;?php echo $eventform -&gt; dropdown('months'); ?&gt; &lt;/select&gt; &lt;select name="eventday" tabindex="7" id="eventday"&gt; &lt;?php echo $eventform -&gt; dropdown('days'); ?&gt; &lt;/select&gt; &lt;select name="eventyear" tabindex="9" id="eventyear"&gt; &lt;?php echo $eventform -&gt; dropdown('years'); ?&gt; &lt;/select&gt; &lt;label&gt; &lt;input type="submit" name="register" value="register" tabindex="10" id="register" /&gt; &lt;input type="reset" name="reset" value="reset" tabindex="11" id="reset" /&gt; &lt;/label&gt; &lt;/form&gt; &lt;/fieldset&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>CSS Code</strong></p> <pre><code>body{ font-family: arial, verdana, sans-serif; font-size: 0.8em; font-weight: normal; font-style: normal; } h1 { } p { } fieldset { border: 1px solid #D9D9D9; background-color: #F5F5F5; } fieldset legend { color: #FFFFFF; background-color: #8B8378; padding: 5px; padding-right: 9px; padding-left: 9px; } label { display: block; padding: 5px; } label.cuisine { display: inline; } </code></pre> <p><strong>Inlcudes - Base</strong></p> <pre><code>&lt;?php $parentdirectory = dirname(dirname(__FILE__)); define('BASE_DIRECTORY', $parentdirectory); ini_set('include_path', $parentdirectory.'/includes/'); ?&gt; </code></pre> <p><strong>Includes - Class</strong></p> <pre><code>&lt;?php class eventform { //Declare data members/properties private $fname, $lname, $email, $cuisine, $eventday, $timezone, $eventmonth; //Generate months public function eventmonths($startingmonth=1, $endingmonth=12) { //Default timezone $this-&gt;timezone = date_default_timezone_set('UTC'); //Loop through months $months = range($startingmonth, $endingmonth); $returnmonths = ''; foreach($months as $key) { $returnmonths .= date('F', mktime(0, 0, 0, $key)).','; } return rtrim($returnmonths, ','); } //Generate years public function eventyears() { //Get current year $year = date('Y'); //Loop through years $startyear = $year; // $endyear = date('Y', strtotime('+5 years')); $endyear = date('Y', mktime(0,0,0,12,30,$year+5)); $returnyears = ''; for($startyear; $startyear &lt; $endyear; $startyear=$startyear+1) { $returnyears .= $startyear.','; } return rtrim($returnyears, ',') ; } //Loop through days for a specific month and year public function eventdays($month, $year) { // return date('t', strtotime($someYear . '-' . $someMonth . '-01')); // return date('t', strtotime($someYear . '-' . $someMonth )); // $numberofdays = date('t', strtotime($Year. '-' .$Month)); $numberofdays = date('t', mktime(0,0,0,$month,1,$year)); $startdays = 1; $returndays = ''; for($startdays; $startdays &lt;= $numberofdays; $startdays=$startdays+1) { $returndays .= $startdays.','; } return rtrim($returndays, ','); // return substr($returndays, 0, -1); } //Define the type of dropdown public function dropdown($type) { switch($type) { case('days'): $stringdays = $this-&gt;eventdays(1, 2011); $arraydays = explode(',', $stringdays); foreach($arraydays as $day) { echo '&lt;option value="'.$day.'"&gt;'.$day.'&lt;/option&gt;'; } break; case('months'): $stringmonths = $this-&gt;eventmonths(); $arraymonths = explode(',', $stringmonths); foreach($arraymonths as $month) { echo '&lt;option value="'.date('n', strtotime($month)).'"&gt;'.$month.'&lt;/option&gt;'; } break; case('years'): $stringyears = $this-&gt;eventyears(); $arrayyears = explode(',', $stringyears); foreach($arrayyears as $key) { echo '&lt;option value="'.$key.'"&gt;'.$key.'&lt;/option&gt;'; } break; } } //Define the type of radiobuttons public function radiobuttons ($type) { switch($type) { case('cuisine'): $cuisines = array('italian', 'russian', 'malaysian'); $cuisinetype = array_combine(range(1, count($cuisines)), $cuisines); foreach($cuisinetype as $key =&gt; $value) { if(isset($_POST['register']) &amp;&amp; $_POST['register'] == 'register') { if(isset($_POST['cuisine']) &amp;&amp; $_POST['cuisine'] == $value) { $status = 'checked=checked'; } else { $status = ''; } } else { $status = ''; } echo '&lt;input type="radio" name="cuisine" value="'.$value.'" tabindex="'.$key.'" id="'.$value.'" '.$status.'&gt;', '&lt;label for="'.$value.'" class="cuisine"&gt;'.ucfirst($value).'&lt;/label&gt;'; } break; } } //Validate form public function validateform() { if(isset($_POST['register']) &amp;&amp; $_POST['register'] == 'register') { $this-&gt;fname = isset($_POST['fname']) ? $_POST['fname'] : ''; $this-&gt;lname = isset($_POST['lname']) ? $_POST['lname'] : ''; $this-&gt;email = isset($_POST['email']) ? $_POST['email'] : ''; $this-&gt;cuisine = isset($_POST['cuisine']) ? $_POST['cuisine'] : ''; $this-&gt;eventday = isset($_POST['eventday']) ? $_POST['eventday'] : ''; $errormsg = array(); if(empty($this-&gt;fname)) { $errormsg[0] = 'Please enter your first name'; } if(empty($this-&gt;lname)) { $errormsg[1] = 'Please enter your last name'; } if(empty($this-&gt;email)) { $errormsg[2] = 'Please specify an email address'; } if(empty($this-&gt;cuisine)) { $errormsg[3] = 'Please select a cuisine'; } if(empty($this-&gt;eventday)) { $errormsg[4] = 'Please select an event day'; } foreach($errormsg as $key =&gt; $value) { echo $value.'&lt;br /&gt;'; } //Basic email validation if(!empty($this-&gt;email)) { if(!preg_match('/^[a-zA-Z0-9_\.\-]+[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9_\.\-]+\.[a-zA-Z]{1,6}$/', $this-&gt;email)) { echo 'Please enter a valid email address'; } } } } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T04:42:21.637", "Id": "3692", "Score": "0", "body": "One quick critique: you shouldn't have echos in your class. Instead you should return strings and echo those strings in the xhtml. It makes things clearer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T16:58:42.280", "Id": "3707", "Score": "0", "body": "@generalhenry - Thanks. How would I `return` strings prior to a break. My understanding is that a return would stop a function immediately especially if I have grouped case statements?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T18:12:39.960", "Id": "3710", "Score": "0", "body": "That's actually one of the nicer parts of using returns, you don't need to use a break unless there's more stuff added later on. Which makes it easy to read through the code and see where things end. A break might be the end, a return IS the end." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T19:35:05.063", "Id": "3712", "Score": "0", "body": "@generalhenry - When you say `more stuff is added later on`, do you mean other case statements?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T22:54:20.613", "Id": "3714", "Score": "0", "body": "I mean code beyond the case statements, replacing the breaks with returns makes it very clear that there is none with a quick glace at the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T23:24:20.673", "Id": "3749", "Score": "0", "body": "@generalhenry - Sorry, I don't quite follow what you meant by `replacing the breaks with returns makes it very clear that there is none with a quick glace at the code`" } ]
[ { "body": "<ul>\n<li><p>Why you create class <code>eventform</code> 3 times in XHTML? I think one is enough.</p></li>\n<li><p><code>&lt;?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?&gt;</code> This is a classical example of <a href=\"http://en.wikipedia.org/wiki/Cross-site_scripting\" rel=\"nofollow\">XSS-attack</a>, don't do that. Use <code>htmlspecialchars()</code> to escape possible HTML-code.</p></li>\n<li><p>Instead of <code>$errormsg[0] = '...'</code> you may just write <code>$errormsg[] = '...'</code> In this case PHP append your message to the end of array. Also this eliminates from magick numbers in your program.</p></li>\n</ul>\n\n<p><strong>Updated:</strong></p>\n\n<ul>\n<li><p><code>eventform</code> violates <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">Single Responsibility Principle</a> -- it works with dates, holds values and generated HTML-code. Better approach is to follow to <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">MVC pattern</a> and separate view from logic.</p></li>\n<li><p>I suggest also to choose codestyle and follow to it. For example, <a href=\"http://framework.zend.com/manual/en/coding-standard.html\" rel=\"nofollow\">Zend Coding Standart</a> or <a href=\"http://pear.php.net/manual/en/standards.php\" rel=\"nofollow\">PEAR Coding Standart</a></p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T16:57:11.987", "Id": "3706", "Score": "0", "body": "I wasn't aware I could instantiate the object once. I thought I had to instantiate each time I started a new code block. \n\nI didn't have a look at sanitizing the data as at this stage I was only looking at my attempt at object oriented code. Thanks for the reminder though. Should look at incorporating it from the get go.\n\nCool. I'll bear that in mind. What are `magick numbers`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T18:34:24.293", "Id": "3711", "Score": "0", "body": "@peanutsmonkey Magick numbers is \"unique values with unexplained meaning or multiple occurrence which could (preferably) be replaced with named constants\" (from http://en.wikipedia.org/wiki/Magic_number_%28programming%29)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T19:36:05.687", "Id": "3713", "Score": "0", "body": "Thanks. Will have a read of that. How was the rest of my coding? Did my object oriented coding make sense? Was it easy to follow?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T04:25:25.277", "Id": "3717", "Score": "0", "body": "@peanutsmonkey When you use one object your code is not object oriented yet IMHO. I updated my answer and include more info." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T23:23:28.350", "Id": "3748", "Score": "0", "body": "Thanks. Had no idea of single responsibility principle nor about the coding standards. Sorry I apologise ahead of time but when you say `code style`, what does that actually mean? I don't quite follow what the standards define." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T13:08:11.717", "Id": "2331", "ParentId": "2320", "Score": "1" } }, { "body": "<p>Moving to an answer to post some code examples</p>\n\n<p>class file:</p>\n\n<pre><code>public function radiobuttons ($type) {\n switch($type) {\n case('cuisine'):\n $cuisines = array('italian', 'russian', 'malaysian');\n $cuisinetype = array_combine(range(1, count($cuisines)), $cuisines);\n $output = '';\n foreach($cuisinetype as $key =&gt; $value) {\n if(isset($_POST['register']) &amp;&amp; $_POST['register'] == 'register') {\n if(isset($_POST['cuisine']) &amp;&amp; $_POST['cuisine'] == $value) {\n $status = 'checked=checked';\n }\n else {\n $status = '';\n }\n }\n else {\n $status = '';\n }\n $output .= '&lt;input type=\"radio\" name=\"cuisine\" value=\"'.$value.'\" tabindex=\"'.$key.'\" id=\"'.$value.'\" '.$status.'&gt;',\n '&lt;label for=\"'.$value.'\" class=\"cuisine\"&gt;'.ucfirst($value).'&lt;/label&gt;';\n }\n return $output;\n }\n //code here would run with a break\n // but not run with a return\n // so when reviewing the code you'd need to scroll down and check here if you use a break\n // but not if you use a return\n}\n</code></pre>\n\n<p>xhtml file :</p>\n\n<pre><code> &lt;?php\n //makes it clear that it's outputing text\n echo $eventform -&gt; radiobuttons('cuisine');\n ?&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T00:01:48.823", "Id": "2356", "ParentId": "2320", "Score": "1" } } ]
{ "AcceptedAnswerId": "2356", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T03:09:24.400", "Id": "2320", "Score": "2", "Tags": [ "php", "html", "css", "object-oriented" ], "Title": "Event Registration" }
2320
<p>At my work, I need to create a script that third-party webmasters could include in their pages without need to include something else. But this script had dependencies on jQuery and some amount of their plug-ins.</p> <p>On the Internet, I have found libraries that have same functionality except for an important one: they don't check are needed library already exist on a page.</p> <p>Yes, I could execute the needed libraries in local scope of my script, but I've decided to reduce the number of HTTP connections and traffic with this function:</p> <pre><code>var require = function (lib, obj, libs_obj) { // if obj is function than `require` called directly by user and we // must transform it to object. It's for reduce number of used // variables. When we call `require` recursively, we use this object // instead of function var lib_is_list = typeof(lib) === 'object'; if (typeof obj === 'function') obj = { callback: obj, count: lib_is_list ? lib.length : 1 } if (lib_is_list) { // this is list of libs for (var i in lib) require(lib[i], obj, libs_obj); return; } var lib = libs_obj[lib]; if (lib.callbacks === undefined) lib.callbacks = []; if (lib.check()) { if (obj.callback) obj.callback(); return; } lib.callbacks.push(obj); if (lib.pending) { return; } lib.pending = true; function ready() { function script_downloaded() { lib.pending = false; var obj; while (obj = lib.callbacks.pop()) { obj.count--; if (obj.count == 0) obj.callback(); } } download_script(lib.link, script_downloaded); } function download_script(src, callback) { var script = document.createElement('script'); script.type = 'text/javascript'; script.async = 'async'; script.src = src; // Based on jQuery jsonp trick if (callback) { script.onload = script.onreadystatechange = function() { if (!script.readyState || /loaded|complete/.test(script.readyState)) { script.onload = script.onreadystatechange = null; callback(); } }; } document.getElementsByTagName('head')[0].appendChild(script); } var deps_count = lib.deps ? lib.deps.length : 0; if (deps_count &lt; 1) { ready(); return; } var new_obj = { callback: ready, count: deps_count }; require(lib.deps, new_obj, libs_obj); }; </code></pre> <p>This function work in IE6+ (and, of course, in other browsers) and written in pure JS. To call this function, use syntax like this:</p> <pre><code>require(['list', 'of', 'libraries'], function () { alert 'All libs loaded'; }, libs_obj), </code></pre> <p>where libs_obj is object like this:</p> <pre><code>{ list: { check: function() { return list_exist(); }, // function to check whether the required functionality link: 'js/list_js_file.js', // link to script deps: ['libraries', 'of'] // list of dependencies of current library // If not, library doesn't have dependencies }, of: { check: function() { return of_exist_and_version_is('1.2.3'); }, link: 'js/another_file.js', }, libraries: { check: funcion() { return libraries_exist() || analog_exist(); }, link: 'http://www.example.com/js/libraries.js', deps: ['of'] } } </code></pre> <p>Callback function are optional - if we don't need it, we can just type <code>false</code> or <code>undefined</code>. Of course, this function must be called after all third-party scripts. Bottom of page is better place to script with this function. Please tell me where I went wrong or give me useful advice.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T01:52:42.237", "Id": "3716", "Score": "0", "body": "Parts of it are very clear, but the callback handling could use some comments or reworking. You have `obj` which can be a function or an object with a `callback` property, and `libs_obj` can have its own callbacks (one or many per library?). In some cases these are combined, and it wasn't clear when or why. Of course, I read it last night and only got a chance to comment on it today. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T05:05:12.933", "Id": "3719", "Score": "0", "body": "Thanx. But `libs_obj` doesn't have a callback for libraries - it just a object that contain info about each library - how to check its availability, path to it and list of dependencies." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T06:00:30.447", "Id": "3720", "Score": "0", "body": "Right, `libs` is the one with the optional `callbacks` property." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T11:06:57.727", "Id": "5500", "Score": "4", "body": "I don't really understand how loading libraries asynchronously will reduce HTTP connections or even traffic. Can you clarify?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T05:05:52.847", "Id": "7490", "Score": "0", "body": "@EricBréchemier With this library we load needed libs only if they are not loaded later - so, this will reduce traffic and HTTP connections. As you can see in first sentence, this lib created for using on 3rd party websites by webmasters." } ]
[ { "body": "<p>My 2 cents:</p>\n\n<ul>\n<li>please use lowercase camelcase ( lib_is_list -> libIsList )</li>\n<li>The first 5 lines seem clumsy\n<ul>\n<li>Checking for an array with typeof 'object' is odd</li>\n<li>Changing the type of a variable/parameter is odd and not recommended, you do this twice</li>\n<li>Dont drop newlines <code>( for (var i in lib) require(lib[i], obj, libs_obj); )</code></li>\n</ul></li>\n<li>You can use <code>lib.callbacks = lib.callbacks || []</code> instead of <code>if (lib.callbacks === undefined) lib.callbacks = [];</code></li>\n<li>Why would you assign first callbacks, and then check() whether you should return</li>\n<li>Your handling of <code>obj</code> , <code>count</code> and <code>callbacks</code> is roundabout, the lack of newlines dont help, </li>\n<li>The function name <code>ready()</code> is unfortunate, <code>ready</code> is most commly used for the callback after http requests</li>\n<li>You should consider merging/reworking <code>ready</code>/<code>script_downloaded</code>/<code>download_script</code></li>\n<li>The src parameter is unfortunate, since it does not contain the source, maybe url ?</li>\n<li>I like defensive programming, but checking for <code>callback</code> seems much, since your code guarantees it</li>\n</ul>\n\n<p>Overal, I have to say this seems over-engineered, I think you are trying to be too smart.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-16T22:02:13.260", "Id": "37549", "ParentId": "2324", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T07:59:32.850", "Id": "2324", "Score": "4", "Tags": [ "javascript" ], "Title": "On demand JS loader review" }
2324
<p>I am trying to learn OOP using PHP5 and I wrote a simple MySQL connection class. Please take a look and give me some feedback on better practices, critical errors, and any other feedback you can provide.</p> <p>Note: in the <code>verifyDatabaseConnection</code> method, I used an <code>@</code> symbol to curb the error I was receiving.</p> <pre><code>&lt;?php class Mysql { private $user; private $pass; private $data; private $host; public function __construct($user,$pass,$data,$host) { $this-&gt;user = $user; $this-&gt;pass = $pass; $this-&gt;data = $data; $this-&gt;host = $host; $this-&gt;verifyNullFields(); } private function verifyNullFields() { if($this-&gt;user == NULL) { print('mysql error : username is null'); } if($this-&gt;data == NULL) { print('mysql error : database name is null'); } else if($this-&gt;host == NULL) { print('mysql error : host name is null'); } else { $this-&gt;verifyDatabaseConnection(); } } private function verifyDatabaseConnection() { $link = @mysql_connect($this-&gt;host,$this-&gt;user,$this-&gt;pass); if(!$link) { die('mysql error : databse connection issue'); } else { $this-&gt;verifyDatabaseExist(); } } private function verifyDatabaseExist() { $db = mysql_select_db($this-&gt;data); if(!$db) { die('mysql error : database selection issue'); } } } ?&gt; &lt;?php $m = new Mysql("root","","test","localhost"); ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T17:01:35.267", "Id": "3693", "Score": "0", "body": "i don't think this is a site for people to critique your code. this is a place to ask questions" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T17:05:27.310", "Id": "3695", "Score": "0", "body": "@ d'o-o'b, I guess I could of simply asked \"Is this the proper way to create a MySQL connection class?\" Thanks for the heads up though :-)" } ]
[ { "body": "<p>Nothing seems <em>too</em> amiss (the fact that you're suppressing errors via <code>$link = @mysql_connect</code> is OK, as you're explicitly checking the <code>$link</code> variable afterwards.)</p>\n\n<p>That said I'm really not sure why you wouldn't use <a href=\"http://www.php.net/mysqli\" rel=\"nofollow\">MySQLi</a> or (better still) <a href=\"http://www.php.net/manual/en/book.pdo.php\" rel=\"nofollow\">PDO</a> in this day and age if you're starting a new project.</p>\n\n<p>Also, they fact that you're simply outputting an error message may not be the most useful approach. (You may want to return a boolean true/false as well, etc. although I'm not sure what use this would be within your constructor.) </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T17:08:27.633", "Id": "3696", "Score": "0", "body": "Hmm, I will read up on MySQLi and PDO. I have heard of MySQLi, but never heard of PDO. I will reading up on PDO that right now. Thank you :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T17:25:41.980", "Id": "3697", "Score": "0", "body": "I guess error messages would lead to attacks huh, lol. Boolean would be a much better approach. The OOP book I am reading mentioned that good practice is to always have a construct, but that could be directed more towards High Level Programming, is it good practice in PHP?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T17:37:14.857", "Id": "3698", "Score": "0", "body": "@user738910 The constructor is fine, but the problem is that it's effectively blocking any return from your verify methods. (i.e.: It can't pass it back up to whatever called the object.) As such, you might want to call the verify method in the same scope that you created the object." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T17:01:58.777", "Id": "2326", "ParentId": "2325", "Score": "1" } }, { "body": "<ul>\n<li><p>Don't print anything or call <code>die()</code> from this class because it may breaks caller's code/page. For example, you may want to show customized error page when error occurs, but all text printed by your code will break and stops this. One point is return boolean, as already said. But I personally prefer using exceptions for that (and even more -- I create special excepton which extends standard <code>Exception</code> class. This approach allows to differentiate one exception from another.).</p></li>\n<li><p>Get rid of chained method calls. Don't call <code>verifyDatabaseConnection()</code> from <code>verifyNullFields()</code>, <code>verifyDatabaseExist()</code> from <code>verifyDatabaseConnection()</code> and so on. Your method should do only one thing as declared in their name.</p></li>\n<li><p>Rename <code>data</code> member to something more meaningful.</p></li>\n<li><p>At your opinion: you may replace <code>$this-&gt;user == NULL)</code> check to <code>is_null($this-&gt;user)</code></p></li>\n<li><p>Also, when you will need to create similar class for PostgreSQL database (or abother DB) you should <a href=\"http://sourcemaking.com/refactoring/extract-class\" rel=\"nofollow\">extract base class</a></p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-13T01:34:23.147", "Id": "3790", "Score": "0", "body": "I am going to create a new thread for everyone to look at. But, before I do is there a way for me to do it in this current thread? Thanks-" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T11:56:18.287", "Id": "2329", "ParentId": "2325", "Score": "2" } }, { "body": "<p>In the question title, you ask us to judge your \"first OOP attempt\", and again in the body, \"I am trying to learn OOP\".</p>\n\n<p>Well, the code example cannot be considered OOP in my eyes. You are merely grouping related functionality into a class.</p>\n\n<p>OOP is a programming paradigm. It is a mindset about how you code and structure your program. It is about how to use abstractions to solve complex business rules, how to use abstractions to allow dependencies to be replaced, e.g. for testability, or for easy migration to new platforms.</p>\n\n<p>OOP is much more than just grouping code in classes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T20:50:31.173", "Id": "32823", "Score": "0", "body": "Hey Pete, thanks for your input. I understand what your're saying and the more I've been reading and learning I can see A TON of people write classes that are just organized functions, but since it's wrapped in `class` they call it OOP. Other than WIKI, what are some resources you recommend me reading and or learning videos that could help? Thanks again :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T08:05:07.843", "Id": "32846", "Score": "0", "body": "Hey. The book that really made me understand what OOP is about is, 'Design Patterns'. It is an old book though with examples in C++ and SmallTalk, so maybe not the easiest to read. But it probably should be on every developers bookshelf. Otherwise, I could recommend, 'Domain Driven Design', which talks about modelling domain concepts, and perhaps after that 'Analysis Patterns' which contains examples about how you could model domain concepts in well-known domains (also an older book)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T08:09:33.830", "Id": "32847", "Score": "0", "body": "But those book recommendations are just based on what is on my bookshelf. Each programmer has his or her own favorites." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T22:06:01.687", "Id": "20399", "ParentId": "2325", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T16:58:50.667", "Id": "2325", "Score": "3", "Tags": [ "php", "mysql", "php5" ], "Title": "MySQL connection class" }
2325
<p>I have designed the code but the problem is it timeouts as the range is 1000000000 but works fine with 1000. Any idea to optimize this or a mathematic logic for it? I just need to find the no of <code>pairs(a,b)</code> such that <code>a &lt; b</code> and <code>a*b % a+b == 0</code> if a range is given, eg: 15 - o/p 4 as (3,6)(4,12)(6,12)(10,15).</p> <p>php code:</p> <pre><code>$count = 0; $no = 1000; for($b = 1; $b &lt;= $no; $b ++) { for($a = 1; $a &lt; $b; $a ++) { $sum = $a + $b; $prod = ($a * $b); if (($prod % $sum == 0) { ++ $count; } $arr [$b] = $count; } } echo '&lt;pre&gt;'; print_r($arr); echo '&lt;pre&gt;'; </code></pre> <p>I need some math logic to get no of pairs rather performing actual process as above. If I found a relation or expression for this then actual process is not required.</p>
[]
[ { "body": "<p>I have no algorithm that gives you the number for a given number (and I doubt there is one), but I can see a little improvement: indeed, if both <code>a</code> and <code>b</code> are odd, <code>a + b</code> which is even cannot divide <code>a * b</code> which is odd, so <code>a * b % a + b == 0</code> is wrong.</p>\n\n<p>Here is a little implementation of this trick:</p>\n\n<pre><code>$count = 0;\n$no = 1000;\n$odd_b = True\nfor($b = 1; $b &lt;= $no; $b ++) {\n if ($odd_b) {\n for($a = 2; $a &lt; $b; $a += 2) {\n $sum = $a + $b;\n $prod = ($a * $b);\n\n if (($prod % $sum == 0) {\n ++ $count;\n }\n $arr [$b] = $count;\n }\n } else {\n for($a = 1; $a &lt; $b; $a ++) {\n $sum = $a + $b;\n $prod = ($a * $b);\n\n if (($prod % $sum == 0) {\n ++ $count;\n }\n $arr [$b] = $count;\n }\n }\n $odd_b = ! $odd_b;\n}\n\necho '&lt;pre&gt;';\nprint_r($arr);\necho '&lt;pre&gt;';\n</code></pre>\n\n<p>I used a boolean for performance (avoids to test for each value of <code>b</code> that <code>b % 2 == 0</code>). With this you should avoid around 1 case out of 4, so 25% improvement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T10:36:29.807", "Id": "3699", "Score": "0", "body": "yes i agree too.I can add it.vote for 25% improvement." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T09:33:54.783", "Id": "2328", "ParentId": "2327", "Score": "3" } }, { "body": "<p>These kind of puzzles have to be solved by first analyzing the problem.\nIf you look at the samples that you have already found you will notice that in all samples the two numbers share a rather large common factor. This makes sense, since if a and b have a common factor then both a+b and a*b are divisible by this common factor, which increases the probability that a+b divides a*b. So let's try to find out more formally when (a,b) is a good pair:</p>\n\n<p>Let g=gcd(a,b). Then there exist integers r,s with</p>\n\n<pre><code>a = r * g\nb = s * g\n</code></pre>\n\n<p>Then </p>\n\n<pre><code>a + b = (r+s)*g\na * b = r*s*g^2\n</code></pre>\n\n<p>Thus a+b divides a*b if (r+s)*g divides r*s*g^2 and hence if r+s divides r*s*g.\nAlso since g is the greatest common divisor it follows that r and s have no divisor in common (i.e. gcd(r,s)=1). From <a href=\"http://en.wikipedia.org/wiki/Euclidean_algorithm\">Euclid's algorithm</a> follows that gcd(r+s,r) = 1 and \ngcd(r+s, s) = 1 and hence also gcd(r+s, r*s) = 1. Thus if r+s divides r*s*g then \nr+s must divide g.</p>\n\n<p>Thus all the good pairs below a bound N can be described as follows:\nIf r,s,k are integers such that 1 &lt; r &lt; s &lt; N^0.5, gcd(r,s)=1 and s * (r + s) * k &lt;= N then (a,b) = (r * (r + s) * k, s * (r + s) * k) is a good pair.</p>\n\n<p>Implementing this isn't hard. Running the algorithm up to 10^9 takes a few minutes (depending on the programming language).</p>\n\n<p>One big question remains: Why on earth has the problem been migrated to \"Code review\"?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T00:14:25.503", "Id": "3767", "Score": "0", "body": "+1 nice answer. I suspect that the phrase you used \"increases the probability that\" is more accurately worded \"is a requirement for\"; coded in my language of choice, I ran the algorithm up to n=40k and all of the solution pairs shared a common factor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T09:07:57.580", "Id": "3769", "Score": "0", "body": "very gd algorithm" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T17:47:42.213", "Id": "2352", "ParentId": "2327", "Score": "7" } } ]
{ "AcceptedAnswerId": "2352", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T07:36:35.273", "Id": "2327", "Score": "9", "Tags": [ "php", "algorithm" ], "Title": "Find the no of pairs whose sum divides the product from 0 - 1000000000" }
2327
<p>I tried putting a script i saw together, plus used an existing script to make something run as a service. Now I have the following pl script and the init.d / start/stop scripts.</p> <p>They work, but I am wondering if I did it right, because when I start the service and i would start it again, it would just start again and give a new PID number (is this what I want? shouldn't it be saying "already running?") Also what I didn't understand is what the "cache" part of the STDIN and STDOUT does. Nor the filecheck (file set in the beginning and in the final loop checked for newer version...not sure what that does) Here goes:</p> <pre><code>#!/usr/bin/perl #use strict; use POSIX; use DateTime; use Fcntl qw(:flock); use File::CacheDir qw(cache_dir); Log("Initializing..."); # Find and read config file if (@ARGV != 1) { print("Usage: miniserv.pl &lt;config file&gt;"); die; } if ($ARGV[0] =~ /^([a-z]:)?\//i) { $config_file = $ARGV[0]; } else { print("NO CORRECT CONFIG FILE SPECIFIED"); die; } %config = &amp;read_config_file($config_file); Log("Initialized..."); Log("Loaded config file."); my $file = $0; my $age = -M $file; Log("File - ".$file.", age - ".$age); # Change dir to the server root @roots = ( $config{'root'} ); for($i=0; defined($config{"extraroot_$i"}); $i++) { push(@roots, $config{"extraroot_$i"}); } chdir($roots[0]); Log("Changed working directory: ".$roots[0]); Status("Daemonizing..."); my $pid = fork; if(!defined $pid) { LogError("Unable to fork : $!"); die; } if($pid) { Log("Parent process exiting, let the deamon (".$pid.") go..."); sleep 3; exit; } POSIX::setsid; if(-e $config{'pidfile'}) { open(PID, "&lt;".$config{'pidfile'}); my $runningpid = &lt;PID&gt;; close PID; unlink $config{'pidfile'}; while(-e "/proc/".$runningpid) { Status("Waiting for ".$runningpid." to exit..."); Log("Waiting for ".$runningpid." to exit..."); sleep 1; } } open(PID, "&gt;".$config{'pidfile'}) || die "Failed to create PID file $_[0] : $!"; print PID $$; close PID; Log("The deamon is now running..."); Status("Deamon running"); my $stdout = cache_dir({base_dir =&gt; $config{'root'}.'/cache', ttl =&gt; '1 day', filename =&gt; "STDOUT".$$}); my $stderr = cache_dir({base_dir =&gt; $config{'root'}.'/cache', ttl =&gt; '1 day', filename =&gt; "STDERR".$$}); Log("STDOUT : ".$stdout); Log("STDERR : ".$stderr); open STDIN, '/dev/null'; open STDOUT, '&gt;&gt;'.$stdout; open STDERR, '&gt;&gt;'.$stderr; while(1) { #### Code to be performed by the daemon if($age - (-M $file)) { Log("File modified, restarting"); open(FILE, $file ." |"); close(FILE); last; } if(!-e $config{'pidfile'}) { Log("Pid file doesn't exist, time go exit."); last; } sleep 5; } sub Log { my $string = shift; if($string) { my $time = DateTime-&gt;now(); if(open(LOG, "&gt;&gt;".$config{'logfile'})) { flock(LOG, LOCK_EX); print LOG $$." [".$time-&gt;ymd." ".$time-&gt;hms."] - ".$string."\r\n"; close LOG; } } } sub LogError { my $string = shift; if($string) { my $time = DateTime-&gt;now(); if(open(LOG, "&gt;&gt;".$config{'errorlog'})) { flock(LOG, LOCK_EX); print LOG $$." [".$time-&gt;ymd." ".$time-&gt;hms."] - ".$string."\r\n"; close LOG; } } } sub Status { my $string = shift; if($string) { $0 = "My Daemon- ".$string; } return $0; } # read_config_file(file) # Reads the given config file, and returns a hash of values sub read_config_file { local %rv; if(-e $_[0]) { open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!"; while(&lt;CONF&gt;) { s/\r|\n//g; if (/^#/ || !/\S/) { next; } /^([^=]+)=(.*)$/; $name = $1; $val = $2; $name =~ s/^\s+//g; $name =~ s/\s+$//g; $val =~ s/^\s+//g; $val =~ s/\s+$//g; $rv{$name} = $val; } close(CONF); return %rv; } else { print("COULD NOT FIND CONFIG FILE"); die; } } </code></pre> <p>start script</p> <pre><code>#!/bin/sh echo Starting reliand server in /usr/libexec/reliand trap '' 1 LANG= export LANG #PERLIO=:raw unset PERLIO export PERLIO PERLLIB=/usr/libexec/reliand export PERLLIB exec '/usr/libexec/reliand/miniserv.pl' /etc/reliand/miniserv.conf </code></pre> <p>init script</p> <pre><code>#!/bin/sh # chkconfig: 235 99 10 # description: Start or stop the reliand server # ### BEGIN INIT INFO # Provides: reliand # Required-Start: $network $syslog # Required-Stop: $network # Default-Start: 2 3 5 # Default-Stop: 0 1 6 # Description: Start or stop the reliand server ### END INIT INFO start=/etc/reliand/start stop=/etc/reliand/stop lockfile=/var/lock/subsys/reliand confFile=/etc/reliand/miniserv.conf pidFile=/var/reliand/miniserv.pid name='reliand' case "$1" in 'start') $start &gt;/dev/null 2&gt;&amp;1 &lt;/dev/null RETVAL=$? if [ "$RETVAL" = "0" ]; then touch $lockfile &gt;/dev/null 2&gt;&amp;1 fi ;; 'stop') $stop RETVAL=$? if [ "$RETVAL" = "0" ]; then rm -f $lockfile fi pidfile=`grep "^pidfile=" $confFile | sed -e 's/pidfile=//g'` if [ "$pidfile" = "" ]; then pidfile=$pidFile fi rm -f $pidfile ;; 'status') pidfile=`grep "^pidfile=" $confFile | sed -e 's/pidfile=//g'` if [ "$pidfile" = "" ]; then pidfile=$pidFile fi if [ -s $pidfile ]; then pid=`cat $pidfile` kill -0 $pid &gt;/dev/null 2&gt;&amp;1 if [ "$?" = "0" ]; then echo "$name (pid $pid) is running" RETVAL=0 else echo "$name is stopped" RETVAL=1 fi else echo "$name is stopped" RETVAL=1 fi ;; 'restart') $stop ; $start RETVAL=$? ;; *) echo "Usage: $0 { start | stop | restart }" RETVAL=1 ;; esac exit $RETVAL </code></pre>
[]
[ { "body": "<p>Oh crap, no. You have <code>use strict</code> commented out. Always, always, always <code>use strict</code> and <code>use warnings</code> until you understand when you might want to selectively turn off parts of what they do. Failure to do so will add huge amounts of extra debugging to your future. Without them you'll also be subject to incessant (and correct) nagging every time you post your code to any perl forum that's worth a crap.</p>\n\n<p>Ok, second, your PID file is supposed to prevent two or more copies from running simultaneously. The logic is:</p>\n\n<pre><code>Does the pid file exist?\n No - cool, we can run.\n Yes - Need more tests.\nLoad the PID from the pid file.\nIs there a process running with the PID from the pid file?\n No - cool, we can run.\n Yes - uh oh, gotta abort.\n</code></pre>\n\n<p>Right now your logic doesn't do that.</p>\n\n<p>The <code>cache_dir()</code> stuff comes from the CPAN module <a href=\"http://search.cpan.org/perldoc?File%3a%3aCacheDir\" rel=\"nofollow\">File::CacheDir</a>. It looks like it handles some log rotation mumble.</p>\n\n<p>The big block of code that frobs the STDIN/STDOUT/STDERR is reopening all the standard IO output to point to some autorotated files managed by <code>cache_dir</code>.</p>\n\n<p>Unless this is a learning exercise for teaching yourself how to write a daemon, consider <a href=\"http://www.perlmonks.org/?node_id=478839\" rel=\"nofollow\">reading this Perlmonks article</a>, and using CPAN modules like <code>Proc::Pid_File</code> and <code>Proc::Daemon</code>.</p>\n\n<p>Next, break your code into subroutines. Any functional block of code should, if possible, fit on one screen of text. You code should look like this:</p>\n\n<pre><code>use strict;\nuse warnings;\n# A bunch of use statements here\nuse Blarg;\n\nmy %args = process_command_line(@ARGV);\nmy $cfg = load_config_file( %args );\n\ndaemonize($cfg);\n\nwhile (1) {\n\n do_stuff($cfg);\n\n check_pid_file($cfg-&gt;{pid_file});\n\n}\n</code></pre>\n\n<p>Everything else is in subroutines. Each as short as possible.</p>\n\n<p>Remember, your code will be maintained by a homicidal maniac with anger management issues and a very short attention span. Make your code skimmable and you might survive.</p>\n\n<p>Finally, don't use two argument open with global file handles. This has been considered a bad idea for more than a decade.</p>\n\n<p>For example, when you open your config file, do this:</p>\n\n<pre><code>my $config_file_path = shift;\n\nopen my $conf, $config_file_path\n or die \"Failed to open config file '$config_file_path': $!\\n\";\n\nmy %config;\n\nwhile( my $line = &lt;$conf&gt; ) {\n $line =~ s/\\r|\\n//g;\n\n next if /^#/; # Skip comments\n\n next unless /\\S/; # Skip blank lines\n\n next unless /^\\s*([^=]+)\\s*=\\s*(.*)\\s*$/; # Skip malformed lines.\n\n my $name = $1;\n my $val = $2;\n\n $config{$name} = $val;\n}\n\nreturn \\%config;\n</code></pre>\n\n<p>I changed your while loop to use an explicit variable, because <code>$_</code> is not localized automatically by while. I also changed your capture to skip capturing the leading and trailing whitespace. Munged the line skipping logic for brevity.</p>\n\n<p>But the real answer here is to use a module like <code>Config::IniFiles</code> or <code>Config::Any</code> to handle configuration files.</p>\n\n<p>The shell stuff looks pretty much standard and OK.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-28T16:58:19.517", "Id": "2685", "ParentId": "2330", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T12:22:44.507", "Id": "2330", "Score": "3", "Tags": [ "perl", "bash" ], "Title": "service build with perl - is it correct" }
2330
<p>Anyone want to comment on this plugin I'm making? (improvements, etc)</p> <pre><code>(function($) { var methods = { init: function(data) { var options = { function: null, timeout: 1000, option: undefined } return this.each(function() { var self = $(this); $.extend(options, data); setTimeout(function() { self[options.function].apply(self, [options.options]); }, options.timeOut) }) } } $.fn.waitForit = function(method) { // Method calling logic if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.waitForit'); } }; })(jQuery); </code></pre> <p>Here is a fiddle: <a href="http://jsfiddle.net/maniator/Ad3pv/" rel="nofollow">http://jsfiddle.net/maniator/Ad3pv/</a></p>
[]
[ { "body": "<p>jQuery already has this functionality. Multiple animations on an element already automatically queue and wait until the previous animation has run. If you want to have a pause between two animations you can use <code>.delay()</code>. </p>\n\n<p>For example: </p>\n\n<pre><code>$('div.B').show('blind').delay(1000).fadeOut().delay(500).fadeIn(1000);\n</code></pre>\n\n<p>will do what your example with the plugin does (timing may needed to be adjusted a bit).</p>\n\n<p>Also animation methods call take a callback function as an argument, which will be called, when that specific animation is finished.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T15:10:47.190", "Id": "3732", "Score": "0", "body": "yes, but i made this for a user whose `delay()` was not working" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T15:17:54.310", "Id": "3733", "Score": "2", "body": "Then it would be better to find out *why* `delay()` isn't working. Most likely because`delay()` is only for animations and he's using it with non-animation methods. If he's using it with AJAX methods he should be using callbacks and `setTimeout` instead, or look into the new Deferred functionality of jQuery 1.5. And if that doesn't work, then post an example of the non-working code on Stack Overflow (not here)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T15:20:04.870", "Id": "3734", "Score": "0", "body": "@RoTada. lol thats why i gave this solution. it uses `setTimeout` and the like, it is basically a `delay` but for non animations" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T15:25:01.890", "Id": "3735", "Score": "0", "body": "But your solution is more complex and inflexible (only one argument possible), than directly using built-in callbacks." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T14:36:31.803", "Id": "2351", "ParentId": "2332", "Score": "4" } } ]
{ "AcceptedAnswerId": "2351", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T19:18:47.207", "Id": "2332", "Score": "-7", "Tags": [ "javascript", "jquery" ], "Title": "waitForIt Plugin" }
2332
<p>As a personal challenge, I am trying to make a very basic calculator without using any CLR's integer and arithmetic operations, but to only use memory. The idea was to do what CLR/OS does. i came up with a basic counter, Addition and multiplication, which works fine but multiplication takes long time to compute (if i use big number). Any advice for code improvement for better performance?</p> <pre><code>partial class FastCalculator { static LinkedList&lt;Char&gt; numbers = new LinkedList&lt;Char&gt;(new Char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }); static Dictionary&lt;Char, LinkedListNode&lt;Char&gt;&gt; fastNumbers = new Dictionary&lt;Char,LinkedListNode&lt;Char&gt;&gt;(); static FastCalculator() { LinkedListNode&lt;Char&gt; zero = numbers.First; while (zero != null) { fastNumbers[zero.Value] = zero; zero = zero.Next; } } //static void Main(string[] args) //{ // try // { // System.Diagnostics.Debug.WriteLine(0 + " PlusOne is " + PlusOne("0")); // System.Diagnostics.Debug.WriteLine(5 + " PlusOne is " + PlusOne("5")); // System.Diagnostics.Debug.WriteLine(9 + " PlusOne is " + PlusOne("9")); // System.Diagnostics.Debug.WriteLine(10 + " PlusOne is " + PlusOne("10")); // System.Diagnostics.Debug.WriteLine(999 + " PlusOne is " + PlusOne("999")); // System.Diagnostics.Debug.WriteLine(256 + " PlusOne is " + PlusOne("256")); // System.Diagnostics.Debug.WriteLine("Multiply 999*256 =" + Multiply("999", "256")); // } // catch (Exception ex) // { // System.Diagnostics.Debug.WriteLine(ex.Message); // } //} static string PlusOne(string num) { if (!string.IsNullOrEmpty(num)) { LinkedList&lt;Char&gt; input = new LinkedList&lt;Char&gt;(num.ToCharArray()); if (input.Last.Value != numbers.Last.Value)// not 9 { input.Last.Value = fastNumbers[input.Last.Value].Next.Value; return LinkedListToString(input); } else // if 9 { LinkedListNode&lt;Char&gt; in_last = input.Last; bool doCarryOver = true; while (in_last != null) { if (in_last.Value == numbers.Last.Value) { if (doCarryOver) { in_last.Value = numbers.First.Value; doCarryOver = true; } } else { if (doCarryOver) { in_last.Value = fastNumbers[in_last.Value].Next.Value; doCarryOver = false; } } in_last = in_last.Previous; } if (doCarryOver) { input.AddFirst(numbers.First.Next.Value);//1 } return LinkedListToString(input); } } return "0"; } static string Add(string left, string right) { string zero = numbers.First.Value.ToString(); if (string.IsNullOrEmpty(left) &amp;&amp; string.IsNullOrEmpty(right)) { return zero; } while (zero != right) { left = PlusOne(left); zero = PlusOne(zero); } return left; } static string Multiply(string left, string right) { string zero = numbers.First.Value.ToString(); if (string.IsNullOrEmpty(left) &amp;&amp; string.IsNullOrEmpty(right)) { return zero; } string rtn = zero; while (zero != right) { rtn = Add(rtn, left); zero = PlusOne(zero); } return rtn; } private static string LinkedListToString(LinkedList&lt;Char&gt; num) { StringBuilder sb = new StringBuilder(); if (num != null) { LinkedListNode&lt;Char&gt; first = num.First; while (first != null) { sb.Append(first.Value); first = first.Next; } } return sb.ToString(); } } </code></pre> <p><em><strong>Edit:</em></strong> Thank you everyone, special thanks to @RobinGreen (i implemented your solution which increased my performance drastically) and @interjay for referring to an excellent book (although will require some time to understand properly ;) ) I also used cache on basic operations to improve performance.</p> <p>one more thing which i learned was these operations are done in hardware. i wonder how? Also i did not do binary conversion because it would require extra overhead to convert decimal to binary and binary to decimal. Also if there is room for even more improvement please let me know. </p> <pre><code>partial class FastCalculator { static Dictionary&lt;string, LinkedList&lt;char&gt;&gt; operationCache = new Dictionary&lt;string, LinkedList&lt;char&gt;&gt;(); static void Main(string[] args) { try { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); System.Diagnostics.Debug.WriteLine(MultiplyVer2("5492012742638447789741521173787972956681294295296", "22867376956627844231881057173787972956681294295296")); watch.Stop(); TimeSpan ts = watch.Elapsed; string elapsedTime = String.Format("{0:00}h:{1:00}m:{2:00}s.{3:00}ms", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); System.Diagnostics.Debug.WriteLine("elapsedTime " + elapsedTime); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } static string AddVer2(string left, string right) { string zero = numbers.First.Value.ToString(); if (string.IsNullOrEmpty(left)) { left = zero; } if (string.IsNullOrEmpty(right)) { right = zero; } if (LengthLessThan(left, right)) //(left.Length &lt; right.Length),make sure left is always greater { string tmp = left; left = right; right = tmp; } LinkedList&lt;Char&gt; rightIn = new LinkedList&lt;Char&gt;(right.ToCharArray()); LinkedList&lt;Char&gt; leftIn = new LinkedList&lt;Char&gt;(left.ToCharArray()); var leftInLast = leftIn.Last; var rightInLast = rightIn.Last; bool doCarryOver = false; while (leftInLast != null) { if (rightInLast != null) { LinkedList&lt;Char&gt; add = AddSymbols(leftInLast.Value, rightInLast.Value); if (doCarryOver) { //since carry is always 1, we will do PlusOne add = new LinkedList&lt;Char&gt;(PlusOne(LinkedListToString(add)).ToCharArray()); } leftInLast.Value = add.Last.Value; if (add.Last.Previous != null) { doCarryOver = true; } else { doCarryOver = false; } rightInLast = rightInLast.Previous; } else { LinkedList&lt;Char&gt; add = AddSymbols(leftInLast.Value, numbers.First.Value); if (doCarryOver) { //since carry is always 1, we will do PlusOne add = new LinkedList&lt;Char&gt;(PlusOne(LinkedListToString(add)).ToCharArray()); } leftInLast.Value = add.Last.Value; if (add.Last.Previous != null) { doCarryOver = true; } else { doCarryOver = false; } } leftInLast = leftInLast.Previous; } if (doCarryOver) { leftIn.AddFirst(numbers.First.Next.Value);//1 } return LinkedListToString(leftIn); } static LinkedList&lt;char&gt; MultiplySymbols(char left, char right) { string inputStr = left + "*" + right; if (operationCache.ContainsKey(inputStr)) { return operationCache[inputStr]; } string zero = numbers.First.Value.ToString(); string rightStr = right.ToString(); string leftStr = left.ToString(); string rtn = zero; while (zero != rightStr) { rtn = AddVer2(rtn, leftStr); zero = PlusOne(zero); } operationCache[inputStr] = new LinkedList&lt;Char&gt;(rtn.ToCharArray()); return operationCache[inputStr]; } static LinkedList&lt;char&gt; AddSymbols(char left, char right) { string inputStr = left + "+" + right; if (operationCache.ContainsKey(inputStr)) { return operationCache[inputStr]; } string zero = numbers.First.Value.ToString(); string rightStr = right.ToString(); string leftStr = left.ToString(); while (zero != rightStr) { leftStr = PlusOne(leftStr); zero = PlusOne(zero); } operationCache[inputStr] = new LinkedList&lt;Char&gt;(leftStr.ToCharArray()); return operationCache[inputStr]; } static string MultiplyVer2(string left, string right) { string zero = numbers.First.Value.ToString(); if (string.IsNullOrEmpty(left) || string.IsNullOrEmpty(right)) { return zero; } if (LengthLessThan(left, right))//(left.length &lt; right.length) make sure left is always greater { var tmp = left; left = right; right = tmp; System.Diagnostics.Debug.WriteLine("swapped"); } string rtn = zero; LinkedList&lt;Char&gt; rightIn = new LinkedList&lt;Char&gt;(right.ToCharArray()); LinkedList&lt;Char&gt; leftIn = new LinkedList&lt;Char&gt;(left.ToCharArray()); LinkedList&lt;string&gt; result2sum = new LinkedList&lt;string&gt;(); var rightInLast = rightIn.Last; while (rightInLast != null) { var leftInLast = leftIn.Last; System.Diagnostics.Debug.WriteLine("right symbol " + rightInLast.Value); LinkedList&lt;Char&gt; temp = new LinkedList&lt;char&gt;(); String carry = string.Empty; while (leftInLast != null) { System.Diagnostics.Debug.WriteLine("left symbol " + leftInLast.Value); LinkedList&lt;Char&gt; mult = MultiplySymbols(leftInLast.Value, rightInLast.Value); if (!string.IsNullOrEmpty(carry)) { mult = new LinkedList&lt;Char&gt;(AddVer2(LinkedListToString(mult), carry).ToCharArray()); carry = string.Empty; } temp.AddFirst(mult.Last.Value); if (mult.Last.Previous != null) { carry = mult.Last.Previous.Value.ToString(); } leftInLast = leftInLast.Previous; } if (!string.IsNullOrEmpty(carry)) { temp.AddFirst(Convert.ToChar(carry)); } result2sum.AddFirst(LinkedListToString(temp)); rightInLast = rightInLast.Previous; } var result = result2sum.Last; string sum = numbers.First.Value.ToString();//0 string sumShift = string.Empty; while (result != null) { //string r = result.Value; System.Diagnostics.Debug.WriteLine("sum " + sum + " with " + result.Value + sumShift); sum = AddVer2(sum, result.Value + sumShift); sumShift = sumShift + numbers.First.Value.ToString(); result = result.Previous; } return sum; } static bool LengthLessThan(string left, string right) { LinkedList&lt;Char&gt; rightIn = new LinkedList&lt;Char&gt;(right.ToCharArray()); LinkedList&lt;Char&gt; leftIn = new LinkedList&lt;Char&gt;(left.ToCharArray()); var leftInLast = leftIn.Last; var rightInLast = rightIn.Last; while (leftInLast != null &amp;&amp; rightInLast != null) { leftInLast = leftInLast.Previous; rightInLast = rightInLast.Previous; } if (leftInLast == null &amp;&amp; rightInLast == null) { return false; } if (leftInLast != null &amp;&amp; rightInLast == null) { return false; } if (leftInLast == null &amp;&amp; rightInLast != null) { return true; } return false; } } </code></pre>
[]
[ { "body": "<p>It's a cool project you've got; but the performance is going to stink. The truth is, what you are doing is very different from what would happen when you perform basic math with + - / * in .NET. </p>\n\n<p>The obvious answer is to use the + - / * but that would defeat the purpose of what your doing (which again, I think it's a really cool sandbox type app). </p>\n\n<p>I'm hesitant to suggest machine language or asm, but you'd find that things like multiplication are handled for you there too.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T21:20:49.520", "Id": "2335", "ParentId": "2334", "Score": "0" } }, { "body": "<ol>\n<li>Arithmetic is implemented in hardware, not by the OS or the CLR (except for things that need a large number of bits to represent - software is used to help with those).</li>\n<li>Binary is used by the hardware, not decimal.</li>\n<li>You can find fast arithmetic algorithms in <a href=\"http://rads.stackoverflow.com/amzn/click/0073523402\" rel=\"nofollow\">Dasgupta, Papadimitriou and Vazirani (2006)</a>. I recommend this book, it's great.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T21:23:28.073", "Id": "2336", "ParentId": "2334", "Score": "10" } }, { "body": "<p>To represent integers, you're using the string representation of them as decimal numbers. So to do addition and multiplication, you can use the same algorithms that you were taught in elementary school:</p>\n\n<p>For addition, add the digits one by one from right to left, taking care of carry along the way.</p>\n\n<p>For multiplication, preinitialize a multiplication table of all products of the digits 0-9. Then use standard long multiplication, using the multiplication table for any product of two digits, and your addition function from above to add together intermediate products.</p>\n\n<p>Doing this will give you results much faster than your current algorithm: Your algorithm takes exponential time in the length of the inputs, while these versions take polynomial time.</p>\n\n<p>You'll have an easier time if you use the binary representation of numbers rather than decimal: This will make operations on single digits much easier, since there are only two possibilities for each digit. The general algorithms will remain the same.</p>\n\n<p>By the way, this is definitely not the way that addition and multiplication are performed by the CLR. The CLR simply uses your processor's native addition and multiplication instructions, which do the calculations in hardware.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T21:26:29.637", "Id": "2337", "ParentId": "2334", "Score": "4" } }, { "body": "<p>Consider that each number is an array of characters and pad zeros on the left.</p>\n\n<pre><code>00000008\n00000045\n</code></pre>\n\n<p>Then handle each column (ones, tens, hundreds, etc) separately. Make a function that handles just one column in isolation.</p>\n\n<p>Add(left:\"8\", top:\"5\", remainder:\"0\")\n returns { value: \"3\", remainder:\"1\" }</p>\n\n<p>Then do the next column, etc. And similar long-hand for each operation ( *, /, +, - ).</p>\n\n<p>Optimize further by using enumerations instead of characters for each digit. That way you can use switch statements if you want to stay away from math.</p>\n\n<p>enum Digits { Zero = 0, One = 1, etc }</p>\n\n<p>Just a thought...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T21:30:44.113", "Id": "2338", "ParentId": "2334", "Score": "0" } }, { "body": "<p>The computational complexity of multiplication as it is implemented in that example ( as nice as it is), is at least quadratic. You need to define multiplication without using the addition implementation. Although conceptually it makes sense to have multiplication defined in terms of addition, it is not a requirement. You are handling arithmatic in a symbolic way. The question you have to answer is that symbolically how to (re)define multiplication to stay linear.</p>\n\n<p>First hint is not to define it using the Addition implementation as you have in your approach.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T03:16:32.303", "Id": "2339", "ParentId": "2334", "Score": "0" } } ]
{ "AcceptedAnswerId": "2337", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-09T21:12:50.290", "Id": "2334", "Score": "13", "Tags": [ "c#", "algorithm" ], "Title": "To make a calculator from scratch" }
2334
<p>Please help me improve this function that compares the jQuery version currently available <sup>(or not)</sup> with the one required.</p> <pre><code>function(need) { if (typeof(jQuery) != 'undefined') { if (!need) return true; var re = /(\d+)\.(\d+)\.(\d+)/, cur = re.exec(jQuery.fn.jquery), need = re.exec(need); return (need[1] &lt;= cur[1] &amp;&amp; need[2] &lt;= cur[2] &amp;&amp; need[3] &lt;= cur[3]); } else return false; } </code></pre>
[]
[ { "body": "<p>I'm sorry, but that code is completely broken. </p>\n\n<ul>\n<li>It doesn't work if either version contains only two numbers such as the current \"1.6\".</li>\n<li>It uses string comparison instead of integer comparison, so that it will return <code>true</code> if you \"need\" (theoretical) version \"1.4.10\" but only \"1.4.2\" is included, because <code>\"10\" &lt; \"2\"</code> is <code>true</code>.</li>\n<li>It doesn't stop comparing minor version numbers, if the major number is already bigger. For example it will return <code>false</code> if \"1.4.2\" is \"needed\", but \"1.5.1\" is included, because <code>\"2\" &gt; \"1\"</code></li>\n<li>And finally you should keep in mind that \"newer\" isn't necessarily better. For example, the new 1.6 version changes how <code>.attr()</code> works, and scripts that rely on the old functionality of <code>.attr()</code> may break.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T13:43:13.367", "Id": "2347", "ParentId": "2340", "Score": "5" } }, { "body": "<p>I just made a plugin.</p>\n\n<pre><code>$.versioncompare(version1[, version2 = jQuery.fn.jquery])\n</code></pre>\n\n<p><a href=\"https://github.com/zuzara/jQuery-version-compare-plugin\" rel=\"nofollow\">https://github.com/zuzara/jQuery-version-compare-plugin</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T05:46:01.303", "Id": "5617", "ParentId": "2340", "Score": "1" } }, { "body": "<p>I feel like I'm missing something, but I got it down to one line for a compressed version, or a few lines for a verbose explination.</p>\n\n<p><strong>Compressed version:</strong></p>\n\n<pre><code>(parseInt(jQuery.fn.jquery.split('.').join('')) &gt; 140) ? alert(\"Running jquery greater than 1.4.0\") : alert(\"current jquery version is 1.4.0 or less\");\n</code></pre>\n\n<p><strong>Long version for clarity:</strong></p>\n\n<pre><code>// get version as a string and get rid of the periods. \nversion = jQuery.fn.jquery.split('.').join('');\n\n// Make into one long number for easy comparison. Example, 171, or 141.\nversion = parseInt(version);\nif(version &gt; 141){\n alert(\"We're using a version greater than 1.4.1\");\n}else{\n alert(\"jQuery version is 1.4.1 or lower\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T15:03:09.243", "Id": "21941", "Score": "0", "body": "Sorry, this is just as broken. It only works for two versions with the same number of parts and if those part only have 1 digit part. Examples: It will falsely conclude that \"1.5\" < \"1.4.1\" and \"1.10\" < \"1.9\"." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-26T23:10:07.527", "Id": "11238", "ParentId": "2340", "Score": "-1" } } ]
{ "AcceptedAnswerId": "2347", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T05:20:29.983", "Id": "2340", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "Improve this function that compares jQuery versions" }
2340
<p>I want the fastest way in Mathematica 7 to generate a list of the factors (not prime factors) of an integer into a specified number of terms, with each factor greater than one.</p> <p>For example, 240 into three terms:</p> <pre><code>{{2,2,60}, {2,3,40}, {2,4,30}, {2,5,24}, {2,6,20}, {2,8,15}, {2,10,12}, {3,4,20}, {3,5,16}, {3,8,10}, {4,4,15}, {4,5,12}, {4,6,10}, {5,6,8}} </code></pre> <p>My starting code is based on a recursive method the source of which I have forgotten, but probably someone on <a href="http://projecteuler.net/" rel="nofollow">projecteuler.net</a>:</p> <pre><code>f[n_, 1, ___] := {{n}} f[n_, k_, x_: 2] := Join @@ Table[ If[q &lt; x, {}, {q, ##} &amp; @@@ f[n/q, k - 1, q]], {q, # ~Take~ ⌈Length@#/k⌉ &amp; @ Divisors @ n} ] f[240, 3] </code></pre> <hr> <p>Memoization can be applied in several places. In the case of large integers this is much faster, at the expense of memory usage of course. Here, with memoization at three points:</p> <pre><code>Clear[f, div] div@n_ := div@n = Divisors@n div[n_, k_] := div[n, k] = # ~Take~ ⌈Length@#/k⌉ &amp; @ div @ n f[n_, 1, ___] := {{n}} f[n_, k_, x_: 2] := f[n, k, x] = Join @@ Table[ If[q &lt; x, {}, {q, ##} &amp; @@@ f[n/q, k - 1, q]], {q, n~div~k} ] </code></pre> <p>Compared to Sasha's code on a large composite integer:</p> <pre><code>f[10080^2, 5] // Length // Timing </code></pre> <pre><b> {0.891, 103245}</b></pre> <pre><code>FactorIntoFixedTerms[10080^2, 5] // Length // Timing </code></pre> <pre><b> {25.594, 103245}</b></pre> <h3>Can this be further improved?</h3>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T12:51:38.990", "Id": "3725", "Score": "0", "body": "Welcome to CodeReview, Mr. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T16:39:11.437", "Id": "3740", "Score": "0", "body": "@belisarius why don't you have the Gold badge for \"math\" tag on StackOverflow? You seem to have more than enough votes!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T16:59:21.373", "Id": "3741", "Score": "0", "body": "@Mr. I'm not sure, but I guess it is because you need to have posted at least 200 answers in that tag. Most of my votes come from only one answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T17:03:17.500", "Id": "3742", "Score": "0", "body": "@belisarius That must have been quite an answer! O_O" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T17:17:44.133", "Id": "3743", "Score": "0", "body": "@Mr. Just luck http://stackoverflow.com/questions/3956478/understanding-randomness/3956538#3956538" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T17:22:13.630", "Id": "3744", "Score": "0", "body": "@belisarius that looks like a good answer, but WOW that's a lot of votes!" } ]
[ { "body": "<p>Because <code>Divisor</code> is quite efficient at its job, the only optimization I see, is to avoid unnecessary calls to it, by using memoization technique:</p>\n\n<pre><code>FactorIntoFixedTerms[in_Integer, terms_Integer] := Block[{f, div},\n div[n_] := (div[n] = Divisors[n]);\n f[n_, 1] := {{n}}; \n f[n_, k_] := \n Join @@ Table[{q, ##} &amp; @@@ \n Select[f[n/q, \n k - 1], #[[1]] &gt;= \n q &amp;], {q, #[[2 ;; \\[LeftCeiling]Length@#/\n k\\[RightCeiling]]] &amp;@div@n}];\n f[in, terms]\n ]\n</code></pre>\n\n<p>This can lead to substantial timing reduction:</p>\n\n<pre><code>In[683]:= FactorIntoFixedTerms[1453522322112240, 6] // Length // Timing\n\nOut[683]= {0.047, 47}\n\nIn[685]:= foriginal[1453522322112240, 6] // Length // Timing\n\nOut[685]= {0.39, 47}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T18:00:54.163", "Id": "2344", "ParentId": "2342", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T15:36:41.180", "Id": "2342", "Score": "2", "Tags": [ "algorithm", "wolfram-mathematica" ], "Title": "List of integer factorization into n terms" }
2342
<p><strong>Requirement</strong>: Parse a String into chunks of numeric characters and alpha characters. Alpha characters should be separated from the numeric, other characters should be ignored. </p> <p><strong>Example Data:</strong></p> <pre> Input Desired Output 1A [1, A] 12 [12] 12G [12, G] 12ABC-SFS513 [12, ABC, SFS, 513] AGE+W#FE [AGE, W, FE] -12WE- [12, WE] -12- &%3WE- [12, 3, WE] </pre> <p><strong>Question:</strong></p> <p>The code below accomplishes this. However, I am looking for any suggestions as to a better way to accomplish this (maybe a crazy regex using <code>String.split()</code>? ) or any changes that could make this code more readable/easy to follow.</p> <p><strong>Code:</strong></p> <pre><code>private static String VALID_PATTERN = "[0-9]+|[A-Z]+"; private List&lt;String&gt; parse(String toParse){ List&lt;String&gt; chunks = new LinkedList&lt;String&gt;(); toParse = toParse + "$"; //Added invalid character to force the last chunk to be chopped off int beginIndex = 0; int endIndex = 0; while(endIndex &lt; toParse.length()){ while(toParse.substring(beginIndex, endIndex + 1).matches(VALID_PATTERN)){ endIndex++; } if(beginIndex != endIndex){ chunks.add(toParse.substring(beginIndex, endIndex)); } else { endIndex++; } beginIndex = endIndex; } return chunks; } </code></pre>
[]
[ { "body": "<p>I'm sure this possible with some crazy RegExp and <code>.split()</code>, but I would avoid RegExps for \"simple\" tasks like these.</p>\n\n<p>One thing I would change, is the check if a \"chunk\" matches the pattern. For example, when working on the string <code>\"AB12\"</code>, then currently you first check if <code>\"A\"</code> fits the pattern, and then if <code>\"AB\"</code> does, but we already know that <code>\"A\"</code> matches, so it isn't really necessary to do it a again. </p>\n\n<p>Also adding a \"invalid\" character to the end, seems the wrong way to exit. </p>\n\n<p>My suggestion would be to do it like this (untested):</p>\n\n<pre><code>private int charType(char c) {\n if ('A' &lt;= c &amp;&amp; c &lt;= 'Z')\n return 1;\n else if ('0' &lt;= c &amp;&amp; c &lt;= '9')\n return 2;\n else\n return 0;\n}\n\nprivate List&lt;String&gt; parse(String toParse){\n List&lt;String&gt; chunks = new LinkedList&lt;String&gt;();\n int length = toParse.length();\n int beginIndex = 0;\n int endIndex = 0;\n int currentType;\n while (endIndex &lt; length) {\n currentType = charType(toParse.charAt(endIndex));\n if (currentType != 0) {\n do {\n endIndex++;\n } while (endIndex &lt; length &amp;&amp; currentType == charType(toParse.charAt(endIndex)));\n chunks.add(toParse.substring(beginIndex, endIndex)); \n } else {\n endIndex++;\n } \n beginIndex = endIndex;\n } \n return chunks;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T14:24:41.553", "Id": "3729", "Score": "2", "body": "Why would you avoid regexps in this case - especially since the OP's regex is so simple (and thus perfectly readable)? `'A' <= c && c <= 'Z'` seems in no way more readable to me then `[A-Z]`. Further using regex allows you to find the matches much more easily than this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T14:40:03.660", "Id": "3731", "Score": "0", "body": "Granted, my goal wasn't readability, but speed. A RegExp is most likely much slower than a few simple numerical comparisons." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T02:49:26.287", "Id": "3768", "Score": "0", "body": "The switch statement in `charType` isn't valid Java. The case expressions need to be compile time constant expressions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T09:40:56.413", "Id": "3771", "Score": "0", "body": "@Stephan C: Duh. Confused it with JavaScript. I'll change it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T14:11:16.237", "Id": "2348", "ParentId": "2345", "Score": "4" } }, { "body": "<p>First of all, yes there is a crazy regex you can give to <code>String.split</code>:</p>\n\n<pre><code>\"[^A-Z0-9]+|(?&lt;=[A-Z])(?=[0-9])|(?&lt;=[0-9])(?=[A-Z])\"\n</code></pre>\n\n<p>What this means is to split on any sequence of characters which aren't digits or capital letters as well as between any occurrence of a capital letter followed by a digit or any digit followed by a capital letter. The trick here is to match the space between a capital letter and a digit (or vice-versa) without consuming the letter or the digit. For this we use look-behind to match the part before the split and look-ahead to match the part after the split.</p>\n\n<p>However as you've probably noticed, the above regex is quite a bit more complicated than your <code>VALID_PATTERN</code>. This is because what you're really doing is trying to extract certain parts from the string, not to split it.</p>\n\n<hr>\n\n<p>So finding all the parts of the string which match the pattern and putting them in a list is the more natural approach to the problem. This is what your code does, but it does so in a needlessly complicated way. You can greatly simplify your code, by simply using <code>Pattern.matcher</code> like this:</p>\n\n<pre><code>private static final Pattern VALID_PATTERN = Pattern.compile(\"[0-9]+|[A-Z]+\");\n\nprivate List&lt;String&gt; parse(String toParse) {\n List&lt;String&gt; chunks = new LinkedList&lt;String&gt;();\n Matcher matcher = VALID_PATTERN.matcher(toParse);\n while (matcher.find()) {\n chunks.add( matcher.group() );\n }\n return chunks;\n}\n</code></pre>\n\n<hr>\n\n<p>If you do something like this more than once, you might want to refactor the body of this method into a method <code>findAll</code> which takes the string and the pattern as arguments, and then call it as <code>findAll(toParse, VALID_PATTERN)</code> in <code>parse</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T14:30:59.770", "Id": "3730", "Score": "0", "body": "I had not looked into the Matcher class. This is excellent." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T14:20:59.323", "Id": "2349", "ParentId": "2345", "Score": "15" } }, { "body": "<p>You should have a look at <a href=\"http://code.google.com/p/guava-libraries/\" rel=\"nofollow\">Guava</a>, especially at CharMatcher and Splitter. While both \"manual\" splitting and regexes certainly work, there is no need to make your life more complicated if there is already an easy and safe solution available.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T10:57:22.443", "Id": "3773", "Score": "0", "body": "sepp2k answer was nice and simple, plus did not need an external library. If there is better match in Guava I might consider it, but even it was one line of code and super simple, I don't think it is work adding another library." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T06:57:06.053", "Id": "2377", "ParentId": "2345", "Score": "1" } }, { "body": "<p>If you do not care what order it is in, this worked for me</p>\n\n<pre><code>MyString = MyString.replaceAll(\"[^A-Z ]\", \"\") + \" \" + MyString.replaceAll(\"[^0-9 ]\", \"\");\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T11:16:25.893", "Id": "26576", "Score": "0", "body": "The order is important, but this is interesting for those who might not." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-10T19:22:15.970", "Id": "14536", "ParentId": "2345", "Score": "2" } } ]
{ "AcceptedAnswerId": "2349", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T13:35:46.913", "Id": "2345", "Score": "13", "Tags": [ "java", "strings", "parsing", "regex" ], "Title": "Simplify splitting a String into alpha and numeric parts" }
2345
<p>Beeing on .NET 3.5 i don't have access to the TPL. Yet i have become fed up of having to manage manually the logic behind delegate.BeginInvoke type of scenarios each time and i set up to implement my own Task class.</p> <p>Functionality it should support:</p> <ul> <li>starting a parallel execution (using a thread pool thread)</li> <li>capable of Waiting on the result with a specific timeout</li> <li>capable of aborting said execution</li> <li>should provide event for callbacks to attach to</li> </ul> <p>This is my implementation. Can you guys please review it and specify if there are any issues i might not have considered or maybe more effective ways to implement some things?</p> <pre><code>public class Task&lt;T&gt; { #region Members private IAsyncResult _async; private Func&lt;T&gt; _action; private Func&lt;T&gt; _innerAction; private WaitHandle _waitHandle; private Thread _thread; private object _completedLock = new object(); private object _abortLock = new object(); private T _result; private bool _endCalled = false; #endregion #region Properties public object Tag { get; private set; } public bool IsCompleted { get; private set; } public bool IsRunning { get; private set; } public T Result { get { if (!_endCalled) { lock (_completedLock) { if (!_endCalled) { try { if (_async != null) { _result = _innerAction.EndInvoke(_async); IsCompleted = true; } } finally { _endCalled = true; } } } } return _result; } } #endregion #region Events public event EventHandler Completed; #endregion public Task(Func&lt;T&gt; action, object tag) : this(action) { Tag = tag; } public Task(Func&lt;T&gt; action) { _action = action; _innerAction = () =&gt; { try { _thread = Thread.CurrentThread; var result = _action(); return result; } finally { lock (_abortLock) { IsRunning = false; } } }; } #region Public Methods public void Run() { if (!IsRunning || IsCompleted) { lock (_completedLock) { if (!IsRunning || IsCompleted) { ResetState(); _async = _innerAction.BeginInvoke(obj =&gt; OnCompleted(), null); IsRunning = true; return; } } } throw new InvalidOperationException("Task is already running"); } public bool WaitForCompletion(TimeSpan timeout) { if (IsRunning &amp;&amp; !IsCompleted) { lock (_completedLock) { if (!IsCompleted) { _waitHandle = _async.AsyncWaitHandle; return _waitHandle.WaitOne(timeout); } } } return IsCompleted; } public bool WaitForCompletion(int timeoutMilliseconds) { return WaitForCompletion(TimeSpan.FromMilliseconds(timeoutMilliseconds)); } public bool Abort() { bool result = false; if (!IsCompleted) { lock (_abortLock) { if (!IsCompleted &amp;&amp; IsRunning) { if (_thread != null) { _thread.Abort(); } result = true; } ResetState(); } } return result; } #endregion private void ResetState() { _async = null; _endCalled = false; _result = default(T); _thread = null; IsCompleted = false; IsRunning = false; } private void OnCompleted() { lock (_completedLock) { IsCompleted = true; if (_waitHandle != null) { _waitHandle.Close(); _waitHandle = null; } } if (Completed != null) { try { Completed(this, EventArgs.Empty); } catch { //We swallow this as there is no way to catch it at an upper level //on the execution thread and do something about it. //Callbacks should not throw anyway. } } } } </code></pre>
[]
[ { "body": "<ul>\n<li><p>You may want to consider replacing the flags (<code>IsRunning</code>/<code>IsCompleted</code>) with a single state enum.</p></li>\n<li><p>Some state checks use <code>_abortLock</code> while others use <code>_completedLock</code>.</p>\n\n<ol>\n<li>If <code>Abort()</code> is called on a Task that has not started,</li>\n<li>a context switch happens just before <code>ResetState()</code> is called,</li>\n<li>a second thread calls <code>Run()</code> and the new inner thread starts,</li>\n<li>another context switch happens and the first thread resumes to call <code>ResetState()</code></li>\n</ol>\n\n<p>Yeah, a few moons would need to be in alignment for this to happen ... but still.</p></li>\n<li><p>If <code>Run()</code> is called followed by <code>Abort()</code> before the inner thread actually starts, then _thread could be null resulting the thread not actually being aborted and inconsistent state. (again with the moons.)</p></li>\n<li><p>Abort will not terminate the thread immediately, you should wait for it to complete before resetting the state.</p></li>\n<li><p>I'm not sure aborting a thread pool thread is a good idea.</p></li>\n<li><p>You set Tag in one of the constructors, but I don't see it being used anywhere.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-13T10:22:25.427", "Id": "3793", "Score": "0", "body": "thank for the suggestions. Some answers to your questions:" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-13T10:32:03.577", "Id": "3794", "Score": "0", "body": "I am very well aware of the non deterministic nature of Abort(). It should not be used anyway too often. Aborting a threadPool thread is ok in my tests as the thread gets recycled and started again for a new execution just fine. The only difficulty is making sure you abort it while it's running your task and not some other thing scheduled by the pool. I am trying to be sure of that with the locks on _abortLock in the finally clause of the delegate and the Abort method" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-13T10:37:24.277", "Id": "3795", "Score": "0", "body": "on your specific case i think i need to add an lock(_abortLock) to run in addition to the present _completedLock. That should take care of this scenarion" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-13T10:40:14.880", "Id": "3796", "Score": "0", "body": "the Tag property is there so i can mark a task with some identifier and be able to differentiate it from other similar tasks in the same collection." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T12:07:38.293", "Id": "3802", "Score": "0", "body": "@AZ01, It might be better to just use the one lock object for both \"_completedLock\" and \"_abortLock\" (and just give it a more generic name). Regarding the Tag, I had thought it was intended for use by the inner thread but saw no easy way for the inner thread to access it. If its for the organization of the tasks then it should be fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T11:59:14.420", "Id": "3840", "Score": "0", "body": "one single lock object would cause problems with a long running task that has a WaitForCompletion on it. The wait call will acquire the lock and it would block any Abort calls that might be needed. That's why i have a separate lock for abort and another for completion. As no one else has posted a better analysis on this question i will mark yours as accepted. Thanks." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T12:20:28.797", "Id": "2365", "ParentId": "2346", "Score": "6" } }, { "body": "<p>Maybe <a href=\"http://social.msdn.microsoft.com/Forums/en/parallelextensions/thread/aa1dd834-3c3d-409b-907e-196ee8f427bf\" rel=\"nofollow\">this link</a> helps you:</p>\n\n<blockquote>\n <p>If you download Reactive Extensions for .NET 3.5SP1 from <a href=\"http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx</a>, you'll find a System.Threading.dll assembly... that contains TPL for .NET 3.5.</p>\n</blockquote>\n\n<p>PS: The Rx page has moved to: <a href=\"http://msdn.microsoft.com/en-us/data/gg577609\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/data/gg577609</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-13T10:06:06.440", "Id": "3792", "Score": "2", "body": "-1 thanks for the links but my request was for review of the existing code" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T19:52:33.540", "Id": "2369", "ParentId": "2346", "Score": "3" } } ]
{ "AcceptedAnswerId": "2365", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T13:35:48.240", "Id": "2346", "Score": "10", "Tags": [ "c#", ".net" ], "Title": "Async Task implementation" }
2346
<p>About a week ago, I put up this code and got some really good help. I've modified it a bit and was seeking if someone would review my second iteration. Original can be found <a href="https://codereview.stackexchange.com/questions/2290/pig-latin-translator">here</a>.</p> <p>Here's the new stuff. Basically, I stuck it all in a module, added support for the option of a dash or no dash. And gave it the ability to work with sentences.</p> <pre><code>module PigLatin class Translator #how all the words end ENDING = "ay" def initialize (options = {:dash =&gt; true}) @dash = options[:dash] end def translate (phrase) sentences = phrase.split(".") translated_sentences = sentences.map do |sentence| translation(sentence) + "." end translated_sentences.join(" ") end private def translation (phrase) words = phrase.split translated_words = words.map do |word| if vowel_is_first(word) translate_with_vowel(word) else translate_with_consonant(word) end end translated_phrase = translated_words.join(" ") if @dash == false translated_phrase = translated_phrase.delete("-") end translated_phrase.capitalize end def vowel_is_first(word) return true if word[0] =~ /a|e|i|o|u|A|E|I|O|U/ return false end def translate_with_vowel(word) "#{word}-#{"w"+ENDING}" end def translate_with_consonant(word) return "#{word[1]}-#{word[0]+ENDING}" if word.size == 2 second_segment, first_segment = split(word) return "#{first_segment}-#{second_segment+ENDING}" end def split(word) split_location = word =~ /a|e|i|o|u/ second_segment = word[0,split_location] first_segment = word[split_location,word.size] return second_segment, first_segment end end class InputAcceptor def initialize input, options @options = options @input = input end def do_it pig_latin = Translator.new(@options) pig_latin.translate(@input) end end end j = PigLatin::InputAcceptor.new("Hello. You. Guy.",{:dash =&gt; false}) p j.do_it </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T19:16:46.807", "Id": "3745", "Score": "0", "body": "Any reason you didn't go with `String#split` to split the word into segments?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T20:08:40.150", "Id": "3746", "Score": "0", "body": "I couldn't get it to work correctly. If I remember correctly it wasn't splitting the words at the right spot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T20:18:51.013", "Id": "3747", "Score": "0", "body": "Now that I look at it again, what it was doing was eating up the vowel it split on (sorry about that), but that can easily be fixed by using lookahead in the regex." } ]
[ { "body": "<p>I think this is a great way to work on your skills, and I applaud your perseverance here. In particular, it is important to recognize that building software is incremental, and ideally there is a tight loop of development, review, re-factoring, re-review, etc.</p>\n\n<p>Here are some comments from me:</p>\n\n<pre><code>def vowel_is_first(word)\n return true if word[0] =~ /a|e|i|o|u|A|E|I|O|U/\n return false\nend\n</code></pre>\n\n<p>In general, it's not standard style to use strings like arrays, and you can essentially always find a different way to express what you need without doing that. Additionally, rather than using alternation (<code>|</code>) in the regular expression, you should use a character class - simpler, clearer, and more atomic. My suggestion:</p>\n\n<pre><code>def vowel_is_first(word)\n return word =~ /^[aeiouAEIOU]/\nend\n</code></pre>\n\n<p>The caret (<code>^</code>) matches at the beginning of a string (or the beginning of a line, but we aren't dealing with multi-line strings), and then our character class matches one occurence of any character inside the square brackets. This will return a non-nil value if the first character is a vowel, and nil otherwise.</p>\n\n<p>Moving on to:</p>\n\n<pre><code>\"#{word}-#{\"w\"+ENDING}\"\n</code></pre>\n\n<p>You dont need to put literal strings within interpolation, and concatenating strings with <code>+</code> should generally be a no-no. This would be clearer as:</p>\n\n<pre><code>\"#{word}-w#{ENDING}\"\n</code></pre>\n\n<p>Next,</p>\n\n<pre><code>return \"#{word[1]}-#{word[0]+ENDING}\" if word.size == 2\n</code></pre>\n\n<p>We need to do away with these array-style references again. This is a perfect spot for a gsub:</p>\n\n<pre><code>return word.gsub(/^(.)(.)$/, \"\\\\2-\\\\1#{ENDING}\") if word.size == 2\n</code></pre>\n\n<p>We capture two single characters, which we are guaranteed due to the conditional. Then, we reverse their order, putting a dash between them and ending with, well, our ending.</p>\n\n<p>With regard to the most complicated part of the code; viz. translate_with_consonant for words with longer than 2 letters - which basically means the split method which you wrote. I agree with <a href=\"https://codereview.stackexchange.com/users/128/sepp2k\">sepp2k</a> that you could use the built-in split with a clever regular expression to split on, but I think the whole thing can be done in a gsub again. You should try to come up with it yourself.</p>\n\n<blockquote class=\"spoiler\">\n <p> <code>return word.gsub(/^([^aeiouAEIOU]+)([aeiouAEIOU][A-Za-z]*)/, \"\\\\2-\\\\1ay\")</code></p>\n</blockquote>\n\n<p>Weird, using backticks and spoiler together makes it less spoiler. Oh well.</p>\n\n<p>Explanation:</p>\n\n<blockquote class=\"spoiler\">\n <p> We look for a non-vowel to begin the string (inside of a character class, the caret means to take the inverse; look for anything but what is listed). If we get more than one non-vowel, that's OK (<code>+</code> means one or more), but we capture the second part starting with the first vowel, and continuing through the last letter.</p>\n</blockquote>\n\n<p>The great thing about this regular expression is that you can use it for the entirety of translate_with_consonant - the two-letter words fit right in. And no need for splitting, joining, concatenating, or another method. Additionally, it works better if I pass you an exclamation point or a comma - try it!</p>\n\n<p>Finally, I would say that you don't need the InputAcceptor class at all. Keep the interface simple, as sepp2k suggested, and make the translation happen in one method call.</p>\n\n<p>I look forward to seeing more!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T12:22:53.963", "Id": "3776", "Score": "1", "body": "I disagree that it's bad style to index strings. I also think that your spoilered `gsub` call is less readable than using `split`. But other than that, these are all good points. +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T04:33:37.303", "Id": "2374", "ParentId": "2353", "Score": "3" } }, { "body": "<p>Some points in addition to what checkorbored pointed out:</p>\n\n<ol>\n<li><p>You should use character classes and the <code>i</code> flag for your regexen. E.g. instead of <code>/a|e|i|o|u|A|E|I|O|U/</code> you can write <code>/[aeiou]/i</code>.</p></li>\n<li><p>You should get rid of the explicit <code>return</code> statements where not necessary.</p></li>\n<li><pre><code>return foo if bar\nreturn baz\n</code></pre>\n\n<p>should really be written as</p>\n\n<pre><code>if bar\n foo\nelse\n baz\nend\n</code></pre>\n\n<p>Except if <code>foo</code> and <code>baz</code> are booleans in which case the whole thing can just be replaced by <code>bar</code> or <code>!bar</code>.</p></li>\n<li><pre><code>def initialize (options = {:dash =&gt; true})\n @dash = options[:dash]\nend\n</code></pre>\n\n<p>In this case it doesn't matter because there's only one option in your options hash, but the usual idiom to implement keyword arguments with defaults looks like this:</p>\n\n<pre><code>def initialize (options = {})\n options = {:dash =&gt; true}.merge(options)\n @dash = options[:dash]\nend\n</code></pre>\n\n<p>The reason that <code>(options = {defaults})</code> is generally not used, is that it doesn't allow the user to specify some options, but use the default for others. So if you do <code>def bla(options = {:foo =&gt; 42, :bar =&gt; 23}</code>) and the user calls <code>bla(:bar =&gt; 24)</code> the value for <code>:foo</code> will be <code>nil</code>, not 42. That doesn't happen if you use <code>merge</code> instead.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T12:28:54.883", "Id": "2381", "ParentId": "2353", "Score": "4" } }, { "body": "<p>My 2-cents:</p>\n\n<p>No spaces between function name and parenthesis: <code>def function(arg1, args)</code></p>\n\n<p>No if <code>something == true</code> or <code>if something == false</code>, directly <code>if something</code> or <code>if !something</code>.</p>\n\n<p>You can continue writing code after an <code>end</code>.</p>\n\n<pre><code> def translate(phrase)\n translated_sentences = phrase.split(\".\").map do |sentence|\n translation(sentence) + \".\"\n end.join(\" \")\n end\n</code></pre>\n\n<p>Don't reuse/update variables, create new ones or write it in other way:</p>\n\n<pre><code>translated_phrase = translated_words.join(\" \")\nif @dash == false\n translated_phrase = translated_phrase.delete(\"-\")\nend\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>translated_phrase0 = translated_words.join(\" \")\ntranslated_phrase = @dash ? translated_phrase0 : translated_phrase0.delete(\"-\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T14:52:33.537", "Id": "2388", "ParentId": "2353", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T19:01:39.193", "Id": "2353", "Score": "7", "Tags": [ "ruby", "pig-latin" ], "Title": "Pig Latin Translator - follow-up" }
2353
<p>I am wondering if this code will work in 10.1.</p> <p>This <a href="http://resources.arcgis.com/gallery/video/arcgis-server/details?entryID=C0806E5E-1422-2418-A02E-CF00BF8ABEC7" rel="nofollow noreferrer">video</a> at 1:02 says not to create mxd based services. I think that just means not using <a href="http://help.arcgis.com/en/sdk/10.0/arcobjects_net/componenthelp/index.html#/IMapServerObjects3_Interface/001200000m0q000000/" rel="nofollow noreferrer">IMapServerObjects3</a>, but seems like IMapDocument should be OK.</p> <pre><code>#region IServerObjectExtension Members private IPageLayout m_Layout = null; public void Init(IServerObjectHelper pSOH) { serverObjectHelper = pSOH; // open an mxd and grab the layout IMapDocument mapDoc = new MapDocumentClass(); mapDoc.Open(@"\\sharedFolder\Mymapdocument.mxd"); m_Layout = mapDoc.PageLayout; mapDoc.Close(); } public void Shutdown() { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(m_Layout); } #endregion </code></pre> <p>Edit: Here's a <a href="https://gis.stackexchange.com/questions/5519/is-accessing-an-mxd-from-an-msd-based-soe-safe">related question on GIS.stackexchange</a>.</p>
[]
[ { "body": "<p>The reason why the video states that you should not create SOEs on top of MXD based map services is because in 10.1 you will not be able to start a service from an mxd. You will need to convert your map document into a service definition. </p>\n\n<p>One of the issues you will find with MXD-based SOEs in 10 when you upgrade to 10.1, is that your code most likely will be accessing layers or layouts in the map service. This is pretty common in MXD-based SOEs because it is through layers that you get to the datasets you want to use in your code etc. At 10.1, your SOE code will break, because layers, layouts etc are only available in MXD-based SOE map services. If you create an MSD-based map service and build an SOE on top of it, you will notice the same. With MSD-based SOEs you need to use IMapServerDataAccess to get to the data sources in your map. And that code will just work in 10.1. So writting SOE's on top of MSD is a good way to understand what will be possible in 10.1</p>\n\n<p>I suggest you look at <a href=\"http://blogs.esri.com/dev/blogs/arcgisserver/archive/2010/11/12/accessing-optimized-map-services-with-server-object-extensions.aspx\" rel=\"nofollow\">this</a> and <a href=\"http://blogs.esri.com/Dev/blogs/arcgisserver/archive/2011/04/26/Considerations-for-ArcGIS-Server-developers_3A00_-A-look-toward-10.1.aspx\" rel=\"nofollow\">this</a>.</p>\n\n<p>As for using IMapDocument... go for it. It will work fine in 10.1</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T01:27:10.610", "Id": "2357", "ParentId": "2355", "Score": "4" } } ]
{ "AcceptedAnswerId": "2357", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-10T22:58:30.130", "Id": "2355", "Score": "4", "Tags": [ "c#" ], "Title": "IMapDocument in a 10.1 SOE" }
2355
<p>I found a SERP checker written in PHP and I decided, in order to better learn to program, I would re-write it in Ruby.</p> <p>All I have written so far takes a list of keywords that a user inputs and cleans the list and turns each keyword into a url for Google search.</p> <p>Here is the code:</p> <pre><code>require 'sinatra' require 'rspec' get '/serp_checker' do "&lt;form action='/ranked' method='post'&gt; &lt;label for='keyword'&gt;Keyword&lt;/label&gt; &lt;textarea name='keyword' id='keyword' type='text' /&gt;&lt;/textarea&gt; &lt;label for='url'&gt;URL&lt;/label&gt; &lt;input name='url' id='url' type='text' /&gt; &lt;input type='submit' value='Go!' /&gt; &lt;/form&gt;" end def clean_up_keywords(str) str.gsub("\n", ",").delete("\r").split(',') end def clean_up_list(arr) arr.reject(&amp;:empty?).each(&amp;:lstrip!) end def make_strings_url_friendly(arr) arr.each do |e| e.gsub!(" ", "+") end end def make_urls(arr) arr.map {|e| "http://www.google.com/search?num=100&amp;q=" + e} end post '/ranked' do dirty_list = clean_up_keywords(params[:keyword]) clean_list = clean_up_list(dirty_list) url_ready_list = make_strings_url_friendly(clean_list) url_list = make_urls(url_ready_list) end </code></pre> <p>Here is the spec:</p> <pre><code>require_relative '../lib/rankypanky.rb' describe "#clean_up_keywords" do it "should push items separated by a newline into array as separate items" do clean_up_keywords("apples\noranges").should == ["apples", "oranges"] end it "should delete all \r chars" do clean_up_keywords("Chat\r").should == ["Chat"] end it "should push items separated by commas into an array" do clean_up_keywords("Chat, Meta, About").should == ["Chat", " Meta", " About"] end it "should push items separated ONLY by a \s char into array as one item" do clean_up_keywords("New York, apples").should == ["New York", " apples"] end end describe "#clean_up_list" do it "should not include empty strings/items in array" do clean_up_list(["apples", "", "oranges"]).should == ["apples", "oranges"] end it "should remove any leading white space from items in array" do clean_up_list([" oranges", "apples"]).should == ["oranges", "apples"] end end describe "#make_strings_url_friendly" do it "should replace /s with a +" do make_strings_url_friendly(["oranges apples"]).should == ["oranges+apples"] end end describe "#make_urls" do it "should append array items to http://www.google.com/search?num=100&amp;q=" do make_urls(["pie"]).should == ["http://www.google.com/search?num=100&amp;q=pie"] end end </code></pre> <p>Basically I'm looking for any better ways to do this as well as whether my code meets hmmm standards... just some general critique. Thank you so much!</p>
[]
[ { "body": "<p>I see you haven't got any response on this for a long while, so I'll give it a try.</p>\n\n<p>I don't really see anything to pick on when it comes to style or technique. To me this looks very good. A few questions though:</p>\n\n<ol>\n<li>why do you <code>require \"rspec\"</code> in the controller code? Shouldn't this be in the test code instead?</li>\n<li>You don't do any attempt to sanitize or verify that the code works with non-english characters, or other characters that may cause trouble. What if someone type <code>\"tørris&amp;message=&lt;script&gt;alert(\"Hoy there\");&lt;/script&gt;\"</code> in the input form? (I guess google will sanitize it, but it would probably be better to do it before passing the url to them.)</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T13:54:28.477", "Id": "3803", "ParentId": "2358", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T05:45:05.150", "Id": "2358", "Score": "5", "Tags": [ "ruby" ], "Title": "Critique some Ruby + RSpec Code for a SERP checker" }
2358
<p>With some advice from SO, I developed this system, which I think is quite strong for bots to automatically post comments.</p> <p><strong>index.php</strong> </p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="jquery.js"&gt;&lt;/script&gt; &lt;script&gt; function main() { var str=$("#key").load("getToken.php",function (responseText) { $("#key").val(responseText); } ); setTimeout("main()", 100000); } &lt;/script&gt; &lt;/head&gt; &lt;body onload='main()'&gt; &lt;form name="f" action="poster.php" method="post"&gt; &lt;input type="text" name="text"/&gt;&lt;br&gt; &lt;input type="text" name="key" id="key" value=""/&gt;&lt;br&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>getToken.php</strong></p> <pre><code>&lt;?php $key=date("Y-m-d H:i:s"); $hash=sha1($key.'mySecretKey'); echo $key.'#'.$hash; ?&gt; </code></pre> <p><strong>poster.php</strong></p> <pre><code>&lt;?php if (!isset($_POST['key'])) exit; $parts = explode('#',$_POST['key'],2); $key = $parts[0]; $hash = $parts[1]; $date1 = $key; $date2 = date("Y-m-d H:i:s"); $diff = abs(strtotime($date2) - strtotime($date1)); $years = floor($diff / (365*60*60*24)); $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24)); $hours = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60)); $minuts = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60); $seconds = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minuts*60)); if ($seconds &lt; 5) echo $seconds.' Too fast, must be a naughty bot &lt;br&gt;'; else if ($seconds&gt;5 &amp;&amp; $seconds &lt; 600) echo $seconds.' In time &lt;br&gt;'; else echo $seconds.' time out &lt;br&gt;'; if ($hash == (sha1($key.'sou'))) echo $_POST['text']; else echo 'You are a bot !'; ?&gt; </code></pre>
[]
[ { "body": "<ul>\n<li><p><code>365*60*60*24</code> should be a constant.</p></li>\n<li><p>You should really improve your variable naming.</p>\n\n<pre><code>$date2 = date(\"Y-m-d H:i:s\");\n</code></pre></li>\n<li><p><code>date2</code>? Does that say anything? <code>currentTime</code> is more like it. <em>Always</em> describe what variables contain, not what they are.</p></li>\n<li><p>Isn't <code>$diff</code> already the number of seconds?</p></li>\n<li><p>Most part of the date/time checking could be rewritten to:</p>\n\n<pre><code>$seconds = time() - strtotime($key);\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T10:04:33.180", "Id": "3753", "Score": "0", "body": "Yes, you are correct ! But anything else which can enhance the security or something like that ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T10:07:23.033", "Id": "3754", "Score": "0", "body": "the security part is fine" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T10:10:42.300", "Id": "3756", "Score": "0", "body": "But i think a bad human can program a bot which gets the token fill it in a dummy form and submit. any way to stop that ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T10:24:52.823", "Id": "3757", "Score": "0", "body": "how would anyone discover your encrypted token?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T11:45:09.023", "Id": "3759", "Score": "1", "body": "if a bot visit **getToken.php** , he get the token and filled it in a hidden field named KEY, and submit the form :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T11:48:26.993", "Id": "3760", "Score": "0", "body": "That another question, which belongs at SO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T11:49:17.713", "Id": "3761", "Score": "0", "body": "But the problem is which i built is almost a exact duplicate of SO's anti bot system, and it works :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-26T13:03:38.293", "Id": "4133", "Score": "1", "body": "@Sourav: no you didn;t." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T10:00:39.890", "Id": "2363", "ParentId": "2362", "Score": "6" } }, { "body": "<p>Why are you using <code>abs()</code>?</p>\n\n<p>Why are there a 6-7 lines of code to just get the number of seconds between each timestamp? Just use the diff between <code>$_SERVER['REQUEST_TIME']</code> and whatever time is pulled out of the token.</p>\n\n<p>If all you are doing is checking the speed of the submit, ie. between page load and subsequent submit of the form, then you don't need a fancy hashed token - and you definitely don't need any javascript! Just write in the page load time into a hidden field, or store it in a session and compare to the submit time.</p>\n\n<p>Also, most bots disable javascript, so that invalidates your entire solution.</p>\n\n<p>My advice: Sign up to askimet or another 3rd party spam service, roll your own spam detection library with a bunch of keywords / phrases.</p>\n\n<p>Don't take this the wrong way - a good attempt &amp; keep up the effort! :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-26T13:02:55.657", "Id": "2628", "ParentId": "2362", "Score": "3" } } ]
{ "AcceptedAnswerId": "2363", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T09:51:57.917", "Id": "2362", "Score": "7", "Tags": [ "php", "security", "php5", "ai" ], "Title": "Anti-Bot comment system" }
2362
<p>I want to perform a search in several columns of a table. I use the following query:</p> <pre><code>select * from Tabela t inner join "TabelaPai" tp on tp."ID" = t."RefTabelaPai" and tp."RefProject" = 'projectid' where not t."Deleted" and (t.Col1 ~ '.*__param1__.*' or t.Col2 ~ '.*__param1__.*' or t.Col3 ~ '.*__param1__.*' or t.Col4 ~ '.*__param1__.*' or t.Col5 ~ '.*__param1__.*' or t.Col6 ~ '.*__param1__.*' or t.Col7 ~ '.*__param1__.*' or t.Col8 ~ '.*__param1__.*' or t.Col9 ~ '.*__param1__.*'); </code></pre> <p>This will search for the keyword <code>__param1__</code> in any of the columns and it's working fine. </p> <p>But I don't like the way the query looks like. Any suggestion on how to refactor the query so it can look 'prettier' (without those <code>~ '.*__param1__.*'</code> repetitions, for example)?</p> <p>Edit: A little of context about the query:</p> <p>What leads to this usage is that I can parameterize the data in the table. For example, I have a column in a table where scripts are saved. My application allows the users to parametrize the script using something like <code>__param1__</code>. If the user wants to rename the parameter I'll have to search for the usage of the parameter in every column that is parameterizable, and this is the query that finds where the parameter is used.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-25T20:09:53.310", "Id": "4104", "Score": "2", "body": "I think this is more of a database design issue rather than a query issue. How is your database used such that you need to search for the same value *across several columns* to find something? What's your database schema?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-26T08:18:48.063", "Id": "4118", "Score": "0", "body": "I think your kind of right.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-26T08:24:41.607", "Id": "4120", "Score": "0", "body": "Question updated with context." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-26T08:59:28.877", "Id": "4121", "Score": "0", "body": "With such a task maybe you should keep variable name separately from its usage. Instead of storing script with variable name you can store it with some placeholder like `{param1}`. This will allow renaming parameters easily but you will have to replace placeholders in return." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-26T12:29:19.870", "Id": "4131", "Score": "0", "body": "The placehoders are the __ in the beggining and in the end. The user interacts with the name param1." } ]
[ { "body": "<p>I must admit, I don't really see what's wrong with the repetition — assuming it <em>is</em> what you're wanting to do (and your columns aren't <em>actually</em> named <code>t.Colx</code>!). If I came across this query in a project, I'd know pretty quickly what it's doing I think: searching a bunch of columns for a single supplied value (e.g. searching name, address, phone, etc. with a single search box, perhaps).</p>\n\n<p>As for the matter of storing scripts and their parameters in a database: I'd probably go for a second key-value table, something like:</p>\n\n<pre><code>scripts { id, name, body }\nscript_parameters { id, script_id, name, value }\n</code></pre>\n\n<p>And you'd fetch the script and parameters and substitute the latter into the former in the app.</p>\n\n<p>But then, I'm probably quite missing the point of what you're trying to do! :-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-27T08:15:38.053", "Id": "4150", "Score": "0", "body": "Well, maybe I'm just being picky... When I see an example like this with so many repetitions I think immediately that it can be generalized. But as you said maybe there is nothing wrong with this query and just have to let it go :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-27T07:51:34.813", "Id": "2649", "ParentId": "2364", "Score": "5" } }, { "body": "<p>Something &quot;<strong>prettier</strong>&quot;? And so many repetitions call for generalization?</p>\n<pre><code>SELECT *\nFROM tabela <b>AS t</b>\nJOIN \"TabelaPai\" tp ON tp.\"ID\" = t.\"RefTabelaPai\"\nWHERE NOT t.\"Deleted\" \nAND tp.\"RefProject\" = 'projectid'\nAND <b>t::text</b> LIKE '%\\_\\_param1\\_\\_%';</code></pre>\n<p>Or cleaner:</p>\n<pre><code>...\nAND t.*::text LIKE '%\\_\\_param1\\_\\_%';\n</code></pre>\n<p>A nested column of the same name (<code>t</code> in this case) would take precedence. The more verbose syntax <code>t.*</code> makes it an unambiguous reference to the table row.</p>\n<p>You can reference the composite type of any relation in the <code>SELECT</code> list. <a href=\"https://www.postgresql.org/docs/current/rowtypes.html\" rel=\"nofollow noreferrer\">The manual</a>:</p>\n<blockquote>\n<p>Whenever you create a table, a composite type is also automatically\ncreated, with the same name as the table, to represent the table's row type.</p>\n</blockquote>\n<p>You can <strong>cast the whole row</strong> (the composite type) to its text representation in one fell swoop, which is a very convenient syntactical shorthand. The resulting filter in my query is guaranteed to find <strong>every occurrence in the whole row</strong>.</p>\n<p>The <code>LIKE</code> operator is generally faster than regular expression pattern matching (<code>~</code>). Regular expressions are far more powerful, but whenever <code>LIKE</code> can do the job, use it. Its syntax is simpler, too.</p>\n<p>Underscores (<code>_</code>) have a special meaning for the <code>LIKE</code> operator, so you need to escape literal <code>_</code>. Default escape character is <code>\\</code>.</p>\n<p>Since Postgres 9.1, the setting <a href=\"https://www.postgresql.org/docs/current/runtime-config-compatible.html#GUC-STANDARD-CONFORMING-STRINGS\" rel=\"nofollow noreferrer\"><code>standard_conforming_strings</code></a> is <code>on</code> by default. Else, or with <code>E''</code> syntax to declare Posix escape strings explicitly, escape <code>\\</code> like:</p>\n<pre><code>t::text LIKE E'%\\\\_\\\\_param1\\\\_\\\\_%'\n</code></pre>\n<p>If the separator in text representation (<code>,</code> by default) or double quotes (which can enclose strings) can be part of the search pattern, there can be false positives (across columns). So this is corner-case &quot;dirty&quot;.</p>\n<p>Asides:</p>\n<p>It is cleaner to write <code>AND tp.&quot;RefProject&quot; = 'projectid'</code> as <code>WHERE</code> clause, as it has no connection to <code>tabela</code>. Else you could put <code>NOT t.&quot;Deleted&quot;</code> into the <code>JOIN</code> condition as well. Either way, same result.</p>\n<p>Avoid CaMeL-case spelling of identifiers in Postgres like <code>Tabela</code> or <code>RefTabelaPai</code>. Without double-quotes, all <a href=\"https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS\" rel=\"nofollow noreferrer\">identifiers are folded to lower case automatically</a>.<br />\nMy standing advice is to use legal. lower case identifiers exclusively in PostgreSQL and avoid avoid double-quoting and possible confusion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-08T16:58:07.620", "Id": "175809", "Score": "0", "body": "Jesus Crist man! This is powerful !" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-12-28T21:16:17.260", "Id": "7231", "ParentId": "2364", "Score": "10" } }, { "body": "<p><a href=\"http://www.postgresql.org/docs/current/interactive/textsearch-tables.html#TEXTSEARCH-TABLES-SEARCH\" rel=\"nofollow\">http://www.postgresql.org/docs/current/interactive/textsearch-tables.html#TEXTSEARCH-TABLES-SEARCH</a></p>\n\n<pre><code>SELECT *\nFROM \"TAble\"\nWHERE to_tsvector(\"QUARTER1\"||' '||\"QUARTER2\") @@ to_tsquery('abc');\n</code></pre>\n\n<p>selects any row that contains <code>abc</code> in column <code>QUARTER1</code> or <code>QUARTER2</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T14:29:37.770", "Id": "33235", "ParentId": "2364", "Score": "1" } } ]
{ "AcceptedAnswerId": "2649", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T11:11:45.173", "Id": "2364", "Score": "9", "Tags": [ "sql", "postgresql" ], "Title": "SQL: Search for a keyword in several columns of a table" }
2364
<p>I am 100% self-taught, and so I try to read as much as I can about best practices, conventions, etc. However I freelance, and have been in a long-term contract position for the past little while with almost no peers to review my code. So I get nervous about developing bad habits.</p> <p>Looking closely at this function I wrote (meant to give me a quick look over the db make sure nothing else is signed that ought to be unsigned):</p> <pre><code>$db = Database::instance(); $tables = array(); $result = $db-&gt;query('SHOW TABLES'); foreach($result as $table) { $create = $db-&gt;query("SHOW CREATE TABLE `".current($table)."`"); $tables[current($create-&gt;current())] = end($create-&gt;current()); } echo var_dump($tables); </code></pre> <p>I see a couple things - <code>$tables</code> and <code>$table</code> are similar things, but <code>$tables</code> is not made up of every <code>$table</code>, so it could be confusing.</p> <p>I tend to name all query results as <code>$result</code> unless there is a potential naming conflict.</p> <p>Concatenating a function result within a query call seems more a quality of 'fast code' than 'good code'.</p> <p>Am I being too nit-picky? Does this code look like it was written by an amateur/bad programmer?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T21:06:51.873", "Id": "3786", "Score": "0", "body": "Your style is very readable. Almost makes me feel like I would be able to pick up PHP with ease." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-13T15:07:31.657", "Id": "3798", "Score": "0", "body": "If you're concerned about possible confusion between two variable names, why not change one of them to eliminate the confusion? You've already identified a potential problem; whether it's a real problem or not is a matter of taste, but it won't take you 10 seconds to fix it." } ]
[ { "body": "<p>Your code looks like its good quality code. And yes, you’re right to be concerned. Most likely, after you’re gone, somebody else will (eventually) maintain, or change the code that you’ve written to date. I suggest that you comment and write the code so that a maintainer understands its purpose at first read.</p>\n\n<p>For example ...</p>\n\n<pre><code>/*\n * Look quickly over the database to make sure nothing else is signed that ought to be unsigned.\n * TODO: Explain why unsigned is better than signed…\n */\n\n$db = Database::instance();\n$all_tables = array();\n$result = $db-&gt;query('SHOW TABLES');\nforeach($result as $unique_table)\n{\n $show_created_table = $db-&gt;query(\"SHOW CREATE TABLE `\".current($unique_table).\"`\");\n $all_tables[current($show_created_table-&gt;current())] = end($show_created_table-&gt;current());\n}\necho var_dump($all_tables);\n</code></pre>\n\n<p>It's worth doing for yourself, for memory sake, if you haven't touched the code for a longtime.\nIt will also help the maintainer understand the intented purpose of the function. Now, if your project is large and complex, I'd recommend that you use <a href=\"http://phpdoc.org/features.php\">phpdoc</a> -- it's a good standard.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T19:39:25.147", "Id": "2391", "ParentId": "2370", "Score": "7" } }, { "body": "<p>Personally I find that a db query should return a query object, which should then have exposed result() and num_rows() etc methods. IMO don't like seeing things like <code>$create-&gt;current();</code> - which I'm not actually sure I understand... What exactly are you achieving with the current method? Why is the db query method returning what seems like an array when first used, but then an object when used in the loop?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-26T12:53:00.920", "Id": "2627", "ParentId": "2370", "Score": "0" } } ]
{ "AcceptedAnswerId": "2391", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T23:32:56.007", "Id": "2370", "Score": "6", "Tags": [ "php", "mysql" ], "Title": "Working with databases in PHP" }
2370
<ol> <li><p>This function computes and returns the number of divisors an integer has. But it is very slow and I believe it can be optimized for speed.</p> <pre><code>unsigned long long int find_no_of_divisors(unsigned long long int myno,FILE *ifp) { unsigned long long int divsrs = 2; unsigned long long int k = 2; if(myno == 1) { return 1; } if(myno == 2) { return 2; } while(1) { if((myno % k) == 0) { divsrs++; if(divsrs == MY_ULLONG_MAX) { printf("Overflow detected in the calculated value for divisors of a number... Exiting"); fclose(ifp); exit(-1); } } k++; if(k &gt; (myno/2)) { break; } } return divsrs; } </code></pre></li> <li><p>This one computes and returns the sum of first <em>n</em> integers:</p> <pre><code>unsigned long long int next_no(unsigned long long int idx,unsigned long long int cur_no,FILE *ifp) { unsigned long long int next_no; next_no = ((idx)*(idx + 1))/2; if((next_no - idx) != cur_no) { printf("Overflow detected in the value of the calculated number... Exiting"); fclose(ifp); exit(-1); } return next_no; } </code></pre></li> </ol> <p>Could there be any glitches or functionality issues? (PS - I did not want to use a <code>sqrt()</code> function due to my portability constraints.)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T09:35:42.240", "Id": "3770", "Score": "0", "body": "I believe the formatting was messed up a bit due to the numberings in your question, adding some extra spacing seemed to have solved it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T10:14:50.267", "Id": "3772", "Score": "0", "body": "@Steven: Thanks. Yes i tried but couldn't fix it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T11:22:20.410", "Id": "3774", "Score": "0", "body": "You should give some context for the second function. From the code it looks to me as if you're iterating from 0 to some number N and on each iteration calling `next_no` with the current index and the result from the last call of `next_no`. So you're basically calculating the sum from 0 to `idx` for each `idx` from 0 to `N`. However for now that's just me guessing, so you should be more specific about that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T11:28:46.443", "Id": "3775", "Score": "0", "body": "@sepp2k:Yes, I am computing summation of integers uptox idx for each idx passed in. And this function can be called with idx value possibly from 0 to ULLONG_MAX." } ]
[ { "body": "<p>The first function can be sped up by just iterating up to <code>sqrt(myno)</code> and adding 2 instead of 1 to <code>divsrs</code> when <code>k</code> divides <code>myno</code> unless <code>k</code> is the square root of <code>myno</code> (in which case you would only add 1).</p>\n\n<p>The second function already takes constant, but you can get rid of the multiplication and division, by simply returning <code>cur_no + idx</code> and using <code>cur_no &lt; ULLONG_MAX - idx</code> to check whether there'd be an overflow.</p>\n\n<hr>\n\n<p>Now a couple of style notes on the code:</p>\n\n<p>First of all, it seems strange to me to pass the file handle to the functions, if they don't actually write to (or read from) the file. I see that you did so you could close the file before exiting the program in case of an overflow. I would rather recommend that you return an error value when an overflow occurs and then close the file and exit in the calling code.</p>\n\n<p>Further your <code>while(1)</code> loop in <code>find_no_of_divisors</code> is actually a pretty plain <code>for</code>-loop and should be written as one. No need for complicated control flow for something so simple.</p>\n\n<p>Lastly I would not recommend dropping (some) vowels from variable names like you do in <code>divsrs</code> - that just leads to typos.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T13:00:29.327", "Id": "3777", "Score": "0", "body": "The first change may not be appropriate - if he really wants all the divisors (not just prime factors) then I think his way is the only way to do it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T13:11:02.257", "Id": "3778", "Score": "0", "body": "@DHall: Can you give an example where the algorithm I outlined would not give the correct number of divisors? It definitely does not return the number of prime factors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T13:15:51.717", "Id": "3779", "Score": "1", "body": "Sorry, I misread it. Your way is correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T14:15:24.193", "Id": "3780", "Score": "0", "body": "Edited my OP. Can u pls. check OP again and see if this code incorporates the optimizations correctly." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T12:02:25.010", "Id": "2380", "ParentId": "2378", "Score": "4" } }, { "body": "<p>Additional to sepp2k's excellent answer some math that could help you:</p>\n\n<p>If you have the prime factors of a number, you just take the exponents, increase every one by one and take the product.</p>\n\n<pre><code>E.g. 12 = 2^2 * 3^1 -&gt; [2,1] -(+1)-&gt; [3,2] -&gt; 6\n12 has 6 divisors: 1,2,3,4,6,12 \n\nE.g. 100 = 2^2 * 5^2 -&gt; [2,2] -(+1)-&gt; [3,3] -&gt; 9\n100 has 9 divisors: 1,2,4,5,10,20,25,50,100\n</code></pre>\n\n<p>The smallest divisor of a number (greater than 1) is always prime. The algorithm in pseudocode looks like (untested):</p>\n\n<pre><code>divisors(N) {\n result = 1\n for (p = 2; p &lt;= sqrt(N); p++) { //check all divisors\n if (n mod p == 0) {\n for(f = 0; n mod p == 0; n = n / p) { //try to divide as often as possible\n f++ //count how often we divide\n }\n result = result * (f+1) \n } \n }\n if (N == 1) return result //number completely factored\n else return 2 //then we found no factor -&gt; N itself is prime \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T20:35:05.597", "Id": "2392", "ParentId": "2378", "Score": "2" } } ]
{ "AcceptedAnswerId": "2380", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T09:10:14.613", "Id": "2378", "Score": "7", "Tags": [ "optimization", "c", "mathematics" ], "Title": "Find number of divisors for integer and sum of integers" }
2378
<p>I think that the <code>slice()</code> is a bit hacky, and prone to breaking if I change my mind about the <code>id</code> names, but I wanted this to be generic so I could add types easily.</p> <p>Is there maybe another / better way to do this just using CSS nesting the 'panels' inside the li elements?</p> <p>Markup:</p> <pre class="lang-html prettyprint-override"><code> &lt;ul id="type-select"&gt; &lt;li&gt;&lt;a id="type-1" href="#"&gt;1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id="type-2" href="#"&gt;2&lt;/a&gt;&lt;/li&gt; ... &lt;/ul&gt; &lt;div id="panel-1" class="panel"&gt;blah&lt;/div&gt; &lt;div id="panel-2" class="panel"&gt;blah&lt;/div&gt; ... </code></pre> <p>JavaScript:</p> <pre class="lang-js prettyprint-override"><code>function switchType(type){ $("#type-select li a").removeClass("selected-type"); $("#type-"+type).addClass("selected-type"); $(".panel").removeClass("selected-panel"); $("#panel-"+type).addClass("selected-panel"); } // initial state $("#no-results").hide(); switchType("1"); $("#type-select li a").click(function(){switchType(this.id.slice(5))}); </code></pre>
[]
[ { "body": "<p>This kind of navigation is usually referred to as tabs or tabbed navigation. There are loads of ready scripts on the net for this - for exampe - since you are using jQuery - <a href=\"http://jqueryui.com/demos/tabs/\">jQuery UI</a>. But since this is really a quite trivial functionality, it's quite okay to implement it yourself.</p>\n\n<p>To make the implementation cleaner, you can add a direct reference to the matching panel in the link. I would use the <code>href</code> attribute and refer to the panel using a URL hash. This has the advantage, that it will work without JavaScript or CSS by scrolling to the chosen panel.</p>\n\n<p>You can drop the <code>id</code>s on the links and use a direct reference to them in the function.</p>\n\n<pre><code>&lt;ul id=\"type-select\"&gt;\n &lt;li&gt;&lt;a href=\"#panel-1\"&gt;1&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#panel-2\"&gt;2&lt;/a&gt;&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>Consider using the CSS <code>:target</code> pseudo class for the functionality:</p>\n\n<pre><code>.panel { display: none; }\n.panel:target { display: block; }\n</code></pre>\n\n<p>And add JavaScript, for browsers that don't support it and to set the classes:</p>\n\n<pre><code>$(\"#type-select li a\").click(function(){return switchType(this)});\n\nfunction switchType(link){\n var hashPos = link.href.indexOf(\"#\");\n if (hashPos &gt;= 0) {\n // Parsing out the hash and removing '#', in case the href\n // attribute contains a complete URL, and in case some other\n // method than a CSS selector is used to find the panel\n var panelId = link.href.substring(hashPos + 1);\n\n $(\"#type-select li a\").removeClass(\"selected-type\");\n $(link).addClass(\"selected-type\");\n $(\".panel\").removeClass(\"selected-panel\");\n $(\"#\" + panelId).addClass(\"selected-panel\"); \n }\n return false;\n}\n</code></pre>\n\n<p>Don't forget to return <code>false</code> so the the default action of the link (which will lead to unnecessary scrolling) is canceled.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T13:43:24.440", "Id": "2384", "ParentId": "2379", "Score": "5" } } ]
{ "AcceptedAnswerId": "2384", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T09:32:26.997", "Id": "2379", "Score": "6", "Tags": [ "javascript", "jquery", "html" ], "Title": "JavaScript navigation UI" }
2379
<p>I am looking to optimize the following computation. First, some explanations:</p> <p><strong>Explanation</strong></p> <p>I have a directed graph whose adjacency matrix may only contain 1s and 0s. The <em>similarity</em> of nodes <em>i</em> and <em>j</em> is defined as follows:</p> <ol> <li>count how many nodes have an edge pointing to both <em>i</em> and <em>j</em>, and count how many nodes do both <em>i</em> and <em>j</em> point to</li> <li>divide the sum of these two counts by the total number of nodes either <em>i</em> or <em>j</em> is connected to</li> </ol> <p>I need to find the maximum similarity of each node in graph (its similarity with any other node except itself), and compute the average of these numbers.</p> <p>The graphs I'm working with are not necessarily connected, but they don't have components of size 1 (i.e. nodes that are not connected to any other nodes).</p> <p><strong>The code</strong></p> <pre><code>meanMaxSim[g_Graph] := Module[{am, pList, similarityMatrix}, am = AdjacencyMatrix[g]; pList = Transpose@Join[am, Transpose[am]]; similarityMatrix = Outer[Total[#1 #2]/Total[Sign[#1 + #2]] &amp;, pList, pList, 1]; Mean[Max /@ dropDiagonal[similarityMatrix]] ] </code></pre> <p>(<code>Sign</code> is used to keep 0s and convert anything larger to 1s.)</p> <p>This function just removes the elements on the diagonal of an <em>n</em> by <em>n</em> matrix, ending up with an <em>n</em> by <em>n</em> - 1 matrix:</p> <pre><code>dropDiagonal[matrix_] := MapThread[Drop[#1, {#2}] &amp;, {matrix, Range@Length[matrix]}] </code></pre> <p><code>Graph[]</code> is only available in Mathematica 8, but this is irrelevant here as most of the time is spent in <code>Outer[]</code> anyway. If you have an earlier version, just assume that you have the adjacency matrix as a <code>SparseArray</code> as starting point.</p> <p>I am looking for modifications that speed this up significantly (more than 3x), but any other comment on the code is most welcome. Hopefully a speedup is possible without a significant increase in code complexity.</p> <p><strong>Notes</strong></p> <p>Doing the computations with machine-numbers is okay, but I didn't bother doing that since it doesn't provide a significant speedup.</p> <p>A note about self-loops: they are allowed in the graph, and yes, they're double-counted in this implementation.</p> <p><strong>EDIT:</strong></p> <p>I was too quick to ask this question. Here's a ~4x speedup using <code>Compile</code>. I'm still interested in comments / further speedups.</p> <pre><code>simMatCompiled = Compile[{{p, _Real, 2}}, Table[Total[a b]/Total@Sign[a + b], {a, p}, {b, p}] ]; mxSim[g_Graph] := Module[{am, pList, similarityMatrix}, am = N@AdjacencyMatrix[g]; pList = Transpose@Join[am, Transpose[am]]; similarityMatrix = simMatCompiled[Normal[pList]]; Mean[Max /@ dropDiagonal[similarityMatrix]] ] </code></pre> <p>I needed to change <code>Outer</code> to <code>Table</code> in order for <code>Compile</code> to be able to do its job.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T15:35:05.230", "Id": "3782", "Score": "0", "body": "Please see my latest edit." } ]
[ { "body": "<p>Minor improvements, but consider using:</p>\n\n<pre><code>pList = ArrayFlatten[{{am\\[Transpose], am}}];\n</code></pre>\n\n<p>and</p>\n\n<pre><code>dropDiagonal = MapThread[Delete, {#, Range@Length@#}] &amp;;\n</code></pre>\n\n<p>I also tried <code>dropDiagonal = MapIndexed[Drop, #] &amp;</code> but this is slower, at least in v7.</p>\n\n<hr>\n\n<p>Replace:</p>\n\n<pre><code>Total[#1 #2]/Total[Sign[#1 + #2]] &amp;\n</code></pre>\n\n<p>With:</p>\n\n<pre><code>#.#2 / Tr@Unitize[#1 + #2] &amp;\n</code></pre>\n\n<hr>\n\n<p>I believe this is an improvement to your compiled function:</p>\n\n<pre><code>Compile[{{p, _Real, 2}}, \n With[{b = p\\[Transpose]},\n #.b / Total@Sign[# + b] &amp; /@ p\n ]\n]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T14:17:11.430", "Id": "2386", "ParentId": "2385", "Score": "5" } } ]
{ "AcceptedAnswerId": "2386", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T13:52:13.963", "Id": "2385", "Score": "7", "Tags": [ "optimization", "wolfram-mathematica" ], "Title": "Directed graph similarity calculation -- optimizing Mathematica code" }
2385
<p>I use the following code to put all of my error messages for the application in one javascript variable. Is this efficient way to store my error messages?</p> <pre><code>var cosmoBase = { messages: { empty: "Please enter ", numeric: "Please enter a valid number for ", date: "Please enter a valid date for " } }; //Error messages var cosmo = { messages: { lastName: { empty: cosmoBase.messages.empty + "Last Name" }, dob: { empty: cosmoBase.messages.empty + "Date of Birth", invalid: cosmoBase.messages.date + "Date of Birth" }, ssn: { empty: cosmoBase.messages.empty + "SSN", invalid: cosmoBase.messages.numeric + "SSN" }, studentId :{ empty: cosmoBase.messages.empty + "Student ID", invalid: cosmoBase.messages.numeric + "Student ID" } } }; </code></pre> <p>MORE INFO</p> <p>The code above is stored in a js file</p> <p>I am referencing the error messages like this :</p> <pre><code>var validator = $("form:first").validate({ errorClass: 'Input_State_Error', rules: { lastName: { required: true }, dob: { required: true, date: true, minlength: 10 }, ssn: { required: true, minlength: 4 }, studentId: { required: true } }, messages: { lastName: cosmo.messages.lastName.empty, dob: { required: cosmo.messages.dob.empty, date: cosmo.messages.dob.invalid }, ssn: cosmo.messages.ssn.empty, studentId: cosmo.messages.studentId.empty }, errorPlacement: function(error, element) { error.appendTo($('#msg')); } }); </code></pre>
[]
[ { "body": "<p>I would recommend you use a factory instead.</p>\n\n<pre><code>cosmo.error = function(id) {\n ...\n};\n</code></pre>\n\n<p>then just use <code>cosmo.error(\"ssn-empty\")</code></p>\n\n<p>Having your logic in a factory rather then an object gives you more control and makes your code significantly more DRY.</p>\n\n<p>Implementation of <code>error</code>:</p>\n\n<pre><code>var error = (function() {\n var base = {\n empty: \"Please enter \",\n numeric: \"Please enter a valid number for \",\n date: \"Please enter a valid date for \",\n ssn: \"SSN\",\n lastName: \"Last Name\",\n dob: \"Date of Birth\",\n studentId: \"Student ID\"\n };\n\n var methods = {\n \"ssn\": function(id) {\n if (id === \"invalid\") {\n return base.numeric + base.ssn;\n }\n },\n \"dob\": function(id) {\n if (id === \"invalid\") {\n return base.date + base.dob;\n }\n },\n \"studentId\": function(id) {\n if (id === \"invalid\") {\n return base.numeric + base.studentId;\n }\n },\n };\n\n return function(id) {\n var parts = id.split(\"-\");\n if (parts[1] === \"empty\") {\n return base.empty + base[parts[0]];\n } else {\n return methods[parts[0]](parts[1]);\n }\n }\n}());\n\nconsole.log(error(\"ssn-invalid\"));\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/GTVES/4/\" rel=\"nofollow\">live example</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T16:34:36.663", "Id": "3783", "Score": "0", "body": "Does `cosmo.error` replace both variables or just `var cosmo = {` ?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T16:23:06.837", "Id": "2389", "ParentId": "2387", "Score": "4" } }, { "body": "<p>I see you're using </p>\n\n<pre><code>errorPlacement: function(error, element) {\n error.appendTo($('#msg'));\n}\n</code></pre>\n\n<p>If you make something in JS store your error log, you can do some really cool things.</p>\n\n<p>For instance, I use this quick thing to log my errors out to a div...</p>\n\n<pre><code>var logLine = function(comment, element) {\n this.count = this.count + 1 || 0;\n element = element || $(\"\");\n comment = comment || \"undescribed event\";\n $(\"pre.log\").append(this.count + \" - \" +comment + \"\\n\");\n}\n</code></pre>\n\n<p>But something I'm about to do is take my plan of going this.count, and making a spot to store all my error objects.</p>\n\n<p>So for instance,</p>\n\n<pre><code>var logLine = function(comment) {\n this.count = this.count + 1 || 0;\n this.errorLog = this.errorLog || [];\n comment = comment || \"undescribed event\";\n\n var logEntry = {}\n logEntry.id = this.count;\n logEntry.error = this.comment;\n logEntry.time = new Date().getTime();\n //Anything else you want from https://developer.mozilla.org/en/DOM/window.navigator\n\n this.errorLog.push(logEntry)\n}\n</code></pre>\n\n<p>This makes my error storing more portable, and more powerful. The real advantage in my mind here is I could create an event that sends ajax details about all my errors to my server.</p>\n\n<p>Design knowing that your error code needs to have the object global somewhere for this.count to preserve state, unless you make this a special plugin to some framework or something.</p>\n\n<p>This is really storing your errors after they occur, not how to store a template of them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T16:55:24.367", "Id": "3784", "Score": "0", "body": "That sounds pretty interesting, but this is for feedback to the user." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T16:47:57.633", "Id": "2390", "ParentId": "2387", "Score": "2" } } ]
{ "AcceptedAnswerId": "2389", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T14:44:06.180", "Id": "2387", "Score": "6", "Tags": [ "javascript" ], "Title": "Is this a good way to store error messages to display back to the user?" }
2387
<p>How do I handle multi-tenancy with routes in ASP.NET MVC?</p> <p>The application is a multitenant ASP.NET MVC 3 application. Tenants are identified based on hostname so this does not interfere with routing.</p> <p>Other important information:</p> <ul> <li><p>The application has a number of features (or plugins). These are essentially other web projects with their own controllers, views and routes.</p></li> <li><p>ASP.NET MVC routing serves as our entry point into these features.</p></li> <li><p>One key point is that all the features function the SAME way for all tenants. The variable is whether the tenant is actually subscribed to the feature.</p></li> </ul> <p>So imagine we have a "blog" feature with a route like so:</p> <pre><code>/blog/{instance}/posts </code></pre> <p>When our application starts we register the routes of all "routable" features. <strong>However, we need to ensure that this route is only matched if the tenant is subscribed to that feature</strong>.</p> <p>Currently I'm doing this with a custom route:</p> <pre><code>private readonly IFeatureMetadata feature; public FeatureRoute(IFeatureMetadata feature, string url, RouteValueDictionary defaults, IRouteHandler handler) : base(url, defaults, handler) { if (feature == null) throw new ArgumentNullException("feature"); this.feature = feature; } public override RouteData GetRouteData(System.Web.HttpContextBase httpContext) { var routeData = base.GetRouteData(httpContext); if (routeData == null) return null; var context = DependencyResolver.Current.GetService&lt;ISiteContext&gt;(); var site = context.GetSite(); var matchedInstances = site.FeatureInstances.Where(f =&gt; f.Feature.FeatureType == feature.FeatureType); if (!matchedInstances.Any()) return null; if (routeData.Values["instance"] == null) { routeData.Values["instance"] = matchedInstances.First().Id; } return routeData; } </code></pre> <p>One thing that I need to cater for is routes that do not specify an instance.</p> <p>For example, a tenant may have one or more blogs. If he only has one then outgoing routes should just generate:</p> <pre><code>http://[domain]/blog/posts </code></pre> <p>If he has more than one then we should generate:</p> <pre><code>http://[domain]/blog/{instance}/posts </code></pre> <p>Currently I'm handling this by registering 2 routes (one with the <code>{instance}</code> parameter and one without). In the code above you can see that if the instance parameter doesn't exist in RouteData we just add the <code>id</code> of the first matched feature instance.</p> <p>This is then sufficient for me to make a call to my blog service:</p> <pre><code>GetPosts(int featureInstanceId); </code></pre> <p>While everything "works", I'm looking for feedback on my implementation. As a freelance developer this seems to be the only way I can get my code reviewed.</p>
[]
[ { "body": "<p>One way to handle it is to write an ActionFilter that does checking against the list of features the customer owns, and if they don't own that feature, it redirects them to buy it. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T21:32:49.697", "Id": "3787", "Score": "2", "body": "I prefer to handle this at the routing level as it keeps such logic out of the controllers. We have an account management application for upgrades so I'm too concerned with redirecting if they do not have the feature." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T19:37:21.880", "Id": "2394", "ParentId": "2393", "Score": "0" } }, { "body": "<p>You could also create a route constraint that redirects or changes the routedata to \"buy module\".</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/cc668201.aspx#adding_constraints_to_routes\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/cc668201.aspx#adding_constraints_to_routes</a></p>\n\n<p><a href=\"http://www.jfarrell.net/2008/11/asp-net-mvc-authentication-strategies.html\" rel=\"nofollow\">http://www.jfarrell.net/2008/11/asp-net-mvc-authentication-strategies.html</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T09:33:49.557", "Id": "7015", "ParentId": "2393", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T14:41:48.413", "Id": "2393", "Score": "14", "Tags": [ "c#", "asp.net", "asp.net-mvc-3", "url-routing" ], "Title": "\"Pluggable\" routes in ASP.NET MVC" }
2393
<p>I have posted an <a href="https://codereview.stackexchange.com/questions/2325/critique-my-first-oop-attempt">earlier version of this</a> and here is the improved version from the feedback I recieved. Some of the feedback I received was;</p> <ul> <li>Don't chain method (tried my best to limit this)</li> <li>Do not use print() or die() and an error response (still a little lost, but I did attempt to use a redirect to a custom error page)</li> </ul> <p>I tried my best to rewrite the code, I am still very new to this so go easy. I did read up on OOP methodology and read about Interfacing and Implementation, so I tried to incorporate that in my class.</p> <p>I would love to see some different ideas on how to make this the most efficient as possible. I am sure it needs a ton of changing, but that is why I am here to help me learn and grow. I am a visual learner so if possible actual code would be awesome, but any response would be greatly appreciated.</p> <pre><code>&lt;?php class Mysql { private $user; private $pass; private $data; private $host; public function __construct($user,$pass,$data,$host) { $this-&gt;user = $user; $this-&gt;pass = $pass; $this-&gt;data = $data; $this-&gt;host = $host; $this-&gt;process(); } /* INTERFACE */ private function process() { if($this-&gt;verifyNullFields()==true) { if($this-&gt;verifyDatabaseConnection()==true) { if($this-&gt;verifyDatabaseExist()==true) { print('ALL PASSED'); //for debugging } else { print('redirect to custom error page will go here'); } } else { print('redirect to custom error page will go here'); } } else { print('redirect to custom error page will go here'); } } /* IMPLEMENTATIONS */ private function verifyNullFields() { if($this-&gt;user != NULL) { if($this-&gt;data != NULL) { if($this-&gt;host != NULL) { return true; } else { return false; } } else { return false; } } else { return false; } } private function verifyDatabaseConnection() { $link = @mysql_connect($this-&gt;host,$this-&gt;user,$this-&gt;pass); if(!$link) { return false ; } else { return true; } } private function verifyDatabaseExist() { $db = @mysql_select_db($this-&gt;data); if(!$db) { return false; } else { return true; } } } ?&gt; &lt;?php $m = new Mysql("root","","magic","localhost"); ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-26T08:09:16.250", "Id": "4116", "Score": "0", "body": "Not too bad, way too much conditional nesting though. Move your verification code to another method and try and reduce all that nesting. `$this->data != NULL` is the same as `!$this->data`. Think of a better structure for the verifyNullFields() method, something simple but more readable could be `if (!$this->user || !$this->data || !$this->host) return false; else return true;`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-06T17:36:24.760", "Id": "4371", "Score": "0", "body": "You probably want to use the 4th mysql_connect param. As is, if you try to initiate 2 connections with the only difference being \"mysql_select_db\", you'll probably get the same connection with the primary database being changed, which most likely isn't what you'd be looking for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-30T20:15:55.953", "Id": "9989", "Score": "0", "body": "REPLACE: if (!$link) TO: if (!$this->link)" } ]
[ { "body": "<p>Let me show my version of this code:</p>\n\n<p><code>DatabaseException.php</code>:</p>\n\n<pre><code>class DatabaseException extends Exception {\n}\n</code></pre>\n\n<p><code>Database.php</code>:</p>\n\n<pre><code>abstract class Database {\n protected $login;\n protected $password;\n protected $database;\n protected $hostname;\n\n public function __construct($login, $password, $database, $hostname) {\n // NB: password not checked and may be empty\n $this-&gt;throwExceptionIfNotSet('login', $login);\n $this-&gt;throwExceptionIfNotSet('database', $database);\n $this-&gt;throwExceptionIfNotSet('hostname', $hostname);\n\n $this-&gt;login = $login;\n $this-&gt;password = $password;\n $this-&gt;database = $database;\n $this-&gt;hostname = $hostname;\n }\n\n private function throwExceptionIfNotSet($argName, $argValue) {\n if (empty($argValue)) {\n throw new DatabaseException(\"'${argName}' not set\");\n }\n }\n\n}\n</code></pre>\n\n<p><code>Mysql.php</code>:</p>\n\n<pre><code>class Mysql extends Database {\n\n private $link = null;\n\n public function __construct($login, $password, $database, $hostname) {\n parent::__construct($login, $password, $database, $hostname);\n $this-&gt;connect();\n $this-&gt;selectDatabase();\n }\n\n public function connect() {\n if (! is_null($this-&gt;link)) {\n return;\n }\n\n $link = @mysql_connect($this-&gt;hostname, $this-&gt;login, $this-&gt;password);\n if (! $link) {\n throw new DatabaseException(\n sprintf(\n 'Cannot connect to database. mysql_connect() to %s with login %s fails',\n $this-&gt;hostname,\n $this-&gt;login\n )\n );\n }\n }\n\n public function selectDatabase() {\n $ret = @mysql_select_db($this-&gt;database, $this-&gt;link);\n if (! $ret) {\n throw new DatabaseException(\"Cannot select database {$this-&gt;database}\");\n }\n }\n\n}\n</code></pre>\n\n<p><code>application.php</code>:</p>\n\n<pre><code>try {\n $db = new Mysql('root', '', 'magic', 'localhost');\n print('ALL PASSED'); //for debugging\n\n} catch (DatabaseException $ex) {\n print('redirect to custom error page will go here');\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T14:10:32.743", "Id": "3803", "Score": "0", "body": "@php-coder - Thank you for your example. I have been playing with it to better understand it and I have just a couple questions. Question 1, why did you break up Database and Mysql into two different files? I think I understand why DatabaseException is seperate and that's because it needs to be modular. Question 2, why did you make the Database class abstract? I have read up on abstract, but I am really not understanding it's use.... Thanks again for your example, it was very informative and is exatly what I needed :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T15:28:14.863", "Id": "3805", "Score": "0", "body": "@php-grasshoppa 1) `Database` and `Mysql` classes in different files because I preffer to place each class to separate file. Easy to maintain and easy to search when you need it. Why it in different classes? In this case, it is looks useless and no needed really. But if you will add support for MSSQL, PostgreSQL etc, then base class will be usefull. It contains common information with database' credentials. 2) `Database` class marked as `abstract` because this class should not be created by `new Database` in program. As I said above it encapsulates common information with related methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T19:35:56.710", "Id": "3812", "Score": "0", "body": "@php-coder - I fully understand what you are saying about organization with classes. I never thought about putting one class per file, and I love that idea ..... nice :-) As for abstract, I bought an OOP book and it is describing the reason behind it, so thanks again for your time and knowledge." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-26T08:06:46.750", "Id": "4115", "Score": "0", "body": "surely use ` === null ` rather than `is_null` ? Why use sprintf when you could just use normal concatenation? Also, `empty` ? surely you can just do a falsey check? Otherwise.. an improvement :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-26T11:18:52.813", "Id": "4125", "Score": "0", "body": "@skippychalmers IMHO these made code more readable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-26T12:43:43.950", "Id": "4132", "Score": "0", "body": "@php-coder without wanting to seem arrogant or upset you, but still being as blunt as possible: no. It's absolutely not more readable. If you're struggling to read `if ($var === null)` or `$var = 'str 1'.$var2.'str 2';` then you need to go back to php school." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-13T04:34:13.653", "Id": "2397", "ParentId": "2395", "Score": "5" } }, { "body": "<p>Please change this line:</p>\n\n<pre><code>$link = @mysql_connect($this-&gt;hostname, $this-&gt;login, $this-&gt;password);\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>$this-&gt;link = @mysql_connect($this-&gt;hostname, $this-&gt;login, $this-&gt;password);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-03T11:51:27.367", "Id": "2797", "ParentId": "2395", "Score": "1" } }, { "body": "<p>This now old question needs another answer. No-one has warned of the dangerous nature of the @ operator!</p>\n\n<p>@ suppresses errors (hides them). This is a very bad thing. You can use it and get away with it if you do everything correctly (checking for boolean flags etc.). But <strong>when</strong> you make a mistake you won't know why. I make mistakes, everyone I know does. So, I suggest against the use of the @ operator.</p>\n\n<p>mysql_* is now softly deprecated (use PDO or mysqli).</p>\n\n<p>Your method names can be improved:</p>\n\n<ul>\n<li>process gives me no idea what it is doing.</li>\n<li>verifyDatabaseConnection actually connects to the database! verify should only be used to check things, not do things.</li>\n<li>verifyDatabaseExist similarly selects the database (you need to use the right verb).</li>\n</ul>\n\n<p>The problem with your verify methods are that they are doing 2 things. Connecting or Selecting and then Verifying.</p>\n\n<p>Please read <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">Jeff Attwood's Flattening Arrow Code</a>.</p>\n\n<p>Keep work out of the constructor for good OO. Don't call process. While I would never write mysql_* this is what your class should have looked like:</p>\n\n<pre><code>class Mysql\n{\n private $db;\n\n public function __construct($host, $user, $pass)\n {\n $this-&gt;db = mysql_connect($host, $user, $pass);\n\n if (!$this-&gt;db)\n {\n throw new RuntimeException(\n __METHOD__ . ' could not connect to DB due to error: ' .\n mysql_error());\n }\n }\n\n public function selectDatabase($database)\n {\n $db_selected = mysql_select_db($database, $this-&gt;db);\n\n if (!$db_selected)\n {\n throw new RuntimeException(\n __METHOD__ . ' could not select database: ' . $database .\n ' error: ' . mysql_error());\n }\n }\n}\n</code></pre>\n\n<p>No errors will be suppressed and it is simple and easy to read.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-24T15:37:13.997", "Id": "17746", "Score": "0", "body": "Hey Paul, thanks for all your input. This is great information :) I have transitioned to PDO after reading about the simplicity it offers as well as tightened security." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-24T04:50:21.230", "Id": "11132", "ParentId": "2395", "Score": "3" } } ]
{ "AcceptedAnswerId": "2397", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-13T02:18:07.537", "Id": "2395", "Score": "5", "Tags": [ "php", "php5", "object-oriented" ], "Title": "Learning OOP PHP, simple MySQL connection class." }
2395
<p>Here's some explanation for <code>accuracy</code> and <code>neg_accuracy</code>:</p> <p>It's meant to keep all the values in terms of what the user specified he wanted (how many decimal digits deep they want to go). <code>accuracy</code> is meant to cut the huge number returned by <code>GetTickCount()</code> to size, and <code>neg_accuracy</code> actually turns it into a decimal by dividing.</p> <p>I'm just hoping to get some criticism on efficiency and be notified of any better ways to do things.</p> <pre><code>// -----------------------------------INSTRUCTIONS----------------------------------- // create a timer class object with with this function: ___Stopwatch PLACE_NAME_HERE( int NumberOfDecimals, string Command);___ // Stopwatch PLACE_NAME_HERE( int NumberOfDecimals, //put how many decimal integers deep you want tracked time to be ( // 1 decimal = 0.0, inserting an integer with value 2 here = 0.00) // string Command); // putting the command "Start" here makes it start timing right away // member functions include: Start() {starts the timer} // Restart() {restarts the timer but doesn't clear saved Times} // TimeElapsed() {returns the time elapsed since the Start() function was called} // Wait( long float TIME_TO_WAIT) {doesn't return until time specified is over} // SaveTime() {Saves the current time elapsed into a vector which can be accesed with:} // GetTime( int TIME_TO_GET ) {returns the specified time; if you specify 1 you get the first time you saved // otherwise the funciton returns 0 if there is no time saved at specified location} // ClearTime() {Clears all saved times in the vector} // Call these functions by simply typing "STOPWATCH_NAME.A_FUNCTION();" and filling in the capitalized variables // Windows stuff #include &lt;Windows.h&gt; // STL stuff #include &lt;string&gt; #include &lt;vector&gt; using namespace std; class Stopwatch { protected: int accuracy, neg_accuracy; unsigned long int initial_ilu; unsigned long int current_ilu; long float output_fl; vector&lt;long float&gt; times; public: Stopwatch(int DecNumb, string command = "void") { // default command if (DecNumb&gt;3) DecNumb = 3; // I made here before DecNumb gets changed int I = 3 - DecNumb; // so accuracy*10 isn't 0 for(accuracy = 1;I&gt;0;I--) accuracy = accuracy*10; for(neg_accuracy = 1;DecNumb&gt;0;DecNumb--) neg_accuracy = neg_accuracy*10; if(command == "start" ||command == "Start") Start();}; void Start(){initial_ilu = GetTickCount()/accuracy;}; void Restart(){initial_ilu = GetTickCount()/accuracy;}; long float ElapsedTime() { current_ilu = GetTickCount()/accuracy; output_fl = ((long float)current_ilu - (long float)initial_ilu)/(long float)neg_accuracy; return output_fl; }; void Wait(long float seconds) { for(unsigned long int waitTime = GetTickCount() + (seconds*1000); waitTime &gt; GetTickCount();) {} // stay stuck in for loop until time specified is up }; void SaveTime(){times.push_back(ElapsedTime());}; void ClearTime(){times.clear();times.resize(0);}; // WILL THIS WORK? (untested) long float GetTime(int location){int test = times.size(); if(times.size() &gt;= location) return times[location-1]; }; }; </code></pre>
[]
[ { "body": "<p>Why are you using strings to command the class? They may be fast enough for your needs (since you're only using tick) but they are generally slow, and if you were to extend the class to support faster timing it could throw off your results. Consider using an enum or define to command the class:</p>\n\n<p>In your header, define the following:</p>\n\n<pre><code>enum{\nSTOPTIMER = 0,\nSTARTTIMER = 1\n};\n</code></pre>\n\n<p>Then modify your class:</p>\n\n<pre><code>Stopwatch(..., int command = STOPTIMER) { \n...\nif(command == STARTTIMER) Start();};\n</code></pre>\n\n<p>I'm not a big fan of some of your coding style, but at least consider keeping it consistent. If you're going to put braces at the end of the line elsewhere, do it for the class declaration as well. Consider indenting the code in the loops so the looping structure is obvious.</p>\n\n<p>Also, note that <code>GetTickCount()</code> is not very accurate - you should consider making certain that your class advertises just how accurate it can be, since you give them the ability to choose an accuracy. They may choose one that the class really can't support. Not only is it accurate to a millisecond (only 3 decimal places) it's only updated 64 times a second, so it's really only accurate to just under 2 decimal places. See <a href=\"http://en.wikipedia.org/wiki/GetTickCount\">http://en.wikipedia.org/wiki/GetTickCount</a> for more info. There are other system timing functions that will give you very accurate mS and uS timing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T00:44:13.143", "Id": "3800", "Score": "0", "body": "Can you suggest any other system timing functions i can use to easily replace GetTickCount() ? Thanks for the answer too!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-13T13:54:45.433", "Id": "2401", "ParentId": "2398", "Score": "5" } }, { "body": "<p>The most accurate timing mechanism on Windows is <a href=\"http://msdn.microsoft.com/en-us/library/ms644904.aspx\" rel=\"nofollow\">QueryPerformanceCounter</a>. If you use this together with <a href=\"http://msdn.microsoft.com/en-us/library/ms644905.aspx\" rel=\"nofollow\">QueryPerformanceCounterFrequency</a> you can create a microsecond accurate timer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T18:02:07.083", "Id": "2410", "ParentId": "2398", "Score": "4" } } ]
{ "AcceptedAnswerId": "2401", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-13T04:47:48.983", "Id": "2398", "Score": "7", "Tags": [ "c++", "optimization", "timer" ], "Title": "Homemade Stopwatch class" }
2398
<p>I'm building a navigation that has a breadcrumb with drop down menus. I want the menus to open up when I click the open link, then there are many instances when the menu should close:</p> <ul> <li>The link is clicked a second time, with the intention of closing the menu</li> <li>When another menu is open, the first menu should close</li> <li>When a menu is open, and anywhere outside the menu is clicked</li> <li>When a menu item is clicked</li> </ul> <p>I'm anticipating that I'll have many click events to handle, and many different types of menus, pop-ups and drop downs through the entire site, so I'm trying to handle that efficiently, thus the <code>switch</code> statement.</p> <pre><code>$().ready(function () { //Click event mayhem! $('html').click(function (event) { event.stopPropagation(); var target = $(event.target); switch (target.attr('class')) { case 'expandDropDown': handleBreadCrumbDropDownClick(target); break; case 'headlineTitle': event.preventDefault(); handleAccordionItemClick(target); break; default: //Always close dropdown menus, unless they're specifically being opened toggleDropDown('.BC-DropDown-Open'); } }); }); function handleBreadCrumbDropDownClick(target) { //Get the drop down list being targeted var dropDownList = '#' + target.attr('itemprop'); //Offset of the expander link var offset = target.offset(); if ($(dropDownList).hasClass('BC-DropDown-Open')) { //Dropdown is being closed with the expandDropDown link $(dropDownList) .hide() .toggleClass('BC-DropDown-Open'); } else { //Dropdown is being opened with the expandDropDown link if ($('.BC-DropDown-Open').length &gt; 0) { //Close existing drop down lists if any toggleDropDown('.BC-DropDown-Open'); } //Open selected dropdown toggleDropDown(dropDownList, offset); } } </code></pre>
[]
[ { "body": "<p>The switch statement isn't needed.</p>\n\n<p>Just set a click function for each class.</p>\n\n<pre><code>$(document).ready(function ready () { \n $('.expandDropDown').click( handleBreadCrumbDropDownClick );\n $('.headlineTitle').click( handleAccordionItemClick );\n});\n\nfunction handleBreadCrumbDropDownClick() {\n var target = $(this);\n var dropDownList = $('#' + target.attr('data-itemprop'));\n var offset = target.offset();\n if ( dropDownList.hasClass('BC-DropDown-Open') ) {\n dropDownList\n .hide()\n .toggleClass('BC-DropDown-Open');\n } else {\n if ( $('.BC-DropDown-Open').length ) {\n toggleDropDown('.BC-DropDown-Open');\n }\n toggleDropDown(dropDownList, offset);\n } \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T13:03:44.680", "Id": "3876", "Score": "0", "body": "Thanks for the feedback, also, thanks for referencing the 'data-' attribute. I just barely heard of that and haven't seen a usage yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T13:53:38.663", "Id": "3877", "Score": "0", "body": "While I like the cleaner look of your suggestion, without assigning a click to $('html') the menus will not close when clicking on other elements on the page. Do you have any suggestions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T19:52:02.653", "Id": "3882", "Score": "0", "body": "I'd need to see the html. But in short it's more manageable to bind to the individual elements than to listen to the whole page and try to sort it out afterwards. A `$('html *:not(.expandDropDown, .headlineTitle)').click(defaultClick);` would have the same effect, but it's still messy." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T17:38:23.457", "Id": "3970", "Score": "0", "body": "I definitely want to maintain manageability, especially since I don't think I'll be the one to finish this project. I'm trying to find the best solution for something that might end up being rather large." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-13T22:45:00.490", "Id": "2402", "ParentId": "2400", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-13T13:39:00.583", "Id": "2400", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "Handling click events to open and close menus depending on the click target" }
2400
<p>I have been working through the exercises in <a href="http://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours/Parsing">a Write Yourself a Scheme in 48 Hours/Parsing</a> and hacked together something to get parseString to comprehend escaped characters. Also had some inspiration from Real World Haskell chapter 16 minus the applicative parts.</p> <pre><code>parseString :: Parser LispVal parseString = do char '"' x &lt;- many $ chars char '"' return $ String x where chars = escaped &lt;|&gt; noneOf "\"" escaped = choice $ map tryEscaped escapedChars tryEscaped c = try $ char '\\' &gt;&gt; char (fst c) &gt;&gt; return (snd c) escapedChars = zip "bnfrt\\\"/" "\b\n\f\r\t\\\"/" </code></pre> <p>This works but I am not fond of my 'tryEscaped' definition. What are the alternatives?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T14:31:37.643", "Id": "3804", "Score": "0", "body": "Is `\\/` really a valid escape sequence in scheme?" } ]
[ { "body": "<p>Some suggestions:</p>\n\n<ul>\n<li>Replace <code>fst</code> and <code>snd</code> with a pattern match or explicit function arguments.</li>\n<li>Extract the common <code>char '\\\\'</code> parser. You can then avoid the <code>try</code>.</li>\n<li>Strings with lots of escaped characters are hard to read and it's hard to visually\nverify that the escape codes are correctly matched with their replacements. Consider\nspelling them out and aligning them to make this easy to see. </li>\n</ul>\n\n<p>Here's what I came up with:</p>\n\n<pre><code>escaped = char '\\\\' &gt;&gt; choice (zipWith escapedChar codes replacements)\nescapedChar code replacement = char code &gt;&gt; return replacement\ncodes = ['b', 'n', 'f', 'r', 't', '\\\\', '\\\"', '/']\nreplacements = ['\\b', '\\n', '\\f', '\\r', '\\t', '\\\\', '\\\"', '/']\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-08T14:21:15.937", "Id": "190303", "Score": "1", "body": "Hey, please note in 7.10 you will get an error message suggesting you enable FlexibleContext. This is due to not having an explicit type signature on the function escapedChar.\n\nThe proper fix, IMO, is to give it an explicit type signature:\n\nescapedChar :: Char -> Char -> Parser Char\n\nor you may be able to utilize an anonymous function to the same effect." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-23T18:09:06.187", "Id": "2572", "ParentId": "2406", "Score": "11" } }, { "body": "<p>The OP is doing this as exercise, but for anyone who found this question on google like I did and wants a fast solution: import Parsec's <code>Token</code> and <code>Language</code>.</p>\n\n<p>Then you can do this in GHCi:</p>\n\n<pre><code>&gt;&gt;&gt;let lexer = makeTokenParser haskellDef\n&gt;&gt;&gt;let p = stringLiteral lexer\n&gt;&gt;&gt;runParser p () \"\" \"\\\"Hi\\\\n\\\"\"\nRight \"Hi\\n\"\n</code></pre>\n\n<p>According to the Parsec docs:</p>\n\n<blockquote>\n <p>the literal string is parsed according to the grammar rules defined in the Haskell report (which matches most programming languages quite closely)</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-11-09T13:34:52.317", "Id": "341818", "Score": "0", "body": "I was looking for an out of the box solution. This works great!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-24T20:36:26.917", "Id": "105643", "ParentId": "2406", "Score": "8" } } ]
{ "AcceptedAnswerId": "2572", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T13:49:33.557", "Id": "2406", "Score": "15", "Tags": [ "haskell", "parsec" ], "Title": "Parsing strings with escaped characters using Parsec" }
2406
<p>Suppose you have a list of the diameters of some circular holes, and a list of the diameters of some cylindrical pegs. Now the problem is finding all the ways you can fit the pegs in the holes, where the order in which you put them in doesn't matter, and it's OK to put a peg in a hole that's too large.</p> <p>I've written the code below to solve the problem, and it <em>works</em> as intended. The innermost tuples of the answer matches a peg to a hole, i.e. (4, 7) means put d4 peg in d7 hole, and these tuples make up a set that represents one way of putting all the pegs in.</p> <p>I'm not completely happy with the solution. It's not... snappy enough, and it feels overly complicated. Is there a smarter way to go about it?</p> <pre><code>def fit(pegs, holes): for h in holes: for p in pegs: if p &lt;= h: pegs_left = [x for x in pegs if x != p] if pegs_left: free_holes = [x for x in holes if x != h] for rest in fit(pegs_left, free_holes): yield frozenset(((p, h),)) | rest else: yield frozenset(((p, h),)) def fitted(pegs, holes): return sorted(sorted(x) for x in set(fit(pegs, holes))) pegs = [2, 4, 7] holes = [1, 3, 4, 6, 9] print fitted(pegs, holes) # [[(2, 3), (4, 4), (7, 9)], # [(2, 3), (4, 6), (7, 9)], # [(2, 4), (4, 6), (7, 9)], # [(2, 6), (4, 4), (7, 9)]] </code></pre>
[]
[ { "body": "<ol>\n<li>I recommend against using single letter variable names, in particular your use of p and h. \nI think the code is clearer if you use peg and hole. </li>\n<li>Your code is going to break if you have multiple holes or pegs of the same size.</li>\n<li>You'd be better off using tuples instead of frozensets. You don't appear to be using the set features.</li>\n</ol>\n\n<p>In order to have better code/algorithm you need to look at the problem differently. Right now you are trying to find peg/hole combinations. Instead, you should try to figure out where each peg fits. </p>\n\n<p>You have the pegs: 2, 4, 7</p>\n\n<p>Your goal is to select three of the holes: 1, 3, 4, 6, 9 which fit the pegs.</p>\n\n<pre><code>itertools.permutations(holes, 3)\n</code></pre>\n\n<p>will produce an iterator over all possible choices of 3 holes from the list. Something like:</p>\n\n<pre><code>1 3 4\n1 3 6\n1 3 9\n1 4 3\n...\n</code></pre>\n\n<p>We interpret each value as an assignment of holes to pegs. So 1,3,4 means (2, 1), (4, 3), (7,4). Of course not all such assignments are valid. So we filter out the invalid ones (i.e. where the pegs don't fit). </p>\n\n<p>As an added bonus, itertools.permutations generates its values in sorted order. Because we only filter the results, the resulting function will also produce its values in sorted order. This removes the neccesity of doing the sorting yourself.</p>\n\n<p>Here is my implementation:</p>\n\n<pre><code>import itertools\n\ndef check_fits(pegs, holes):\n for peg, hole in zip(pegs, holes):\n if peg &gt; hole:\n return False\n return True\n\ndef fit(pegs, holes):\n assert len(pegs) &lt;= len(holes)\n for selected_holes in itertools.permutations(holes, len(pegs)):\n if check_fits(pegs, selected_holes):\n yield zip(pegs, selected_holes)\n\npegs = [2, 4, 7]\nholes = [1, 3, 4, 6, 9]\n\nfor item in fit(pegs, holes):\n print item\n</code></pre>\n\n<p>itertools.permutations will generate many invalid assignment of pegs to holes. For example, in the example above, it will generate a significant number of assignment which attempt to fit a peg of size 2 into a hole of size 1. A simple recursive function could avoid spending time on so many bad assignments. However, itertools.permutation is written in C, and so probably still has a speed advantage over such a recursive algorithm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T17:47:47.317", "Id": "3807", "Score": "0", "body": "Thank you for a very nice answer! Timeit shows that your solution, in addition to being more readable and nicer overall, also is over an order of magnitude faster; 13.3 usec vs. 650 usec. A couple of comments: 1) Frozenset is there so the order in which the pegs are inserted won't matter, so it had a purpose! 2) In your solution, `assert (...)` should probably be replaced by `if (...); raise ValueError()`, since `assert` statements are ignored when python runs in optimized mode." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T17:53:59.587", "Id": "3808", "Score": "0", "body": "Oh, and I suppose you meant \"1,3,4 means (2, 1), (4, 3), (7, 4)\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T18:47:46.293", "Id": "3809", "Score": "0", "body": "@lazyr, re: frozenset, I understand now" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T18:47:59.307", "Id": "3810", "Score": "0", "body": "@lazyr, re: numbers, you are correct. I've edited" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T18:51:19.227", "Id": "3811", "Score": "0", "body": "@lazy, re: assert. it seems to me that depends on the context. Any sort of reusable function should raise a ValueError. However, if its strictly for internal use within one module then I'd probably use an assert. (In this case I was just trying to clarify that the code made that assumption. I didn't think too hard about it)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T10:16:58.770", "Id": "3839", "Score": "0", "body": "Another optimization I thought of: eliminate the holes that are smaller than the smallest peg before beginning. I.e. `min_peg = min(pegs)`, `holes = [hole for hole in holes if hole >= min_peg]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T14:10:38.550", "Id": "3844", "Score": "0", "body": "@lazyr, I doubt that will help a whole lot, but it might." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T17:16:07.020", "Id": "2408", "ParentId": "2407", "Score": "6" } } ]
{ "AcceptedAnswerId": "2408", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-14T15:47:54.207", "Id": "2407", "Score": "5", "Tags": [ "python", "optimization", "algorithm" ], "Title": "all the ways to fit some pegs into given holes" }
2407
<p>I have \$ N^2 \$ matrices. Each one is a \$ 3 \times 3 \$ matrix. I want to concatenation them to a \$ 3N \times 3N \$ matrix. I know that the big matrix is symmetric. Evaluation of whole \$ 3 \times 3 \$ matrices are time consuming so I want to speed up my program. </p> <p>Do you have any suggestion to speed it up? </p> <pre><code>clc load rv load a %# Nx3 matrix [x1 y1 z1;x2 y2 z2;... ]. %# vectors construct a sphere L=(301:500)*1e-9; K=2*pi./L; %# 1x200 array %# some constants ========================================================= I=eye(3); e0=1; [npoints,ndims]=size(rv); N=npoints; d0=(4*pi/(3*N))^(1/3)*5e-9; V=N*d0^3; aeq=(3*V/(4*pi))^(1/3); E0y=ones(N,1); E0z=E0y; Cext=zeros(1,length(L)); Qext=zeros(1,length(L)); A=zeros(3,3,N^2); % ================================= r=sqrt(sum(rv,2).^2); %# [Nx1] lengrh of each rv vector for i=1:N for j=1:N dx(i,j)=rv(i,1)-rv(j,1); %# The x component of distances between each 2 point [NxN] dy(i,j)=rv(i,2)-rv(j,2); %# The y component of distances between each 2 point [NxN] dz(i,j)=rv(i,3)-rv(j,3); %# The z component of distances between each 2 point [NxN] end end dv=cat(3,dx,dy,dz); %# d is the distance between each 2 point (a 3D matrix) [NxNx3] d=sqrt(dx.^2+dy.^2+dz.^2); %# length of each dv vector nx=dv(:,:,1)./d; ny=dv(:,:,2)./d; nz=dv(:,:,3)./d; n=cat(3,nx,ny,nz); %# Unit vectors for points that construct my sphere for s=1:length(L) E0x=exp(1i*K(s)*rv(:,1))'; % ' #closing the quote for syntax highlighting % 1x200 array in direction of x(in Cartesian coordinate system) % Main Loop ================================================= p=1; for i=1:N for j=1:N if i==j A(:,:,p)=a(s)*eye(3); %# 3x3 , a is a 1x200 constant array p=p+1; %# p is only a counter else A(:,:,p)=-exp(1i*K(s)*d(i,j))/d(i,j)*(-K(s)^2*([nx(i,j);ny(i,j);nz(i,j)]... *[nx(i,j) ny(i,j) nz(i,j)]-I)+(1/d(i,j)^2-1i*K(s)/d(i,j))... *(3*[nx(i,j);ny(i,j);nz(i,j)]*[nx(i,j) ny(i,j) nz(i,j)]-I)); p=p+1; end end end %=============================================================== B = reshape(permute(reshape(A,3,3*N,[]),[2 1 3]),3*N,[]).'; %# From :gnovice %# concatenation of N^2 3x3 matrixes into a 3Nx3N matrix for i=1:N E00(:,i)=[E0x(i) E0y(i) E0z(i)]'; end b=reshape(E00,3*N,1); P=inv(B)*b; Cext(s)=(4*pi*K(s))*imag(b'*P); Qext(s)=Cext(s)/(pi*aeq^2); end Qmax=max(Qext); Qext=Qext/Qmax; L=L*1e9; plot(L,Qext,'--');figure(gcf) %# The B matrix is symmetric(B_ij=B_ji) so I can reduce the computations %# I think I should write sth like this % for i=1:N % for j=i:N % if i==j % A(:,:,p)=a(s)*eye(3); %# 3x3 , a is a 1x200 constant array % p=p+1; %# p is only a counter % else % A(:,:,p)=... [just same as above] % p=p+1; % end % end % end % But how concatenate them like befor in order? </code></pre> <p>Pls get a.mat : <a href="http://dl.dropbox.com/u/21031944/Stack/a.mat" rel="nofollow">http://dl.dropbox.com/u/21031944/Stack/a.mat</a></p> <pre><code> rv.mat: http://dl.dropbox.com/u/21031944/Stack/rv.mat </code></pre> <p>Or sth like this (for symmetry part):</p> <pre><code>for i=1:N for j=1:N if i==j A(:,:,p)=a(s)*eye(3); %# 3x3 , a is a 1x200 constant array p=p+1; %# p is only a counter elseif i&gt;j A(:,:,p)=... [just same as above] p=p+1; else A(:,:,p)=A(:,:,??); p=p+1; end end end </code></pre> <p>I don't know is program clear?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-15T04:58:48.113", "Id": "3814", "Score": "0", "body": "A bigger [rv](http://dl.dropbox.com/u/21031944/Stack/rv_bigger.mat)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-15T04:59:51.340", "Id": "3815", "Score": "0", "body": "http://i.stack.imgur.com/AJKJl.png\n\nhttp://i.stack.imgur.com/AJKJl.png\n\nhttp://i.stack.imgur.com/SOpya.png\n\nhttp://i.imgur.com/podvp.png" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-27T14:52:29.997", "Id": "31924", "Score": "0", "body": "Could you run the profiler to find out which part exactly requires the speedup?" } ]
[ { "body": "<p>In my experience with finite element problems, I found that creating the large matrix <code>A</code> easily took as long, if not longer, than calculating the solution <code>x = A/b</code>. Matlab does a good job with that matrix inverse. </p>\n\n<p>In (old) FORTRAN creation of <code>A</code> is done with nested loops. In Matlab this iteration is very slow. One trick is to reverse the order of the nesting, so you iterate on small dimensions (the <code>3x3</code>), and use matrix operations on the large ones (<code>N</code>). A further step is to do everything with matrix operations (on 4D arrays if needed), but that is harder to conceptualize.</p>\n\n<p>I suspect your <code>A</code> matrix is sparse (lots of <code>eye</code> components). In that case the Matlab sparse matrix operations can be your friend. Basically you create 3 large vectors, <code>I</code>, <code>J</code>, <code>V</code>, where 2 identify the coordinates, and the third the (nonzero) value at each. If a specific pair of coordinates is repeated, the corresponding values are added, which in some matrix definitions is convenient. But that is more than I can explain here.</p>\n\n<p><a href=\"https://codereview.stackexchange.com/a/30101/27783\">https://codereview.stackexchange.com/a/30101/27783</a>\ntakes a simple heat diffusion model, using loops and indexing, and speeds it up in several steps. Simply vectorizing the inner loops helps a lot. The best speed came generating a matrix using <code>eye</code> (or <code>diag</code>), and doing fast matrix multiplication (with <code>np.dot</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T12:53:10.743", "Id": "48058", "Score": "0", "body": "If the goal is just solving linear equations, then indeed using `ldivide` or `rdivide` seems to be the way to go." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-22T01:31:34.843", "Id": "30056", "ParentId": "2413", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-15T04:57:32.200", "Id": "2413", "Score": "4", "Tags": [ "matrix", "matlab" ], "Title": "Set of linear equations" }
2413
<p>Here's my function but it sometimes has unpredicted results with entering different numbers but with the same number of digits getting different results. I figure it has something to do with a computers inaccurate decimal saving tecnique but i would like to know how to make it more accurate.</p> <pre><code>/////////////////////// Numb_Digits() //////////////////////////////////////////////////// enum{DECIMALS = 10, WHOLE_NUMBS = 20, ALL = 30}; template&lt;typename T&gt; unsigned long int Numb_Digits(T numb, int scope) { unsigned long int length= 0; unsigned long int whole_numb= (int)numb; // gets the number of whole numbers for(int mod =0; mod!=whole_numb; length++) mod = whole_numb% (int)pow(10, (double)length); int numb_of_wholes= length-1; length= 0; bool all = false; double test = 0, test2= 0; switch(scope){ case ALL: all = true; // different order to avoid decimal inaccuracies // like 2.4 being 2.39999 // 10 bil (10 zeros) case DECIMALS: numb*=10000000000; numb-=whole_numb*10000000000; for(; numb != 0; length++) numb-=((int)(numb/pow((double)10, (double)(9-length))))* pow((double)10, (double)(9-length)); if(all != true) break; case WHOLE_NUMBS: length += numb_of_wholes; if(all != true) break; default: break;} return length; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-15T12:51:08.377", "Id": "3824", "Score": "2", "body": "For one, the formatting of that code looks awful. No room to breath. ;p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-15T14:23:02.827", "Id": "3825", "Score": "0", "body": "If your code doesn't work, it shouldn't be on code review. This is a better question for stackoverflow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-15T14:52:56.663", "Id": "3827", "Score": "0", "body": "@Winston: In this case it 'kinda' works. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-15T18:21:06.803", "Id": "3828", "Score": "1", "body": "@Jeuris, kinda doesn't cut it. The FAQ makes it clear that codereview is not for debugging help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-15T21:17:52.637", "Id": "3830", "Score": "0", "body": "and as Steve said please, for the love of god fix your code formatting. This isn't your first post like this. Help us help you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-18T06:56:44.757", "Id": "157694", "Score": "1", "body": "Is this just 'log(n)'" } ]
[ { "body": "<p>To get the number of whole numbers, <a href=\"https://stackoverflow.com/questions/554521/how-can-i-count-the-digits-in-an-integer-without-a-string-cast\">you can just use log10</a>.</p>\n\n<pre><code>int wholeNumbers = ( number == 0 ) ? 1 : (int)log10( abs( number ) ) + 1;\n</code></pre>\n\n<p>I implemented your function in C#. By using the <em>decimal</em> type for the calculation of the numbers after the decimal sign, precision issues are automatically solved. Most likely a simple for loop is more performant than using <em>pow</em> as in your solution. The result of numbers after the decimal sign for infinite precise numbers (like PI) is dependent on the precision of the type. With this code, I get 14 digits after comma for PI.</p>\n\n<pre><code>public static int AmountOfDigits( double number, DecimalPart decimalPart = DecimalPart.WholeNumbers )\n{\n double absNumber = Math.Abs( number );\n int amountOfDigits = 0;\n\n // Amount of digits before decimal sign.\n if ( decimalPart == DecimalPart.WholeNumbers || decimalPart == DecimalPart.EntireDecimal )\n {\n amountOfDigits += (absNumber == 0) ? 1 : (int)Math.Log10( absNumber ) + 1;\n }\n\n // Amount of digits after decimal sign.\n if ( decimalPart == DecimalPart.AfterDecimalSign || decimalPart == DecimalPart.EntireDecimal )\n {\n // Use decimal for more precision!\n decimal afterDecimalSign = (decimal)absNumber;\n while ( afterDecimalSign - Math.Truncate( afterDecimalSign ) != 0 )\n {\n amountOfDigits++;\n afterDecimalSign *= 10;\n }\n }\n\n return amountOfDigits;\n}\n</code></pre>\n\n<p>You do have to ask yourself where you will use this code however. When you are going to use it to calculate correct padding for string output, it's probably better to just convert the numbers to strings and count the amount of characters. It would be an interesting benchmarking test to compare that solution to this one.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-15T12:57:57.230", "Id": "2418", "ParentId": "2414", "Score": "3" } } ]
{ "AcceptedAnswerId": "2418", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-15T06:59:56.147", "Id": "2414", "Score": "2", "Tags": [ "c++" ], "Title": "How can i make my Get_Numb_of_Digits_in_a_number() function more accurate?" }
2414
<p>This is a quick script I whipped up to collapse some folder trees down to individual folders. The specific situation that arose was my formerly-itunes collection (it's currently organized <code>Music\artist\album\songs.(mp3|m4a)</code> and I'd really prefer it to be <code>Music\artist\song.(mp3|m4a)</code>).</p> <pre><code>#!/usr/bin/ruby require 'optparse' require 'pp' require 'fileutils' ### parsing command line options via optparse, nothing to see here options={} optparse = OptionParser.new do|opts| opts.on('-h', '--help', 'Display this screen') do puts opts exit end opts.on('-t', '--type a,b,c', Array, 'Specify filetypes to flatten out (defaults to mp3,m4a)') do|t| options[:types] = t end end optparse.parse! ### the setup (ideally, this would be in a `let` statement) origin = Dir.pwd if not options[:types] options[:types] = ["mp3", "m4a"] end ### the actual work ARGV.each do |target| FileUtils.cd("#{origin}/#{target}") options[:types].each{|ext| `find -iname '*.#{ext}' -exec mv {} ./ \\\;`} `find -depth -type d -empty -exec rmdir {} \\\;` end FileUtils.cd(origin) </code></pre> <p>Am I doing anything eye-stabbingly wrong? Is there a better way of handling any of the above? </p> <p>Specifically, I suspect that I could replace the find calls with native Ruby methods, but I can't see how without complicating it significantly. I also suspect that there's a better way of writing <code>FileUtils.cd("#{origin}/#{target}")</code>, but a cursory reading of <a href="http://ruby-doc.org/core/classes/Dir.html" rel="nofollow">Dir</a> doesn't reveal anything. Any tips?</p> <hr> <pre><code>#!/usr/bin/ruby require 'optparse' require 'pp' require 'fileutils' ### parsing command line options via optparse options={:types =&gt; ["mp3", "m4a"]} optparse = OptionParser.new do|opts| opts.on('-h', '--help', 'Display this screen') do puts opts exit end opts.on('-t', '--type a,b,c', Array, 'Specify filetypes to flatten out (comma separated, defaults to mp3,m4a)') do|t| options[:types] = t end end optparse.parse! ### the actual work ARGV.each do |target| FileUtils.cd(target) do options[:types].each{|ext| `find -iname '*.#{ext}' -exec mv {} ./ \\\;`} ##move all matched files into [target] `find -depth -type d -empty -exec rmdir {} \\\;` ##recursively delete all empty folders in [target] end end </code></pre> <ul> <li><code>options</code> is now initialized beforehand rather than being checked after <code>.parse!</code></li> <li>using the block option on <code>FileUtils.cd</code></li> <li>removed useless final <code>cd</code> back</li> <li>tried the <code>glob</code> option, but it just errors without continuing if it hits a matched file in <code>target</code> (ie. one that needs to stay where it is). This seems to happen when I pass <code>:force =&gt; TRUE</code> too. The <code>find</code> call notes such files, but still flattens what it can. The <code>glob</code> route also doesn't seem to be case-insensitive.</li> </ul>
[]
[ { "body": "<pre><code>options={}\n# ...\nif not options[:types]\n options[:types] = [\"mp3\", \"m4a\"]\nend\n</code></pre>\n\n<p>I would initialize <code>options</code> with the default values first, instead of checking whether the option is set afterwards. I.e.</p>\n\n<pre><code>options = {:types =&gt; [\"mp3\", \"m4a\"]}\n</code></pre>\n\n<hr>\n\n<pre><code>options[:types].each{|ext| `find -iname '*.#{ext}' -exec mv {} ./ \\\\\\;`}\n</code></pre>\n\n<p>This can be done with a glob. For this I'd first change <code>options[:types]</code> to be string (i.e. replace <code>Array</code> with <code>String</code> in the optparse code and use <code>\"mp3,m4a\"</code> instead of <code>[\"mp3\", \"m4a\"]</code> as the default. Then you can use <code>Dir.glob</code> with <code>FileUtils.mv</code> like this:</p>\n\n<pre><code>Dir.glob(\"**/*.{#{ ext }}\") {|f| FileUtils.mv(f, \".\")}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>I suspect that I could replace the find calls with native Ruby methods, but I can't see how without complicating it significantly.</p>\n</blockquote>\n\n<p>For the first one see above. However the second one would indeed be more complicated to replace, so I'd just stick with the <code>find</code> call.</p>\n\n<hr>\n\n<blockquote>\n <p>I also suspect that there's a better way of writing <code>FileUtils.cd(\"#{origin}/#{target}\")</code></p>\n</blockquote>\n\n<p>Yes, there is: <code>cd</code> optionally takes a block. When given a block, <code>cd</code> will cd into the given directory, execute the block, and then cd back. So you can get rid of <code>origin</code> and just do</p>\n\n<pre><code>FileUtils.cd(target) do\n ...\nend\n</code></pre>\n\n<hr>\n\n<pre><code>FileUtils.cd(origin)\n</code></pre>\n\n<p>Even without using the block version of <code>cd</code> the above line would be completely unnecessary. Changing the directory at the end of a script has no effect. Any cd performed in a process will never affect the parent process.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-15T20:10:01.927", "Id": "2423", "ParentId": "2419", "Score": "5" } } ]
{ "AcceptedAnswerId": "2423", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-15T16:41:42.747", "Id": "2419", "Score": "5", "Tags": [ "ruby", "shell" ], "Title": "Collapsing Folder Trees with Ruby" }
2419
<blockquote> <p>Traverse a binary search tree in iterative inorder.</p> </blockquote> <p>Note that the iterative methods below contain the meat of the code; the remaining code is included for completeness.</p> <pre><code>// tree node struct node { int elem; node *left, *right; // Statically create a node, given an element static node* create(int elem) { node *newnode = new node; newnode-&gt;elem = elem; newnode-&gt;left = newnode-&gt;right = NULL; return newnode; } // Statically destroy a node static void destroy (node *&amp; mynode) { delete mynode; mynode-&gt;left = mynode-&gt;right = NULL; } }; typedef stack&lt;const node*&gt; nodestack; typedef vector&lt;const node*&gt; nodevect; // tree class class tree { private: node *root; nodestack mystack; public: // initialize tree tree(int elem) { root = node::create(elem); } /* --------- INSERTION METHODS BEGIN --------- */ // Insert a new element into a subtree whose root node is given bool insert(node *travnode, int elem) { node *newnode = node::create(elem); // Insert to left subtree if(elem &lt; travnode-&gt;elem) { if(travnode-&gt;left == NULL) { travnode-&gt;left = newnode; return true; } else return insert(travnode-&gt;left,elem); } else if(elem == travnode-&gt;elem) { delete newnode; return false; } // Insert to right subtree else // if(elem &gt; travnode-&gt;elem) { if(travnode-&gt;right == NULL) { travnode-&gt;right = newnode; return true; } else return insert(travnode-&gt;right,elem); } } // Insert directly into the tree; this method is used externally bool insert(int elem) { return insert(root,elem); } /* --------- INSERTION METHODS END --------- */ /* ------- RECURSIVE METHODS BEGIN -----------*/ // Recursive methods below are used for checking the iterative version // Recursive inorder traversal of a node ; dump nodes traversed into a vector void recursive_inorder(const node *mynode, vector&lt;int&gt; &amp;myvect) const { if(mynode != NULL) { recursive_inorder(mynode-&gt;left,myvect); myvect.push_back(mynode-&gt;elem); recursive_inorder(mynode-&gt;right,myvect); } } // Recursive traversal of the whole tree vector&lt;int&gt; recursive_inorder() const { vector&lt;int&gt; myvect; recursive_inorder(root,myvect); return myvect; } /* -------- RECURSIVE METHODS END -------*/ /* -------- ITERATIVE METHODS BEGIN ---*/ // Go to the leftmost node, stacking nodes along the path void findLeftMostAndStack(const node *mynode) { const node *travnode = mynode; while(travnode != NULL) { mystack.push(travnode); travnode = travnode-&gt;left; } } // Return the stack created thus far nodestack getStack() const {return mystack;} // Get the first element in inorder traversal, stacking all nodes on the way from the root const node* findFirstElement() { while(!mystack.empty()) mystack.pop(); findLeftMostAndStack(root); const node *firstNode = mystack.top(); mystack.pop(); return firstNode; } // Given any node, use the stack to find the successor const node* findSuccessorOf(const node *mynode) { // We're at the last node in traversal; there is no successor if(mystack.empty() &amp;&amp; mynode-&gt;right == NULL) return NULL; // If there is a right child, stack the nodes along the first node in the right subtree if(mynode-&gt;right != NULL) findLeftMostAndStack(mynode-&gt;right); // To find the successor, const node *successor = mystack.top(); mystack.pop(); return successor; } // Use all the methods above to traverse the tree iteratively inorder vector&lt;int&gt; iterative_inorder() { vector&lt;int&gt; myvect; // Get first element const node* nextnode = findFirstElement(); while(nextnode != NULL) // go on till last element is reached { myvect.push_back(nextnode-&gt;elem); // keep finding successors nextnode = findSuccessorOf(nextnode); } return myvect; } /* --------------- ITERATIVE METHODS END *--------------*/ // Friend functions friend tree* makeTree(const vector&lt;int&gt; &amp;); // create tree using a vector // compare recursive &amp; iterative traversals friend bool compareRecIter(tree &amp;T); // Destroy subtree void destroy (node *&amp; mynode) { if(mynode == NULL) return; destroy(mynode-&gt;left); destroy(mynode-&gt;right); delete(mynode); mynode-&gt;left = mynode-&gt;right = NULL; mynode = NULL; } // Destroy tree void destroy() { this-&gt;destroy(root); }; // tree class /* Auxiliary functions */ // Create a tree from a vector of elements tree* makeTree(const vector&lt;int&gt; &amp;v) { assert(v.size()); tree *T = new tree(v[0]); for(size_t i = 1; i != v.size(); ++i) T-&gt;insert(v[i]); return T; } // Compare recursive &amp; iterative traversals of the tree // If equal, return true; else false bool compareRecIter(tree &amp;T) { // Get the 2 vectors, returned by recursive &amp; iterative traversals vector&lt;int&gt; v = T.recursive_inorder(); vector&lt;int&gt; v2 = T.iterative_inorder(); for(int i=0;i!=v.size();++i) cout&lt;&lt;v[i] &lt;&lt;","; cout&lt;&lt;endl; for(int i=0;i!=v2.size();++i) cout&lt;&lt;v2[i] &lt;&lt;","; cout&lt;&lt;endl; // Return true if they are identical return (v == v2); } </code></pre> <p><strong>Test code:</strong></p> <pre><code>int main() { int leftLeaning[5] = {5,4,3,2,1}; tree *T = makeTree(vector&lt;int&gt;(leftLeaning, leftLeaning + 5)); assert(compareRecIter(*T)); T-&gt;destroy(); delete T; T = NULL; cout&lt;&lt;"\n"; int rightLeaning[5] = {1,2,3,4,5}; tree* T2 = makeTree(vector&lt;int&gt;(rightLeaning, rightLeaning + 5)); assert(compareRecIter(*T2)); } </code></pre>
[]
[ { "body": "<p>Your program looks okay for the most part and will probably work without any observable bugs. However there are a couple of problematic areas and sticky points you should address. I'll start with the most important first:</p>\n\n<ul>\n<li><p>Accessing data member of a struct after deletion:</p>\n\n<pre><code>\nstatic void node::destroy( node *& mynode )\n{\n delete mynode;\n mynode->left = mynode->right = NULL;\n mynode = NULL;\n}\n\nvoid tree::destroy( node *& mynode )\n{\n if( mynode == NULL ) return;\n destroy( mynode->left );\n destroy( mynode->right );\n delete( mynode );\n mynode->left = mynode->right = NULL;\n mynode = NULL;\n} \n</code></pre></li>\n</ul>\n\n<p>The above two methods contain undefine behavior because you're trying to assign to <code>left</code> and <code>right</code> after <code>mynode</code> got deleted.</p>\n\n<ul>\n<li>Leaky encapsulation; methods that should be private are not. For example, the first overloaded <code>insert()</code> method should be private, as your comments suggest here:</li>\n</ul>\n\n <pre><code>\n // Insert a new element into a subtree whose root node is given\n bool insert( node *&travnode, int elem )\n //...\n\n // Insert directly into the tree; this method is used externally\n bool insert( int elem )\n //...\n </code></pre>\n\n<p>As well as a couple other methods that outside code using this <code>tree</code> has no business of knowing. Helper functions and methods like <code>destroy()</code>, overloaded <code>recursive_inorder()</code> and <code>find*()</code> used by your tree iteration comes to mind. They belong in the private tree section. Ideally, code using your tree class should not be exposed to the fact that nodes are being used.</p>\n\n<ul>\n<li><p>RAII should be employed for dynamic node allocation. Your tree class should be responsible for cleaning up its own nodes in the destructor rather than forcing client code to call <code>destroy()</code>. To guard against premature leaks have functions that return dynamically allocated memory, like <code>makeTree()</code>, use a smart pointer like <code>auto_ptr&lt;tree&gt;</code>.</p></li>\n<li><p>Use of <code>tree::destroy()</code> is not orthagonal with <code>node::create()</code>. In fact, <code>node::destroy()</code> doesn't seem to be used at all. It also looks like <code>node::destroy()</code> expects whoever's using it to handle the bottom branches of this node. Not that this is necessarily wrong but something like this needs to be commented so it's clear what assumptions are being made. For example, if the tree class didn't handle the left and right child nodes of the parent node that's being deleted then that entire bottom branch just got disconnected.</p></li>\n<li><p>Awkward initialization in the tree constructor. If you change the constructor to accept a range represented by two iterators rather than a single int, it will make the class that much easier to work with. It'll also get rid of the need for a separate <code>makeTree()</code> function.</p></li>\n<li><p><code>bool tree::insert( node *&amp;travnode, int elem )</code> can be refactored with less code. You can do this by pushing the <code>NULL</code> check down to the base case and changing <code>node *travnode</code> into a reference pointer. This also corrects a potential memory leak lurking in your original version.</p>\n\n<pre><code>\nbool insert( node *&travnode, int elem )\n{\n if( travnode == NULL )\n {\n travnode = node::create( elem );\n return true;\n }\n\n if(travnode->elem == elem ) return false;\n\n node *&correct_branch = elem elem ? travnode->left : travnode->right;\n return insert( correct_branch, elem );\n}\n</code></pre></li>\n</ul>\n\n<p>Hopefully the above points provided enough detail to help you better refactor your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T17:56:05.287", "Id": "3850", "Score": "0", "body": "Thanks , I had not had time to think of all these small issues. Your first point is especially relevant." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T11:24:12.187", "Id": "2433", "ParentId": "2422", "Score": "2" } } ]
{ "AcceptedAnswerId": "2433", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-15T19:47:40.443", "Id": "2422", "Score": "4", "Tags": [ "c++", "tree" ], "Title": "Traversing a BST in iterative inorder" }
2422
<p>I am writing a simple raytracer just for fun. I want to iterate over rows, and each row must be an iterator over columns. A strategy I produced is the following:</p> <pre><code>class ViewPlane(object): def __init__(self, resolution, pixel_size, gamma): self.resolution = resolution self.pixel_size = pixel_size self.gamma = gamma def __iter__(self): def genR(): class IterRow(object): def __init__(self, plane, row): self.plane = plane self.row = row def __iter__(self): def genC(): for column in xrange(self.plane.resolution[1]): origin = (self.plane.pixel_size * (column - self.plane.resolution[0] / 2.0 + 0.5) , self.plane.pixel_size * (self.row - self.plane.resolution[1] / 2.0 + 0.5) , 100.0 ) yield ( Ray(origin = origin, direction = (0.0,0.0,-1.0)), (self.row,column) ) return return genC() def __str__(self): return "Row iterator on row "+str(self.row) for row in xrange(self.resolution[0]): yield IterRow(self, row) return genR() </code></pre> <p>Briefly stated: <code>ViewPlane</code> contains the pixel plane. This class implements <code>__iter__</code> which defines and returns a generator function. This generator function yields instances of an internal class <code>IterRow</code>, which in turn has a <code>__iter__</code> method that returns a generator iterating over the columns.</p> <p>I personally think that it's difficult to understand, so I was wondering if there's a cleaner strategy to achieve the same result.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T05:31:17.523", "Id": "3831", "Score": "0", "body": "This is from one who isn't seasoned... why `self.resolution = resolution` if `resolution` is already available to the whole class (among others)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T05:33:14.667", "Id": "3832", "Score": "0", "body": "Can you run pylint on your code. I see for example that you are not using `self.pixel_size`. Or am I missing something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T07:06:12.107", "Id": "3833", "Score": "0", "body": "@Tshepang: I am using it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T12:16:01.897", "Id": "3841", "Score": "0", "body": "Do you use it is some code you are not showing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T13:07:10.790", "Id": "3842", "Score": "0", "body": "@Tshepang: it's right there, at the instantiation of Ray. I know, it's not very readable. I am changing it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T14:58:47.170", "Id": "3845", "Score": "0", "body": "I can't find it. Can you paste the line here. I wanna know if I'm missing something (pls be patient)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T18:13:27.647", "Id": "3851", "Score": "0", "body": "@Tshepang, the line is \"origin = (self.plane.pixel_size *\" (and others)" } ]
[ { "body": "<pre><code>class Foo:\n def __iter__(self):\n def innergen():\n yield something\n return innergen()\n</code></pre>\n\n<p>Is the same as:</p>\n\n<pre><code>class Foo:\n def __iter__(self):\n yield something\n</code></pre>\n\n<p>In other words, there is no need to define the generator, just yield the values.</p>\n\n<p>Defining a class inside the method just serves to make things complicated and hard to read. Define the class outside of the method.</p>\n\n<p>Having return at the end of a function doesn't do anything and makes it look like you don't know what you are doing. (I'm not saying that you don't, but whenever you include code with effect it raises a red flag. Did you think it do something?)</p>\n\n<p>Unless you really need to access the data row by row I suggesting flattening the iterator.</p>\n\n<p>Stylistically, I prefer to break expressions up rather then trying to split them across several lines as you've done. I think it produces less clutter.</p>\n\n<p>Here is my resulting code:</p>\n\n<pre><code>class ViewPlane(object):\n def __init__(self, resolution, pixel_size, gamma):\n self.resolution = resolution\n self.pixel_size = pixel_size\n self.gamma = gamma\n\n def __iter__(self):\n for row in xrange(self.resolution[0]):\n for column in xrange(self.resolution[1]):\n origin_x = self.pixel_size * self.resolution[0] / 2.0 + 0.5\n origin_y = self.pixel_size * self.resolution[1] / 2.0 + 0.5\n origin = (origin_x, origin_y, 100)\n ray = Ray(origin = origin, direction = (0.0, 0.0, -1.0) )\n\n yield ray, (row, column)\n</code></pre>\n\n<p>I'm not familiar enough with RayTracers to know but I question having the iterator over ViewPlane produce Ray objects. An iterator is for producing the contents of the object. Is a really contained inside the ViewPlane? Or should the iterator produce coordinates and let the caller construct the Ray objects?</p>\n\n<p><em>EDIT</em></p>\n\n<p>Here is a version that doesn't flatten the iterator:</p>\n\n<pre><code>class ViewPlane(object):\n def __init__(self, resolution, pixel_size, gamma):\n self.resolution = resolution\n self.pixel_size = pixel_size\n self.gamma = gamma\n\n def row_iter(self, row):\n for column in xrange(self.resolution[1]):\n origin_x = self.pixel_size * self.resolution[0] / 2.0 + 0.5\n origin_y = self.pixel_size * self.resolution[1] / 2.0 + 0.5\n origin = (origin_x, origin_y, 100)\n ray = Ray(origin = origin, direction = (0.0, 0.0, -1.0) )\n\n yield ray, (row, column)\n\n def __iter__(self):\n for row in xrange(self.resolution[0]):\n yield self.row_iter(row)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T18:30:30.570", "Id": "3853", "Score": "0", "body": "well, there are many things to be said. Thank you for your precious feedback. I'll answer you point by point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T18:32:25.653", "Id": "3854", "Score": "0", "body": "`Defining a class inside the method just serves to make things complicated and hard to read. Define the class outside of the method.`. Agreed. I wanted to push the limit with that code in order to stress my understanding of closures and the general feeling. It's not production code, it's *let's see what happens* code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T18:34:24.843", "Id": "3855", "Score": "0", "body": "`Having return at the end of a function doesn't do anything and makes it look like you don't know what you are doing`. That return was supposed to be a raise StopIteration, and I just didn't change it before posting. I wasn't concerned with that, but you are right that both (return or raising) are useless in that context." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T18:37:25.857", "Id": "3856", "Score": "0", "body": "`Unless you really need to access the data row by row I suggesting flattening the iterator.` I need to iterate by row because I render by row, and at each completed row I refresh the GUI. It's easier to roll over the rows, and inside that, roll over the columns. I may also flatten, roll over the pixels and refresh at each new row, but as I said, I'm stressing my knowledge for fun and profit. I wouldn't write that code in production, ever." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T18:38:05.997", "Id": "3857", "Score": "0", "body": "@Stefano Borini, why are you asking for a code review on push your limit code? The whole point of a code review is for helping make it production ready" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T18:38:06.697", "Id": "3858", "Score": "0", "body": "`Stylistically, I prefer to break expressions up rather then trying to split them across several lines as you've done. I think it produces less clutter.` Agreed. It's much more readable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T18:38:39.613", "Id": "3859", "Score": "0", "body": "`I'm not familiar enough with RayTracers to know but I question having the iterator over ViewPlane produce Ray objects.` I am porting to python a design from a book (ISBN: 978-1-56881-272-4). Code is available in C++ under GPL, but again, my objective is to tinker. I tend to follow the book, as introducing variations may make more difficult working on the code in the next chapters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T18:42:45.477", "Id": "3860", "Score": "0", "body": "@Winston : I assumed code review SE was to comment on snippets, not to rework for production ready." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T18:45:20.423", "Id": "3861", "Score": "0", "body": "One comment though: your design yields a continuous stream of Ray instances, not a continuous stream of Rows. I want to iterate on rows first, and then iterate on pixels on each row next. In other words, you need an intermediate Row object which is an explicit class. You can't obtain the same effect without such class but only through smart use of functions and generators, can you ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T18:51:15.630", "Id": "3862", "Score": "0", "body": "@Stefano, its just that your code works and you know its not the best way of writing, what did you hope to get out of asking for code review?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T18:56:38.497", "Id": "3863", "Score": "0", "body": "@Stefano, I've added a version which doesn't flatten the iterator and also doesn't introduce a new class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T20:31:07.487", "Id": "3865", "Score": "0", "body": "@Winston: that's very, very nice. I guess I will have to study again generators. I seldom use them. Thanks." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T18:12:39.127", "Id": "2443", "ParentId": "2424", "Score": "4" } } ]
{ "AcceptedAnswerId": "2443", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-15T21:14:13.107", "Id": "2424", "Score": "6", "Tags": [ "python", "iterator", "raytracing" ], "Title": "Iterator over row and columns" }
2424
<p><strong>How can I improve this PHP MySql Rank generation function?</strong><br> <em>(Mostly looking to improve <strong>speed</strong>, but any feedback is very welcome)</em> </p> <p>Right now I keep <strong>stats</strong> and <strong>ranks</strong> in 2 separate tables. The only problem with this is I don't know how combine the select and update queries to possibly increase speed by cutting the PHP processing of the results and the update out of it. Also this function is very time consuming. It takes about 5-10 minutes to process 300,000+ ranks. This isn't really too bad, except I have to do this 50+ times. I do like how it doesn't lock up my database because getting the ranks only takes a few seconds, and all the updates are done individually, which leaves room for other queries to process instead of locking for 5-10 minutes each time. </p> <pre><code>function get_ranking($rank, $rank_order, $DBH, $test_mode=true) { $test_mode == true ? $limter = ' LIMIT 50' : $limter = ''; $query0 = 'SET @rank=0'; $query1 = 'SELECT @rank:=@rank+1 AS rank, player_id FROM player_stats ORDER BY '.$rank_order.$limter; try { $DBH-&gt;exec($query0); $qh = $DBH-&gt;prepare($query1); $qh-&gt;setFetchMode(PDO::FETCH_ASSOC); if ($qh-&gt;execute()) { while ($result = $qh-&gt;fetch()) { $query2 = 'UPDATE `player_ranks` SET '.$rank.' = \''.$result['rank'].'\' WHERE `player_id` =\''.$result['player_id'].'\''; $qh2 = $DBH-&gt;prepare($query2); $qh2-&gt;execute(); } return true; } return false; } catch (PDOException $e) { save_PDO_error_to_file($e); return false; } } </code></pre> <p>Thanks for any advice/feedback/help!</p>
[]
[ { "body": "<p>It seems like you're just ordering <code>player_stats</code> by some passed-in column and then going through numbering the result starting at 1. It might be simpler to forget storing explicit <code>rank</code> in your DB, and instead implement the numbering on the view layer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T13:52:27.510", "Id": "3843", "Score": "0", "body": "Interesting idea... unfortunately that would void the purpose of this function. I already have what you suggest on a leader-board that I generate with a different function (just slightly different). The purpose of this function is to make each players rank (in each of the 50+ categories) readily accessible for their viewing without having to calculate it out every time the data is accessed. Even numbering it in the view-model for 50x+ 300k+ ranks would be too costly (I have to generate my leader-board on a cron job)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T13:10:28.190", "Id": "2436", "ParentId": "2425", "Score": "1" } }, { "body": "<p>Something you might try is keeping everything inside the database. Using the <code>SELECT</code>, create a temporary table:</p>\n\n<pre><code>CREATE TEMPORARY TABLE tmp_ranks (rank int auto_increment primary key, player_id int)\nAS SELECT NULL AS rank, player_id AS player_id FROM player_stats\nORDER BY '.$rank_order.$limter\n</code></pre>\n\n<p>This should give you a table that looks like</p>\n\n<pre><code>| rank | player_id |\n+------+-----------+\n| 1 | 123456789 |\n| 2 | 123456780 |\n</code></pre>\n\n<p>Now, using an <code>UPDATE</code> with a <code>JOIN</code>, update your <code>player_ranks</code> table:</p>\n\n<pre><code>UPDATE player_ranks, tmp_ranks SET player_ranks.$rank = tmp_ranks.rank\nWHERE player_ranks.player_id = tmp_ranks.player_id;\n</code></pre>\n\n<p>This <em>should</em> run fairly quickly, but given your data size, could take a while. I'd suggest testing it on a non-production box first, in case it locks things up for a good while.</p>\n\n<p>Note that I left your PHP variables inline, so you'll need to fix those.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T15:24:42.740", "Id": "3918", "Score": "0", "body": "You have a good point. I originally used this statement similar to this to update my ranks: `UPDATE dbTable SET rank_fd = @rank := @rank + 1 ORDER BY fd2 DESC, fd3 DESC;`. It was still very slow and locked up my database during the update (which locked up my website). My testing box(i7 920, 6GB RAM, 4x 320GB Raid 0) is a beast in comparison to my server (only a P4, 2GB ram, 250GB HDD). The server runs about 5x+ slower. I'm not familiar with `JOIN`s and `TEMPORARY` tables. I'll have to go test this out though, looks interesting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T15:31:52.937", "Id": "3919", "Score": "0", "body": "I also thought about splitting the queries into smaller queries using `LIMIT`(to fit in php memory, querying all data won't fit) and getting the results for each section and doing a single update query for each player. I'm not really sure if that will be faster, but I'm thinking it would at least cut down on some of the php processing overhead and should cut down on some of the sql overhead(going from 15M update queries to 300K)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T01:41:50.167", "Id": "2474", "ParentId": "2425", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T02:18:02.660", "Id": "2425", "Score": "4", "Tags": [ "php", "mysql", "pdo" ], "Title": "How can I improve this PHP MySql Rank generation function?" }
2425
<pre><code>private string FormatComments(string comments) { //If comments has no space and inserted as a single line then following code will break //the comments into multiple lines. StringBuilder sb = new StringBuilder(); int c = 65; int l = comments.Length; if (l &lt; c) return comments; int r = l % c; int lines = (l - r) / c; if (lines == 0) return comments; int index = 0; for (int i = 0; i &lt; lines; i++) { if (index &gt; comments.Length) break; string indexVal = comments[index + c].ToString(); sb = sb.AppendLine(comments.Substring(index, c) + (indexVal == " " ? "" : "- ")); index = index + c; } if(r &gt; 0) sb = sb.AppendLine(comments.Substring(index, r)); return sb.ToString(); } </code></pre> <p>&nbsp;</p> <pre><code>private void SaveValuesInViewState() { string[] roomStr = this.RoomsString.Split('~'); List&lt;Room&gt; rooms = new List&lt;Room&gt;(); Room room = null; foreach (string str in roomStr) { room = new Room(); string[] vals = str.Split('|'); // room.NoOfRooms = Convert.ToInt32(vals[0]); room.Type = (RoomType)Enum.Parse(typeof(RoomType), vals[1]); room.NumberOfCots = Convert.ToInt32(vals[2]); string[] childInfo = vals[3].Split('^'); if (Convert.ToInt32(childInfo[0]) &gt; 0) { foreach (string age in childInfo[1].Split(',')) { room.ChildrenAges.Add(Convert.ToInt32(age)); } } rooms.Add(room); } this.Rooms = rooms; } </code></pre>
[]
[ { "body": "<p>Using a lower-case \"el\" as an identifier is a bad practice. It is easy to confuse it with the literal 1 in many fonts.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T17:16:37.307", "Id": "3915", "Score": "4", "body": "Then use a better font. (l is bad for being cryptic regardless, but one should use a font that makes the difference clear when coding)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T16:28:14.707", "Id": "2441", "ParentId": "2426", "Score": "5" } }, { "body": "<p>1) You're introducing too many variables, understanding the code tends to be less easy more variables (useless variables) you have and more mutable they are. In your first method I would remove <code>l</code> and <code>r</code> variables. Instead of <code>l</code> you can simply use <code>comments.Length</code> and <code>r</code> is not that needed (see next point). I would also remove <code>lines</code> and <code>i</code> iterator, <code>index</code> can be used instead: </p>\n\n<pre><code>for (int index = 0 ; index &lt;= comments.Length ; index += c) { }\n</code></pre>\n\n<p>2) Following condition seems to be useless, I can't imagine any reasonable values for <code>comments.Length</code> and <code>c</code> which would make this condition to be <code>true</code> keeping in mind that we have already checked that <code>l &gt;= c</code>: </p>\n\n<pre><code> int r = l % c;\n int lines = (l - r) / c;\n\n if (lines == 0)\n return comments; \n</code></pre>\n\n<p>3) <strong>Use less crypty names for variables</strong>. We do not do math here. Why <code>c</code>? I can guess it probably but I won't like to. </p>\n\n<p>4) Why <code>string</code> here? It is definitely a <code>char</code>:</p>\n\n<pre><code>string indexVal = comments[index + c].ToString(); \n</code></pre>\n\n<p>5) Do not introduce <code>room</code> variable in second method <strong>outside</strong> of loop. It is used only inside so it should be defined there. </p>\n\n<p>6) You use overcomplicated format in for rooms in second method, especially around child ages. Right now you have something like this: <code>5|1|3|0~5|1|3|2^8,10</code>. You have 4 different separators here, but I think <code>^</code> can be safely removed. Just put there ages if you have any or leave empty you have no children ages. You should be definitely able to parse this instead: <code>5|1|3|~5|1|3|8,10</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T20:50:03.767", "Id": "3885", "Score": "1", "body": "I would recommend using a good serialization format for your view model data. Take a look at JSON.net. `JsonConvert.SerializeObject(rooms)` and `JsonConvert.Deserialize<List<Room>>(jsonString)` would be all code required to get your data back and forth." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T19:46:43.733", "Id": "2445", "ParentId": "2426", "Score": "8" } }, { "body": "<p>I agree with all the comments posted so far but no one has explicity addressed the magic number 65 referenced by 'c'. Don't use magic numbers, given enough time they will bite you in the butt!! </p>\n\n<p>It's better to pass in the these types of constraints. So I would refactor the code to either be:</p>\n\n<pre><code>private string FormatComments(string comments, int characterLimit) { ... } \n</code></pre>\n\n<p>or make it a class member, which I think is better:</p>\n\n<pre><code>private string FormatComments(string comments) \n{ \n ...\n\n if( comments.length &lt; this.CharacterLimit ) \n return comments; \n\n int overflow = comments.length % this.CharacterLimit; \n int lines = (comment.length - overflow) / this.CharacterLimit; \n\n ...etc... \n} \n</code></pre>\n\n<p>Finally, again -- just to restate, don't use one letter variable names unless it's i, j, k, n, or x or unless your function is less than 3 lines long. Never use 'l' for a variable name, go ahead and spell out 'len' if you are storing a length. </p>\n\n<p>Remember, you write code for other programmers. BTW, consider yourself in the \"other programmers\" group because a year from now when you are debugging your old code you'll appreciate that you took the time to write readable code; don't take shortcuts. Check out <a href=\"http://cleancoders.com\" rel=\"nofollow\">http://cleancoders.com</a> for tips and ideas.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T14:17:10.400", "Id": "2466", "ParentId": "2426", "Score": "3" } }, { "body": "<p>As others have mentioned, the big things are:</p>\n\n<ul>\n<li>Try using more descriptive names for your variables (<code>MaxLineLength</code>, <code>comments.Length</code>, <code>charsOnLastLine</code>, etc.)</li>\n<li>Make <code>c</code> a constant (<code>const int MaxLineLength = 65</code>), a class variable or an argument to the method.</li>\n</ul>\n\n<p>I would move <code>StringBuilder sb = new StringBuilder();</code> down close towards the for loop. If <code>l &lt; c</code> (or indeed <code>lines == 0</code> somehow) then you will have wasted creating a <code>StringBuilder</code> for no reason.</p>\n\n<p>You do not need to assign <code>sb</code> back to <code>sb</code>. You can just do <code>sb.AppendLine(…);</code>. <code>StringBuilder</code> is a mutable object, and any operations (such as <code>AppendLine</code>) change the state of <code>StringBuilder</code>. The reason why you need to do things like <code>stringVar = stringVar + \"bar\"</code> is because <code>string</code> is immutable, and all operations create new strings because the original string can't be changed.</p>\n\n<p>There is no need to convert indexVal to a string.</p>\n\n<pre><code>char indexVal = comments[index + MaxLineLength];\nsb = sb.AppendLine(comments.Substring(index, MaxLineLength) + (indexVal == ' ' ? \"\" : \"- \"));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-21T10:32:34.920", "Id": "2521", "ParentId": "2426", "Score": "0" } } ]
{ "AcceptedAnswerId": "2445", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T05:25:00.733", "Id": "2426", "Score": "4", "Tags": [ "c#", ".net", "asp.net" ], "Title": "Comment formatter" }
2426
<p>I had to find the corresponding process for a windows service the other day, and I kept on getting this one exception. I've spent some time researching the exception only to find that this exception will occur if the process is terminating, Hence my question, is it really that bad to catch expected exceptions ?</p> <p>Sample Code:</p> <pre><code>try { if (proc.MainModule.FileName == controller.ImagePath) { //Logic goes here } } catch (System.ComponentModel.Win32Exception ex) { // Thrown if process is already terminating, // the process is a Win16 exe or the process // could not be accessed. MyLogger.Debug( "The following Win32Exception occurred while trying to access the MainModule information: " + ex.ToString()); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T20:38:12.497", "Id": "3866", "Score": "1", "body": "and who told you it was bad to catch expected exceptions? If you didn't expect the exception, how are you supposed to catch it?" } ]
[ { "body": "<p>Sometimes they are hard to avoid, as in your example. I would consider it bad practice only in cases where the exception is easy to avoid (e.g. by testing the sign before calculating the square root).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T08:38:47.227", "Id": "2430", "ParentId": "2429", "Score": "3" } }, { "body": "<p>In general, if we assume that the exception is going to be thrown (i.e. there's no simple / cheap / reliable way to avoid it), then there is nothing wrong with catching it. However, the question is whether you are going to achieve much by doing so.</p>\n\n<ul>\n<li><p>If the exception is complaining about something that the end user is likely to be able remedy, then reporting it with a <em>helpful</em> and <em>informative</em> message is a good ides.</p></li>\n<li><p>If the exception is complaining about something that the end user won't understand and won't be able to remedy, then the best idea would be to let it propagate, catch it at the top level (e.g. using a root exception class), log it, and then tell the user to contact \"support\".</p></li>\n</ul>\n\n<p>The other thing that you have to watch for is that you don't \"squash\" the exception. For instance, your code looks like it might be catching an exception with serious consequences, logging it as a \"minor\" issue (level == debug) ... and then continuing as if nothing bad had happened. This approach is a bad idea. It makes bugs harder to find than if you'd just let the exception propagate and produce an ugly stack trace ... or whatever.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T10:00:21.183", "Id": "2432", "ParentId": "2429", "Score": "4" } }, { "body": "<p>In general, only use exceptions for exceptional cases. Everything which could be written using normal conditional checks should be written as such. (Hence the name <strong>exceptions</strong>.)</p>\n\n<p>In your particular scenario, you should wonder why the process is being terminated. Is there no way you could prevent the exception from being thrown? Perhaps you could solve the issue better by attaching logic to the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited.aspx\" rel=\"nofollow\"><code>Exited</code> event</a>. It all depends on what your sample code is doing.</p>\n\n<p>A simplified <strong>wrong</strong> example:</p>\n\n<pre><code>int[] ints = new[] { 0, 1, 2 };\ntry\n{\n Console.WriteLine( ints[ 10 ] );\n}\ncatch ( IndexOutOfRangeException ) {}\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>int[] ints = new[] { 0, 1, 2 };\nint toDisplay = 10;\nif ( toDisplay &lt; ints.Length )\n{\n Console.WriteLine( ints[ toDisplay ] );\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-21T08:11:05.680", "Id": "3977", "Score": "0", "body": "\"Hence the name exceptions\" - with that attitude we'd never have invented rugby." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T12:52:49.917", "Id": "2435", "ParentId": "2429", "Score": "2" } }, { "body": "<p>There are some exceptions I classify as \"exogenous\" exceptions. That is, they are exceptions that state \"the world is not how you assumed it would be, and we can't do the thing you asked\". The problem with exogenous exceptions is that the world is constantly changing. You think you're going to be able to access that file, and then someone changes its permissions from another process, or the tape drive catches on fire, or someone unplugs the router, or whatever, and oops, you can't access the file after all.</p>\n\n<p>Exogenous exceptions are precisely the ones you should be catching; they indicate situations that are rare enough and dangerous enough to reasonably be exceptions, but common enough that you can have some clue ahead of time as to what they are, and reasonably recover from them.</p>\n\n<p>The other class of exceptions you need to catch are the \"vexing\" exceptions. That is, the exceptions where someone wrote you a library that communicates with you via exceptions in non-exceptional circumstances. Ideally you should never write a library that requires the developer to catch a vexing exception; rather, expose tools that allow them to prevent the exception.</p>\n\n<p>For example, suppose you write a method that turns a string into an int. You might say</p>\n\n<pre><code>public static int Parse(string s) { ... }\n</code></pre>\n\n<p>And if the string is malformed, it throws an exception. That is vexing! The developer might have a string where they don't know whether it is well-formed or not, because a user typed it in. The work they have to do to avoid the exception is equivalent to simply not calling the method in the first place. A better way to do it is:</p>\n\n<pre><code>public static bool IsWellFormedIntString(string s) { ... }\npublic static int Parse(string s) { ... }\n</code></pre>\n\n<p>or</p>\n\n<pre><code>public static int? Parse(string s) { ... }\n</code></pre>\n\n<p>or</p>\n\n<pre><code>public static bool TryParse(string s, out int result) { ... }\n</code></pre>\n\n<p>Or whatever; there are lots of ways to avoid the vexing exception situation.</p>\n\n<p>More thoughts on this topic here:</p>\n\n<p><a href=\"http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx\">http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T20:25:04.117", "Id": "3864", "Score": "2", "body": "I must disagree regarding \"vexing\" exceptions. Why is a bool return value better then an exception?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T20:50:11.293", "Id": "3867", "Score": "1", "body": "@winston ...especially considering the exception may give us a clue what the problem is where the bool tells us nothing other than that something is wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T21:18:51.090", "Id": "3868", "Score": "5", "body": "@Winston: Exceptions are slow. Exceptions are noisy when you're debugging. Many high-reliability products are configured to log all exceptions and treat them as bugs. (I once added a by-design exception on a common control path in Active Server Pages and boy, did I hear about that the day afterwards, when suddenly their error logs had several hundred thousand new entries.) Exceptions are intended to represent *exceptional* situations, not common situations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T22:00:13.283", "Id": "3869", "Score": "1", "body": "@Eric Lippert, the way I see it, code using \"vexing\" exceptions is more readable and less error-prone then code that doesn't. TEverything else should follow from what makes code readable, not the other way around. Language implementers should make exceptions faster, debuggers should handle such exceptions better, and loggers shouldn't assume that all exceptions are bugs. Having said that, you have to follow the guidelines of your language/code base. If exceptions are frowned upon, then you can't use them. But nothing in the feature itself restricts it to only being useful in exceptional cases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T04:53:36.917", "Id": "3870", "Score": "6", "body": "@Winston: Even if exceptions were cheap and so on, they'd still be a lousy control flow best left to exceptional circumstances. **An exception is a goto without even a label**. Their power comes at an extremely high cost; it becomes impossible to understand the flow of the program using only local analysis; the whole program must be understood. This is especially true when you mix exceptions with more exotic control flows like event-driven or asynchronous programming. Avoid, avoid, avoid; use exceptions only in the most exceptional circumstances, where the benefits outweigh the costs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T14:08:53.803", "Id": "3880", "Score": "2", "body": "@Eric, I agree that exceptions can be used in a way that makes it impossible to understand the flow of the program. However, this isn't true if the \"vexing\" exceptions are caught as soon as they are thrown. (I.e. the function that calls ParseInt catching the ParseIntError) If the exception isn't caught that quickly its really a boneheaded error because its a bug in your program, an error happened that you thought couldn't happpen." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T15:58:27.040", "Id": "2440", "ParentId": "2429", "Score": "13" } } ]
{ "AcceptedAnswerId": "2440", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T07:59:55.437", "Id": "2429", "Score": "9", "Tags": [ "c#" ], "Title": "Is catching 'expected' exceptions that bad?" }
2429
<p>This is an emulator I am currently re-writing for my Operating Systems course. It is a simple emulator that is supposed to represent hardware, OS, etc. It is strictly for learning purposes and I want to propose my solution to the teacher as a method of modern C++ (since his solution is more "C with classes"). </p> <p>However, before I do that, I would like to make sure I don't embarrass myself with bad code.</p> <p>Right now I'm debating on my association between hardware and OS. They are currently written like so:</p> <pre><code>// Hardware.h class OS; class Hardware : boost::noncopyable { friend class OS; private: Hardware(OS *os); void load_job(boost::shared_ptr&lt;Job&gt; job); void run_job(); private: void execute_instruction(Instruction const&amp; instruction); void handle_interrupt(Instruction const&amp; trap); private: enum { NumberOfRegisters = 32 }; enum { InstructionMemorySize = 1024 }; enum { DataMemorySize = 1024 }; OS *m_pOS; std::vector&lt;int&gt; m_Registers; boost::ptr_vector&lt;Instruction&gt; m_InstructionMemory; std::vector&lt;int&gt; m_DataMemory; boost::optional&lt;int&gt; m_Counter; }; // OS.h class Hardware; class OS : boost::noncopyable { friend class Hardware; public: OS(); // Load jobs void boot(); // Execute jobs void run(); private: // "Interrupts" void trap_halt(int status); void trap_getw(int&amp; receiver); void trap_putw(int value); void trap_dump(); void time_elapsed(); private: void get_next_job(); private: boost::scoped_ptr&lt;Hardware&gt; m_pHardware; boost::scoped_ptr&lt;Parser&gt; m_pParser; boost::ptr_deque&lt;Job&gt; m_Jobs; boost::ptr_deque&lt;Job&gt; m_JobsInProgress; }; </code></pre> <p>The question is: I don't want the <code>Hardware</code> to be accessible by any other class other than OS. Declaring Hardware private and friending OS is a step in the right direction, but it bothers me that OS now has access to <strong>all</strong> functions. Is there a way I can restrict <code>OS</code>?</p> <p>Also, I did some researching on callbacks, but the C++ FAQ suggests that you shouldn't make callbacks to member functions of a class. Are there other solutions such that my <code>Hardware</code> class does not need a pointer to <code>OS</code> in order to call its functions? </p> <p>Secondly, I'm wondering, at what point does the <code>pImpl</code> idiom become a viable solution? I mean, how large does a class have to be, or how many includes must it have, to seriously consider moving the class into a <code>struct</code>?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T16:51:59.923", "Id": "97025", "Score": "0", "body": "[Boost.Signal](http://www.boost.org/doc/libs/1_46_0/doc/html/signals.html)\nalso provides good tools for implementing callbacks." } ]
[ { "body": "<p>That's not what friends are for. Friends are for tightly integrated classes which need to be able to play with each other's private data. OS and Hardware are not tightly related; they interact through a specifically designed interface.</p>\n\n<p>If you don't want other classes besides OS to call the hardware functions, don't write code in those other classes which call the hardware functions. Better yet, simply only give the Hardware pointer to the OS class so only it can call the hardware functions.</p>\n\n<p>For callbacks have a look at the boost::function library. It will allow you to create callbacks to the OS methods. You can create pointers to methods but you need both the method pointer and the object point for it to work. Boost::function hides all of this behind the scenes. </p>\n\n<p>pImpl is workaround because C++ is such a silly language. Its purpose is to make it so that you do not have to recompile the header file whenever the private members of the class change. More modern languages essentially do this automatically for all classes. pImpl makes sense only when your compile times get too large. A class project probably doesn't get large enough for that to be a big concern.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T16:06:59.093", "Id": "3846", "Score": "0", "body": "I might have been confusing myself a little, but I wanted to protect my Hardware class from being accessed by another programmer. This friendship would have prevented other class from wrongfully calling Hardware. I was approaching this from a mentality, that a student would want to create changes to my design; this should have been a clear indicator to stay the hell away from my Hardware class. Do you agree with this assertion, or am I overcomplicating my design with this thinking?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T17:04:39.433", "Id": "3848", "Score": "0", "body": "@SoulBeaver, the question here is why you are trying to prevent students from making changes to your design." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T17:05:51.977", "Id": "3849", "Score": "1", "body": "@SoulBeaver: Think of what interface you want your Hardware class to have and write that, then do the same with OS. Having the OS take a pointer to an instance of a Hardware makes the relationship between them clear and allows for alternative implementations of both OS and Hardware to still reuse parts of your code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T14:21:22.477", "Id": "2438", "ParentId": "2437", "Score": "8" } } ]
{ "AcceptedAnswerId": "2438", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T13:50:43.757", "Id": "2437", "Score": "10", "Tags": [ "c++", "boost" ], "Title": "Emulator for representing hardware and operating systems" }
2437
<p>Before I tried to <a href="http://www.mssqlcity.com/Tips/tipCursor.htm" rel="nofollow">avoid using cursor</a> because of performance issues. But now I have to do some calculations to reach some goals. I have a stored procedure that has a code like this:</p> <pre><code>DECLARE Outer_Cursor CURSOR FOR... OPEN Outer_Cursor FETCH NEXT FROM Outer_Cursor INTO ... WHILE @@FETCH_STATUS = 0 BEGIN DECLARE Inner_Cursor CURSOR FOR... OPEN Inner_Cursor FETCH NEXT FROM Inner_Cursor INTO ... WHILE @@FETCH_STATUS = 0 BEGIN ... FETCH NEXT FROM Inner_Cursor INTO ... END CLOSE Inner_Cursor DEALLOCATE Inner_Cursor FETCH NEXT FROM Outer_Cursor INTO ... END CLOSE Outer_Cursor DEALLOCATE Outer_Cursor </code></pre> <p>Is it possible to avoid (minimize) so expensive cursor recreation for inner cursor. How can I reuse inner cursor declaration, if it is possible? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-01T18:05:24.053", "Id": "4302", "Score": "2", "body": "it might be easier for someone to give you an answer if you actually post what is going into the cursors" } ]
[ { "body": "<p>If the inner cursor can be run through one time, create a table variable and store the results there to be re-used before working within the outer cursor.</p>\n\n<p>And as far as calculations go, is it possible to do away with the cursors by using common table expressions?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-13T04:21:33.347", "Id": "4067", "ParentId": "2439", "Score": "2" } }, { "body": "<p>Best practice is to do away with cursors. Both of them. There is always a better-performing solution.</p>\n\n<p>If possible, reduce the problem to one that can be solved with sets instead of iteration.</p>\n\n<p>But, if this nested iteration cannot be avoided, you will still get far better performance using table variables and WHILE loops instead of a cursor. For example:</p>\n\n<pre><code>DECLARE @outerData TABLE (outerID INT, outerColumn VARCHAR(50), PRIMARY KEY (outerID))\nDECLARE @innerData TABLE (innerID INT, innerColumn VARCHAR(50), PRIMARY KEY (innerID))\nDECLARE @currOuter INT\nDECLARE @currInner INT\n\nINSERT INTO @outerData\nSELECT EmployeeID, EmployeeName\nFROM dbo.Employee\n\nWHILE EXISTS (SELECT outerID FROM @outerData)\nBEGIN\n SELECT @currOuter = TOP outerID FROM @outerData\n\n INSERT INTO @innerData\n SELECT SaleID, SaleDesc\n FROM EmployeeSales \n WHERE EmployeeID = @outerID\n\n WHILE EXISTS (SELECT innerID FROM @innerData)\n BEGIN\n SELECT @currInner = TOP innerID FROM @innerData\n\n --Do work with inner data\n\n ...blah-de-blah...\n\n --Delete after work is finished\n DELETE FROM @innerData WHERE innerID = @currInner\n END\n\n --Delete current outerID and empty the innerdata table \n --to prepare to move to the next record\n\n DELETE FROM @outerData WHERE outerID = @currOuter\n DELETE FROM @innerData\nEND\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T17:13:33.827", "Id": "6877", "ParentId": "2439", "Score": "5" } } ]
{ "AcceptedAnswerId": "6877", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T14:54:34.400", "Id": "2439", "Score": "4", "Tags": [ "performance", "sql", "sql-server" ], "Title": "Inner cursor performance issues" }
2439
<p>I need to implement a TCP client application. The client and the server send messages to each other. I want to make this program scalable enough to handle connections to multiple servers at the same time. It seems like asynchronous sockets is the way to go for this. I'm new to C# so I'm pretty sure I don't know what I'm doing here. I wrote some classes and a simple console program to get started with. Eventually, I want to create a Windows Forms application but I want to start small and simple first. The <code>Client</code> class runs in its own thread. Is this all thread-safe and correctly done? It's a lot of code and I tried to cut out some fat.</p> <p>Program.cs</p> <pre><code> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace FastEyeClient { class Program { static void Main(string[] args) { Client client = new Client(); client.ConnectEvent += new ConnectEventHandler(OnConnect); client.SetLiveStatusEvent += new SetLiveStatusEventHandler(OnSetLiveStatus); client.Connect("hostname", 1987); Thread.Sleep(1000); client.SetLiveStatus("hostname", true); } private static void OnConnect(object sender, ConnectEventArgs e) { Console.WriteLine(e.Message); } private static void OnSetLiveStatus(object sender, SetLiveStatusEventArgs e) { Console.WriteLine(e.Message); } } } </code></pre> <p>Client.cs</p> <pre><code> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; namespace FastEyeClient { public delegate void ConnectEventHandler(object sender, ConnectEventArgs e); public delegate void SetLiveStatusEventHandler(object sender, SetLiveStatusEventArgs e); public class Client : IDisposable { public event ConnectEventHandler ConnectEvent; public event SetLiveStatusEventHandler SetLiveStatusEvent; ServerManager m_Manager; EventWaitHandle m_WaitHandle; readonly object m_Locker; Queue&lt;Event&gt; m_Tasks; Thread m_Thread; public Client() { m_Manager = new ServerManager(this); m_WaitHandle = new AutoResetEvent(false); m_Locker = new object(); m_Tasks = new Queue&lt;Event&gt;(); m_Thread = new Thread(Run); m_Thread.Start(); } public void EnqueueTask(Event task) { lock (m_Locker) { m_Tasks.Enqueue(task); } m_WaitHandle.Set(); } public void Dispose() { EnqueueTask(null); m_Thread.Join(); m_WaitHandle.Close(); } private void Run() { while (true) { Event task = null; lock (m_Locker) { if (m_Tasks.Count &gt; 0) { task = m_Tasks.Dequeue(); if (task == null) { return; } } } if (task != null) { task.DoTask(m_Manager); } else { m_WaitHandle.WaitOne(); } } } public void Connect(string hostname, int port) { EnqueueTask(new ConnectEvent(hostname, port)); } public void SetLiveStatus(string hostname, bool status) { EnqueueTask(new SetLiveEvent(hostname, status)); } public void OnConnect(bool isConnected, string message) { if (ConnectEvent != null) { ConnectEvent(this, new ConnectEventArgs(isConnected, message)); } } public void OnSetLiveStatus(string hostname, string message) { if (SetLiveStatusEvent != null) { SetLiveStatusEvent(this, new SetLiveStatusEventArgs(hostname, message)); } } } } </code></pre> <p>Server.cs</p> <pre><code> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace FastEyeClient { public class Server { private ServerManager m_Manager; private string m_Hostname; private bool m_IsLive; private class StateObject { public Socket AsyncSocket = null; public const int BufferSize = 1024; public byte[] Buffer = new byte[BufferSize]; public StringBuilder Builder = new StringBuilder(); } public Server(ServerManager manager, Socket socket) { try { m_Manager = manager; IPEndPoint endPoint = (IPEndPoint)socket.RemoteEndPoint; IPAddress ipAddress = endPoint.Address; IPHostEntry hostEntry = Dns.GetHostEntry(ipAddress); Hostname = hostEntry.HostName; IsLive = false; StateObject state = new StateObject(); state.AsyncSocket = socket; socket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); } catch (Exception) { } } public string Hostname { get { return m_Hostname; } set { m_Hostname = value; } } public bool IsLive { get { return m_IsLive; } set { m_IsLive = value; } } private void ReceiveCallback(IAsyncResult result) { try { StateObject state = (StateObject)result.AsyncState; Socket socket = state.AsyncSocket; int read = socket.EndReceive(result); if (read &gt; 0) { state.Builder.Append(Encoding.ASCII.GetString(state.Buffer, 0, read)); if (state.Builder.Length &gt; 1) { string messages = state.Builder.ToString(); ParseMessages(messages); } } StateObject newState = new StateObject(); newState.AsyncSocket = socket; socket.BeginReceive(newState.Buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), newState); } catch (Exception) { } } private void ParseMessages(string messages) { string[] messagesArray = messages.Split('\n'); foreach (string message in messagesArray) { string[] tokens = message.Split(','); if (tokens[0].Contains("@")) { ParseServerMessage(tokens); } } } private void ParseServerMessage(string[] tokens) { tokens[0].Remove(0, 1); if (tokens[0] == "4") { bool status; if (tokens[1] == "0") { status = false; m_Manager.SetLiveStatus(m_Hostname, status); } else if (tokens[1] == "1") { status = true; m_Manager.SetLiveStatus(m_Hostname, status); } } } } } </code></pre> <p>ServerManager.cs</p> <pre><code> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace FastEyeClient { public class ServerManager { private Client m_Client; private Dictionary&lt;string, Server&gt; m_Servers; private object m_Locker; public ServerManager(Client client) { m_Client = client; m_Servers = new Dictionary&lt;string, Server&gt;(); m_Locker = new object(); } public void AddServer(string hostname, int port) { try { IPAddress[] IPs = Dns.GetHostAddresses(hostname); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.BeginConnect(IPs, port, new AsyncCallback(ConnectCallback), socket); } catch (Exception) { bool isConnected = false; string message = "Could not connect to server."; m_Client.OnConnect(isConnected, message); } } private void ConnectCallback(IAsyncResult ar) { bool isConnected; string message; try { Socket socket = (Socket)ar.AsyncState; socket.EndConnect(ar); IPEndPoint endPoint = (IPEndPoint)socket.RemoteEndPoint; IPAddress ipAddress = endPoint.Address; IPHostEntry hostEntry = Dns.GetHostEntry(ipAddress); string hostname = hostEntry.HostName; lock (m_Servers) { if (m_Servers.ContainsKey(hostname)) { isConnected = false; message = "Client is already connected to server"; } else { m_Servers.Add(hostname, new Server(this, socket)); isConnected = true; message = "Successfully connected."; } } m_Client.OnConnect(isConnected, message); } catch (Exception) { isConnected = false; message = "Could not connect to server."; m_Client.OnConnect(isConnected, message); } } public void SetLiveStatus(string hostname, bool newStatus) { string message; lock (m_Locker) { if (m_Servers.ContainsKey(hostname)) { if (m_Servers[hostname].IsLive == newStatus) { message = "Server is already set to this status."; } else { m_Servers[hostname].IsLive = newStatus; message = "Successfully set new status."; } } else { message = "Server not found."; } } m_Client.OnSetLiveStatus(hostname, message); } } } </code></pre>
[]
[ { "body": "<p><H2>Thread safety stuff.</H2></p>\n\n<p><H3>Raising events</H3></p>\n\n<p>This is not thread safe:</p>\n\n<pre><code>if (SetLiveStatusEvent != null)\n{\n SetLiveStatusEvent(this, new SetLiveStatusEventArgs(hostname, message));\n}\n</code></pre>\n\n<p>The value of SetLiveStatusEvent could change after the check for null, but before you invoke it. This not an issue in the example code you posted, but would be in a more complex system. Try something like this instead:</p>\n\n<pre><code>var handler = SetLiveStatusEvent;\nif (handler != null)\n{\n handler(this, new SetLiveStatusEventArgs(hostname, message));\n}\n</code></pre>\n\n<p>When you are writing your event listeners, keep in mind that there is it possibility that they will be invoked after they have been unsubscribed from the event.</p>\n\n<p><H3>Use of Queue class with manual synchronization</H3>\nI don't see any problems with how you interact with the Queue, but in .Net 4.0 there is the System.Collection.Concurrent.BlockingCollection class that will take care of all of the synchronization logic for you.</p>\n\n<p><H2>Other stuff</H2></p>\n\n<p><H3>Explicit delegate creation</H3></p>\n\n<p>You don't need to create a new instance of a delegate.</p>\n\n<pre><code>socket.BeginConnect(IPs, port, new AsyncCallback(ConnectCallback), socket);\nclient.ConnectEvent += new ConnectEventHandler(OnConnect);\n</code></pre>\n\n<p>You can just pass the name of the method.</p>\n\n<pre><code>socket.BeginConnect(IPs, port, ConnectCallback, socket);\nclient.ConnectEvent += OnConnect;\n</code></pre>\n\n<p><H3>Empty catch clause</H3></p>\n\n<p>In the ReceiveCallback method and some other places, there are empty catch (Exception) blocks, in production code I would want to at least see the exception logged.</p>\n\n<p>Also, when possible avoid catching Exception in favor of more specific exceptions.</p>\n\n<p><H3>Auto Properties</H3></p>\n\n<p>Assuming you are using C# 4.0, you could use:</p>\n\n<pre><code>public string Hostname\n{\n get;\n set;\n}\n</code></pre>\n\n<p>Instead of:</p>\n\n<pre><code>public string Hostname\n{\n get\n {\n return m_Hostname;\n }\n set\n {\n m_Hostname = value;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-21T23:48:11.243", "Id": "2545", "ParentId": "2444", "Score": "5" } }, { "body": "<p>Running Code Analysis in Visual Studio on this code throws up a few issues, with which I shall combine some of my own remarks.</p>\n\n<h2>Program.cs</h2>\n\n<blockquote>\n<pre><code>Thread.Sleep(1000);\n</code></pre>\n</blockquote>\n\n<p>Why is this here? If it's because you're waiting for the client to connect, this is a bad idea because you don't know if the client might actually take longer than 1 second to connect. Instead, you should execute the next line inside the <code>OnConnect</code> event handler:</p>\n\n<pre><code>static void Main(string[] args)\n{\n Client client = new Client();\n client.ConnectEvent += new ConnectEventHandler(OnConnect);\n client.SetLiveStatusEvent += new SetLiveStatusEventHandler(OnSetLiveStatus);\n\n client.Connect(\"hostname\", 1987);\n}\n\nprivate static void OnConnect(object sender, ConnectEventArgs e)\n{\n Console.WriteLine(e.Message);\n client.SetLiveStatus(\"hostname\", true);\n}\n</code></pre>\n\n<p>As mjcopple said in his answer, this:</p>\n\n<blockquote>\n<pre><code>client.ConnectEvent += new ConnectEventHandler(OnConnect)\n</code></pre>\n</blockquote>\n\n<p>and its equivalent on the next line, is redundant: you should only use <code>new ConnectEventHandler</code> when you're passing in a delegate, and even then not always. Rewrite those two lines:</p>\n\n<pre><code>client.ConnectEvent += OnConnect;\nclient.SetLiveStatusEvent += OnSetLiveStatus;\n</code></pre>\n\n<blockquote>\n<pre><code>\"hostname\"\n</code></pre>\n</blockquote>\n\n<p>What sorcery is this? You've conjured a string from thin air! Where did that come from? You should avoid magic strings where possible, instead assigning them to a <code>List&lt;string&gt;</code> or <code>Dictionary&lt;string, string&gt;</code> of commonly used phrases within your application. The same can be said for <code>1987</code> in the <code>Connect</code> call: what is 1987 and where did it come from? Assign it to a resource list.</p>\n\n<h2>Client.cs</h2>\n\n<p><strong>Code Analysis Says:</strong> Implement <code>IDisposable</code> correctly.<br>\nYour <code>Client</code> class nominally implements <code>IDisposable</code>, but you've only written half the implementation. You also need a <code>Dispose(bool)</code> method, called by <code>Dispose()</code>. If called as <code>Dispose(true)</code>, it should also clean up managed resources; if it's <code>Dispose(false)</code> you should only clean up your class' resources. You also need to tell the garbage collector <em>not</em> to run the finalizer on your class because you've already implemented <code>Dispose</code>. In this case there's no difference that I can see, so a few simple modifications:</p>\n\n<pre><code>public void Dispose()\n{\n this.Dispose(true);\n GC.SuppressFinalize(this);\n}\npublic void Dispose(bool includeManaged)\n{\n EnqueueTask(null);\n m_Thread.Join();\n m_WaitHandle.Close();\n}\n</code></pre>\n\n<p><strong>Naming</strong><br>\nYou've got some strange names in this class.</p>\n\n<blockquote>\n<pre><code>EnqueueTask()\n</code></pre>\n</blockquote>\n\n<p>What is this verb \"Enqueue\"? Method names of this format should be verb-object, as in \"do this to this thing\". If <code>EnqueueTask</code> simply adds the passed object to a queue, the correct name is <code>QueueTask</code>.</p>\n\n<blockquote>\n<pre><code>m_\n</code></pre>\n</blockquote>\n\n<p>Don't prefix your names like that. If you're adding a prefix, it should still follow all the rules of variable naming for C#. For private fields, variables are named in <code>_lowerCamelCase</code>, with the underscore before it. Public properties are named in <code>PascalCase</code>. So, you can rename a number of variables, for example <code>m_client</code> should be <code>_mClient</code>.</p>\n\n<h2>Server.cs</h2>\n\n<p>I do believe I've found an error here.</p>\n\n<blockquote>\n<pre><code>IPEndPoint endPoint = (IPEndPoint)socket.RemoteEndPoint;\nIPAddress ipAddress = endPoint.Address;\nIPHostEntry hostEntry = Dns.GetHostEntry(ipAddress);\nHostname = hostEntry.HostName;\n</code></pre>\n</blockquote>\n\n<p><s>Where is <code>Hostname</code> declared? I can't find a field or property called <code>Hostname</code> in this class. If <code>Hostname</code> is a type, it needs a variable identifier after it; if it's a declaration and identifier, it needs a type before it. Were you trying to assign to <code>m_Hostname</code>?</s> I stand corrected: the property concerned does exist.</p>\n\n<p><strong>Naming</strong> - the same points apply here as to Client.</p>\n\n<blockquote>\n<pre><code>catch(Exception) {\n}\n</code></pre>\n</blockquote>\n\n<p>Did you just... catch a generic exception? <em>And</em> ignore it? You need to work out what exceptions to catch and what to do with them. In this case, you're most likely to get a <code>SocketException</code> or <code>InvalidOperationException</code>, assuming your arguments are constructed properly so you don't get an <code>ArgumentException</code> or <code>ArgumentNullException</code>. So instead of catching a generic exception, catch both of those and <em>tell</em> someone about them. Something's gone wrong and this program doesn't work, I want to know why.</p>\n\n<pre><code>catch(SocketException e)\n{\n Console.WriteLine(\"Could not receive data from the client - there was an error in the connection.\");\n Console.WriteLine(\"Error message: {0}\", e.Message);\n}\ncatch(InvalidOperationException e)\n{\n Console.WriteLine(\"Could not receive data from the client - some of the server's data is invalid.\");\n Console.WriteLine(\"Error message: {0}\", e.Message);\n}\n</code></pre>\n\n<h2>ServerManager.cs</h2>\n\n<p>This class is generally good, apart from naming. Rename your variables here and you're OK on this class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-01T10:38:37.137", "Id": "92342", "ParentId": "2444", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-16T18:36:16.597", "Id": "2444", "Score": "6", "Tags": [ "c#", "multithreading", "asynchronous", "socket" ], "Title": "Asynchronous Sockets" }
2444
<p>I need some thoughts about an approach a colleague and I am are taking with Entity Framework. Basically, the entities are represented by contracts. These contracts hold a collection of business rules so when they are finally persisted we know they are valid. We can also check the validity from Entity Framework, but that is not as important. Since EF requires you not to have a parameterized constructor we do not pass the actual domain entity into EF, but rather the contract that represents it.</p> <p>So how this works is, first a context is established. Next, we create a contract and then create the domain entity by passing it the contract. Inside the constructor of the domain entity a call to an IsValid method is made. This runs through all the business rules. If any one fails, the domain entity is considered invalid and an exception of some kind is thrown. If it is valid, we then add the contract to the context and persist the changes and pass back the domain entity. Here is some code that demonstrates the idea:</p> <pre><code> /// &lt;summary&gt; /// Interface the all Contracts will impelement /// &lt;/summary&gt; public interface IEntityContract { bool IsValid(); } /// &lt;summary&gt; /// Business Rule Loigc /// &lt;/summary&gt; public class BusinessRule&lt;TEntity&gt; where TEntity: IEntityContract { //Logic to handle business rules } /// &lt;summary&gt; /// Abstract class that represents a Base Contract /// &lt;/summary&gt; /// &lt;typeparam name="TEntity"&gt;&lt;/typeparam&gt; public abstract class EntityContract&lt;TEntity&gt;: IEntityContract where TEntity: IEntityContract { private readonly List&lt;BusinessRule&lt;TEntity&gt;&gt; _businessRules = new List&lt;BusinessRule&lt;TEntity&gt;&gt;(); public bool IsValid() { var entityIsValid = true; foreach (var businessRule in _businessRules) { //IF any rule fails the entityIsValid = fale } return entityIsValid; } protected void RegisterBusinessRule(BusinessRule&lt;TEntity&gt; rule) { _businessRules.Add(rule); } } public interface IUserContract: IEntityContract { string UserName { get; set; } string Password { get; set; } } internal sealed class UserContract: EntityContract&lt;IUserContract&gt;, IUserContract { public UserContract() { this.RegisterBusinessRule(new BusinessRule&lt;IUserContract&gt;()); this.RegisterBusinessRule(new BusinessRule&lt;IUserContract&gt;()); } public string UserName { get; set; } public string Password { get; set; } } /// &lt;summary&gt; /// Abstract class the represetn a base domain entity /// &lt;/summary&gt; /// &lt;typeparam name="TEntity"&gt;&lt;/typeparam&gt; public abstract class EntityBase&lt;TEntity&gt; where TEntity: IEntityContract { protected EntityBase(TEntity contract) { if(!contract.IsValid()) { throw new Exception("Business Rule Violation"); } } public Guid Id { get; set; } protected void BuildProperties() { //This method will iterate the TEntity properties from the contract and build the actual domain entity } } /// &lt;summary&gt; /// Class that represent a domain entity /// &lt;/summary&gt; public class User: EntityBase&lt;IUserContract&gt; { public User(IUserContract contract) : base(contract) { this.BuildProperties(); } } //Domonstration of idea public class TestClass { public void TestUserEnity() { //Using Entity Framework 4.1 we instantiate a DbContext var dataContext = new SomeEntityFrameworkDbContext(); //Create the UserContract var userContract = new UserContract {UserName = "someUserName@place.com", Password = "thePassword"}; try { //Create a new user and pass it the UserContract var user = new User(userContract); //If evertyhing goes ok, add the new eneity to the context dataContext.Add(userContract); //Persist the data dataContext.SaveChanges(); } catch (Exception) { //throw the excpetion and send back the failures } } } </code></pre>
[]
[ { "body": "<p>your <code>IUserContract</code> inherits <code>IEntityContract</code> but doesn't implement the <code>bool IsValid();</code> method, I always assumed that if you inherit an interface that you have to implement everything inside that interface.</p>\n<p>that is the only thing that I can see that looks out of place.</p>\n<p><strong>EDIT</strong></p>\n<p>as Retailcoder pointed out whatever inherits the last Interface would have to implement everything in all the interfaces in the chain. this means that inside the <code>internal sealed class UserContract</code> there should be an implementation of the <code>bool IsValid();</code> method, which there isn't.</p>\n<p>The abstract class <code>EntityBase</code> is also missing the <code>bool IsValid();</code> method</p>\n<hr />\n<h3>Merged answer</h3>\n<p>Having an Interface that only does one thing doesn't seem right to me.</p>\n<p>the way that you set up your User Class in your answer is much better than having an interface that forces you to create the User Credentials. I like that much better.</p>\n<p>I also like the new <code>IEntityContract&lt;TEntity&gt;</code> as it forces more than just a <code>IsValid</code> Method. it looks like it has more of the logic that is needed for other things that will be forced in one way or another, reducing the amount of Interfaces and eventually code.</p>\n<p>I like the new layout and structure that you have provided in your answer, it seems a lot clearer and more readable.</p>\n<p>I know that this is a review of a review, but seeing as the OP is the one that posted the review that I am reviewing (still referring back to the original review) I think that this answer is still valid.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T17:25:16.563", "Id": "57964", "Score": "0", "body": "I have never tried to inherit an interface into another interface, so I am not certain, I am running reports at this minute but I will look into it more when I am done" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T17:26:37.790", "Id": "57966", "Score": "2", "body": "An `interface` can derive from another without any problems - interfaces don't *implement* anything. You could do `public interface ISomething : ISomethingElse` and then a type that implements `ISomething` would have to implement all members from both interfaces." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T02:58:24.570", "Id": "58062", "Score": "1", "body": "@Malachi, The UserContract Inherits from EntityContract<TEntity> which implements the IsValid method. The IsValid method will be available without having to specifically implement it. We could make the IsValid virtual in the EntityContract<TEntity> so it could be overridden in the UserContract." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T16:59:24.733", "Id": "35697", "ParentId": "2448", "Score": "3" } }, { "body": "<p>Considering Entity Framework does not like parameterized constructors, I think the only solution is when the entity is attached to the context or on SaveChanges we evaluate the the entity. </p>\n\n<p>Perhaps instead of evaluating the entity directly in the context we do it in a class that employs the repository pattern. Now, this code is obviously not complete and we would want to leverage a <a href=\"http://msdn.microsoft.com/en-us/magazine/dd882510.aspx\">Unit Of Work</a> that abstracts the context, possibly. Here is the refactored code</p>\n\n<pre><code>public class User\n {\n public string Username { get; set; }\n public string Password { get; set; }\n }\n\n public interface IRepository&lt;TEntity&gt; where TEntity : class\n {\n void Create(TEntity entity);\n void Update(TEntity entity);\n void Delete(TEntity entity);\n }\n\n\n public class Repository&lt;TEntity&gt; : IRepository&lt;TEntity&gt; where TEntity : class\n {\n private readonly IEntityContract&lt;TEntity&gt; _contract;\n private readonly DbContext _context;\n\n public Repository(IEntityContract&lt;TEntity&gt; contract, DbContext context)\n {\n _contract = contract;\n _context = context;\n }\n\n public void Create(TEntity entity)\n {\n //beofre we try to create it, lets evaluate it\n if (!_contract.IsValid(entity))\n {\n //possibly throw an exception or let the client know there was an issue.\n }\n\n\n //Now implement your create code.\n _context.Add(entity);\n _context.SaveChanges();\n }\n\n public void Update(TEntity entity)\n {\n //beofre we try to update it, lets evaluate it\n if (!_contract.IsValid(entity))\n {\n //possibly throw an exception or let the client know there was an issue.\n }\n\n //Now implement your update code.\n _context.Attach(entity);\n _context.SaveChanges();\n }\n\n public void Delete(TEntity entity)\n {\n //delete code\n }\n }\n\n /// &lt;summary&gt;\n /// Interface the all Contracts will impelement\n /// &lt;/summary&gt;\n public interface IEntityContract&lt;TEntity&gt; where TEntity: class \n {\n bool IsValid(TEntity entity);\n void RegisterBusinessRule(BusinessRule&lt;TEntity&gt; rule);\n IList&lt;BusinessRule&lt;TEntity&gt;&gt; Rules { get; set; }\n }\n\n /// &lt;summary&gt;\n /// Business Rule Loigc\n /// &lt;/summary&gt;\n public class BusinessRule&lt;TEntity&gt; where TEntity : class\n {\n //Logic to handle business rules\n }\n\n\n /// &lt;summary&gt;\n /// Abstract class that represents a Base Contract\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"TEntity\"&gt;&lt;/typeparam&gt;\n public abstract class EntityContract&lt;TEntity&gt; : IEntityContract&lt;TEntity&gt; where TEntity : class\n {\n\n protected EntityContract()\n {\n Rules = new List&lt;BusinessRule&lt;TEntity&gt;&gt;();\n }\n\n protected EntityContract(IList&lt;BusinessRule&lt;TEntity&gt;&gt; rules)\n {\n Rules = rules;\n }\n\n public virtual bool IsValid(TEntity entity)\n {\n var entityIsValid = true;\n foreach (var businessRule in Rules)\n {\n //IF any rule fails the entityIsValid = false\n }\n\n return entityIsValid;\n }\n\n public IList&lt;BusinessRule&lt;TEntity&gt;&gt; Rules { get; set; }\n\n\n public void RegisterBusinessRule(BusinessRule&lt;TEntity&gt; rule)\n {\n Rules.Add(rule);\n }\n\n }\n\n public interface IUserContract : IEntityContract&lt;User&gt;\n {\n\n }\n\n public class UserContract : EntityContract&lt;User&gt;, IUserContract\n {\n\n }\n\n //Domonstration of idea\n public class TestClass\n {\n public void TestUserEntity()\n {\n\n //Using Entity Framework 4.1 we instantiate a DbContext\n var dataContext = new SomeEntityFrameworkDbContext();\n\n var respository = new Repository&lt;User&gt;(new UserContract(), dataContext);\n //Create the UserContract\n\n var user = new User()\n {\n Password = \"123456\",\n Username = \"me@domain.com\"\n };\n\n\n try\n {\n respository.Create(user);\n }\n catch (Exception ex)\n {\n\n //lets assume an excpetion gets thrown if the IsVlaid fails.\n }\n\n }\n }\n</code></pre>\n\n<p>As you can see, now we take the responsibility of validating the entity away from the entity itself. Which, I feel is better to keep the entity as clean as possible and leave any logic out of the entity. This is how I have been feeling int he past few couple years.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T14:41:28.033", "Id": "58134", "Score": "1", "body": "I was thinking that the Interfaces weren't holding much, and I was going to post something to that effect, but I was so tired last night I don't think it would have been very coherent. but it looks like you covered that here and made the interfaces do more. I approve." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T14:41:45.393", "Id": "58135", "Score": "0", "body": "please don't be afraid to down vote my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T14:34:45.403", "Id": "58586", "Score": "0", "body": "I'm reluctant to employ Repository/UoW with EF. I find it's an abstraction over an abstraction. I have yet to be convinced that `DbContext` is a bad UoW." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-24T05:36:46.463", "Id": "58765", "Score": "1", "body": "@DDiVita you can mark it as accepted, thanks for posting your answer here, many wouldn't have bothered. Is the [review monster awake?](http://meta.codereview.stackexchange.com/questions/1041/the-review-monster-is-awake)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T14:23:29.530", "Id": "35757", "ParentId": "2448", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T00:46:25.067", "Id": "2448", "Score": "15", "Tags": [ "c#", "entity-framework" ], "Title": "Constructing a Data Contract interface that can be used with Entity Framework 4.1 to ensure entity validity" }
2448
<p>After solving the error in SO (like suggested) I return now for codereview. :-)</p> <p>The task is to parse a huge file <code>dblp.xml</code> (~800 MB) presented by <a href="http://dblp.uni-trier.de/xml/">DBLP</a>. The records in this huge file do look for example like <a href="http://dblp.uni-trier.de/rec/bibtex/journals/dm/ErdosMST06.xml">this</a> or <a href="http://dblp.uni-trier.de/rec/bibtex/conf/stoc/AharoniEL85.xml">this</a>. In particular:</p> <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt; &lt;!DOCTYPE dblp SYSTEM "dblp.dtd"&gt; &lt;dblp&gt; record_1 ... record_n &lt;/dblp&gt; </code></pre> <p>I wrote some code, that shall get me ech tag of some records (will bes tored in a database).</p> <p>I adapted this approach from an article from <a href="http://www.ibm.com/developerworks/xml/library/x-hiperfparse/">IBM developerWorks</a> which refers to the article <a href="http://effbot.org/zone/element-iterparse.htm#incremental-parsing">Incremental Parsing on effbot.org</a>. Is this the correct approach for this task? Or is there a better way?</p> <pre><code>import sys import os import MySQLdb from lxml import etree def fast_iter2(context, cursor): # Available elements are: article|inproceedings|proceedings|book|incollection|phdthesis|mastersthesis|www elements = set(['article', 'inproceedings', 'proceedings', 'book', 'incollection', 'phdthesis', "mastersthesis", "www"]) # Available tags are: author|editor|title|booktitle|pages|year|address|journal|volume|number|month|url|ee|cdrom|cite| # publisher|note|crossref|isbn|series|school|chapter childElements = set(["title", "booktitle", "year", "journal", "ee"]) paper = {} # represents a paper with all its tags. authors = [] # a list of authors who have written the paper "together". paperCounter = 0 for event, element in context: tag = element.tag if tag in childElements: if element.text: paper[tag] = element.text # print tag, paper[tag] elif tag == "author": if element.text: authors.append(element.text) # print "AUTHOR:", authors[-1] elif tag in elements: paper["element"] = tag paper["mdate"] = element.get("mdate") paper["dblpkey"] = element.get("key") # print tag, element.get("mdate"), element.get("key"), event if paper["element"] in ['phdthesis', "mastersthesis", "www"]: pass # throw away "unwanted" records. else: populate_database(paper, authors, cursor) paperCounter += 1 print paperCounter paper = {} authors = [] # if paperCounter == 100: # break element.clear() while element.getprevious() is not None: del element.getparent()[0] del context def main(): cursor = connectToDatabase() cursor.execute("""SET NAMES utf8""") context = etree.iterparse(PATH_TO_XML, dtd_validation=True, events=("start", "end")) fast_iter(context, cursor) cursor.close() if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T12:35:14.083", "Id": "3873", "Score": "0", "body": "Since you are getting an error (million author record), isn't this material for SO?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T13:58:06.477", "Id": "3878", "Score": "0", "body": "Yes, because the code has an error it does not belong on coderview. Code review is for working code that needs improvement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T14:00:54.727", "Id": "3879", "Score": "0", "body": "I had two questions, one regarding code optimizations and one regarding the logic error. I'll try to solve the Error in SO and come back and refraze the question for code optimization. Sorry fro wrong posting. :-)" } ]
[ { "body": "<p>The name fast_iter2 seems to lack much of a connection with the function is actually doing.</p>\n\n<p>Rather then having your two sets be local variables, I suggest putting them as global constants.</p>\n\n<p>Calling them elements and childElements is kinda generic. I suggest something more specific</p>\n\n<p>Your loop is a bit awkward. Rather then collecting them in that iterative format, just grab everything when looking at the element tags. This makes the code filling up paper/authors more straightforward. </p>\n\n<p>Rather then having an empty if block and using the else block, invert the logic.</p>\n\n<p>I suggest moving the element clearing code into its own function. This helps make the function actual task clearer avoiding the question of how to clear.</p>\n\n<p>The <code>del context</code> line is useless. Del doesn't destory the object, it merely removes the object from the current context. If this was the only context in which object was refereed to then its reference count would drop to zero. However, that's not the case here as the calling function will keep it alive anyways. Even if it did, the memory savings aren't worth worrying about since the whole script is about to end anyways.</p>\n\n<p>My reworking of your code, no testing has been done on it:</p>\n\n<pre><code> CATEGORIES = set(['article', 'inproceedings', 'proceedings', 'book', 'incollection', 'phdthesis', \"mastersthesis\", \"www\"])\n SKIP_CATEGORIES = set(['phdthesis','mastersthesis', 'www'])\n DATA_ITEMS = [\"title\", \"booktitle\", \"year\", \"journal\", \"ee\"]\n\n def clear_element(element):\n element.clear()\n while element.getprevious() is not None:\n del element.getparent()[0]\n\n def fast_iter2(context, cursor):\n # Available elements are: article|inproceedings|proceedings|book|incollection|phdthesis|mastersthesis|www\n # Available tags are: author|editor|title|booktitle|pages|year|address|journal|volume|number|month|url|ee|cdrom|cite|\n # publisher|note|crossref|isbn|series|school|chapter\n\n paperCounter = 0\n for event, element in context:\n if element.tag in CATEGORIES:\n authors = [author.text for author in element.findall(\"author\")]\n paper = {\n 'element' : element.tag,\n 'mdate' : element.get(\"mdate\"),\n 'dblpkey' : element.get('key')\n }\n for data_item in DATA_ITEMS:\n data = element.find(data_item)\n if data is not None:\n paper[data_item] = data\n\n if paper['element'] not in SKIP_CATEGORIES:\n populate_database(paper, authors, cursor)\n\n\n paperCounter += 1\n print paperCounter\n\n clear_element(element)\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>How to avoid an explicit counter:</p>\n\n<pre><code> CATEGORIES = set(['article', 'inproceedings', 'proceedings', 'book', 'incollection', 'phdthesis', \"mastersthesis\", \"www\"])\n SKIP_CATEGORIES = set(['phdthesis','mastersthesis', 'www'])\n DATA_ITEMS = [\"title\", \"booktitle\", \"year\", \"journal\", \"ee\"]\n\n def clear_element(element):\n element.clear()\n while element.getprevious() is not None:\n del element.getparent()[0]\n\n def extract_paper_elements(context):\n for event, element in context:\n if element.tag in CATEGORIES:\n yield element\n clear_element(element) \n\n def fast_iter2(context, cursor):\n for paperCounter, element in enumerate(extract_paper_elements(context)):\n authors = [author.text for author in element.findall(\"author\")]\n paper = {\n 'element' : element.tag,\n 'mdate' : element.get(\"mdate\"),\n 'dblpkey' : element.get('key')\n }\n for data_item in DATA_ITEMS:\n data = element.find(data_item)\n if data is not None:\n paper[data_item] = data\n\n if paper['element'] not in SKIP_CATEGORIES:\n populate_database(paper, authors, cursor)\n\n\n print paperCounter\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T19:54:42.987", "Id": "3883", "Score": "0", "body": "Thank you very much @Winston. May I ask you, how do you get to see all those things. Certainly it es a lot of experience, but there must be a way to learn faster, perhaps by books or vertain tutorials? Could you recommend something? I am eager to learn. :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T20:35:31.387", "Id": "3884", "Score": "0", "body": "@Aufwind, I can't really say that its anything besides experience and a hyper-critical attitude that I'm trying to funnel in a productive manner here. I'm not aware of any tutorials that really focus on cleaning up this sort of stuff." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T21:09:28.890", "Id": "3886", "Score": "1", "body": "@Aufwind, I've posted on my blog trying to explain some of my though process to see if it helps: http://www.winstonewert.com/2011/05/reworking-code.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T21:13:47.490", "Id": "3887", "Score": "0", "body": "@Winston, the article in your blog is great. It gives me insight into your thoughts while revoking my code. Helps a lot, thank you very much!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T21:18:20.857", "Id": "3888", "Score": "0", "body": "@Winston, you write *Its possible to eliminate the explicit counting,...* to these lines: `paperCounter += 1; print paperCounter;`. This bothers me too, but I don't know how to do it else. How would you avoid the explicit counting?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T21:27:12.767", "Id": "3889", "Score": "0", "body": "@Aufwind, I've edited with how to do it. I use some more advanced python techniques which is why I didn't do it earlier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T21:31:37.100", "Id": "3890", "Score": "0", "body": "@Winston, ah I see you are using a generator. I am struggling to master this python technique at the moment. But often I don't see when exactly they are appropriate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T21:35:20.407", "Id": "3891", "Score": "0", "body": "@Aufwind, it becomes clear when you think about looping in a pythonic way. Maybe one day I'll write a blog post about that, but it needs more thought first." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T17:59:09.993", "Id": "2454", "ParentId": "2449", "Score": "8" } } ]
{ "AcceptedAnswerId": "2454", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T07:18:26.023", "Id": "2449", "Score": "7", "Tags": [ "python", "xml" ], "Title": "Parsing huge xml file with lxml.etree.iterparse in python" }
2449
<p>Can i refactor these code ? </p> <p>The diffrent between these block of code are.</p> <ol> <li>They are using different casting type.</li> <li><p>They call different property </p> <pre><code> var objBillOfMaterialRow = (MISheetDataSet.BillOfMaterialRow)pObjDataset.Tables["BillOfMaterial"].Rows[0]; if (objBillOfMaterialRow.mi1_BillOfMaterial == ShowReport.False) { pObjDataset.Tables["BillOfMaterial"].Clear(); } var objLayerBuildUpRow= (MISheetDataSet.LayerRow)pObjDataset.Tables["LayerBuildUp"].Rows[0]; if (objLayerBuildUpRow.mi1_LayerBuildUp == ShowReport.False) { pObjDataset.Tables["LayerBuildUp"].Clear(); } var objConstructionRow = (MISheetDataSet.ConstructionRow)pObjDataset.Tables["Construction"].Rows[0]; if (objConstructionRow.mi2_Construction == ShowReport.False) { pObjDataset.Tables["Construction"].Clear(); } </code></pre></li> </ol>
[]
[ { "body": "<p>This should work if you don't want to change anything in your classes: </p>\n\n<pre><code>var rows = new Dictionary&lt;string, Func&lt;DataRow, ShowReport&gt;&gt;\n {\n {\"BillOfMaterial\", dr =&gt; ((MISheetDataSet.BillOfMaterialRow)dr).mi1_BillOfMaterial},\n {\"LayerBuildUp\", dr =&gt; ((MISheetDataSet.LayerRow)dr).mi1_LayerBuildUp},\n {\"Construction\", dr =&gt; ((MISheetDataSet.ConstructionRow)dr).mi2_Construction},\n };\n\nforeach (var row in rows)\n{\n var dataRow = pObjDataset.Tables[row.Key].Rows[0];\n var showReportExtractor = row.Value;\n var showReport = showReportExtractor(dataRow);\n if (showReport == ShowReport.False)\n pObjDataset.Tables[row.Key].Clear();\n}\n</code></pre>\n\n<p>(Don't forget to give meaningful names to variables)</p>\n\n<p>But I would consider refactoring classes to allow more straightforward extraction of these <code>mi1_BillOfMaterial</code>, <code>mi1_LayerBuildUp</code>, <code>mi2_Construction</code> members. You have three classes here, each of them has <code>ShowReport</code> property but with different name. The idea is to extract a base class which will have this property, in this case we won't need to know the exact type of the row: </p>\n\n<pre><code>public abstract class RowBase\n{\n public abstract ShowReport ShowReport { get; }\n}\n\npublic class BillOfMaterialRow : RowBase\n{\n public override ShowReport ShowReport { get { return mi1_BillOfMaterial; } }\n}\n\n// Two other classes implemented in the same way\n</code></pre>\n\n<p>And then your method will be as simple as: </p>\n\n<pre><code>var rows = new []\n {\n \"BillOfMaterial\",\n \"LayerBuildUp\",\n \"Construction\", \n };\n\nforeach (var tableName in rows)\n{\n var row = (RowBase)pObjDataset.Tables[tableName].Rows[0];\n if (row.ShowReport == ShowReport.False)\n pObjDataset.Tables[tableName].Clear();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T11:14:32.700", "Id": "3871", "Score": "0", "body": "Thank you a lot Snowbear, This is the first time i've seen this technique. I am excited to try it right now :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T12:35:19.603", "Id": "3874", "Score": "0", "body": "Thank you it works :)\nWhat is your idea about refactoring classes to allow more straightforward extraction of these please, i would like to know more about it ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T13:01:32.797", "Id": "3875", "Score": "0", "body": "@Sarawut, expanded answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T14:13:54.887", "Id": "3881", "Score": "0", "body": "JIM-compiler - Thanks, I will try if Dataset can do that or not :D" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T10:16:30.207", "Id": "2451", "ParentId": "2450", "Score": "4" } } ]
{ "AcceptedAnswerId": "2451", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T09:51:07.887", "Id": "2450", "Score": "2", "Tags": [ "c#" ], "Title": "Is Refactoring with different class casting and property calling possible ?" }
2450
<p>I often use C API's in C++ that force me to use C-style arrays. I got sick of constantly using a dynamic vector with <code>&amp;vec[0]</code>, so I wrote this C-style array container. Please review and give suggestions.</p> <p>I also have one question: is my implementation of <code>swap</code> correct? My biggest worry is swapping two C-style arrays with different allocators, will this go boom on the deallocation?</p> <p>The current "demands" for the C-style array:</p> <ul> <li>Static size, so no <code>resize()</code>.</li> <li>Implicitly converts to <code>T*</code> when needed to pass to C functions.</li> <li>Support all of <code>std::vector</code>'s methods, as long as they are compatible with the two demands earlier.</li> </ul> <p>This is what I have:</p> <pre><code>/* Carray - a C++ container that resembles a C-style array very closely while supporting high-level methods and dynamic memory allocation. Description: A Carray is an Random Access Container (http://www.sgi.com/tech/stl/Container.html, http://www.sgi.com/tech/stl/RandomAccessContainer.html). The number of elements in a Carray is fixed and can not vary after construction. Memory management is automatic. Template arguments: Carray&lt;typename T, typename A = std::allocator&lt;T&gt; &gt; T is the type of each element in the array and A is the allocator for the array. The allocator defaults to std::allocator. Carray&lt;int, std::allocator&lt;int&gt; &gt; Constructors: Carray(size_t n) - create new Carray with n uninitialized elements Carray(size_t n, value_type newobj) - create new Carray with n elements initialized to newobj Carray(const Carray&amp; carray) - copy constructor Example: Carray&lt;int&gt; arr(50) - Carray of 50 ints - garbage values Carray&lt;int&gt; arr(50, int()) - Carray of 50 ints - initialized to default int, 0 Carray supports all of the associated types, members and methods described on these pages: http://www.sgi.com/tech/stl/Container.html http://www.sgi.com/tech/stl/ForwardContainer.html http://www.sgi.com/tech/stl/ReversibleContainer.html http://www.sgi.com/tech/stl/RandomAccessContainer.html */ /* Copyright 2011 Orson Peters. All rights reserved. Redistribution of this work, with or without modification, is permitted if Orson Peters is attributed as the original author or licensor of this work, but not in any way that suggests that Orson Peters endorses you or your use of the work. This work is provided by Orson Peters "as is" and any express or implied warranties are disclaimed. Orson Peters is not liable for any damage arising in any way out of the use of this work. */ #ifndef CARRAY_H #define CARRAY_H #include &lt;memory&gt; // std::allocator #include &lt;algorithm&gt; // std::uninitialized_copy #include &lt;iterator&gt; // std::reverse_iterator #include &lt;stdexcept&gt; // std::out_of_range #include &lt;cstddef&gt; // size_t &amp;&amp; ptrdiff_t template&lt;typename T, typename A = std::allocator&lt;T&gt; &gt; class Carray { public: // types typedef T value_type; typedef A allocator_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; // for C typedef const T* const_pointer; // for C typedef T* iterator; typedef const T* const_iterator; typedef std::reverse_iterator&lt;iterator&gt; reverse_iterator; typedef std::reverse_iterator&lt;const_iterator&gt; const_reverse_iterator; typedef T&amp; reference; typedef const T&amp; const_reference; // contructors Carray(size_type size) { // array with N uninitialized elements elements = size; data = allocator.allocate(size); } Carray(size_type size, const_reference newobj) { // array with N elements initialized to newobj elements = size; data = allocator.allocate(size); for (iterator it = begin(); it != end(); it++) allocator.construct(it, newobj); } Carray(const Carray&lt;value_type&gt;&amp; other) { // copy constructor elements = other.size(); data = allocator.allocate(elements); std::uninitialized_copy(other.begin(), other.end(), begin()); } Carray&lt;value_type, allocator_type&gt;&amp; operator=(const Carray&lt;value_type, allocator_type&gt;&amp; other) { // same as copy constructor elements = other.size(); data = allocator.allocate(elements); std::uninitialized_copy(other.begin(), other.end(), begin()); } ~Carray() { for (iterator it = begin(); it != end(); it++) allocator.destroy(it); if (data != 0) { allocator.deallocate(data, elements); data = 0; elements = 0; } } // iterators and references reference back() { return data[elements - 1]; } const_reference back() const { return data[elements - 1]; } reference front() { return data[0]; } const_reference front() const { return data[0]; } iterator begin() { return iterator(data); } const_iterator begin() const { return const_iterator(data); } iterator end() { return iterator(data + elements); } const_iterator end() const { return const_iterator(data + elements); } reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } // methods bool empty() const { return elements == 0; } size_type max_size() const { return allocator.max_size(); } size_type size() const { return elements; } allocator_type get_allocator() const { return allocator; } void swap(Carray&lt;value_type&gt;&amp; other) { std::swap(data, other.data); std::swap(elements, other.elements); } // subscripting reference at(size_type n) { if (n &gt;= elements) throw std::out_of_range("Carray::at(size_type n)"); return data[n]; } const_reference at(size_type n) const { if (n &gt;= elements) throw std::out_of_range("Carray::at(size_type n)"); return data[n]; } reference operator[](difference_type n) { return data[n]; } // difference_type to prevent ambiguity with (operator pointer())[n] const_reference operator[](difference_type n) const { return data[n]; } // difference_type to prevent ambiguity with (operator pointer())[n] operator pointer() { return data; } // implicit conversion to pointer for C support operator const_pointer() const { return data; } // implicit conversion to const pointer for C support private: allocator_type allocator; pointer data; size_type elements; }; // comparison operators - operator== and operator&gt; are primitives, the rest is derived from them template&lt;typename T, typename A&gt; bool operator==(const Carray&lt;T,A&gt;&amp; x, const Carray&lt;T,A&gt;&amp; y) { return x.size() == y.size() &amp;&amp; std::equal(x.begin(), x.end(), y.begin()); } template&lt;typename T, typename A&gt; bool operator&lt;(const Carray&lt;T,A&gt;&amp; x, const Carray&lt;T,A&gt;&amp; y) { return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } template&lt;typename T, typename A&gt; bool operator&gt;(const Carray&lt;T,A&gt;&amp; x, const Carray&lt;T,A&gt;&amp; y) { return y &lt; x; } template&lt;typename T, typename A&gt; bool operator!=(const Carray&lt;T,A&gt;&amp; x, const Carray&lt;T,A&gt;&amp; y) { return !(x == y); } template&lt;typename T, typename A&gt; bool operator&gt;=(const Carray&lt;T,A&gt;&amp; x, const Carray&lt;T,A&gt;&amp; y) { return !(x &lt; y); } template&lt;typename T, typename A&gt; bool operator&lt;=(const Carray&lt;T,A&gt;&amp; x, const Carray&lt;T,A&gt;&amp; y) { return !(x &gt; y); } #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T09:39:50.493", "Id": "3893", "Score": "1", "body": "I will take my stab at this design in a second, but wasn't boost::Array an option for you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T10:20:53.500", "Id": "3894", "Score": "0", "body": "@SoulBeaver: Perhaps, but this was both an exercise, and I don't like the design of boost::array. For example I don't like to explicitly call `data()` all the time. Normally I'm fond of strict-ness, but IMO if you go as far as replacing vector with a C-style array wrapper then make it behave as a C-style array. And the size as template parameter is against my design principles for this array because I want a static-sized array, not necessarily compile-time fixed size." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T10:34:04.520", "Id": "3896", "Score": "0", "body": "It doesn't seem to implicitly convert to `T*` at the moment. Am I missing something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T10:38:19.740", "Id": "3897", "Score": "0", "body": "@Tim Martin: It does. It supports `operator pointer()` where pointer is `typedef T* pointer`. Try passing the Carray to a C function like strcpy (make sure you pass a `Carray<char>` ofc)." } ]
[ { "body": "<p>Alright, I made a couple of minor changes:</p>\n\n<ol>\n<li><p>Changed ctor to use initialization list:</p>\n\n<pre><code>Carray(size_type size) \n: elements(size), data(allocator.allocate(size))\n{ }\n\nCarray(size_type size, const_reference newobj) \n: elements(size), data(allocator.allocate(size))\n{ // array with N elements initialized to newobj\n for (iterator it = begin(); it != end(); it++) \n allocator.construct(it, newobj);\n}\n\nCarray(const Carray&lt;value_type&gt;&amp; other) \n: elements(other.size), data(allocator.allocate(elements))\n{ // copy constructor\n std::uninitialized_copy(other.begin(), other.end(), begin());\n} \n</code></pre></li>\n<li><p>Rearranged members (you were initializing in the wrong order):</p>\n\n<pre><code>allocator_type allocator;\nsize_type elements;\npointer data;\n</code></pre></li>\n<li><p>Used the copy-and-swap idiom on your <code>operator=</code>:</p>\n\n<pre><code>Carray&lt;value_type, allocator_type&gt;&amp; operator=(const Carray&lt;value_type, allocator_type&gt;&amp; other) { // same as copy constructor\n // This may be a short piece of code, but why not use the copy-and-swap idiom? \n Carray&lt;T, A&gt; temp(other);\n swap(*this, temp);\n\n return *this;\n}\n</code></pre></li>\n<li><p>Make your swap have the no-throw guarantee:</p>\n\n<pre><code>void swap(Carray&lt;value_type&gt;&amp; other) throw()\n</code></pre></li>\n</ol>\n\n<p>I would also like to add that your <code>throw()</code> in the <code>at()</code> functions isn't very descriptive. This probably isn't a problem, since the error is apparent from looking at the function, but why not give it a more descriptive message anyway? Then I won't even have to look at the function to know what went wrong.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>As Tim Martin pointed out, the <code>throw()</code> is usually bad style and should be avoided. I have included it for the swap function because of two reasons:</p>\n\n<ol>\n<li><p>It is usually a non-throwing swap, which is more of a semantic rather than syntactic choice. This let's the programmer know that swap should not ever throw, but it is not prevented.</p></li>\n<li><p>Quoting Herb Sutter from Exceptional C++ Item 12:</p>\n\n<blockquote>\n <p>Note that Swap() supports the strongest exception guarantee of\n all—namely, the nothrow guarantee; Swap() is guaranteed not to throw\n an exception under any circumstances. It turns out that this feature\n of Swap() is essential, a linchpin in the chain of reasoning about\n [Container]'s own exception safety.</p>\n</blockquote></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T10:27:17.767", "Id": "3895", "Score": "0", "body": "Thanks, this was very helpful. I'm not known with the copy-and-swap idiom yet. But I think you meant `swap(*this, temp);`. And perhaps you could add some information about my `swap` implementation, especially about swapping between two `Carray`'s with different allocators." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T10:54:57.550", "Id": "3899", "Score": "0", "body": "I'm guessing you know, but it never hurts to emphasise: the `throw()` annotation on the declaration doesn't prevent the function from throwing an exception, and doesn't cause the compiler to warn if the code within can throw. Sutter and Alexandrescu in *C++ Coding Standards* recommend against using exception specifications for this reason." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T10:55:19.343", "Id": "3900", "Score": "0", "body": "@nightcracker: edited, and I wouldn't allow the swapping with containers that have differing allocators. An easy way to prevent this is by changing the declaration of swap to `void swap(Carray<T, A>& other) throw()`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T10:57:39.160", "Id": "3903", "Score": "0", "body": "I know it's easy to prevent. I was thinking that it might be possible to swap two Carray's with different allocators, but it was foolish. They are essentially different types." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T10:04:38.040", "Id": "2462", "ParentId": "2455", "Score": "4" } }, { "body": "<p>It's a subjective point, but declarations of template containers in the standard library don't use the typedefs for the template type for the rest of the declaration. For example,</p>\n\n<pre><code>template &lt;class T, class Allocator&gt;\nclass deque {\npublic:\n typedef T value_type;\n\n //...\n\n void push_front( const T&amp; x );\n // not void push_front(const value_type&amp; x);\n\n //...\n}\n</code></pre>\n\n<p>I'm used to looking for the template parameter in member function declarations, and your use of <code>value_type</code> etc. confused me.</p>\n\n<p>Personally, I don't like the implicit conversion to <code>T*</code>. You need to make sure you've thought of all the cases where this could cause unexpected behaviour, e.g. in boolean contexts, arithmetic operators and with <code>ostream::operator&lt;&lt;</code>. In my opinion an extra function call on the conversion is a small price to pay for avoiding cases where code looks right, compiles and does something subtly wrong.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T10:52:32.817", "Id": "3898", "Score": "0", "body": "Ahh, my use of `pointer` confused you :) I'll think about it and look in compiler implementations too to see what the majority of library designers think and adapt to that. I like to write semantically, so for me using typedefs like `const_reference` and `value_type` are easier to understand." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T10:48:58.863", "Id": "2463", "ParentId": "2455", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T20:55:23.263", "Id": "2455", "Score": "8", "Tags": [ "c++", "c", "classes", "array" ], "Title": "C-style array class" }
2455
<p><a href="https://en.wikipedia.org/wiki/C_%28programming_language%29" rel="nofollow noreferrer">C</a> (pronounced "See", like the letter C) is a general-purpose computer programming language developed between 1969 and 1973 by <a href="http://cm.bell-labs.com/who/dmr/" rel="nofollow noreferrer">Dennis Ritchie</a> at the <a href="https://en.wikipedia.org/wiki/Bell_Labs" rel="nofollow noreferrer">Bell Telephone Laboratories</a> for use with the <a href="https://en.wikipedia.org/wiki/UNIX" rel="nofollow noreferrer">UNIX operating system</a>. Its design provides constructs that map efficiently to typical machine instructions, and, therefore, it found lasting use in applications that had formerly been coded in assembly language. It is a highly efficient procedural oriented programming language and has emphasis on functions, whereas latest object-oriented programming languages have emphasis on data.</p> <p>Although C was designed for implementing system software, it is also widely used for developing portable application software.</p> <p>C is one of the most widely used programming languages of all time and there are very few computer architectures for which a C compiler does not exist. C has greatly influenced many other popular programming languages, most notably <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged &#39;c++&#39;" rel="tag">c++</a>, which began as an extension to C.</p> <h2>Design</h2> <p>C is an imperative (<a href="https://en.wikipedia.org/wiki/Procedural_programming" rel="nofollow noreferrer">procedural</a>) systems implementation language. It was designed to be compiled using a relatively straightforward compiler, to provide low-level access to memory, to provide language constructs that map efficiently to machine instructions, and to require minimal run-time support. C was therefore useful for many applications that had formerly been coded in assembly language.</p> <p>Despite its low-level capabilities, the language was designed to encourage cross-platform programming. A standards-compliant and portably written C program can be compiled for a very wide variety of computer platforms and operating systems with few changes to its source code. The language has become available on a very wide range of platforms, from embedded micro-controllers to supercomputers.</p> <h3>Is it C, C++ or both?</h3> <p>This tag is for questions related to C, not <a href="https://stackoverflow.com/questions/tagged/c++">C++</a>. In some cases, you may be working with both and applying both tags is entirely appropriate. However, please refrain from using both tags in an effort to help your question reach a wider audience. After all, C++ answers <em>won't</em> help you solve the problem in C, and good C answers often do not describe the best approach in C++.</p> <h3>Important notes that may save you time</h3> <ul> <li><a href="http://c-faq.com/" rel="nofollow noreferrer">The comp.lang.c FAQ</a> has answers to many frequently asked C questions. For example, see <a href="http://c-faq.com/decl/spiral.anderson.html" rel="nofollow noreferrer">The Clockwise/Spiral Rule</a> for parsing C declarations.</li> </ul> <h2>Definitive Book Guide</h2> <p>The following list of books has been compiled by <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a> users as a definitive list of quality references for all levels of C programmer. If you are looking to learn or improve your C, you may find some of the following texts highly useful.</p> <p><strong>Reference Style - All Levels</strong></p> <ul> <li><a href="http://rads.stackoverflow.com/amzn/click/0131103628" rel="nofollow noreferrer">The C Programming Language (Second edition)</a> - Brian W. Kernighan and Dennis M. Ritchie </li> <li><a href="http://rads.stackoverflow.com/amzn/click/013089592X" rel="nofollow noreferrer">C: A Reference Manual</a> - Samuel P. Harbison and Guy R. Steele</li> <li><a href="http://rads.stackoverflow.com/amzn/click/0596004362" rel="nofollow noreferrer">C Pocket Reference (O'Reilly)</a> - Peter Prinz, Ulla Kirch-Prinz</li> <li><a href="http://rads.stackoverflow.com/amzn/click/0201179288" rel="nofollow noreferrer">C - Traps and Pitfalls</a> - Andrew R. Koenig (Bell Labs)</li> </ul> <p><strong>Beginner</strong></p> <ul> <li><a href="http://rads.stackoverflow.com/amzn/click/0321776410" rel="nofollow noreferrer">Programming in C (4th Edition)</a> - Stephen Kochan</li> <li><a href="http://rads.stackoverflow.com/amzn/click/0672326965" rel="nofollow noreferrer">C Primer Plus</a> - Stephen Prata</li> <li><a href="http://knking.com/books/c2/index.html" rel="nofollow noreferrer">C Programming: A Modern Approach</a> - K. N. King</li> <li><a href="http://rads.stackoverflow.com/amzn/click/0201183994" rel="nofollow noreferrer">A Book on C</a> - Al Kelly/Ira Pohl</li> <li><a href="http://c.learncodethehardway.org/" rel="nofollow noreferrer">Learn C The Hard Way</a> - Zed Shaw</li> <li><a href="http://publications.gbdirect.co.uk/c_book/" rel="nofollow noreferrer">The C book</a> - Mike Banahan, Declan Brady and Mark Doran</li> </ul> <p><strong>Intermediate</strong></p> <ul> <li><a href="http://www.planetpdf.com/codecuts/pdfs/ooc.pdf" rel="nofollow noreferrer">Object-oriented Programming with ANSI-C</a> - Axel-Tobias Schreiner</li> <li><a href="http://www.cs.princeton.edu/software/cii/" rel="nofollow noreferrer">C Interfaces and Implementations</a> - David R. Hanson</li> <li><a href="http://rads.stackoverflow.com/amzn/click/0201604612" rel="nofollow noreferrer">The C Puzzle Book</a> - Alan R. Feuer</li> <li><a href="https://rads.stackoverflow.com/amzn/click/0131315099" rel="nofollow noreferrer">The Standard C Library</a> - P.J. Plauger</li> <li><a href="http://rads.stackoverflow.com/amzn/click/0673999866" rel="nofollow noreferrer">Pointers on C</a> - Kenneth Reek</li> </ul> <p><strong>Above Intermediate</strong></p> <ul> <li><a href="http://rads.stackoverflow.com/amzn/click/0131774298" rel="nofollow noreferrer">Expert C Programming: Deep C Secrets</a> - Peter van der Linden</li> <li><a href="http://www.powells.com/biblio?inkey=4-0201179288-0" rel="nofollow noreferrer">C Traps and Pitfalls</a> - Andrew Koenig</li> <li><a href="https://rads.stackoverflow.com/amzn/click/0534951406" rel="nofollow noreferrer">Advanced C Programming by Example</a> - John W. Perry</li> </ul> <h3>Free C Programming Books</h3> <ul> <li><a href="http://beej.us/guide/bgnet/" rel="nofollow noreferrer">Beej's Guide to Network Programming</a></li> <li><a href="http://publications.gbdirect.co.uk/c_book/" rel="nofollow noreferrer">The C book</a></li> <li><a href="http://cslibrary.stanford.edu/101/EssentialC.pdf" rel="nofollow noreferrer">Essential C</a></li> <li><a href="http://c.learncodethehardway.org/book/" rel="nofollow noreferrer">Learn C the hard way</a></li> <li><a href="http://www.knosof.co.uk/cbook/cbook.html" rel="nofollow noreferrer">The new C standard - an annotated reference</a></li> <li><a href="http://www.planetpdf.com/codecuts/pdfs/ooc.pdf" rel="nofollow noreferrer">Object Oriented Programming in C</a> (PDF)</li> </ul> <h2>Chat Room</h2> <p>Chat about C with Stack Overflow users</p> <ul> <li><a href="https://chat.stackoverflow.com/rooms/21757/loungec">Language C</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T21:42:00.087", "Id": "2456", "Score": "0", "Tags": null, "Title": null }
2456
C is a general-purpose computer programming language used for operating systems, games, and other high performance work and is clearly distinct from C++. It was developed in 1972 by Dennis Ritchie for use with the Unix operating system.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T21:42:00.087", "Id": "2457", "Score": "0", "Tags": null, "Title": null }
2457
<p>This program converts Brainfuck source code to C and compiles it with gcc. It runs very well (that was my first time I played <a href="http://jonripley.com/i-fiction/games/LostKingdomBF.html">Lost Kingdom</a>), however, the code is quite long because some parts are repeated.</p> <p>Is there a way to reduce the code? What about the "optimization" method? Can this simple optimization be improved?</p> <p>PS: This code is for Linux, but can be changed for Windows.</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdbool.h&gt; #include&lt;string.h&gt; #include&lt;stdlib.h&gt; int main(int argv, char* argc[]){ //help message if(argv==1){ printf("\n"); printf("How to use : %s filename [-o output|-c|-d|-r]\n",argc[0]); printf("-o output : Set output file name\n-c : Do not compile\n-d : Do not delete C source file\n"); printf("INFO : You SHOULD type 'export MALLOC_CHECK_=0' manually to remove warning.\n"); printf("\n"); return 0; } printf("INFO : You may type 'export MALLOC_CHECK_=0' manually to remove warning.\n"); int i; bool doCompile = true; bool deleteSource = true; char* fileName = argc[1]; char* outFileName; outFileName = (char*)malloc(1024); strncpy(outFileName,fileName,1000); strcat(outFileName,".o"); bool isSetOut = false; //set flags for(i=2;i&lt;argv;i++){ if(isSetOut){ isSetOut = false; outFileName = argc[i]; } else if(strcmp(argc[i],"-c")==0){ doCompile = false; } else if(strcmp(argc[i],"-d")==0){ deleteSource = false; } else if(strcmp(argc[i],"-o")==0){ isSetOut = true; } } char outFileC[1024]; strncpy(outFileC,outFileName,1000); strcat(outFileC,".c"); //bf file FILE* bfFile; bfFile = fopen(fileName,"r"); if(bfFile==NULL){ printf("ERROR : FILE %s DOES NOT EXIST\n",fileName); return 2; } char c; //c source code FILE* cFile; cFile = fopen(outFileC,"w"); int add = 0; char prevC = '\0'; fputs("#include&lt;stdio.h&gt;\n#include&lt;stdlib.h&gt;\n",cFile); fputs("int main(){",cFile); fputs("unsigned char* _=(unsigned char*)malloc(32*1024);/*32kB*/if(_==0){printf(\"MEMORY ERROR!\\n\");return 1;}",cFile); //write codes do{ c = fgetc(bfFile); if(c!=EOF){ bool isPrint = false; switch(c){ case '&gt;': case '&lt;': if((prevC=='+'||prevC=='-')&amp;&amp;add){//process something like +++- = ++ if(add==1||add==-1){ if(add==1) fputs("++*_",cFile); else fputs("--*_",cFile); } else fprintf(cFile,"(*_)%c=%d",add&gt;0?'+':'-',add&gt;0?add:-add); fputs(";",cFile); add=0; } if(c=='&gt;') add++; else add--; break; case '+': case '-': if((prevC=='&gt;'||prevC=='&lt;')&amp;&amp;add){//process something like &gt;&gt;&gt;&lt; = &gt;&gt; if(add==1||add==-1){ if(add==1) fputs("++_",cFile); else fputs("--_",cFile); } else fprintf(cFile,"_%c=%d",add&gt;0?'+':'-',add&gt;0?add:-add); fputs(";",cFile); add=0; } if(c=='+') add++; else add--; break; case '.': case ',': case '[': case ']': if(add){ if(prevC=='&gt;'||prevC=='&lt;'){//process something like &gt;&gt;&gt;&lt; = &gt;&gt; if(add==1||add==-1){ if(c=='.'){ isPrint = true; if(add==1) fputs("putchar(*(++_))",cFile); else fputs("putchar(*(--_))",cFile); }else{ if(add==1) fputs("++_",cFile); else fputs("--_",cFile); } } else if(c=='.'){ isPrint = true; fprintf(cFile,"putchar(*(_%c=%d))",add&gt;0?'+':'-',add&gt;0?add:-add); }else fprintf(cFile,"_%c=%d",add&gt;0?'+':'-',add&gt;0?add:-add); fputs(";",cFile); add=0; }else if(prevC=='+'||prevC=='-'){//process something like +++- = ++ if(add==1||add==-1){ if(c=='.'){ isPrint = true; if(add==1) fputs("putchar(++*_)",cFile); else fputs("putchar(--*_)",cFile); }else{ if(add==1) fputs("++*_",cFile); else fputs("--*_",cFile); } } else if(c=='.'){ isPrint = true; fprintf(cFile,"putchar((*_)%c=%d)",add&gt;0?'+':'-',add&gt;0?add:-add); }else fprintf(cFile,"(*_)%c=%d",add&gt;0?'+':'-',add&gt;0?add:-add); fputs(";",cFile); add=0; } } switch(c){ case '.': if(!isPrint) fputs("putchar(*_);",cFile); break; case ',': fputs("*_=getchar();",cFile); break; case '[': fputs("while(*_){",cFile); break; case ']': fputs("}",cFile); break; } break; } } if(c=='&gt;'||c=='&lt;'||c=='+'||c=='-'||c=='.'||c==','||c=='['||c==']') prevC = c; }while(c!=EOF); fputs("free(_);return 0;}",cFile); fclose(bfFile); fclose(cFile); if(!doCompile){ printf("Output C code : %s\n",outFileC); return 0; } printf("Compile with GCC...\n"); char op[2048] = "gcc "; strcat(op,outFileC); strcat(op," -o "); strcat(op,outFileName); system(op); if(deleteSource){ strcpy(op,"rm "); strcat(op,outFileC); system(op); } printf("Done.\nOutput file name : %s\n",outFileName); return 0; } </code></pre>
[]
[ { "body": "<ol>\n<li>Don't put everything in a giant main function, that just makes it hard to follow</li>\n<li>Print error message, such as usage information to stderr</li>\n<li>You have argc (argument <strong>count</strong>) and argv (argument <strong>vector</strong>) backwards</li>\n<li>You don't free anything you malloc</li>\n<li>There is no point in mallocing, because you can create your arrays on the stack</li>\n<li>Rather then passing a significantly lower value as your size to strncpy, use strncat for the concatenation.</li>\n<li>Repeated constants like the size of the strings you are using are best made #defines</li>\n<li>Since you appear to be using a recent version of C, don't split definitions and assignments onto seperate lines unneccesairly</li>\n<li>I prefer putting logic into else blocks rather then depending on return skipping the rest.</li>\n<li>Rather then calling rm, use the standard library function \"unlink\" for deleteing files</li>\n<li>Don't generate code using ++/-- it would won't help the final speed and makes your code more complicated</li>\n<li>Don't try to subtract instead of adding negative numbers, the compiler is smart enough to handle that.</li>\n<li>Why isn't the semicolon inside the printf?</li>\n<li>The name add isn't very clear. It took me a while to figure out what it was doing</li>\n<li>In general you spend a lot of effort trying to generate more compact C code. But the C compiler will be smarter at doing that then you are, so don't try.</li>\n</ol>\n\n<p>Having cleaned up those issues I can see the problematic repetition of logic. The first thing is that all of non-bf characters are causing complications. We'll write function which calls fgetc but filters out all the characters we want to ignore.</p>\n\n<p>Next, rather then trying to respond one character at a time, have loops which eat the characters.</p>\n\n<p>Here is the result:</p>\n\n<pre><code>#include&lt;stdio.h&gt;\n#include&lt;stdbool.h&gt;\n#include&lt;string.h&gt;\n#include&lt;stdlib.h&gt;\n\n#define STRING_SIZE 1024\n\ntypedef struct CommandOptions\n{\n bool doCompile;\n bool deleteSource;\n char * fileName;\n char outFileName[STRING_SIZE];\n char outFileC[STRING_SIZE];\n}CommandOptions;\n\nbool parse_command_line(CommandOptions * options, int argc, char * argv[])\n{\n //help message\n if(argc==1){\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"How to use : %s filename [-o output|-c|-d|-r]\\n\",argv[0]);\n fprintf(stderr, \"-o output : Set output file name\\n-c : Do not compile\\n-d : Do not delete C source file\\n\");\n fprintf(stderr, \"INFO : You SHOULD type 'export MALLOC_CHECK_=0' manually to remove warning.\\n\");\n fprintf(stderr, \"\\n\");\n return false;\n }\n\n // set the default options\n options-&gt;doCompile = true;\n options-&gt;deleteSource = true;\n options-&gt;fileName = argv[1];\n\n strncpy(options-&gt;outFileName, options-&gt;fileName, STRING_SIZE);\n strncat(options-&gt;outFileName, \".o\", STRING_SIZE);\n\n // parse the remaining options\n int i;\n bool isSetOut = false;\n\n for(i = 0; i &lt; argc; i++) \n {\n if(isSetOut){\n isSetOut = false;\n strncpy(options-&gt;outFileName, argv[i], STRING_SIZE);\n }\n else if(strcmp(argv[i],\"-c\")==0){\n options-&gt;doCompile = false;\n }\n else if(strcmp(argv[i],\"-d\")==0){\n options-&gt;deleteSource = false;\n }\n else if(strcmp(argv[i],\"-o\")==0){\n isSetOut = true;\n }\n }\n\n strncpy(options-&gt;outFileC,options-&gt;outFileName,STRING_SIZE);\n strncat(options-&gt;outFileC,\".c\", STRING_SIZE);\n\n // don't delete the source if we won't compile it\n if(!options-&gt;doCompile)\n {\n options-&gt;deleteSource = false;\n }\n\n return true;\n\n}\n\nvoid write_header(FILE * cFile)\n{\n fputs(\"#include&lt;stdio.h&gt;\\n\", cFile);\n fputs(\"#include&lt;stdlib.h&gt;\\n\",cFile);\n fputs(\"int main(){\\n\",cFile);\n fputs(\"unsigned char* _=(unsigned char*)malloc(32*1024);/*32kB*/if(_==0){printf(\\\"MEMORY ERROR!\\\\n\\\");return 1;}\\n\",cFile);\n}\n\nvoid write_footer(FILE * cFile)\n{\n fputs(\"free(_);\\nreturn 0;\\n}\\n\",cFile);\n}\n\nint bf_fgetc(FILE * bfFile)\n{\n int c;\n do\n {\n c = fgetc(bfFile);\n }while(c != EOF &amp;&amp; c != '[' &amp;&amp; c != ']' &amp;&amp; c != '&lt;' &amp;&amp; c != '&gt;' &amp;&amp; c != '.' \n &amp;&amp; c != ',' &amp;&amp; c != '+' &amp;&amp; c != '-');\n return c;\n}\n\nvoid compile_to_c(FILE * bfFile, FILE * cFile)\n{\n write_header(cFile);\n int add = 0;\n char prevC = '\\0';\n //write codes \n char c = bf_fgetc(bfFile);\n do{\n int movement_counter = 0;\n while( c == '&gt;' || c == '&lt;')\n {\n movement_counter += c == '&gt;' ? 1 : -1;\n c = bf_fgetc(bfFile);\n }\n if(movement_counter)\n {\n fprintf(cFile,\"_ += %d;\", movement_counter);\n }\n\n int value_counter = 0;\n while( c == '+' || c == '-')\n {\n value_counter += c == '+' ? 1 : -1;\n c = bf_fgetc(bfFile);\n }\n if(value_counter)\n {\n fprintf(cFile,\"*_ += %d;\",value_counter);\n }\n\n if(c == '.') \n {\n fprintf(cFile, \"putchar(*_);\\n\"); \n c = bf_fgetc(bfFile); \n }\n if(c == ',') \n {\n fprintf(cFile, \"*_ = getchar();\\n\");\n c = bf_fgetc(bfFile); \n }\n if(c == '[')\n {\n fprintf(cFile, \"while(*_) {\\n\");\n c = bf_fgetc(bfFile);\n }\n if(c == ']')\n {\n fprintf(cFile, \"}\\n\");\n c = bf_fgetc(bfFile);\n }\n }while(c!=EOF);\n write_footer(cFile);\n}\n\nvoid compileCode(CommandOptions * options)\n{\n printf(\"Compile with GCC...\\n\");\n char op[2048] = \"gcc \";\n strncat(op,options-&gt;outFileC, 2048);\n strncat(op,\" -o \", 2048);\n strncat(op,options-&gt;outFileName, 2048);\n system(op);\n}\n\nint main(int argc, char* argv[]){\n CommandOptions options;\n\n if( !parse_command_line(&amp;options, argc, argv) )\n {\n return 1;\n }\n\n printf(\"INFO : You may type 'export MALLOC_CHECK_=0' manually to remove warning.\\n\");\n\n //bf file\n FILE* bfFile = fopen(options.fileName,\"r\");\n if(bfFile==NULL){\n fprintf(stderr, \"ERROR : FILE %s DOES NOT EXIST\\n\",options.fileName);\n return 2;\n }\n\n //c source code\n FILE* cFile = fopen(options.outFileC, \"w\");\n if(!cFile)\n {\n fclose(bfFile);\n fprintf(stderr, \"ERROR: COULD NOT OPEN %s FILE FOR WRITING\" , options.outFileC);\n return 3;\n }\n\n compile_to_c(bfFile, cFile);\n\n fclose(bfFile);\n fclose(cFile);\n\n if(options.doCompile){\n compileCode(&amp;options);\n }else{\n printf(\"Output C code : %s\\n\", options.outFileC);\n }\n\n if( options.deleteSource )\n {\n unlink(options.outFileC);\n }\n\n printf(\"Done.\\nOutput file name : %s\\n\",options.outFileName);\n return 0;\n}\n</code></pre>\n\n<p>There is still some duplication in the compile_to_c function that I'm not liking. The similarity between &lt;> and +- could easily be exploited easily in a function. Harder would be getting rid of the repeated bf_fgetc calls. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T03:14:08.253", "Id": "3892", "Score": "0", "body": "Thanks! ...I should learn how to use structure and functions properly..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T15:01:21.893", "Id": "3907", "Score": "0", "body": "@JiminP, I recently wrote a BF interpreter and I remembered an optimization I had that you might be useful. During preprocessing I identified \"trivial loops.\" A trivial loop consists only of <>+-, has balanced <> (so it ends up where it started), and results in decrementing the first value (the one that gets tested by [) exactly once. This means I can tell how many iterations to loop will go through right away and can replace the whole loop with one iteration using multiplication to apply the same effect as if it the loop had run many times." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T02:37:47.013", "Id": "2459", "ParentId": "2458", "Score": "17" } }, { "body": "<p>Don't cast malloc. It's unnecessary in C, and can hide a bug if you don't have a valid prototype in scope (ie. you didn't include stdlib.h)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-22T06:35:55.270", "Id": "6433", "Score": "0", "body": "I know, why would anyone ever need dynamic memory allocation, right.....?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-05T14:38:47.990", "Id": "6890", "Score": "2", "body": "@Ed. S he said *cast* not *call*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-06T16:22:17.027", "Id": "6924", "Score": "0", "body": "@Winston... so he did, sorry about that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-20T00:28:15.670", "Id": "4247", "ParentId": "2458", "Score": "3" } }, { "body": "<p>You have two memory management bugs.</p>\n\n<p>Memory returned from <code>malloc()</code> is, in general, not initialized to zero. A good operating system will zero all memory pages that are given to your program (to prevent information leakage from other programs), and your program's first <code>malloc()</code> would likely obtain virgin memory. However, none of that is guaranteed by POSIX. I suggest calling <code>calloc()</code> instead.</p>\n\n<p>The pointer that you <code>free()</code> does not necessarily have the same value that you received from <code>malloc()</code>. The pointer can take on any value as it moves among the cells. If the pointer does not happen to be at cell 0 when the program runs out of instructions to execute, then you end up freeing an arbitrary pointer, which is a pity when you're so close to finishing successfully!</p>\n\n<p>Possible remedies are:</p>\n\n<ul>\n<li>Save a copy of the value returned from <code>malloc()</code> so that you can <code>free()</code> it.</li>\n<li>Don't bother calling <code>free()</code>; just let the OS take care of the cleanup.</li>\n<li>Since you are only doing a fixed-size allocation, just use an array: <code>unsigned char memory[32 * 1024] =</code><a href=\"https://stackoverflow.com/a/1352379/1157100\"><code>{ 0 }</code></a><code>, *_ = memory;</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-15T22:21:08.157", "Id": "39339", "ParentId": "2458", "Score": "5" } } ]
{ "AcceptedAnswerId": "2459", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-17T22:52:26.377", "Id": "2458", "Score": "14", "Tags": [ "c", "converting", "brainfuck" ], "Title": "Brainfuck to C converter" }
2458
<p>I have written the following code that tests if the current time is within a time window. It seems to work ok with my test cases, but I would be interested if anyone can see any possible problems or has any ideas for improvements?</p> <pre><code>Public Function IsCurrentTimeBetween(ByRef dteStartTime As DateTime, ByRef dteEndTime As DateTime) As Boolean Dim dteStart As DateTime, dteEnd As DateTime, dteCurrent As DateTime 'strip off any date portion of the dates dteStart = Format(dteStartTime, "HH:mm:ss") dteEnd = Format(dteEndTime, "HH:mm:ss") dteCurrent = Format(DateTime.Now, "HH:mm:ss") If dteEnd &lt; dteStart Then 'the times span midnight If dteCurrent &lt; dteStart And dteCurrent &lt; dteEnd Then dteCurrent = dteCurrent.AddDays(1) End If dteEnd = dteEnd.AddDays(1) End If Return (dteStart &lt;= dteCurrent AndAlso dteCurrent &lt;= dteEnd) End Function </code></pre> <p>Usage:</p> <pre><code>'Work out if we are between 5 to midnight and quarter past midnight Debug.WriteLine("Is in midnight window? " + IsCurrentTimeBetween("23:55", "00:15").ToString) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-23T14:32:11.017", "Id": "4036", "Score": "0", "body": "Are you implying a date component to your times? e.g IF it is 00:01 on Jan 2 you are asking if that time is between 23:55 on Jan 1 and 00:15 on Jan 2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-23T14:36:33.490", "Id": "4037", "Score": "0", "body": "@dbasnett - Yes that is exactly what I want to find" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-23T14:55:47.757", "Id": "4038", "Score": "0", "body": "Is there some reason you can't use real dates? Also, as has been pointed out this code has a lot of implicit conversion occurring." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-23T15:00:02.390", "Id": "4039", "Score": "0", "body": "@dbasnett - I have settings in the database to store the app sleep and wakeup time they are in the format \"23:55\" and \"00:15\" so I want to know if I am currently within the sleep window or not (the app stays running for days on end so I need some way of this being generic and working on any day)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-23T15:12:01.077", "Id": "4040", "Score": "0", "body": "OK, I agree with Jeff about how this code should be done. See the code I posted below." } ]
[ { "body": "<p>A couple of quick things:</p>\n\n<p>You are passing in the parameters by reference unnecessarily. This method of passing is useful if you need to make modifications to variables that are observed at the callsite, but it should otherwise be avoided, as it could introduce a bug that may be more difficult to track if you make a mistake. Simply receive your parameters <code>ByVal</code>.</p>\n\n<p>Secondly, I would encourage you to move away from hungarian notation. I've been there, I know all the arguments for keeping it. Hogwash. In your code snippet, you have variables like <code>dteStartTime</code> and <code>dteStart</code>. <em>After</em> you change the method parameters to be <code>ByVal</code>, you can then change your code to have a <em>single</em> variable for <code>startTime</code> and then another for <code>endTime</code>. If you give your variables meaningful names, you'll find that you never miss the old hungarian style. Indeed, I find that using hungarian often is accompanied by the <em>rest</em> of the variable name being an abbreviated, garbled mess. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T12:08:32.133", "Id": "2464", "ParentId": "2460", "Score": "3" } }, { "body": "<p>You are taking a DateTime, formatting it to a string, then assigning that to another datetime, just to get the time of day. That won't compile with Option Strict On. What you want is provided by DateTime.TimeOfDay.</p>\n\n<p>I would also change ByRef to ByVal in the parameter list.</p>\n\n<p>Once you are comparing timespan instead of date, you don't have to do date addition. You can just detect the wrap-around case and you only have to check endTime.</p>\n\n<pre><code> Public Function IsCurrentTimeBetween(ByVal dteStartTime As DateTime, ByVal dteEndTime As DateTime) As Boolean\n\n Dim startTime, endTime, currentTime As TimeSpan\n\n startTime = dteStartTime.TimeOfDay\n endTime = dteEndTime.TimeOfDay\n currentTime = Now.TimeOfDay\n\n If endTime &lt; startTime Then\n 'the times span midnight \n Return (currentTime &lt;= endTime)\n Else\n 'the times do not span midnight\n Return (startTime &lt;= currentTime AndAlso currentTime &lt;= endTime)\n End If\n\nEnd Function\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T15:57:05.280", "Id": "2480", "ParentId": "2460", "Score": "5" } }, { "body": "<p>Agreeing with Jeff P.</p>\n\n<pre><code>Private Sub Button2_Click(sender As System.Object, _\n e As System.EventArgs) Handles Button2.Click\n\n 'Work out if we are between 5 to midnight and quarter past midnight \n Debug.WriteLine(\"Is in midnight window? \" + IsCurrentTimeBetween(DateTime.Parse(\"23:55\"), DateTime.Parse(\"00:15\"), #12:01:00 AM#).ToString)\n\n Dim d As DateTime = #12:00:00 AM#\n Dim de As DateTime = #11:59:00 PM#\n\n Do While d &lt; de\n Debug.WriteLine(\"{0:HH:mm} {1:HH:mm} {2}\", d, d.AddMinutes(20), IsCurrentTimeBetween(d, d.AddMinutes(20), #12:01:00 AM#))\n d = d.AddMinutes(5)\n Loop\nEnd Sub\n\nPublic Function IsCurrentTimeBetween(ByVal dteStartTime As DateTime, _\n ByVal dteEndTime As DateTime, _\n Optional curTime? As DateTime = Nothing) As Boolean\n 'Jeff Paulsen's code with small change for testing\n Dim startTime, endTime, currentTime As TimeSpan\n\n startTime = dteStartTime.TimeOfDay\n endTime = dteEndTime.TimeOfDay\n If Not curTime.HasValue Then currentTime = DateTime.Now.TimeOfDay Else currentTime = curTime.Value.TimeOfDay\n\n If endTime &lt; startTime Then\n 'the times span midnight \n Return (currentTime &lt;= endTime)\n Else\n 'the times do not span midnight\n Return (startTime &lt;= currentTime AndAlso currentTime &lt;= endTime)\n End If\n\nEnd Function\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-23T15:10:24.697", "Id": "2569", "ParentId": "2460", "Score": "0" } }, { "body": "<p>i needed to be able to pass in a string that represents a time. . .so here's my solution (vb.net). Haven't come across a scenario this doesn't work for. </p>\n\n<pre><code>Function isBetween(ByVal timestart As String, ByVal timeEnd As String, ByVal checkDate As Date) As Boolean\n Dim dtBegin As Date = Date.Parse(Now.ToShortDateString &amp; \" \" &amp; timestart)\n Dim dtEnd As Date = Date.Parse(Now.ToShortDateString &amp; \" \" &amp; timeEnd)\n\n If dtBegin &gt; dtEnd Then 'times span midnight\n dtEnd = dtEnd.AddDays(1)\n\n If dtBegin &gt; checkDate And dtEnd &gt; checkDate Then 'checkdate is after midnight, make adjustment\n dtBegin = dtBegin.AddDays(-1)\n dtEnd = dtEnd.AddDays(-1)\n End If\n End If\n\n If checkDate &gt;= dtBegin AndAlso checkDate &lt; dtEnd Then Return True\n\n Return False\nEnd Function\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T12:42:51.923", "Id": "18538", "ParentId": "2460", "Score": "2" } } ]
{ "AcceptedAnswerId": "2480", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T08:49:14.603", "Id": "2460", "Score": "6", "Tags": [ ".net", "vb.net" ], "Title": "Function to test if the current time is within a time window" }
2460
<p>This works:</p> <pre><code>$('#ShowAll').click(function() { if ($(this).prop('checked')) { $('tr.hidden').show(); // todo: There's probably some clever toggle that could be used here. } else { $('tr.hidden').hide(); } }); </code></pre> <p>Is there a one-liner I can be doing instead? When the user clicks on the <code>ShowAll</code> <code>checkbox</code>, then show all the rows that have a class of <code>hidden</code>, else hide all the rows that have a class of <code>hidden</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T13:59:03.683", "Id": "3906", "Score": "1", "body": "$('tr.hidden').setHidden(!!$(this).prop('checked')); // or just look for generic method that toggles visibility. Like set css property or something" } ]
[ { "body": "<p><a href=\"http://api.jquery.com/toggle/\"><code>.toggle()</code></a> exists and seems to do exactly what you want here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T16:50:47.270", "Id": "2471", "ParentId": "2465", "Score": "6" } } ]
{ "AcceptedAnswerId": "2471", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T13:51:08.627", "Id": "2465", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Hidden rows toggle" }
2465
<p>I'm still pretty new to Ruby, and am really enjoying the language. I came across this method in my code base and realized that it could be cleaned up:</p> <pre><code>def friend_all_followers(friends) client.followers.each do |follower| if not friends.include?(follower.screen_name) friend = Friend.new(:screen_name =&gt; follower.screen_name) client.friendship_create(friend.screen_name, true) friend.save end end end </code></pre> <p>So I took the above and changed it to this:</p> <pre><code>def friend_all_followers(friends) followers = client.followers.reject { |f| friends.include?(f) } followers.each do |follower| friend = Friend.new(:screen_name =&gt; follower.screen_name) client.friendship_create(friend.screen_name, true) friend.save end end </code></pre> <p>One less level of nesting, and cleaner than the first method. But I look at this method and can't help but think there's still more to be done. Any ideas?</p> <p>As some background <code>Friend</code> is an <code>ActiveRecord</code> class, <code>client</code> is a wrapper around a Twitter API, <code>client.followers</code> returns an array of <code>follower</code> objects - the objects I believe are just hashes, but I'm not 100% certain at the moment - and <code>friends</code> is a string array of <code>screen_name</code>s.</p>
[]
[ { "body": "<p>You can replace</p>\n\n<pre><code>friend = Friend.new(:screen_name =&gt; follower.screen_name)\nclient.friendship_create(friend.screen_name, true)\nfriend.save\n</code></pre>\n\n<p>With</p>\n\n<pre><code>friend = Friend.create(:screen_name =&gt; follower.screen_name)\nclient.friendship_create(friend.screen_name, true)\n</code></pre>\n\n<p>I'd also suggest wrapping creation of friend in separate class method:</p>\n\n<pre><code>class Friend &lt; ActiveRecord::Base\n def create_with_follower(follower = nil)\n return unless follower\n create :screen_name =&gt; follower.screen_name\n end \nend\n</code></pre>\n\n<p>Then code becomes like this:</p>\n\n<pre><code>friend = Friend.create_with_follower follower\nclient.friendship_create(friend.screen_name, true)\n</code></pre>\n\n<p>I'd probably hide the <code>friendship_create</code> method call somewhere too. Not sure what it does though. Is it separate API call?</p>\n\n<p><strong>update</strong></p>\n\n<p>Now whole code becomes like this:</p>\n\n<pre><code>def friend_all_followers(friends)\n followers = client.followers.reject { |f| friends.include?(f) }\n followers.each do |follower|\n friend = Friend.create_with_follower follower\n client.friendship_create(friend.screen_name, true)\n end\nend\n</code></pre>\n\n<p>Now you can do some readable operation on array. Something like this:</p>\n\n<pre><code>def friend_all_followers(friends)\n (client.followers - friends).each do |follower|\n friend = Friend.create_with_follower follower\n client.friendship_create(friend.screen_name, true)\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T15:31:52.247", "Id": "3909", "Score": "0", "body": "Yup, friendship_create is used to create the friendship in twitter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T15:33:41.607", "Id": "3910", "Score": "0", "body": "Is there any way to simplify the loop as well?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T16:22:03.070", "Id": "3911", "Score": "0", "body": "Please see my update. Not sure where to go from there .)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T16:23:16.960", "Id": "3912", "Score": "0", "body": "Getting rid of the call to save by using create only works if `friendship_create` doesn't do anything that needs to be saved." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T16:24:43.050", "Id": "3913", "Score": "0", "body": "@sepp2k - agreed, but since this is API call - there is no need for it to modify the passed in object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T16:26:38.160", "Id": "3914", "Score": "0", "body": "@sepp2k you're right; luckily there is nothing done by `friendship_create`, so @Eimantas refactoring is correct. Also I didn't know you could use `-` between two arrays. That's awesome!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T14:56:21.903", "Id": "2468", "ParentId": "2467", "Score": "7" } }, { "body": "<p>Letting this percolate, I realized that I'm doing two things in <code>friend_all_followers</code>. The first is filtering new followers based on old followers (calling the variable <code>friends</code> obscures that, so I'll rename it), and the second is friending the new followers. By pulling the filtering into <code>new_followers</code>, I can rename <code>friend_all_followers</code> to a more explicit <code>friend_new_followers</code> like this:</p>\n\n<pre><code>def old_followers\n # ... get old followers\nend\n\ndef new_followers\n client.followers.reject { |f| old_followers.include?(f) }\nend\n\ndef friend_new_followers\n new_followers.each do |follower|\n friend = Friend.create(:screen_name =&gt; follower.screen_name)\n client.friendship_create(friend.screen_name, true)\n end\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T16:08:10.080", "Id": "2469", "ParentId": "2467", "Score": "1" } } ]
{ "AcceptedAnswerId": "2468", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-18T14:24:34.490", "Id": "2467", "Score": "4", "Tags": [ "ruby" ], "Title": "Simplification of loop in Ruby" }
2467
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-20.html" rel="nofollow">SICP</a>:</p> <blockquote> <p><strong>Exercise 3.8</strong></p> <p>When we defined the evaluation model in section 1.1.3, we said that the first step in evaluating an expression is to evaluate its subexpressions. But we never specified the order in which the subexpressions should be evaluated (e.g., left to right or right to left). When we introduce assignment, the order in which the arguments to a procedure are evaluated can make a difference to the result. Define a simple procedure f such that evaluating <code>(+ (f 0) (f 1))</code> will return 0 if the arguments to + are evaluated from left to right but will return 1 if the arguments are evaluated from right to left.</p> </blockquote> <p>I wrote this solution:</p> <pre><code>(define it false) (define (f x) (if it it (begin (set! it (/ x 2)) it))) (+ (f 1) (f 0)) </code></pre> <p>Is there a better way?</p>
[]
[ { "body": "<p>Your code returns 1/2 if the <code>(f 0)</code> is evaluated first, not 0. A better way would be to return the last argument to <code>f</code>, with a default of 0.</p>\n\n<pre><code>(define last 0)\n(define (f x)\n (define temporary last)\n (set! last x)\n temporary\n)\n</code></pre>\n\n<p>When <code>(+ (f 0) (f 1))</code> is evaluated with <code>(f 0)</code> first, execution is as follows:</p>\n\n<ol>\n<li><code>f</code> is called with 0</li>\n<li><code>temporary</code> is set to 0 (the default <code>last</code>) </li>\n<li><code>last</code> is set to 0 (the argument to f) </li>\n<li><code>temporary</code> (0) is returned</li>\n<li><code>f</code> is called with 1</li>\n<li><code>temporary</code> is set to 0</li>\n<li><code>last</code> is set to 1</li>\n<li><code>temporary</code> (0) is returned</li>\n<li>0+0=0</li>\n</ol>\n\n<p>If <code>(f 1)</code> is evaluated first, then execution is as follows:</p>\n\n<ol>\n<li><code>f</code> is called with 1</li>\n<li><code>temporary</code> is set to 0 (the default <code>last</code>) </li>\n<li><code>last</code> is set to 1 (the argument to f) </li>\n<li><code>temporary</code> (0) is returned</li>\n<li><code>f</code> is called with 0</li>\n<li><code>temporary</code> is set to 1</li>\n<li><code>last</code> is set to 0</li>\n<li><code>temporary</code> (1) is returned</li>\n<li>0+1=1</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T00:07:27.267", "Id": "3940", "Score": "0", "body": "I agree - returning the last argument is cleaner than my solution. I don't think that my answer returned 0.5 though - it computes 0/2 (which is 0) and then returns that twice - so it should still be correct? Anyway, I like your solution better. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T00:12:00.513", "Id": "3941", "Score": "0", "body": "@jaresty You're right, it would return 0. I thought 0 was considered false, but was wrong." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T20:30:08.100", "Id": "2488", "ParentId": "2476", "Score": "2" } } ]
{ "AcceptedAnswerId": "2488", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T03:28:53.623", "Id": "2476", "Score": "2", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Order of evaluation of function arguments" }
2476
<p>I have a function that is suppose to store variables based on their datatype, and this is table I have come up with to store those variables into.</p> <p>Is it smarter to have everything broken down like this or would be wiser to only have columns for the largest for the largest datatype of a group (such as string datatypes only having a <code>MEDIUMTEXT</code>)? I am expecting this table to become quite large and I would like to keep the tables storage space demands as small as possible.</p> <pre><code>CREATE TABLE IF NOT EXISTS form_part_detail( form_part_detail_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, form_part_detail_type_id INT NOT NULL, label VARCHAR(255) NOT NULL, `string` VARCHAR(255) NULL, `text` TEXT NULL, `mediumtext` MEDIUMTEXT NULL, `integer` INT NULL, `boolean` TINYINT(1) NULL, `float` FLOAT NULL, `double` DOUBLE NULL, FOREIGN KEY (form_part) REFERENCES `form_part` (form_part_id) FOREIGN KEY (form_part_detail_type_id) REFERENCES `form_part_detail_type` (form_part_detail_type_id) ); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T16:56:16.330", "Id": "3922", "Score": "0", "body": "Can you explain more about the example that motivated this? Normally, when you store data in a database, you know what type you are working with and write the schema accordingly. It seems like you're doing something at a higher level of abstraction here, but it's not clear to me exactly what." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T17:52:49.843", "Id": "3925", "Score": "0", "body": "There are objects (form_part) and each object has details (form_part_details). These details can differ from object to object. All that is certain is that there will be a label and some data for each detail. (I.E. title = VARCHAR, description = TEXT, required = BOOLEAN, etc.) Does this help any?" } ]
[ { "body": "<p>I would probably tackle it like this:</p>\n\n<ol>\n<li><p>The database would have a few columns:</p>\n\n<ul>\n<li><code>id</code></li>\n<li><code>label</code></li>\n<li><code>data</code> (of some type, say, <code>varchar</code> for now)</li>\n</ul></li>\n<li><p>The <code>Wrapper</code> class would be used to store/retrieve data from the database:</p>\n\n<ul>\n<li>Responsible for conversion (serialization) from whatever type is necessary to the backend data store</li>\n</ul></li>\n</ol>\n\n<p>The <code>Wrapper</code> class could have some sanity checks so that you couldn't ask for a int if it really was a string, etc etc.</p>\n\n<p>This probably doesn't satisfy your \"keeping things as small as possible\" requirement, but disk is cheep.</p>\n\n<p>You could create an object and basically serialize that and store the serialized version in the database. You could then deserialize that when you needed to.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T11:57:10.813", "Id": "3950", "Score": "0", "body": "That makes sense to me. I am already heading in that direction. Thanks for the advice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T01:00:26.387", "Id": "2495", "ParentId": "2477", "Score": "2" } } ]
{ "AcceptedAnswerId": "2495", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T13:38:34.820", "Id": "2477", "Score": "3", "Tags": [ "sql", "mysql" ], "Title": "Maintaining a column for each datatype" }
2477
<p>I've got a couple of utility functions to support memoization for functions with anywhere between 0 to 8 arguments:</p> <pre><code>Public Shared Function Mize(Of TResult)(ByVal input_f As System.Func(Of TResult)) As System.Func(Of TResult) Dim is_new = True Dim result As TResult Return Function() If is_new Then result = input_f() is_new = False End If Return result End Function End Function Public Shared Function Mize(Of TArg1 As Structure, TResult)(ByVal input_f As System.Func(Of TArg1, TResult)) As System.Func(Of TArg1, TResult) Dim map = New System.Collections.Generic.Dictionary(Of TArg1, TResult) Return Function(arg1 As TArg1) Dim result As TResult If map.TryGetValue(arg1, result) Then Return result result = input_f(arg1) map.Add(arg1, result) Return result End Function End Function Public Shared Function Mize(Of TArg1 As Structure, TArg2 As Structure, TResult)(ByVal input_f As System.Func(Of TArg1, TArg2, TResult)) As System.Func(Of TArg1, TArg2, TResult) Dim map = New System.Collections.Generic.Dictionary(Of System.Tuple(Of TArg1, TArg2), TResult) Return Function(arg1 As TArg1, arg2 As TArg2) Dim args = System.Tuple.Create(arg1, arg2) Dim result As TResult If map.TryGetValue(args, result) Then Return result result = input_f(arg1, arg2) map.Add(args, result) Return result End Function End Function Public Shared Function Mize(Of TArg1 As Structure, TArg2 As Structure, TArg3 As Structure, TResult)(ByVal input_f As System.Func(Of TArg1, TArg2, TArg3, TResult)) As System.Func(Of TArg1, TArg2, TArg3, TResult) Dim map = New System.Collections.Generic.Dictionary(Of System.Tuple(Of TArg1, TArg2, TArg3), TResult) Return Function(arg1 As TArg1, arg2 As TArg2, arg3 As TArg3) Dim args = System.Tuple.Create(arg1, arg2, arg3) Dim result As TResult If map.TryGetValue(args, result) Then Return result result = input_f(arg1, arg2, arg3) map.Add(args, result) Return result End Function End Function Public Shared Function Mize(Of TArg1 As Structure, TArg2 As Structure, TArg3 As Structure, TArg4 As Structure, TResult)(ByVal input_f As System.Func(Of TArg1, TArg2, TArg3, TArg4, TResult)) As System.Func(Of TArg1, TArg2, TArg3, TArg4, TResult) Dim map = New System.Collections.Generic.Dictionary(Of System.Tuple(Of TArg1, TArg2, TArg3, TArg4), TResult) Return Function(arg1 As TArg1, arg2 As TArg2, arg3 As TArg3, arg4 As TArg4) Dim args = System.Tuple.Create(arg1, arg2, arg3, arg4) Dim result As TResult If map.TryGetValue(args, result) Then Return result result = input_f(arg1, arg2, arg3, arg4) map.Add(args, result) Return result End Function End Function Public Shared Function Mize(Of TArg1 As Structure, TArg2 As Structure, TArg3 As Structure, TArg4 As Structure, TArg5 As Structure, TResult)(ByVal input_f As System.Func(Of TArg1, TArg2, TArg3, TArg4, TArg5, TResult)) As System.Func(Of TArg1, TArg2, TArg3, TArg4, TArg5, TResult) Dim map = New System.Collections.Generic.Dictionary(Of System.Tuple(Of TArg1, TArg2, TArg3, TArg4, TArg5), TResult) Return Function(arg1 As TArg1, arg2 As TArg2, arg3 As TArg3, arg4 As TArg4, arg5 As TArg5) Dim args = System.Tuple.Create(arg1, arg2, arg3, arg4, arg5) Dim result As TResult If map.TryGetValue(args, result) Then Return result result = input_f(arg1, arg2, arg3, arg4, arg5) map.Add(args, result) Return result End Function End Function Public Shared Function Mize(Of TArg1 As Structure, TArg2 As Structure, TArg3 As Structure, TArg4 As Structure, TArg5 As Structure, TArg6 As Structure, TResult)(ByVal input_f As System.Func(Of TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TResult)) As System.Func(Of TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TResult) Dim map = New System.Collections.Generic.Dictionary(Of System.Tuple(Of TArg1, TArg2, TArg3, TArg4, TArg5, TArg6), TResult) Return Function(arg1 As TArg1, arg2 As TArg2, arg3 As TArg3, arg4 As TArg4, arg5 As TArg5, arg6 As TArg6) Dim args = System.Tuple.Create(arg1, arg2, arg3, arg4, arg5, arg6) Dim result As TResult If map.TryGetValue(args, result) Then Return result result = input_f(arg1, arg2, arg3, arg4, arg5, arg6) map.Add(args, result) Return result End Function End Function Public Shared Function Mize(Of TArg1 As Structure, TArg2 As Structure, TArg3 As Structure, TArg4 As Structure, TArg5 As Structure, TArg6 As Structure, targ7 As Structure, TResult)(ByVal input_f As System.Func(Of TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, targ7, TResult)) As System.Func(Of TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, targ7, TResult) Dim map = New System.Collections.Generic.Dictionary(Of System.Tuple(Of TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, targ7), TResult) Return Function(arg1 As TArg1, arg2 As TArg2, arg3 As TArg3, arg4 As TArg4, arg5 As TArg5, arg6 As TArg6, arg7 As targ7) Dim args = System.Tuple.Create(arg1, arg2, arg3, arg4, arg5, arg6, arg7) Dim result As TResult If map.TryGetValue(args, result) Then Return result result = input_f(arg1, arg2, arg3, arg4, arg5, arg6, arg7) map.Add(args, result) Return result End Function End Function Public Shared Function Mize(Of TArg1 As Structure, TArg2 As Structure, TArg3 As Structure, TArg4 As Structure, TArg5 As Structure, TArg6 As Structure, targ7 As Structure, targ8 As Structure, TResult)(ByVal input_f As System.Func(Of TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, targ7, targ8, TResult)) As System.Func(Of TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, targ7, targ8, TResult) Dim map = New System.Collections.Generic.Dictionary(Of System.Tuple(Of TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, targ7, targ8), TResult) Return Function(arg1 As TArg1, arg2 As TArg2, arg3 As TArg3, arg4 As TArg4, arg5 As TArg5, arg6 As TArg6, arg7 As targ7, arg8 As targ8) Dim args = New System.Tuple(Of TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, targ7, targ8)(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) Dim result As TResult If map.TryGetValue(args, result) Then Return result result = input_f(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) map.Add(args, result) Return result End Function End Function </code></pre> <p>The problem is that the memoization algorithm is repeated 6 times (the functions that accept functions with 2 arguments to 8 arguments basically have the same algorithm).</p> <p>I'm clearly violating <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow">DRY</a> here, and I want to modify the code above to not violate DRY.</p> <p>I've tried shifting those repeating algorithm into a separate function, but since VB.NET/C# does not allow <code>System.Delegate</code> as a generic constraint, I'm out of ideas as to how I would do it.</p> <p>What should I do and how can I improve my code above?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T15:12:53.660", "Id": "3958", "Score": "0", "body": "@Pacerier: Next time please say it only one time and use a list of names. ;) Also, would you now be so kindly and press the Delete-Button?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T15:27:47.917", "Id": "3959", "Score": "0", "body": "@Bobby i mean i would like all of them to have the notification" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T08:58:37.307", "Id": "85929", "Score": "0", "body": "Check [this out](http://mullr.wordpress.com/2006/05/02/easy-c-memoization/). Alternatively, you can resort to [AOP](http://dpatrickcaldwell.blogspot.com/2009/02/memoizer-attribute-using-postsharp.html): [Memoizer Attribute Using PostSharp](http://dpatrickcaldwell.blogspot.com/2009/02/memoizer-attribute-using-postsharp.html)" } ]
[ { "body": "<p>Unless you want to go with another approach, like code injection (see Anton's comment), you're pretty much stuck with this. I agree it is ugly and repetitive. Basically you've run up against the edges of the type system. Type parameters are a little like method parameters, and type arguments are a little like passing arguments to a method, but methods are much more flexible. Methods permit all sorts of higher-order programming, methods can be variadic, and so on. There are no variadic generic types in the .NET type system, which is really what you want to make this sort of thing work smoothly. </p>\n\n<p>As for violating the DRY principle, don't worry about it. The reason to not repeat yourself is because if you have the same piece of complex business logic in two different places, and one of them needs fixing, they can get out of sync easily when you forget to fix the other. (The C# compiler codebase is littered with comments that say \"If you change the reference type convertibility algorithm here, don't forget to also change it here, here and here...\") What you're building here is a <em>mechanism</em>: the boring plumbing code that makes the real logic of the program more efficient. DRY is more applicable to business logic than to boring mechanisms.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T14:09:52.237", "Id": "2509", "ParentId": "2478", "Score": "14" } } ]
{ "AcceptedAnswerId": "2509", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T14:59:10.227", "Id": "2478", "Score": "12", "Tags": [ "design-patterns", ".net", "vb.net", "memoization" ], "Title": "Utility functions for supporting memoization for functions" }
2478
<p>I have this set of legacy C++ projects with a large number of public functions. At the start, none of those publicly exposed functions had <code>try..catch</code> insulation inside them. When a C++ exception fired across that boundary, if the caller wasn't compiled with the same C++ compiler and the same project settings, then it easily caused a crash.</p> <p>To help insulate against this problem I first went into every public function and wrapped the public function bodies with all-encompassing <code>try...catch</code> blocks, with the <code>catch</code> attempting to log a message about the exception. Basically just handling the (<code>...</code>) case and logging "<em>Unexpected Exception</em>".</p> <p>With hundreds of public functions (working up to thousands), this became tedious when I decided to add specialized <code>std::exception</code> handlers to them all, other dev team members update some to do something different, etc.</p> <p>In the interests of DRY (<em>Don't Repeat Yourself</em>), I chose to make a <em>generic catch block</em> which gets applied in those instances where I wanted something fast to insulate a function from throwing an exception but get as much info as possible into the log.</p> <p>C++ exceptions being what they are, I couldn't figure out a nice simple portable way to do it without using a macro. Yes, yes, sad but true, another macro is born, but I am interested to learn about any other options considering it must be portable and fast. I don't mean to say macros are portable and fast, but this implementation fits the bill...</p> <pre><code>#define CatchAll( msg ) \ catch( const Poco::Exception &amp;e ) \ { \ try{ LogCritical( Logs.System(), std::string( e.displayText() ).append( msg ) );}catch(...){assert(0);} \ } \ catch( const std::exception &amp;e ) \ { \ try{LogCritical( Logs.System(), std::string( e.what() ).append( msg ) );}catch(...){assert(0);} \ } \ catch(...) \ { \ try{ LogCritical( Logs.System(), std::string( "Exception caught in " __FUNCTION__ ". " ).append( msg ) );}catch(...){assert(0);} \ } </code></pre> <p>So there you have it. The code above gets called like this...</p> <pre><code>try{ // statements that can throw } CatchAll("*Special extra message about what was attempted in the try block*") </code></pre> <p>So that's it, that's the magic. This isn't meant to replace an intelligently coded block of specific exception handling, this <strong>is</strong> meant to quickly put <em>bare-bones</em> insulation where none existed before, and do it in a DRY, portable, fast and easy to grok way.</p> <p>Ok, ok, macros are evil, I know, but what else could be done here?</p> <p>And as goes the way of the macro, they proliferate and multiply. Here's a secondary macro to <em>set an <strong>rc</strong> code</em> in addition to logging, so the function can <em>return a failing rc</em> if an exception throws in the insulated function...</p> <pre><code>/// Catch all generic exceptions and log appropriately. /// Logger is insulated from throwing, so this is a NO THROW operation. /// Sets rc (integer parameter) so wrapping function can perform cleanup /// before returning the error number. #define CatchAllSetRC( rc, msg ) \ catch( const Poco::Exception &amp;e ) \ { \ (rc) = -1; \ try{ LogCritical( Logs.System(), std::string( e.displayText() ).append( msg ));}catch(...){assert(0);} \ } \ catch( const std::exception &amp;e ) \ { \ (rc) = -1; \ try{ LogCritical( Logs.System(), std::string( e.what() ).append( msg ));}catch(...){ assert(0); } \ } \ catch(...) \ { \ (rc) = -1; \ try{ LogCritical( Logs.System(), std::string( "Exception caught in " __FUNCTION__ ". " ).append( msg ));}catch(...){ assert(0); } \ } </code></pre> <p>This expanded version gets called with an rc code so the caller can return it...</p> <pre><code>int rc = 0; try{ // statements that can throw } CatchAll(rc, "Extra info to append to logged exception message") </code></pre>
[]
[ { "body": "<p>Well, there's a way of doing it with template functions, but I don't think I like it any more than your solution:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nusing namespace std;\n\ntemplate&lt;typename P, typename Q, typename Ret&gt;\nRet handle_all( Ret(*fn)(P, Q), P p, Q q) {\n try {\n Ret ret = fn(p, q);\n return ret;\n }\n catch (...) {\n cout &lt;&lt; \"Unexpected exception\" &lt;&lt; endl;\n }\n}\n\ntemplate&lt;typename P, typename Ret&gt;\nRet handle_all(Ret (*fn)(P), P p) {\n try {\n Ret ret = fn(p);\n return ret;\n }\n catch (...) {\n cout &lt;&lt; \"Unexpected exception\" &lt;&lt; endl;\n }\n}\n\nint funky_function(int a, string b) {\n cout &lt;&lt; \"a=\" &lt;&lt; a &lt;&lt; endl;\n cout &lt;&lt; \"b=\" &lt;&lt; b &lt;&lt; endl;\n\n throw \"wild exception\";\n // Throwing strings is stupid, this is just an example...\n}\n\nint other_function(int a) {\n cout &lt;&lt; \"single parameter a=\" &lt;&lt; a &lt;&lt; endl;\n\n throw \"wild exception\";\n}\n\nint main (void) {\n handle_all(funky_function, 12, string(\"some string\"));\n handle_all(other_function, 16);\n}\n</code></pre>\n\n<p>You need to declare a version of <code>handle_all</code> for each different number of function parameters you want to support, but not for every combination of types. That means that every time you change your exception handling you'll have to update more than one piece of code, but only a small number.</p>\n\n<p>The syntax of calling the function to be wrapped is a bit unfortunate, in that the parameters to the function go in the same parameter list as the name of the function to be called. I think you could work around this by using a template functor class rather than a template method (with an overload for <code>operator()</code>).</p>\n\n<p><strong>Edit</strong>: Here's what the functor solution would look like:</p>\n\n<pre><code>template&lt;typename P, typename Q, typename Ret&gt;\nclass handle_all {\n public:\n handle_all(Ret (*fn)(P, Q)) : fn(fn) { }\n\n Ret operator()(P p, Q q) {\n try {\n Ret ret = fn(p, q);\n return ret;\n }\n catch (...) {\n cout &lt;&lt; \"Unexpected exception\" &lt;&lt; endl;\n }\n }\n\n private:\n Ret (*fn) (P, Q);\n};\n</code></pre>\n\n<p>You have to call it like this:</p>\n\n<pre><code>handle_all&lt;int, string,int&gt; runner(funky_function);\nrunner(12, \"some string\");\n</code></pre>\n\n<p>Note that in this case, automatic construction of a temporary <code>std::string</code> from the string literal works as expected. Apart from that, it's not much of an improvement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-29T04:17:10.993", "Id": "4198", "Score": "0", "body": "Like it, but the handler needs to encapsulate more than one function. I guess adding the concept of lamdas might allow it, but if anything inside that block happened to be a macro then the templating of it might bust if there's a macro inside the stuff it surrounds." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T17:42:53.957", "Id": "4221", "Score": "1", "body": "The handler encapsulates any function with the given number of parameters, e.g. all 1-parameter functions. You need a new version of the handler for each possible number of function arguments, but hopefully there aren't that many cases of functions with lots of parameters. I'm not sure this is the code's biggest weakness, though. :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-30T11:37:27.957", "Id": "111774", "Score": "0", "body": "Maybe you could make a single version using variadic templates" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T17:22:33.273", "Id": "2486", "ParentId": "2484", "Score": "3" } }, { "body": "<p>In the catch block, you can rethrow the exception. This can be done in a function:</p>\n\n<pre><code>int rc = 0;\ntry{\n// statements that can throw\n}catch(...){\n HandleException(rc, \"Extra info to append to logged exception message\");\n}\n\n\n\nvoid HandleException(int rc, std::string msg)\n{\n try{\n throw;\n }catch(Poco::Exception &amp;e){\n // ...\n }catch( const std::exception &amp;e){\n // ...\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-29T04:31:30.160", "Id": "4199", "Score": "0", "body": "Great! I had no idea the exception could be rethrown inside a different function called from within the catch block and keep all its original data. This concept will suite my needs perfectly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-17T07:59:40.933", "Id": "115328", "Score": "1", "body": "I have never seen the re-throw used like that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T15:53:44.370", "Id": "2517", "ParentId": "2484", "Score": "18" } }, { "body": "<p>This question is getting old, but there is actually <a href=\"http://blogs.msdn.com/b/vcblog/archive/2014/01/16/exception-boundaries.aspx\" rel=\"nofollow noreferrer\">an elegant way</a> to create such an exception boundary: create a function as the one proposed by @Tim Martin, then wrap the old code into lambdas that will be called by the exception boundary handle. Here it the excception boundary handle:</p>\n\n<pre><code>template&lt;typename Callable&gt;\nauto exception_boundary_handle(Callable&amp;&amp; func, const std::string&amp; msg=\"\"s)\n -&gt; decltype(func())\n{\n try\n {\n return func();\n }\n catch( const Poco::Exception &amp;e )\n {\n try{ LogCritical( Logs.System(), std::string( e.displayText() ).append( msg ) );}catch(...){assert(0);}\n }\n catch( const std::exception &amp;e )\n {\n try{LogCritical( Logs.System(), std::string( e.what() ).append( msg ) );}catch(...){assert(0);\n }\n catch(...)\n {\n try{ LogCritical( Logs.System(), std::string( \"Exception caught in \" __FUNCTION__ \". \" ).append( msg ) );}catch(...){assert(0);}\n } \n}\n</code></pre>\n\n<p>You can use it as follows:</p>\n\n<pre><code>int some_func(int eggs)\n{\n return exception_boundary_handle([&amp;] {\n // put the old code here,\n // I filled it with pseudo-random stuff\n eggs += 42;\n return eggs;\n },\n \"Extra error message if you ever need it\");\n}\n</code></pre>\n\n<p>Of course, since this is not a macro solution, you will have to add another parameter if you want to inject the <code>__FUNCTION__</code> information into the handler:</p>\n\n<pre><code>template&lt;typename Callable&gt;\nauto exception_boundary_handle(Callable&amp;&amp; func,\n const std::string&amp; msg=\"\"s,\n const std::string&amp; func_name=\"\")\n -&gt; decltype(func())\n{\n try\n {\n return func();\n }\n // ...\n catch(...)\n {\n try{ LogCritical( Logs.System(), std::string( \"Exception caught in \"s + func_name + \". \"s ).append( msg ) );}catch(...){assert(0);}\n } \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-01T18:35:20.043", "Id": "71330", "ParentId": "2484", "Score": "6" } } ]
{ "AcceptedAnswerId": "2517", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T16:57:22.787", "Id": "2484", "Score": "18", "Tags": [ "c++", "error-handling", "exception", "macros", "poco-libraries" ], "Title": "Generic C++ exception catch handler macro" }
2484
<p>This is exercise 5-4 from <em>K&amp;R</em>. I spent hours tweaking it but now it seems to work. I'm new to pointers and I'd welcome any comments about how to do it better.</p> <pre><code>/* Function strend(s, t), which returns 1 if the string t * occurs at the end of string s and zero otherwise */ int strend(const char *s, const char *t) { const char *s0, *t0; if (s == 0) { printf("s is NULL pointer\n"); return (-1); } if (t == 0) { printf("t is NULL pointer\n"); return (-1); } s0 = s; t0 = t; while (*s++) ; s -= 2; /* *s points to last real char in s */ while (*t++) ; t -= 2; /* *t points to last real char in t */ if ((t-t0) &gt; (s-s0)) return (0); /* t is longer than s */ while (t&gt;=t0) { if (*s-- != *t--) return (0); /* Mismatch */ } return (1); /* Match */ } </code></pre> <p>Here is <code>main()</code>:</p> <pre><code>/* Test the function strend(s, t), which returns 1 if the string t * occurs at the end of string s and zero otherwise */ #include "jim.h" #include "subs.c" char a[MAXLINE], b[MAXLINE]; int main (void) { printf("Return = %1d, Expect = 1\n", strend("12345", "45")); printf("Return = %1d, Expect = 0\n", strend("12345", "35")); printf("Return = %1d, Expect = 0\n", strend("45", "345")); printf("Return = %1d, Expect = 1\n", strend("12345", "12345")); printf("Return = %1d, Expect = 1\n", strend("12345", "5")); printf("Return = %1d, Expect = 0\n", strend("12345", "4")); printf("Return = %1d, Expect = 1\n", strend("12345", "")); printf("Return = %1d, Expect = 0\n", strend("12345", "+")); printf("Return = %1d, Expect = 0\n", strend("12345", "a2345")); printf("Return = %1d, Expect = 1\n", strend("", "")); printf("Return = %1d, Expect = 0\n", strend("", "Z")); printf("Return = %1d, Expect = 1\n", strend("1", "1")); printf("Return = %1d, Expect = 0\n", strend("1", "1A")); printf("Return = %1d, Expect = -1\n", strend(0, "1A")); printf("Return = %1d, Expect = -1\n", strend("1", 0)); } </code></pre> <p>Here is the output:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Return = 1, Expect = 1 Return = 0, Expect = 0 Return = 0, Expect = 0 Return = 1, Expect = 1 Return = 1, Expect = 1 Return = 0, Expect = 0 Return = 1, Expect = 1 Return = 0, Expect = 0 Return = 0, Expect = 0 Return = 1, Expect = 1 Return = 0, Expect = 0 Return = 1, Expect = 1 Return = 0, Expect = 0 s is NULL pointer Return = -1, Expect = -1 t is NULL pointer Return = -1, Expect = -1 </code></pre> </blockquote>
[]
[ { "body": "<p>Const correct the pointers. The function is not changing anything in memory, no reason they shouldn't be <code>const</code>. Same with variables you declare in the function; Make them <code>const</code></p>\n\n<pre><code>int strend(const char* s, const char* t)\n</code></pre>\n\n<p>Check for NULL in the input pointers.</p>\n\n<p>Use library string functions wherever possible.\nInstead of doing:</p>\n\n<pre><code>while(*s++) ;\ns-=2;\n</code></pre>\n\n<p>call <code>strlen(s);</code> and then substract 1 as needed in your algo. Since you are iterating over the string anyway replacing this with a function call has the same efficiency and makes it more readable.</p>\n\n<p>Add <code>{</code> around the while loop. It is future-proof.</p>\n\n<p>Unit-test to confirm correctness.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T21:44:53.663", "Id": "3933", "Score": "0", "body": "Thx, Chintan. What do you mean by unit-test?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T22:39:05.463", "Id": "3934", "Score": "0", "body": "@grok unit-testing is an agile concept where you write the test code first before implementing the actual function. This is usually done with the support of a unit-testing framework to make this process easy. Just google or search on SO if you need more details." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T23:56:52.903", "Id": "3937", "Score": "0", "body": "@Chintan: After I looked it up I realized that it is what we did 30 years ago in microprocessor design. Create an environment where you can test your part of the chip design (we actually called them units!) thoroughly without using anything outside your unit. It made integration go much easier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T23:58:10.750", "Id": "3938", "Score": "0", "body": "I've edited my question to include all of Chintan's input and showed my main used for unit-testing and the output from the test." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T00:00:52.403", "Id": "3939", "Score": "0", "body": "Don't know why I can't vote your answer up. It wants me to login or register but I'm already logged in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T15:50:39.243", "Id": "3966", "Score": "0", "body": "I disagree with the \"check for null\" thing. If you pass in null you deserve to have your process crash, since that's a bug. The caller should be careful to pass correct parameters, not the callee to ensure them. Of course this is a subjective statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-21T09:53:12.333", "Id": "3980", "Score": "0", "body": "Victor T.'s answer confuses unit testing with test driven development. Unit testing is writing tests for a unit of code (for some definition of a unit e.g. a class or a module). They can be written before, after or in parallel with the code. Test driven development is the practice of always writing the tests first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T21:31:51.627", "Id": "49365", "Score": "0", "body": "Tests (such as unit tests) don't confirm correctness, they confirm incorrectness." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T21:12:23.320", "Id": "2491", "ParentId": "2489", "Score": "6" } }, { "body": "<p>I'd change it more like...</p>\n\n<pre><code>char* start_of_s = s;\nchar* start_of_t = t;\nif(s == NULL || t==NULL) return 0;\nwhile(*s) s++;\nwhile(*t) t++;\nwhile(*s == *t &amp;&amp; s &gt; start_of_s &amp;&amp; t&gt; start_of_t)\n{\n s--; t--;\n}\nreturn (t == start_of_t) &amp;&amp; (*s == *t);\n</code></pre>\n\n<p>also unit tested with your tests (and mine), except I caled it \"string_is_at_end\". I use <a href=\"http://code.google.com/p/seatest/\" rel=\"nofollow\">http://code.google.com/p/seatest/</a> for unit testing. ( mainly coz I wrote it, though I have a much later version which I haven't released yet)</p>\n\n<pre><code> assert_true(string_is_at_end(\"12345\",\"\"));\n assert_true(string_is_at_end(\"123\",\"23\"));\n assert_true(string_is_at_end(\"123\",\"3\"));\n assert_false(string_is_at_end(\"\",\"123\"));\n assert_false(string_is_at_end(\"123\",\"1\"));\n assert_false(string_is_at_end(\"123\",\"2\"));\n assert_true(string_is_at_end(\"12345\", \"45\"));\n assert_false(string_is_at_end(\"12345\", \"35\"));\n assert_false(string_is_at_end(\"45\", \"345\"));\n assert_true(string_is_at_end(\"12345\", \"12345\"));\n assert_true(string_is_at_end(\"12345\", \"5\"));\n assert_false(string_is_at_end(\"12345\", \"4\"));\n assert_true(string_is_at_end(\"12345\", \"\"));\n assert_false(string_is_at_end(\"12345\", \"+\"));\n assert_false(string_is_at_end(\"12345\", \"a2345\"));\n assert_true(string_is_at_end(\"\", \"\"));\n assert_false(string_is_at_end(\"\", \"Z\"));\n assert_true(string_is_at_end(\"1\", \"1\"));\n assert_false(string_is_at_end(\"1\", \"1A\"));\n assert_false(string_is_at_end(0, \"1A\"));\n assert_false(string_is_at_end(\"1\", 0));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T01:05:33.650", "Id": "3942", "Score": "0", "body": "I DLd your stuff and it looks pretty cool. It looks like it could be a match for my project which is:" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T01:06:50.780", "Id": "3943", "Score": "0", "body": "I hate how the return key pops you out of a comment. My project is: \"To design the microprocessor that I wish I had designed in 1975.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T01:09:54.570", "Id": "3944", "Score": "0", "body": "By the way, I like your version better than mine." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T00:12:28.310", "Id": "2492", "ParentId": "2489", "Score": "0" } }, { "body": "<p>Seems like this could be a lot shorter....</p>\n\n<pre><code>/* Function strend(s, t), which returns 1 if the string t \n * occurs at the end of string s and zero otherwise */\nint strend(const char *s, const char *t)\n{\n size_t slen, tlen;\n\n if (!s || !t)\n return -1;\n\n slen = strlen(s);\n tlen = strlen(t);\n\n /* Is t longer than s? */\n if (tlen &gt; slen)\n return 0;\n\n /* Compare the strings... */\n return !strcmp(s + slen - tlen, t);\n}\n</code></pre>\n\n<p>While I'm all in favor of the crazy C style pointer arithmetic loops when they make sense, I don't think it really gains you much to reinvert <code>strlen</code>. And doing the compare backwards is kind of weird, especially where <code>strcmp</code> is perfectly reasonable. I mean, you can deduce the lengths from the previous pass... No need to be all macho.</p>\n\n<p>Also, this is subjective, but I don't think it makes sense to return <code>-1</code> if NULL is passed. Especially since the function lends itself towards use in a boolean expression; <code>if (strend(NULL, \"foo\"))</code> will be true, which is weird. Maybe you should let the program crash in that point. (Since dereferencing NULL is a bug.) Or if that scares you, you could return <code>0</code>. (A NULL pointer can't be said to have a suffix or be a suffix, right?)</p>\n\n<p>I might also consider changing the name. Something like <code>str_contains_suffix</code> maybe?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T21:33:19.620", "Id": "3972", "Score": "0", "body": "Thx, asveikau, good points. I guess that !s will be true is s is null because a null pointer points to address 0, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-21T01:28:56.513", "Id": "3976", "Score": "0", "body": "@grok12 correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T21:30:58.920", "Id": "49364", "Score": "0", "body": "Writing `strlen` yourself has the potential of fusing the loops, i.e. you could calculate the length of both strings in a single loop and bail out immediately if you notice that `s` is shorter than `t` instead of computing the exact length of `t` in all cases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T22:34:44.817", "Id": "49368", "Score": "0", "body": "@FrerichRaabe - I agree that there could be performance benefits to a single-pass rather than doing both `strlen` and `strcmp`. OTOH it might be that your libc's string functions have crazy platform-specific optimizations that you won't be able to beat. Or, for most common data sizes, maybe there'd be no difference at all. And in big-O terms a cost of N and 2N is still O(N)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T08:30:17.670", "Id": "49402", "Score": "0", "body": "@asveikau: Yeah, the point is: if you fuse the loops, you can pull the `tlen > slen` check into the loop. In your code, imagine if `t` is 1048576 bytes and `s` is just two bytes. As it is, the `strlen(t)` call will walk the entire `t` string. If you fuse the loops and pull in the `tlen > slen` check you wouldn't need to compute the exact length of `t` if you can tell that it's longer than `s`. The `if` is quite simple too, so the branch predictor of the processor should have an easy time with it." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T15:21:56.480", "Id": "2516", "ParentId": "2489", "Score": "3" } } ]
{ "AcceptedAnswerId": "2491", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T20:30:56.087", "Id": "2489", "Score": "7", "Tags": [ "c", "strings", "pointers" ], "Title": "Determining if one string occurs at the end of another" }
2489
<p>I would like to efficiently import real numbers stored in CSV format into an array. Is there a way to modify my code to make it faster? Also, is there a way to scan the file and compute the number of rows and columns rather than having to provide these directly?</p> <pre><code>double * getcsv(string fname, int m, int n){ double *a; a = (double *)malloc(n * m * sizeof(double)); ifstream fs(fname.c_str()); char buf[100]; for(int i=0;i&lt;m;i++){ for(int j=0;j&lt;n;j++){ if (j &lt; (n-1) ){ fs.getline(buf,100,',');} else{ fs.getline(buf,100);} stringstream data(buf); data&gt;&gt;a[(i*n)+j]; } } return(a); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T20:57:49.177", "Id": "3932", "Score": "0", "body": "I am not sure how to do the formatting to indicate my code. If someone knows how, I will fix this quickly." } ]
[ { "body": "<ul>\n<li>In C++, we usually avoid <code>malloc</code> - in this case, you could use a <code>std::vector&lt; double &gt;</code> in stead. Doing this, you will allow the user of your code to use RAII in stead of manually managing the allocated memory. You cal tell the vector how much to allocate by initializing it with the right size. The compiler will apply return value optimization to avoid copying the vector (by constructing it into the return value) so you shouldn't worry too much about that.</li>\n<li>You don't preserve the values of <code>m</code> and <code>n</code>. I don't know if this is intentional but if you don't want to burden your client code with lugging it around, consider a <code>struct</code> or a <code>class</code> to carry it, and the values you read, around.</li>\n<li>You don't check the return values of the methods you call on the <code>fstream</code> - you should.</li>\n<li>You'd probably be better off reading the values from the <code>fstream</code> directly into the array, rather than reading them into a buffer, copying that buffer into a <code>stringstream</code> and then reading them from the <code>stringstream</code> to convert. You can save the use of the <code>stringstream</code> (and therefore eliminate it altogether).</li>\n</ul>\n\n<p><strong>Example program:</strong></p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;iterator&gt;\n#include &lt;sstream&gt;\n#include &lt;vector&gt;\n\nusing namespace std;\n\nstruct Data\n{\n Data(unsigned int width, unsigned int height)\n : width_(width)\n , height_(height)\n , data_(width * height)\n { /* no-op */ }\n unsigned int width_;\n unsigned int height_;\n vector&lt; double &gt; data_;\n};\n\nData split(istream &amp;is, unsigned int width, unsigned int height)\n{\n Data retval(width, height);\n double d;\n int i(0);\n\n while (is &gt;&gt; d)\n {\n retval.data_[i++] = d;\n is.ignore(1, ',');\n }\n\n return retval;\n}\n\nint main()\n{\n const char *test_string = \"\"\n \"2.83, 31.26, 2354.3262, 0.83567\\n\"\n \"12.3, 35.236, 2854.3262, 0.83557\\n\"\n \"32.3, 33.26, 2564.3262, 0.83357\\n\"\n \"27.3, 3.2869, 2594.3262, 0.82357\\n\";\n const unsigned int width = 4;\n const unsigned int height = 4;\n stringstream ss(test_string);\n Data data(split(ss, width, height));\n copy(data.data_.begin(), data.data_.end(), ostream_iterator&lt; double &gt;(cout, \" \"));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T02:30:37.620", "Id": "3945", "Score": "0", "body": "Thanks for the feedback. Can you give me a sample of the code I need to write to read the values from fstream directly into an array?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-21T00:04:20.873", "Id": "3975", "Score": "1", "body": "@HenryB I've edited my answer to add sample code. The example is self-sufficient, but having similar input in a file and using `fstream` should yield the same results. Note that only the `split` function is the function you're looking for" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T00:23:40.363", "Id": "2493", "ParentId": "2490", "Score": "3" } }, { "body": "<p>rlc has covered all the important parts in his answer. I merely want to mention <a href=\"http://www.boost.org/doc/libs/1_57_0/libs/iostreams/doc/classes/mapped_file.html\" rel=\"nofollow\"><code>boost::iostreams::mapped_file</code></a> since you specifically asked for performance improvements. Memory-mapping files can give you <a href=\"https://stackoverflow.com/questions/192527/what-are-the-advantages-of-memory-mapped-files\">great speed boosts</a>. Note that unlike <code>std::fstream</code>, the file must exist before being opened. Also, the memory-mapped file is opened in binary mode so you must alter you code accordingly.</p>\n\n<p>Memory-mapped files are much more low-level than your current approach. Only pursue this option if you have profiled your current code and found it to be I/O bound.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-05T19:30:30.520", "Id": "69008", "ParentId": "2490", "Score": "0" } } ]
{ "AcceptedAnswerId": "2493", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-19T20:57:08.133", "Id": "2490", "Score": "2", "Tags": [ "c++", "csv" ], "Title": "Fast import of numbers stored in a CSV file" }
2490
<p>Today, I came across a code example like the following:</p> <pre><code>Option Explicit Sub MySub() Dim iCount As Integer For iCount = 0 To 100 Debug.Print "Arbitrary Code Here" If iCount Mod 2 = 0 Then Dim myString As String 'This is the line I'm curious about myString = iCount Debug.Print myString End If Next iCount End Sub </code></pre> <p>Once a variable goes in scope in VB6 and/or VBA, it stays in scope throughout the procedure. </p> <p>So, is it a bad programming practice to declare a variable in a loop? Is it better to declare myString either at the top of the procedure or, at the very least, above the FOR LOOP?</p>
[]
[ { "body": "<p>It is bad programming practice to declare a variable in a loop, when it's only going to be re-used in the loop, even if in VB it won't be re-initialized every time.</p>\n\n<p>A good link on declarations in VB is <a href=\"http://www.vb6.us/tutorials/vb6-variable-scope\" rel=\"nofollow\">here</a>.</p>\n\n<p>One quote:</p>\n\n<blockquote>\n <p>The recommended practice is to declare\n all local variables within a procedure\n immediately following the Sub or\n Function header and prior to any\n executable statements (although VB\n will allow you to declare variables\n anywhere within the procedure).</p>\n</blockquote>\n\n<p>In a long enough module, you'd want a variable with limited scope to be DIMmed close to where it's being used, but always outside of a loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T13:13:33.867", "Id": "3951", "Score": "0", "body": "Why should it be outside of the loop? You've just said it's preferable to declare it close to where it's used, and if it's only used in the loop that's the closest you can get. Why the double standard?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T15:19:41.467", "Id": "3963", "Score": "0", "body": "@Mark, it's not a double standard. You get it as close to the loop as possible but not in the loop. So in this small case, it should be right with the other DIM statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T16:16:40.603", "Id": "3967", "Score": "0", "body": "The question is about VB6, which treats all variables declared in the procedure as procedure-scoped, and initializes them once. It's a surprising thing the first time you run into it, and leads to defensive measures like manually writing an explicit initializer at the top of every loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T16:24:11.473", "Id": "3968", "Score": "4", "body": "to clarify, I agree with Lance, but not for the reason of multiple re-initialization. I agree because putting the declaration in the loop makes the reader THINK there will be reinitialization." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T16:35:30.830", "Id": "3969", "Score": "0", "body": "@Jeff, thanks, I've edited the answer. Learn something new every day on Stack Exchange." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T03:59:27.213", "Id": "2498", "ParentId": "2496", "Score": "3" } }, { "body": "<p>In most languages, where the variable scope is defined by the block it's defined (such as VB), it's preferred to declare the variable close to where it's going to be used. In others with function-level scope (such as javascript, where a variable declared anywhere is scoped to the whole function where it was defined), I've usually seen it being declared at the beginning of the function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T04:42:24.540", "Id": "2500", "ParentId": "2496", "Score": "4" } }, { "body": "<p>There are a few things to consider here. First we have to consider if the position will matter to the compiler, which depends on the language. VB6 will scope that variable to the function (or sub in this case), so it doesn't matter too much there. In VB.NET, the variable will be scoped to the containing block (in this case the loop), so declaring inside of the loop would let us reuse that same variable name in some other block.</p>\n\n<p>In terms of maintainability, there are two good reasons to put the declaration as close as possible to the first use of the variable. One, it improves readability. Two, it simplifies future refactoring -- imagine that you wanted to move that loop to its own function, that's easier if the variable is right there with the loop.</p>\n\n<p>short answer: In VB6 I think it's best to declare just before the loop. This is mostly so that nobody thinks that the variable will be re-initialized every time the loop runs.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T16:15:37.767", "Id": "2518", "ParentId": "2496", "Score": "8" } } ]
{ "AcceptedAnswerId": "2518", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T01:14:31.587", "Id": "2496", "Score": "6", "Tags": [ "vb6", "vba" ], "Title": "Is it a bad programming practice to declare variable in a loop?" }
2496
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-22.html" rel="nofollow">SICP</a>:</p> <p>For background, here is exercise 3.16:</p> <blockquote> <p><strong>Exercise 3.16</strong></p> <p>Ben Bitdiddle decides to write a procedure to count the number of pairs in any list structure. <code>It's easy,'' he reasons.</code>The number of pairs in any structure is the number in the car plus the number in the cdr plus one more to count the current pair.'' So Ben writes the following procedure:</p> <pre><code>(define (count-pairs x) (if (not (pair? x)) 0 (+ (count-pairs (car x)) (count-pairs (cdr x)) 1))) </code></pre> <p>Show that this procedure is not correct. In particular, draw box-and-pointer diagrams representing list structures made up of exactly three pairs for which Ben's procedure would return 3; return 4; return 7; never return at all.</p> </blockquote> <p>My solution is to the following question:</p> <blockquote> <p><strong>Exercise 3.17</strong></p> <p>Devise a correct version of the count-pairs procedure of exercise 3.16 that returns the number of distinct pairs in any structure. (Hint: Traverse the structure, maintaining an auxiliary data structure that is used to keep track of which pairs have already been counted.)</p> </blockquote> <p>Here it is:</p> <pre><code>(define (count-pairs x) (define (iter x sum already-counted) (if (or (not (pair? x)) (member x already-counted)) (list sum already-counted) (let ((car-result (iter (car x) (+ sum 1) (cons x already-counted)))) (iter (cdr x) (car car-result) (cadr car-result))))) (car (iter x 0 '()))) (define (last-pair x) (if (null? (cdr x)) x (last-pair (cdr x)))) (define a '(a b c)) (count-pairs a) (set-cdr! (last-pair a) a) (count-pairs a) (define b '(a b c)) (set-car! b (last-pair b)) (count-pairs b) </code></pre> <p>Can it be improved?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T03:01:13.143", "Id": "2497", "Score": "1", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Correctly count the number of pairs in an irregular list structure" }
2497
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-22.html" rel="nofollow">SICP</a>:</p> <blockquote> <p>Exercise 3.18. Write a procedure that examines a list and determines whether it contains a cycle, that is, whether a program that tried to find the end of the list by taking successive cdrs would go into an infinite loop. Exercise 3.13 constructed such lists.</p> </blockquote> <p>I wrote the following (revised) solution:</p> <pre><code>(define (has-cycle? l) (define (rec nodes-visited remains) (define (leaf? node) (not (pair? node))) (define (have-seen? node) (define (rec rest) (if (null? rest) #f (or (eq? (car rest) node) (rec (cdr rest))))) (rec nodes-visited)) (cond ((leaf? remains) #f) ((have-seen? remains) #t) (else (or (rec (cons remains nodes-visited) (car remains)) (rec (cons remains nodes-visited) (cdr remains)))))) (rec '() l)) (define (last-pair x) (if (null? (cdr x)) x (last-pair (cdr x)))) (define a '(a b c)) (has-cycle? a) (set-car! (last-pair a) a) a (has-cycle? a) (define b '(a b c)) (set-car! b (last-pair b)) b (has-cycle? b) (define c '(a b c d)) (set-car! (cddr c) (cdr c)) c (has-cycle? c) (define d (cons 'z a)) d (has-cycle? d) (define e '(a b c d e)) e (has-cycle? e) </code></pre> <ol> <li>How can it be improved?</li> </ol> <blockquote> <p>Exercise 3.19. Redo exercise 3.18 using an algorithm that takes only a constant amount of space. (This requires a very clever idea.)</p> </blockquote> <ol> <li>I'm not sure how to fulfill this requirement so far.</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-07T02:56:59.943", "Id": "13656", "Score": "0", "body": "Have you tried this on a cyclic list? I did, and it goes into an infinite loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-07T12:10:04.417", "Id": "13670", "Score": "0", "body": "What list did you use? `(define a...` above makes a cyclic list and it returned ok for me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-07T13:09:23.713", "Id": "13671", "Score": "0", "body": "Try it with a cyclic list where the cycle doesn't begin with the first element, i.e. `(cons 'z a)` where `a` is the same as in your example" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T14:32:33.120", "Id": "13736", "Score": "0", "body": "You're right - I'll need to think about this a bit to see if I can make it work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T18:50:45.797", "Id": "13745", "Score": "0", "body": "Why not just replace the code on top with the updated code, leaving a note that the code is updated? Those who are then interested in seing the changes can see the edit history." } ]
[ { "body": "<p>I can not express it in Lisp, but the idea is as follows:</p>\n\n<p>use two pointers, at start point both to the list head. Then, increment one pointer by 1, and another by 2. If you detect two equal objects eventually, it means that list has a loop. In pseudo-code:</p>\n\n<pre><code>P0 = head;\nP1 = head;\nwhile(P0 != null and P1 != null) // Detect end of the list\n P0 = next(P0);\n P1 = next(next(P1));\n if ( *P0 == *P1 ) signal loop detected\nend while\n</code></pre>\n\n<p>Of course, the list objects should be distinct and comparable, and next function must be correct.</p>\n\n<p>Proof is not complicated. First, consider a case of \"pure\" loop when tail connected to head.</p>\n\n<p>At step n (n'th iteration of the while loop in the code), P0 is at item (n mod N), and P1 is at item (2n mod N), which are equal if N is finite and n mod N == 0, or simply n = N</p>\n\n<p>If the list has loop that starts somewhere inside, one can show that after some iterations the case will be reduced to the previous one.</p>\n\n<p>Hope this helps. You can learn more about <a href=\"http://en.wikipedia.org/wiki/Cycle_detection\" rel=\"nofollow\">Cycle detection</a> on Wikipedia.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-16T13:38:19.673", "Id": "10065", "ParentId": "2499", "Score": "3" } } ]
{ "AcceptedAnswerId": "10065", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T04:02:02.663", "Id": "2499", "Score": "5", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Examine a list for cycles" }
2499
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-22.html" rel="nofollow">SICP</a>:</p> <blockquote> <p>Exercise 3.22. Instead of representing a queue as a pair of pointers, we can build a queue as a procedure with local state. The local state will consist of pointers to the beginning and the end of an ordinary list. Thus, the make-queue procedure will have the form</p> </blockquote> <pre><code>(define (make-queue) (let ((front-ptr ...) (rear-ptr ...)) &lt;definitions of internal procedures&gt; (define (dispatch m) ...) dispatch)) </code></pre> <blockquote> <p>Complete the definition of make-queue and provide implementations of the queue operations using this representation.</p> </blockquote> <p>I wrote the following solution:</p> <pre><code>(define (make-queue) (let ((front-ptr '()) (rear-ptr '())) (define (set-front-ptr! ptr) (set! front-ptr ptr)) (define (set-rear-ptr! ptr) (set! rear-ptr ptr)) (define (empty?) (null? front-ptr)) (define (front-queue) (if (empty?) (error "FRONT called with an empty queue" front-ptr) (car front-ptr))) (define (insert! item) (let ((new-pair (cons item '()))) (cond ((empty?) (set-front-ptr! new-pair) (set-rear-ptr! new-pair) dispatch) (else (set-cdr! rear-ptr new-pair) (set-rear-ptr! new-pair) dispatch)))) (define (delete!) (cond ((empty?) (error "DELETE! called with an empty queue" first-ptr)) (else (set-front-ptr! (cdr front-ptr)))) dispatch) (define (print) front-ptr) (define (dispatch m) (cond ((eq? m 'insert!) insert!) ((eq? m 'front-ptr) front-ptr) ((eq? m 'rear-ptr) rear-ptr) ((eq? m 'empty?) empty?) ((eq? m 'delete!) delete!) ((eq? m 'print) print) (else (error "No such procedure: dispatch" m)))) dispatch)) (define q1 (make-queue)) ((((q1 'insert!) 'a) 'print)) ((((q1 'insert!) 'b) 'print)) ((((q1 'delete!)) 'print)) ((((q1 'delete!)) 'print)) </code></pre> <p>How can it be improved?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T04:48:19.517", "Id": "66045", "Score": "1", "body": "Looking through your questions, you have a lot of titles that unnecessarily contain tags. You should only use titles to briefly describe what your program/method does." } ]
[ { "body": "<p>You did not provide implementations of the queue operations using this representation. In SICP this usually refers to syntactic sugar to make working with a data structure less awkward, e.g.</p>\n<pre><code>(define (queue-insert! q item)\n ((q 'insert!) item) )\n</code></pre>\n<p>Also I would prefer different operation names, e.g.</p>\n<p>append! instead of insert!\nfront instead of front-ptr\n...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-01T21:14:52.220", "Id": "251442", "ParentId": "2501", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T07:06:19.157", "Id": "2501", "Score": "5", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Representing a queue as a procedure with local state" }
2501
<p>I'm trying to solve an <a href="http://code.google.com/codejam/contest/dashboard?c=32003#s=p0" rel="nofollow">old GCJ</a>. It's a very simple puzzle, but I'm trying to sharpen my Scala-fu.</p> <p>Basically, you're getting a list of triple <code>number srcLanguage dstLanguage</code>, where <code>number</code> is an integer given in the numeral system of <code>srcLanguage</code>. You should translate it to the numeral system of <code>dstLanguage</code>.</p> <p>A numeral system is simply a string of all possible digits, in ascending order. The decimal numeral system is represented by <code>0123456789</code>, the binary numeral system is <code>01</code>, and the hexadecimal one <code>0123456789ABCDEF</code>.</p> <p>For example:</p> <blockquote> <pre><code>3 0123456789 01 -&gt; 11 3 0123 AB -&gt; BB </code></pre> </blockquote> <p>Here's how I implemented it in Scala:</p> <pre><code>case class Langs(num:String,srcLang:String,dstLang:String) object Langs {def fromLine(line:String):Langs = { val ar = line.split(" ");return Langs(ar(0),ar(1),ar(2))}} object Translate { def lang2int(lang:String,num:String):Long = { var b = BigDecimal(0) val dmap = (lang.toList.zipWithIndex).toMap val digitsList = num map dmap val valueList = digitsList.reverse.zipWithIndex map ( x =&gt; x._1 -&gt; math.pow(dmap.size,x._2)) return valueList.map(x=&gt;x._1*x._2).sum.toLong } def int2lang(lang:String,_num:Long):String = { var num = _num val dmap = (lang zip (0.toLong to lang.size)).map(_.swap).toMap val sb = StringBuilder.newBuilder while (num &gt; 0) { sb.append(dmap(num % dmap.size)) num = num/dmap.size } sb.reverse.toString } def lang2lang(l:Langs):String = int2lang(l.dstLang,lang2int(l.srcLang,l.num)) } object mymain { def main(args : Array[String]) : Unit = { val s = "A-large-practice" val basef = new java.io.FileInputStream("~/Downloads/"+s+".in") val f = new java.util.Scanner(basef) val out = new java.io.FileWriter(s+".out") val n = f.nextInt f.nextLine for (i &lt;- 1 to n) { val nl = f.nextLine val l = Langs.fromLine(nl) out.write("Case #"+i+": "+Translate.lang2lang(l)+"\n") } out.close } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-04T02:44:45.100", "Id": "4347", "Score": "0", "body": "Here is a similar quizzle (http://codegolf.stackexchange.com/questions/1620/arbitrary-base-conversion/2256#2256). It doesn't fit exactly your interface." } ]
[ { "body": "<ul>\n<li>You should definitely use <code>scala.io.Source</code> for File-IO</li>\n<li>I wouldn't consider String splitting a responsibility of a general-purpose class. This should be done in the main loop</li>\n<li>For tuples you can write map{ case (one,two) => ... }, which is often clearer than using x._1 and x._2</li>\n<li>You don't need to write return if it's the last statement of the block</li>\n<li>You can use pattern matching when defining vals: <code>val Array(x, y, z) = line.split(\" \")</code> </li>\n</ul>\n\n<p>Here is my attempt:</p>\n\n<pre><code>case class Langs(num:String, srcLang:String, dstLang:String)\n\nobject Langs {\n def fromLine(line:String):Langs = {\n val Array(num, srcLang, dstLang) = line.split(\" \")\n Langs(num, srcLang, dstLang)\n }\n}\n\nobject Translate {\n def lang2int(lang:String,num:String):Long = {\n val dmap = lang.toList.zipWithIndex.toMap\n val digitsList = num map dmap\n val valueList = digitsList.reverse.zipWithIndex map {\n case (one, two) =&gt; one -&gt; math.pow(dmap.size, two)}\n valueList.map{case (one,two) =&gt; one*two}.sum.toLong\n }\n\n def int2lang(lang:String, num:Long):String = {\n val dmap = (0.toLong to lang.size zip lang).toMap\n Iterator.iterate(num)( _/dmap.size).takeWhile(_ &gt; 0).map(n =&gt; \n dmap(n % dmap.size)).mkString.reverse\n } \n\n def lang2lang(l:Langs):String = int2lang(l.dstLang,lang2int(l.srcLang,l.num))\n}\n</code></pre>\n\n<p>Eliminating the while loop isn't that straight-forward, maybe someone else has an idea how to avoid that Iterator train-wreck.</p>\n\n<p><strong>[Edit]</strong></p>\n\n<p>I asked in <a href=\"http://scala-forum.org/read.php?3,314,314#msg-314\" rel=\"nofollow\">another forum</a> for a better solution for <code>int2lang</code>, and got this answer:</p>\n\n<pre><code>def int2lang(lang: String, num: Long): String = {\n val dmap = (0L to lang.size) zip lang toMap\n val size = dmap.size\n def loop(num: Long, l: List[Char]): List[Char] =\n if (num == 0) l else loop(num/size, dmap(num%size) :: l)\n loop(num, Nil).mkString\n}\n</code></pre>\n\n<p>The nice thing about this is that the <code>reverse</code> is gone.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T15:27:23.913", "Id": "3964", "Score": "0", "body": "Thanks! Great input. Few questions: How would I emulate `Scanner.readInt` with `io.Source`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T15:34:36.297", "Id": "3965", "Score": "0", "body": "(2) Why is the while loop bad? It might be more efficient is definitely clearer, and is only immutable in the function's scope (if a tree falls and nobody heard of it, does it make sound ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T21:33:48.103", "Id": "3973", "Score": "0", "body": "@Elazar: There is no `readInt`, usually you call `Source.fromFile(...).getLines` and work with the Iterator[String]. Strings have already conversion functions, you can simply write `\"42\".toInt`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T21:42:07.613", "Id": "3974", "Score": "0", "body": "The `while` loop is not \"bad\", but you lose the neat advantages of Scala's collections (as `mkString`). I don't really like my solution either, I have the feeling there must be a better way (especially the `takeWhile` is confusing, the rest is not so bad)..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T12:09:35.073", "Id": "2505", "ParentId": "2502", "Score": "3" } }, { "body": "<p>My suggestions.</p>\n\n<ul>\n<li>Take advantage of the fact that <code>Seq[T]</code> is also a function Int => T.</li>\n<li>Use recursion.</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>def int2lang(lang:String, num:Long): String = \n if (num == 0l) \"\" \n else int2lang(lang, num / lang.size) + lang(num % lang.size toInt)\n</code></pre>\n\n<p>If you want to take advantage of tail recursion, use an accumulator:</p>\n\n<pre><code>@scala.annotation.tailrec\ndef int2lang(lang:String, num:Long, acc: String = \"\"): String = \n if (num == 0l) acc\n else int2lang(lang, num / lang.size, lang(num % lang.size toInt) + acc)\n</code></pre>\n\n<p>But that is suboptimal regarding string concatenation, so you could do this:</p>\n\n<pre><code>@scala.annotation.tailrec\ndef int2lang(lang:String, num:Long, acc: List[Char] = Nil): String = \n if (num == 0l) acc.mkString\n else int2lang(lang, num / lang.size, lang(num % lang.size toInt) :: acc)\n</code></pre>\n\n<p>If you don't like recursion (and tail recursions are <em>very</em> efficiently implemented), use a generic unfold instead of reinventing it:</p>\n\n<pre><code>def unfoldLeft[A, B](seed: B)(f: B =&gt; Option[(B, A)]) = {\n def loop(seed: B)(ls: List[A]): List[A] = f(seed) match {\n case Some((b, a)) =&gt; loop(b)(a :: ls)\n case None =&gt; ls\n }\n\n loop(seed)(Nil)\n}\n\ndef int2lang(lang: String, num: Long) = unfoldLeft(num) { n =&gt;\n if (n == 0) None\n else Some((n / lang.size, lang(n % lang.size toInt)))\n}.mkString\n</code></pre>\n\n<p>If you unfold to get the lang, you fold to get the int:</p>\n\n<pre><code>def lang2int(lang: String, num: String) = {\n val lmap = lang.zipWithIndex.toMap\n num.foldLeft(0l) { case (acc, digit) =&gt; acc * lang.size + lmap(digit) }\n}\n</code></pre>\n\n<p>Note that I use a <code>Map</code> here because I want <code>T =&gt; Int</code>. But since we folded what was unfolded, let's see recursion's converse:</p>\n\n<pre><code>def lang2int(lang: String, num: String) = {\n val lmap = lang.zipWithIndex.toMap\n def recurse(n: String, acc: Long): Long =\n if (n.isEmpty) acc\n else recurse(n substring 1, acc * lang.size + lmap(n(0)))\n recurse(num, 0l)\n}\n</code></pre>\n\n<p>So much for the fun part, let's see the rest. I prefer to turn while loops into iterators, unless performance is critical. So:</p>\n\n<pre><code>for (i &lt;- 1 to n) {\n val nl = f.nextLine\n val l = Langs.fromLine(nl)\n out.write(\"Case #\"+i+\": \"+Translate.lang2lang(l)+\"\\n\")\n}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>val lines = Iterator continually f.nextLine\nfor ((l, i) &lt;- lines map Langs.fromLine zipWithIndex)\n out.write(\"Case #\"+(i+1)+\": \"+Translate.lang2lang(l)+\"\\n\")\n</code></pre>\n\n<p>I could move the <code>map Langs.fromLine</code> to the iterator, making that:</p>\n\n<pre><code>val ns = Iterator continually f.nextLine map Langs.fromLine\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>val ns = Iterator continually (Langs fromLine f.nextLine)\n</code></pre>\n\n<p>And if I needed these numbers for more than one use, make it <code>Stream</code> instead of <code>Iterator</code>. Of course, another alternative would be using <code>Source.io</code>, but that's only for lightweight stuff anyway.</p>\n\n<p>Finally, do not use <code>return</code>. A <code>return</code> is an exception of sorts -- it indicates a function will terminate and return its result before its end.</p>\n\n<p>It can also be used inside closures to escape the function that is executing it and return (and exit) the scope in which it was defined.</p>\n\n<p>At any rate, treat a <code>return</code> as something exceptional, and leave it for exceptional situations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-02T09:29:27.500", "Id": "4308", "Score": "0", "body": "Thanks! (1) Can you please fix the code (you used 3 spaces for indentation), (2) \"If you don't want recursion, use unfold which uses recursion itself\" ;-). Great input, I didn't think about the fact that `Seq[T]` is actually a function (keep in mind that performance is not guaranteed, it could be a `List[T]`...), and didn't remember the Iterator.continually." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-02T12:18:35.560", "Id": "4310", "Score": "0", "body": "@Elazar I used 4 spaces for indentation, except for the code that I copy&pasted (`foldLeft`'s definition and the original `for` loop) and the translation of said loop. Speaking of unfold, the point is that it separates the recursion from the business logic. And, yes, `Seq[T]` might have a slow `apply`, but that's not the case of `String`. :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-02T16:49:24.060", "Id": "4316", "Score": "0", "body": "you missed just one function `def lang2int(lang: String, num: String)` copy it to vim, and go `/ def lang` to find it. I don't have edit rights, otherwise I'd fix it myself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-02T18:44:42.133", "Id": "4319", "Score": "0", "body": "@Elazar Oh, ok, sorry." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-01T19:36:12.037", "Id": "2769", "ParentId": "2502", "Score": "2" } }, { "body": "<p>I'm kind of new to Scala myself, but I like to think that loops are all-but obsolete. Every time I see one now I think, \"A loop - <a href=\"http://www.youtube.com/watch?v=v9kTVZiJ3Uc\" rel=\"nofollow\">how quaint</a>!\"</p>\n\n<p>All the collections have methods you can pass a function to. This approach allows the collection to do various optimizations, particularly for multi-threading that are difficult and time-consuming to program properly on your own. So I'd try to get rid of the for loop and the while loop first.</p>\n\n<p>If you can somehow combine all your processing into one function before passing it to the collection, all the better.</p>\n\n<p>Other people have mentioned a lot of other details making your code more functional, I just think that the loops are the most obvious stylistic element that also affects performance.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T22:25:05.990", "Id": "17655", "ParentId": "2502", "Score": "1" } } ]
{ "AcceptedAnswerId": "2505", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T07:41:11.970", "Id": "2502", "Score": "3", "Tags": [ "scala", "programming-challenge" ], "Title": "Alien Numbers - how Scala-ish is my solution?" }
2502
<h3>Introduction</h3> <p>The name LISP derives from "LISt Processing". It was originally created as a practical mathematical notation for computer programs. See <a href="http://en.wikipedia.org/wiki/Lisp_%28programming_language%29" rel="nofollow">wikipedia</a> for more information.</p> <h3>Hello World Program in Lisp</h3> <pre><code>;;; Hello World in Common Lisp (defun helloworld () (print "Hello World!")) </code></pre> <h3>Popular dialects</h3> <ul> <li><a href="http://stackoverflow.com/questions/tagged/common-lisp">Common Lisp</a></li> <li><a href="http://stackoverflow.com/questions/tagged/scheme">Scheme</a></li> <li><a href="http://stackoverflow.com/questions/tagged/elisp">Emacs Lisp</a></li> <li><a href="http://stackoverflow.com/questions/tagged/clojure">Clojure</a></li> </ul> <h3>Free Lisp Programming Books</h3> <ul> <li><a href="http://www.cs.cmu.edu/Groups/AI/html/cltl/mirrors.html" rel="nofollow">Common Lisp the Language, 2nd Edition</a></li> <li><a href="http://www.cs.cmu.edu/~dst/LispBook/" rel="nofollow">Common Lisp: A Gentle Introduction to Symbolic Computation</a> - David S. Touretzky</li> <li><a href="http://clqr.boundp.org/" rel="nofollow">Common Lisp Quick Reference</a></li> <li><a href="http://letoverlambda.com/index.cl/toc" rel="nofollow">Let Over Lambda - 50 Years of Lisp</a></li> <li><a href="http://www.informatics.susx.ac.uk/research/groups/nlp/gazdar/nlp-in-lisp/index.html" rel="nofollow">Natural Language Processing in Lisp</a></li> <li><a href="http://www.paulgraham.com/onlisp.html" rel="nofollow">On Lisp</a></li> <li><a href="http://www.gigamonkeys.com/book/" rel="nofollow">Practical Common Lisp</a></li> <li><a href="http://psg.com/~dlamkins/sl/" rel="nofollow">Successful Lisp: How to Understand and Use Common Lisp</a> - David Lamkins</li> <li><a href="http://www.bcl.hamilton.ie/~nmh/t3x.org/zzz/" rel="nofollow">Sketchy LISP</a> - Nils Holm</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T14:08:43.037", "Id": "2510", "Score": "0", "Tags": null, "Title": null }
2510
Lisp is a (family of) general purpose programming language(s), based on the lambda calculus, and with the ability to manipulate source code as a data structure.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T14:08:43.037", "Id": "2511", "Score": "0", "Tags": null, "Title": null }
2511
<p><a href="http://www.java.com/en/" rel="nofollow noreferrer" title="Java official Site">Java</a> is a high-level, platform-independent, object-oriented programming language and run-time environment. The Java language derives much of its syntax from <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a> and <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged &#39;c++&#39;" rel="tag">c++</a>, but its object model is simpler than that of <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged &#39;c++&#39;" rel="tag">c++</a> and it has fewer low-level facilities. Java applications are typically compiled to bytecode (called class files) that can be executed by a Java Virtual Machine <a href="/questions/tagged/jvm" class="post-tag" title="show questions tagged &#39;jvm&#39;" rel="tag">jvm</a>, independent of computer architecture. The <a href="/questions/tagged/jvm" class="post-tag" title="show questions tagged &#39;jvm&#39;" rel="tag">jvm</a> manages memory with the help of a garbage collector (see <a href="/questions/tagged/garbage-collection" class="post-tag" title="show questions tagged &#39;garbage-collection&#39;" rel="tag">garbage-collection</a>) in order to handle object removal from memory when not used anymore, as opposed to manually deallocating memory, like other languages such as <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged &#39;c++&#39;" rel="tag">c++</a>.</p> <p><a href="/questions/tagged/java" class="post-tag" title="show questions tagged &#39;java&#39;" rel="tag">java</a> is designed to have as few implementation dependencies as possible, and is intended to allow application developers to &quot;write once, run anywhere&quot; (WORA): code that executes on one platform need not be recompiled to run on another.</p> <h2>Principles</h2> <p><strong>The Java language was created with the following primary goals:</strong></p> <ol> <li>Simple, object-oriented, and familiar.</li> <li>Robust and secure.</li> <li>Architecture-neutral and portable.</li> <li>Execute with high performance.</li> <li>Interpreted, multi-threaded, and dynamic.</li> <li>Write once, run anywhere (WORA).</li> <li>Inheritance.</li> <li>Encapsulation.</li> <li>Polymorphic.</li> </ol> <h2>Background</h2> <p><a href="https://en.wikipedia.org/wiki/Java_%28programming_language%29" rel="nofollow noreferrer">Java</a> is a high-level, platform-independent, <a href="https://en.wikipedia.org/wiki/Object-oriented_programming" rel="nofollow noreferrer">object-oriented programming language</a> originally developed by James Gosling for Sun Microsystems and released in 1995. The Java trademark is currently owned by Oracle, which purchased Sun Microsystems on April 20, 2009.</p> <p>The main reference implementation of Java is open source (the <a href="http://openjdk.java.net/" rel="nofollow noreferrer">OpenJDK</a>), and is supported by major companies including Oracle, Apple, SAP and IBM.</p> <p>Very few computers can run Java programs directly. Therefore, the Java environment is normally made available by installing a suitable software component. For Windows computers, this is usually done by downloading the free Java Runtime Environment (JRE) from <a href="https://java.com/en/" rel="nofollow noreferrer">java.com</a>. On Macintosh computers, the user is prompted to download Java when an application requiring it is started. On <a href="/questions/tagged/linux" class="post-tag" title="show questions tagged &#39;linux&#39;" rel="tag">linux</a>-like systems, Java is typically installed via the package manager.</p> <p>Developers frequently need additional tools which are available in the free Java Development Kit (JDK) alternative to the JRE, which for Windows must be downloaded from <a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html" rel="nofollow noreferrer">Oracle</a> and installed manually.</p> <p>Java is compiled into bytecode which is interpreted on the JVM by compiling into native code. The compilation is done just-in-time (JIT). Initially, this was viewed as a performance hit, but JVM and JIT compilation improvements have made this less of a concern. In some cases, the JVM may even be faster than native code compiled to target an older version of a processor for backward-compatibility reasons.</p> <p><strong>Note:</strong> Other vendors exist, though almost all have license fees. For <a href="/questions/tagged/linux" class="post-tag" title="show questions tagged &#39;linux&#39;" rel="tag">linux</a> and other platforms, consult the operating system documentation.</p> <h2>Versions</h2> <p><strong>Notable Java versions, code names, and release dates include:</strong></p> <pre class="lang-none prettyprint-override"><code>JDK 1.0 (January 23, 1996) JDK 1.1 (February 19, 1997) J2SE 1.2 [Playground] (December 8, 1998) J2SE 1.3 [Kestrel] (May 8, 2000) J2SE 1.4 [Merlin] (February 6, 2002) J2SE 5.0 [Tiger] (September 30, 2004) Java SE 6 [Mustang] (December 11, 2006) Java SE 7 [Dolphin] (July 28, 2011) Java SE 8 [JSR 337] (March 18, 2014) </code></pre> <p>For more code names and release dates, visit <a href="http://www.oracle.com/technetwork/java/javase/codenames-136090.html" rel="nofollow noreferrer">J2SE Code Names</a>. To see release notes for each version of the JDK, visit the <a href="https://en.wikipedia.org/wiki/Java_version_history" rel="nofollow noreferrer">Wikipedia article</a> on Java version history.</p> <p>The <a href="http://www.oracle.com/technetwork/java/eol-135779.html" rel="nofollow noreferrer">End Of Public Updates</a> (Formerly called End Of Life) dates are:</p> <pre class="lang-none prettyprint-override"><code>J2SE 1.4 - Oct 2008 J2SE 5.0 - Oct 2009 Java SE 6 - Feb 2013 Java SE 7 - Mar 2015 </code></pre> <h2>Initial help</h2> <ul> <li>New to Java – need help to get your first Java program running? See the <a href="http://docs.oracle.com/javase/tutorial/getStarted/index.html" rel="nofollow noreferrer">Oracle Java Tutorials section on Getting Started</a>.</li> </ul> <h2>Naming conventions</h2> <p>Java programs should adhere to the <a href="http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html" rel="nofollow noreferrer">following naming conventions</a> to increase readability and decrease chances of accidental errors. By following these naming conventions, you will make it easier for others to understand your code and help you.</p> <ul> <li><strong>Type names</strong> (classes, interfaces, enums, etc.) should begin with a capital letter, and capitalize the first letter of each subsequent word. Examples include: <code>String</code>, <code>ThreadLocal</code>, and <code>NullPointerException</code>. This is sometimes known as PascalCase.</li> <li><strong>Method names</strong> should be camelCased; that is, they should begin with a lowercase letter and capitalize the first letter of each subsequent word. Examples: <code>indexOf</code>, <code>printStackTrace</code>, <code>interrupt</code>.</li> <li><strong>Field names</strong> should be camelCased just like method names.</li> <li><strong>Constant expression names</strong> (<code>static final</code> immutable objects) should be written in ALL_CAPS, with underscores separating each word. Examples: <code>YELLOW</code>, <code>DO_NOTHING_ON_CLOSE</code>. This also applies to values of an <code>Enum</code> class. However, <code>static final</code> references to <em>non</em>-immutable objects should be camelCased.</li> </ul> <h2>Hello World</h2> <pre class="lang-java prettyprint-override"><code>public class HelloWorld { public static void main(String[] args) { System.out.println(&quot;Hello, World!&quot;); } } </code></pre> <p>Compilation and invocation of <strong>Hello World</strong>:</p> <pre><code>javac -d . HelloWorld.java java -cp . HelloWorld </code></pre> <p>Java source code is compiled to an intermediate form (bytecode instructions for the <a href="https://en.wikipedia.org/wiki/Java_virtual_machine" rel="nofollow noreferrer">Java Virtual Machine</a>) that can be executed with the <code>java</code> command.</p> <p>More information:</p> <ul> <li><a href="https://en.wikipedia.org/wiki/Java_%28programming_language%29" rel="nofollow noreferrer">Wikipedia on Java</a></li> <li><a href="https://en.wikipedia.org/wiki/Java_Development_Kit" rel="nofollow noreferrer">Wikipedia on the JDK</a></li> <li><a href="https://en.wikipedia.org/wiki/Java_virtual_machine#Execution_environment" rel="nofollow noreferrer">Wikipedia on the JRE</a></li> <li><a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html" rel="nofollow noreferrer">Download Java from Oracle</a></li> </ul> <h2>Beginners' resources</h2> <ul> <li><a href="http://docs.oracle.com/javase/tutorial/" rel="nofollow noreferrer">The Java Tutorials</a> - Starts from scratch on Windows/Linux/Mac and covers most of the standard library.</li> <li><a href="http://docs.oracle.com/javase/tutorial/java/generics/" rel="nofollow noreferrer">Generics</a></li> <li><a href="http://codingbat.com/java" rel="nofollow noreferrer">Coding Bat (Java)</a> - After learning some basics, refine and hone your Java skills with Coding Bat.</li> <li><a href="http://www.oracle.com/technetwork/java/codeconv-138413.html" rel="nofollow noreferrer">Code Conventions for the Java Programming Language</a></li> <li><a href="http://see.stanford.edu/see/courseinfo.aspx?coll=824a47e1-135f-4508-a5aa-866adcae1111" rel="nofollow noreferrer">Stanford Video Lectures on Java</a></li> <li><a href="https://www.udemy.com/java-tutorial" rel="nofollow noreferrer">Udemy free course on Java</a></li> </ul> <h2>Day-to-day resources</h2> <ul> <li><a href="http://www.oracle.com/technetwork/java/javase/documentation/index.html" rel="nofollow noreferrer">Java SE Documentation</a></li> <li><a href="http://download.oracle.com/javase/7/docs/api" rel="nofollow noreferrer">Java 7 API reference</a></li> </ul> <h2>Advanced resources</h2> <ul> <li><a href="http://docs.oracle.com/javase/specs/" rel="nofollow noreferrer">Java Language and Virtual Machine Specifications</a></li> <li><a href="https://en.wikipedia.org/wiki/List_of_JVM_languages" rel="nofollow noreferrer">Other languages that can be mixed with Java on JVM</a></li> </ul> <h2>Free Java programming books and resources</h2> <ul> <li><a href="http://ptgmedia.pearsoncmg.com/images/013143697X/downloads/013143697X_book.pdf" rel="nofollow noreferrer">Java Application Development on Linux by Carl Albing and Michael Schwarz(PDF)</a></li> <li><a href="http://greenteapress.com/thinkapjava/" rel="nofollow noreferrer">How to Think Like a Computer Scientist</a></li> <li><a href="http://docs.oracle.com/javaee/6/tutorial/doc/javaeetutorial6.pdf" rel="nofollow noreferrer">The Java EE6 Tutorial (PDF)</a></li> <li><a href="http://www.redbooks.ibm.com/redbooks/SG245118.html" rel="nofollow noreferrer">Java Thin-Client Programming</a></li> <li><a href="http://docs.oracle.com/javase/tutorial/" rel="nofollow noreferrer">Oracle's Java Tutorials</a></li> <li><a href="http://www.mindview.net/Books/TIJ/" rel="nofollow noreferrer">Thinking in Java</a></li> <li><a href="http://njbartlett.name/files/osgibook_preview_20091217.pdf" rel="nofollow noreferrer">OSGi in Practice (PDF)</a></li> <li><a href="https://www.mkyong.com/" rel="nofollow noreferrer">Category wise tutorials - J2EE</a></li> <li><a href="http://roseindia.net/java/" rel="nofollow noreferrer">Java Example Codes and Tutorials - J2EE</a></li> <li><a href="https://www.udemy.com/java-design-patterns-tutorial/" rel="nofollow noreferrer">Java Design Pattern Video Training</a></li> <li><a href="http://www.headfirstlabs.com/books/hfjava/" rel="nofollow noreferrer">Head First JAVA</a></li> </ul> <h2>Frequently Asked Questions</h2> <p><em>People often ask about the following Java topics:</em></p> <ul> <li><a href="https://stackoverflow.com/questions/2772763/why-equals-method-when-we-have-operator">Difference between <code>equals()</code> and <code>==</code></a></li> <li><a href="https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java">How do I compare strings in Java?</a></li> <li><a href="https://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java">Overriding <code>equals()</code> and <code>hashCode()</code> in Java</a></li> <li><a href="https://stackoverflow.com/questions/34413/why-am-i-getting-a-noclassdeffounderror-in-java">Why NoClassDefFoundError?</a></li> <li><a href="https://stackoverflow.com/questions/2163411/why-did-java-have-the-reputation-of-being-slow">Why did Java have the reputation of being slow?</a></li> <li><a href="https://stackoverflow.com/questions/271526/how-to-avoid-null-statements-in-java">How do I avoid null checks in Java?</a></li> <li><a href="https://stackoverflow.com/questions/147181/how-can-i-convert-my-java-program-to-an-exe-file">How can I convert my java program to an .exe file</a></li> <li><a href="https://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitl">Is <code>List&lt;Dog&gt;</code> a subclass of <code>List&lt;Animal&gt;</code>? Why aren't Java's generics implicitly polymorphic?</a></li> <li><a href="https://stackoverflow.com/questions/2592501/compare-dates-in-java">Compare dates in Java</a></li> <li><a href="https://stackoverflow.com/questions/40480/is-java-pass-by-reference">Is Java pass by reference?</a></li> <li><a href="https://stackoverflow.com/questions/2647154/java-package-project-nosuchmethod-error">NoSuchMethodError in Java</a></li> <li><a href="https://stackoverflow.com/questions/4937402/moving-decimal-places-over-in-a-double">Why can't I print a double correctly?</a></li> <li><a href="https://stackoverflow.com/questions/223918/java-efficient-equivalent-to-removing-while-iterating-a-collection">Java: Efficient Equivalent to Removing while Iterating a Collection</a></li> <li><a href="https://stackoverflow.com/questions/7056749/scanner-issue-when-using-nextline-after-nextint">Scanner issue when using nextLine after nextInt</a></li> <li>[StringBuilder and StringBuffer in Java] <a href="https://stackoverflow.com/questions/355089/stringbuilder-and-stringbuffer-in-java">53</a></li> <li><a href="https://stackoverflow.com/questions/3590000/what-does-java-lang-thread-interrupt-do">What does java.lang.Thread.interrupt() do?</a></li> <li><a href="https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors">What is a stack trace, and how can I use it to debug my application errors?</a></li> <li><a href="https://stackoverflow.com/questions/2723397/java-generics-what-is-pecs">Java Generics: What is PECS?</a></li> <li><a href="https://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java">How to sort a Map&lt;Key, Value&gt; on the values in Java?</a></li> <li><a href="https://stackoverflow.com/questions/9969690/whats-the-advantage-of-a-java-enum-versus-a-class-with-public-static-final-fiel">What's the advantage of a Java enum versus a class with public static final fields?</a></li> <li><a href="https://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist">When to use LinkedList&lt;&gt; over ArrayList&lt;&gt;?</a></li> <li><a href="https://stackoverflow.com/questions/20651118/boolean-valueofstring-and-booleanutils-tobooleanstring-in-java">Boolean.valueOf(String) and BooleanUtils.toBoolean(String) in java?</a></li> <li><a href="https://stackoverflow.com/questions/20538869/arrays-aslist-in-java">Arrays.asList() in java</a>?</li> <li><a href="https://stackoverflow.com/questions/40471/differences-between-hashmap-and-hashtable">Differences between HashMap and Hashtable?</a></li> <li><a href="https://stackoverflow.com/questions/215497/in-java-whats-the-difference-between-public-default-protected-and-private">Difference between Public,Protected,Private and Default in JAVA</a></li> </ul> <p>(Submitters, please only list questions which actually <em>are</em> frequently asked.)</p> <h2>Chat rooms</h2> <ul> <li><a href="https://chat.stackoverflow.com/rooms/139/java">Stack Overflow chat room for Java</a></li> <li><a href="https://chat.stackoverflow.com/rooms/19132/java-and-android-era">Java and Android era</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-05-20T14:12:10.057", "Id": "2512", "Score": "0", "Tags": null, "Title": null }
2512
Java (not to be confused with JavaScript) is a class-based, object-oriented, strongly typed, reflective language and run-time environment (JRE). Java programs are compiled to bytecode and run in a virtual machine (JVM) enabling a "write once, run anywhere" (WORA) methodology.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T14:12:10.057", "Id": "2513", "Score": "0", "Tags": null, "Title": null }
2513
<p>JavaScript is one of the most ubiquitous programming languages on the earth. It runs on virtually every OS, and a JS engine is included in virtually every mainstream web browser. Standalone JavaScript engines or interpreters are available as well, and there are also embedding frameworks used to allow JS in additional applications. </p> <h2>Notable Implementations</h2> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/d1et7k7c%28v=vs.94%29" rel="nofollow">Chakra (Microsoft JavaScript engine)</a> / <a href="http://msdn.microsoft.com/en-us/library/hbxc2t98%28v=vs.85%29.aspx" rel="nofollow">JScript (previous Microsoft engine)</a> Used in the Universal App platform, Internet Explorer, and Windows Script Host.</li> <li><a href="https://developer.mozilla.org/en/JavaScript" rel="nofollow">SpiderMonkey (Mozilla JavaScript engine)</a> Used in Firefox and related browsers, <a href="http://www.mozilla.org/rhino/" rel="nofollow">Rhino</a>, Gnome 3, and Adobe Acrobat.</li> <li><a href="http://code.google.com/p/v8/" rel="nofollow">V8 (Google Chrome JavaScript engine)</a> Used in Chrome, Chromium, Android, and Node.js.</li> <li><a href="http://trac.webkit.org/wiki/JavaScriptCore" rel="nofollow">JavaScriptCore (Apple / Webkit engine)</a> Used in Safari and IOS.</li> </ul> <p>A <a href="http://en.wikipedia.org/wiki/List_of_ECMAScript_engines" rel="nofollow">more complete list can be found on Wikipedia</a>.</p> <p>JavaScript is often used in the browser where it is provided with the <a href="http://www.w3.org/DOM/DOMTR.html" rel="nofollow">Document Object Model</a>, which effectively acts as a set of global variables, methods, and namespaces. Other environments provide different global elements.</p> <hr> <h3>ECMAScript, JavaScript &amp; JScript</h3> <p>People often use the term "JavaScript" informally. The language and term originated as a creation of Netscape. </p> <p><a href="http://en.wikipedia.org/wiki/ECMAScript" rel="nofollow">ECMAScript</a> was developed as a standardization of Netscape's <a href="http://en.wikipedia.org/wiki/JavaScript" rel="nofollow">JavaScript</a> and Microsoft's independently-developed <a href="http://msdn.microsoft.com/en-us/library/yek4tbz0.aspx" rel="nofollow">JScript</a>. The canonical reference is <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm" rel="nofollow">The ECMA-262 Language Specification</a>. While JavaScript and JScript aim to be compatible with ECMAScript, they also provide additional features not described in the ECMA specifications. <a href="http://en.wikipedia.org/wiki/ECMAScript#Dialects" rel="nofollow">Other implementations</a> of ECMAScript also exist.</p> <p>Most people today who use JavaScript probably don't sweat the differences; they do not distinguish it from ECMAScript.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-20T14:35:58.953", "Id": "2514", "Score": "0", "Tags": null, "Title": null }
2514