body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>For my current project we are commnunicating with an old mainframish hospital information system. This system has a service called 'Facelink' which is a simple TCP connection with a fixed set of commands. The problem is that a user can only be logged in one time. As we're hosting a web frontend with a lot of links to this service and we have some long running jobs running on the backend this can create concurrency issues (user already logged in).</p> <p>To counter this I've created a proxyserver class that is the only thing connected to the Facelink service and my jobs and scripts can connect to this as much as they want. It does what it should but as I am the only programmer working on this I have the nagging feeling that it can be written better. Please give me some tips and pointers.</p> <p>One question i already have is this:<br> The protocol works a bit like this [COMMANDCODE] [MESSAGE], for example 001 User Identification = 1234. I'd like to get rid of the magic numbers and create constants, but since I have a FacelinkConnection class (used to connect to the FL service, now to the proxy), a FacelinkProxyServer class, and a bunch of FacelinkServiceX classes I wouldn't know where to put these. I've heard that a Facelink class with only constants is bad practice.</p> <p>Thanks for helping and sharing.</p> <pre><code>class FacelinkProxyServer { /** * List of client sockets * @var array */ protected $clients = array(); /** * The socket clients will connect to * @var resource */ protected $listenSocket = null; /** * The client socket that connects to the facelink server * @var resource */ protected $facelinkSocket = null; /** * The port we listen on for new connections * @var int */ protected $listenPort = 8000; /** * The IP address we bind to * @var string */ protected $listenHost = '127.0.0.1'; /** * Are we are shutting down (stop accepting new clients) * @var boolean */ protected $shutdown = false; /** * Create a new instance of FacelinkProxyServer * @param array $facelinkConfig * @param string $bindAddress * @param int $bindPort * @return FacelinkProxyServer */ public function __construct (array $facelinkConfig, $bindAddress = '127.0.0.1', $bindPort = 8000) { $this-&gt;listenPort = $bindPort; $this-&gt;listenHost = $bindAddress; $this-&gt;createFacelinkConnection($facelinkConfig); $this-&gt;createListenSocket(); } /** * Connects to the facelink service * @param array $facelinkConfig * @return void */ protected function createFacelinkConnection(array $facelinkConfig) { $this-&gt;facelinkSocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_block($this-&gt;facelinkSocket); $timeout = 10; $time = time(); while (!@socket_connect($this-&gt;facelinkSocket, $facelinkConfig['host'], $facelinkConfig['port'])) { if(is_resource($this-&gt;facelinkSocket)) break; /** * Some sockets first return a error 115, then a error 114 to tell you connecting is in progress */ $errorCode = socket_last_error($this-&gt;facelinkSocket); if ($errorCode == 115 || $errorCode == 114) { if ((time() - $time) &gt;= $timeout) { socket_close($this-&gt;facelinkSocket); $this-&gt;shutdown(); break; } usleep(500000); continue; } } if(is_resource($this-&gt;facelinkSocket)) $this-&gt;facelinkLogin($facelinkConfig['user'], $facelinkConfig['password']); } /** * Logs in to the facelink service * @param $user * @param $password * @return void */ protected function facelinkLogin($user, $password) { $this-&gt;readFacelinkSocket(); $this-&gt;writeFacelinkSocket("001 User Identification = ".$user); $this-&gt;readFacelinkSocket(); $this-&gt;writeFacelinkSocket("002 User Password = ".$password); $result = $this-&gt;readFacelinkSocket(); if(substr($result, 0, 3) == Facelink::CODE_USER_ALREADY_LOGGED_IN) $this-&gt;shutdown(); } /** * Closes the proxy for new clients * @return void */ protected function shutdown() { @socket_close($this-&gt;listenSocket); $this-&gt;shutdown = true; } /** * Closes the connection to the facelink service * @return void */ protected function quit() { @socket_close($this-&gt;facelinkSocket); } /** * Starts the listening socket for clients to connect to * @return void */ protected function createListenSocket() { $this-&gt;listenSocket = @socket_create(AF_INET, SOCK_STREAM, 0); socket_set_nonblock($this-&gt;listenSocket); socket_set_option($this-&gt;listenSocket, SOL_SOCKET, SO_REUSEADDR, 1); $bindResult = @socket_bind($this-&gt;listenSocket, $this-&gt;listenHost, $this-&gt;listenPort); if(!$bindResult) $this-&gt;shutdown(); @socket_listen($this-&gt;listenSocket); } /** * Handles a request from the client to the proxy * @param int $connectionId The connection that sent the command * @return void */ protected function proxyCommand($connectionId) { $clientConnection = $this-&gt;clients[$connectionId]; $clientMessage = $this-&gt;readSocket($connectionId); /** * 003 is the logout command, swallow this. */ if(substr($clientMessage, 0, 3) === "003") { $this-&gt;closeClientSocket($connectionId); $this-&gt;removeSocket($connectionId); } /** * Fake the clients login */ elseif(in_array(substr($clientMessage, 0, 3), array('001', '002'))) $this-&gt;writeClientSocket($connectionId, '999 OK', false); /** * Proxy remote shutdown */ elseif(substr($clientMessage, 0, 3) == 'DIE') $this-&gt;shutdown(); elseif($clientMessage) { $this-&gt;writeFacelinkSocket($clientMessage); $this-&gt;pipeResponseToClient($connectionId); } } /** * Sends the response from the facelink service to the client, don't buffer anything. * @param int $connectionId The connection that sent the original command * @return void */ protected function pipeResponseToClient($connectionId) { while(false !== @socket_recv($this-&gt;facelinkSocket, $data, 1024, 0)) { if(!is_null($data)) $this-&gt;writeClientSocket($connectionId, $data); if(ord(substr($data, -1)) == 26 || ord(substr($data, -1)) == 0 || is_null($data)) { break; } } } /** * Close the client's connection * @param int $connectionId The connection to close * @return unknown_type */ protected function closeClientSocket($connectionId) { $clientConnection = $this-&gt;clients[$connectionId]; $this-&gt;writeClientSocket($connectionId, '999 BYE'); } /** * Removes a client socket from the pool * @param int $connectionId The connection that is to be removed * @return void */ protected function removeSocket($connectionId) { $clientConnection = $this-&gt;clients[$connectionId]; @socket_shutdown($clientConnection, 2); @socket_close($clientConnection); unset($this-&gt;clients[$connectionId]); } /** * Sends a message to a client * @param int $connectionId The connection to sent the command to. * @param string $message The message to send * @param boolean $fromFacelink If we are sending a response from the facelink service * @return void */ protected function writeClientSocket($connectionId, $message, $fromFacelink = true) { if(!is_resource($this-&gt;clients[$connectionId])) { $this-&gt;closeClientSocket(); } /** * Facelink already attaches the chr(26) to the end of the command, the proxy * needs to emulate this behaviour. */ if(!$fromFacelink) { $message .= "\n".chr(26); } $connection = $this-&gt;clients[$connectionId]; @socket_write($connection, $message, strlen($message)); } /** * Write a message from a client to the facelink service * @param string $message The message to send * @return void */ protected function writeFacelinkSocket($message) { if(empty($message)) return; $message .= chr(26); socket_write($this-&gt;facelinkSocket, $message, strlen($message)); } /** * Reads information from a client socket * @param int $connectionId The connection to read from * @return string Information from the client */ protected function readSocket($connectionId) { $connection = $this-&gt;clients[$connectionId]; $response = @socket_recv($connection, $data, 1024, 0); /** * False == No Data * 0 == Widowed socket / Remote client closed connection */ if($response === false || $response === 0) { $this-&gt;removeSocket($connectionId); return ''; } $response = $data; if((ord(substr($response, -1)) == 26 || ord(substr($response, -1)) == 0 || is_null($response)) === false) { while($socketStatus = @socket_recv($connection, $data, 1024, 0)) { /** * false = no data */ if($socketStatus === false) break; /** * 0 = widowed socket -&gt; remote client closed connection; */ if($socketStatus === 0) { $this-&gt;removeSocket($connectionId); break; } if(!is_null($data)) $response .= $data; if(ord(substr($data, -1)) == 26 || ord(substr($data, -1)) == 0 || is_null($data)) break; } } $response = substr($response, 0, -1); return $response; } /** * Reads information from the facelink service * @return string Information from the facelink service */ protected function readFacelinkSocket() { $response = ""; while(false !== @socket_recv($this-&gt;facelinkSocket, $data, 1024, 0)) { if(!is_null($data)) $response .= $data; if(ord(substr($data, -1)) == 26 || ord(substr($data, -1)) == 0 || is_null($data)) { break; } } return $response; } /** * Main loop, starts the proxy * @return void */ public function run () { /* * Client connections' pool */ $this-&gt;clients = array(); while (true) { if(!$this-&gt;shutdown) { $conn = @socket_accept($this-&gt;listenSocket); if (is_resource($conn)) { $conn_id = (integer) $conn; $this-&gt;clients[$conn_id] = $conn; $this-&gt;writeClientSocket($conn_id, "999 HELLO", false); } } /** * If we are shutting down and all the clients have finished their business, close up. */ if($this-&gt;shutdown &amp;&amp; !count($this-&gt;clients)) { $this-&gt;quit(); break; } /** * Create a copy of pool for socket_select() */ $active = $this-&gt;clients; /** * Find active sockets */ socket_select($active, $w = null, $e = null, null); /** * Handle every active client */ foreach ($active as $conn) { $conn_id = (integer) $conn; $this-&gt;proxyCommand($conn_id); } /** * Sleep (a little), if we do the server starts to lock up */ usleep(5000); } $this-&gt;shutdown(); } } </code></pre>
[]
[ { "body": "<p>Why not place the magic numbers into your class as constants?</p>\n\n<pre><code>class FacelinkProxyServer {\n const USER_ID = \"001 User Identification\"\n // and so on\n}\n</code></pre>\n\n<p>Then you can access them in the class as their name and outside as <code>FacelinkProxyServer::USER_ID</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T12:18:56.700", "Id": "2680", "Score": "0", "body": "The problem is that there is also a FacelinkConnection class that is used to setup a connection to either a 'real' facelink service or the proxy. That connection \"shouldn't\" know about a FacelinkProxyServer class and it doesn't feel right to duplicate this." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T13:45:24.160", "Id": "2685", "Score": "0", "body": "Will the constants be needed outside the proxy (in the client code, I mean)? If so I wouldn't have a problem with a separate class. It may be the cleanest solution. I'd actually prefer an enum, but PHP doesn't have them..." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T14:20:41.447", "Id": "2688", "Score": "0", "body": "They will be needed outside of the proxy code because the constants will be like: \n`const COMMAND_NO_RIGHTS = '613';` \nSo they are usable in comparisons: \n`if($result->getCode() == Facelink::COMMAND_NO_RIGHTS)\n{ // SOMETHING HORRIBLE}` \nBut thank you for sharing your thoughts, I will use a Facelink class as a 'container' for protocol details :-)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-29T14:09:46.333", "Id": "1524", "ParentId": "1518", "Score": "3" } } ]
{ "AcceptedAnswerId": "1524", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-29T07:42:36.363", "Id": "1518", "Score": "5", "Tags": [ "php", "object-oriented" ], "Title": "Review for a PHP socket proxy" }
1518
<p>I want to use Tweets sent out by a twitter account as a command to shut down Ubuntu. For this, I've written a Python script using <a href="https://github.com/joshthecoder/tweepy" rel="nofollow">tweepy</a>, a Python library for Twitter. I scheduled the script to run half past the hour every hour (for eg at 5:30, 6:30, and so on) using <code>crontab</code>. </p> <p>Here's the script:</p> <pre><code>import tweepy import os from datetime import datetime p=None api= tweepy.API() for status in api.user_timeline('tweetneag4'): while p==None: #so that it checks only the first tweet if status.text.count(str((datetime.now().hour)+1))&lt; 2 and str((datetime.time.now().hour)+1)==10: p=1 pass elif str((datetime.now().hour)+1) in status.text: print "System shut down in 20 mins." os.system('shutdown -h +20') p=1 </code></pre> <p>Here is a sample tweet:</p> <pre><code>#loadshedding schedule in 10mins: 15:00-21:00 #group4 #nea </code></pre> <p>The twitter account (<a href="http://twitter.com/#!/search/tweetneag4" rel="nofollow">@tweetneag4</a>) tweets an alert 30 mins and 10 mins before the power outage begins (here, the account tweets if and only if there's a power outage next hour). What I've tried to do is check at 5:30 whether it posts a tweet regarding 6 o'clock. I've done this by seeing if the tweet contains the string "6"(when checking at 5). When checking for ten o'clock, an additional complication arises because it may contain "10" in two scenarios- first as in 10 o'clock and second as in 10mins later. (I'm sure there's a better way of doing this)</p> <p>If you see the twitter feed, things should be clearer. How could I improve so that the code become more elegant?</p>
[]
[ { "body": "<pre><code>import tweepy\nimport os\nfrom datetime import datetime\np=None\n</code></pre>\n\n<p>Use of single letter variable names is confusing, I have no idea what p is for.</p>\n\n<pre><code>api= tweepy.API()\n</code></pre>\n\n<p>Put spaces around your =</p>\n\n<pre><code>for status in api.user_timeline('tweetneag4'): \n while p==None: #so that it checks only the first tweet\n</code></pre>\n\n<p>What are you thinking here? If p doesn't get set to a true value, you'll loop over the next block repeatedly in an infinite loop. If you only want the first tweet pass count = 1 to user_timeline</p>\n\n<pre><code> if status.text.count(str((datetime.now().hour)+1))&lt; 2 and str((datetime.time.now().hour)+1)==10:\n\n p=1\n</code></pre>\n\n<p>Setting flags is ugly. If you must set boolean flags use True and False not None and 1.</p>\n\n<pre><code> pass\n elif str((datetime.now().hour)+1) in status.text:\n print \"System shut down in 20 mins.\"\n os.system('shutdown -h +20') \n p=1 \n</code></pre>\n\n<p>It seems to me that a much more straightforward way of doing this is to look at the time at which the status was posted. It seems to be available as status.created_at. Based on that you know that outage is either 30 or 10 minutes after that. So if it has been more then 30 minutes since that message, it must have already happened and we aren't concerned.</p>\n\n<p>Something like this:</p>\n\n<pre><code>import tweepy\nimport os\nfrom datetime import datetime, timedelta\n\napi= tweepy.API()\n\nstatus = api.user_timeline('tweetneag4', count=1)[0]\nage = datetime.now() - status.created_at\nif age &lt; timedelta(minutes = 45):\n print \"System shut down in 20 mins.\"\n os.system('shutdown -h +20') \n</code></pre>\n\n<p>NOTE: I get negative ages when I run this, I'm assuming that's time zones. Its also possible my logic is screwy.</p>\n\n<p>If you really do need to get the actual time from the text, your current strategy of searching for numbers in the text is fragile. Instead you could do something like this:</p>\n\n<pre><code># split the message up by whitespace, this makes it easy to grab the outage time\noutage_time = status.split()[4]\n# find everything up to the colon\nhour_text, junk = outage_time.split(':')\n# parse the actual hour\nhour = int(hour_text)\n</code></pre>\n\n<p>Finally, for more complex examples using regular expressions to parse the text would be a good idea. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T04:11:27.950", "Id": "2675", "Score": "0", "body": "@Winston- Thanks for the critique. I'll try to improve some of my programming habits!! I was really searching for something like `status.created_at` and I'll definitely try out your solution- the logic is much neater." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-29T22:51:04.233", "Id": "1531", "ParentId": "1525", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-29T17:24:54.500", "Id": "1525", "Score": "5", "Tags": [ "python", "datetime", "linux", "twitter" ], "Title": "Using tweet as command to shut down Ubuntu" }
1525
<p>The following code generates all \$k\$-subsets of a given array. A \$k\$-subset of set \$X\$ is a partition of all the elements in \$X\$ into \$k\$ non-empty subsets.</p> <p>Thus, for <code>{1,2,3,4}</code> a 3-subset is <code>{{1,2},{3},{4}}</code>.</p> <p>I'm looking for improvements to the algorithm or code. Specifically, is there a better way than using <code>copy.deepcopy</code>? Is there some <code>itertools</code> magic that does this already?</p> <pre><code>import copy arr = [1,2,3,4] def t(k,accum,index): print accum,k if index == len(arr): if(k==0): return accum; else: return []; element = arr[index]; result = [] for set_i in range(len(accum)): if k&gt;0: clone_new = copy.deepcopy(accum); clone_new[set_i].append([element]); result.extend( t(k-1,clone_new,index+1) ); for elem_i in range(len(accum[set_i])): clone_new = copy.deepcopy(accum); clone_new[set_i][elem_i].append(element) result.extend( t(k,clone_new,index+1) ); return result print t(3,[[]],0); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-02T11:48:53.323", "Id": "154375", "Score": "0", "body": "See also: [Iterator over all partitions into k groups?](http://stackoverflow.com/q/18353280/562769)" } ]
[ { "body": "<p>Here's the obligatory recursive version:</p>\n\n<pre><code>def k_subset(s, k):\n if k == len(s):\n return (tuple([(x,) for x in s]),)\n k_subs = []\n for i in range(len(s)):\n partials = k_subset(s[:i] + s[i + 1:], k)\n for partial in partials:\n for p in range(len(partial)):\n k_subs.append(partial[:p] + (partial[p] + (s[i],),) + partial[p + 1:])\n return k_subs\n</code></pre>\n\n<p>This returns a bunch of duplicates which can be removed using</p>\n\n<pre><code>def uniq_subsets(s):\n u = set()\n for x in s:\n t = []\n for y in x:\n y = list(y)\n y.sort()\n t.append(tuple(y))\n t.sort()\n u.add(tuple(t))\n return u\n</code></pre>\n\n<p>So the final product can be had with</p>\n\n<pre><code>print uniq_subsets(k_subset([1, 2, 3, 4], 3))\n\nset([\n ((1,), (2,), (3, 4)), \n ((1,), (2, 4), (3,)), \n ((1, 3), (2,), (4,)), \n ((1, 4), (2,), (3,)), \n ((1,), (2, 3), (4,)), \n ((1, 2), (3,), (4,))\n])\n</code></pre>\n\n<p>Wow, that's pretty bad and quite unpythonic. :(</p>\n\n<p>Edit: Yes, I realize that reimplementing the problem doesn't help with reviewing the original solution. I was hoping to gain some insight on your solution by doing so. If it's utterly unhelpful, downvote and I'll remove the answer.</p>\n\n<p>Edit 2: I removed the unnecessary second recursive call. It's shorter but still not very elegant.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T07:26:50.793", "Id": "1542", "ParentId": "1526", "Score": "4" } }, { "body": "<p>Couldn't find any super quick wins in itertools.</p>\n\n<p>(Maybe I didn't look hard enough.)\nI did however come up with this,\nit runs pretty slow, but is fairly concise:</p>\n\n<pre><code>from itertools import chain, combinations\n\ndef subsets(arr):\n \"\"\" Note this only returns non empty subsets of arr\"\"\"\n return chain(*[combinations(arr,i + 1) for i,a in enumerate(arr)])\n\ndef k_subset(arr, k):\n s_arr = sorted(arr)\n return set([frozenset(i) for i in combinations(subsets(arr),k) \n if sorted(chain(*i)) == s_arr])\n\n\nprint k_subset([1,2,3,4],3)\n</code></pre>\n\n<p>Some minor wins for speed but less concise, would be to only do the set//frozenset buisness at the end if there are non unique elements in the array, or use a custom flatten function or sum(a_list, []) rather than chain(*a_list).</p>\n\n<p>If you are desperate for speed you might want have a think about another language or maybe:\nwww.cython.org is pretty neat.\nObviously the above algorithms are much better speed-wise for starters.</p>\n\n<p>Also what might be worht a look into is www.sagemath.org...\nIt's an mathematical environment built atop of python, and for example functions like, subsets() , flatten etc and lots of combinatorial things live there.</p>\n\n<p>Cheers,</p>\n\n<p>Matt</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T18:23:01.797", "Id": "1865", "ParentId": "1526", "Score": "3" } }, { "body": "<p>A very efficient algorithm (Algorithm U) is described by Knuth in the Art of Computer Programming, Volume 4, Fascicle 3B to find all set partitions with a given number of blocks. Your algorithm, although simple to express, is essentially a brute-force tree search, which is not efficient.</p>\n\n<p>Since Knuth's algorithm is not very concise, its implementation is lengthy as well. Note that the implementation below moves an item among the blocks one at a time and need not maintain an accumulator containing all partial results. For this reason, no copying is required.</p>\n\n<pre><code>def algorithm_u(ns, m):\n def visit(n, a):\n ps = [[] for i in xrange(m)]\n for j in xrange(n):\n ps[a[j + 1]].append(ns[j])\n return ps\n\n def f(mu, nu, sigma, n, a):\n if mu == 2:\n yield visit(n, a)\n else:\n for v in f(mu - 1, nu - 1, (mu + sigma) % 2, n, a):\n yield v\n if nu == mu + 1:\n a[mu] = mu - 1\n yield visit(n, a)\n while a[nu] &gt; 0:\n a[nu] = a[nu] - 1\n yield visit(n, a)\n elif nu &gt; mu + 1:\n if (mu + sigma) % 2 == 1:\n a[nu - 1] = mu - 1\n else:\n a[mu] = mu - 1\n if (a[nu] + sigma) % 2 == 1:\n for v in b(mu, nu - 1, 0, n, a):\n yield v\n else:\n for v in f(mu, nu - 1, 0, n, a):\n yield v\n while a[nu] &gt; 0:\n a[nu] = a[nu] - 1\n if (a[nu] + sigma) % 2 == 1:\n for v in b(mu, nu - 1, 0, n, a):\n yield v\n else:\n for v in f(mu, nu - 1, 0, n, a):\n yield v\n\n def b(mu, nu, sigma, n, a):\n if nu == mu + 1:\n while a[nu] &lt; mu - 1:\n yield visit(n, a)\n a[nu] = a[nu] + 1\n yield visit(n, a)\n a[mu] = 0\n elif nu &gt; mu + 1:\n if (a[nu] + sigma) % 2 == 1:\n for v in f(mu, nu - 1, 0, n, a):\n yield v\n else:\n for v in b(mu, nu - 1, 0, n, a):\n yield v\n while a[nu] &lt; mu - 1:\n a[nu] = a[nu] + 1\n if (a[nu] + sigma) % 2 == 1:\n for v in f(mu, nu - 1, 0, n, a):\n yield v\n else:\n for v in b(mu, nu - 1, 0, n, a):\n yield v\n if (mu + sigma) % 2 == 1:\n a[nu - 1] = 0\n else:\n a[mu] = 0\n if mu == 2:\n yield visit(n, a)\n else:\n for v in b(mu - 1, nu - 1, (mu + sigma) % 2, n, a):\n yield v\n\n n = len(ns)\n a = [0] * (n + 1)\n for j in xrange(1, m + 1):\n a[n - m + j] = j - 1\n return f(m, n, 0, n, a)\n</code></pre>\n\n<p>Examples:</p>\n\n<pre><code>def pretty_print(parts):\n print '; '.join('|'.join(''.join(str(e) for e in loe) for loe in part) for part in parts)\n\n&gt;&gt;&gt; pretty_print(algorithm_u([1, 2, 3, 4], 3))\n12|3|4; 1|23|4; 13|2|4; 1|2|34; 1|24|3; 14|2|3\n\n&gt;&gt;&gt; pretty_print(algorithm_u([1, 2, 3, 4, 5], 3))\n123|4|5; 12|34|5; 1|234|5; 13|24|5; 134|2|5; 14|23|5; 124|3|5; 12|3|45; 1|23|45; 13|2|45; 1|2|345; 1|24|35; 14|2|35; 14|25|3; 1|245|3; 1|25|34; 13|25|4; 1|235|4; 12|35|4; 125|3|4; 15|23|4; 135|2|4; 15|2|34; 15|24|3; 145|2|3\n</code></pre>\n\n<p>Timing results:</p>\n\n<pre><code>$ python -m timeit \"import test\" \"test.t(3, [[]], 0, [1, 2, 3, 4])\"\n100 loops, best of 3: 2.09 msec per loop\n\n$ python -m timeit \"import test\" \"test.t(3, [[]], 0, [1, 2, 3, 4, 5])\"\n100 loops, best of 3: 7.88 msec per loop\n\n$ python -m timeit \"import test\" \"test.t(3, [[]], 0, [1, 2, 3, 4, 5, 6])\"\n10 loops, best of 3: 23.6 msec per loop\n\n$ python -m timeit \"import test\" \"test.algorithm_u([1, 2, 3, 4], 3)\"\n10000 loops, best of 3: 26.1 usec per loop\n\n$ python -m timeit \"import test\" \"test.algorithm_u([1, 2, 3, 4, 5, 6, 7, 8], 3)\"\n10000 loops, best of 3: 28.1 usec per loop\n\n$ python -m timeit \"import test\" \"test.algorithm_u([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], 3)\"\n10000 loops, best of 3: 29.4 usec per loop\n</code></pre>\n\n<p>Notice that <code>t</code> runs much slower than <code>algorithm_u</code> for the same input. Furthermore, <code>t</code> runs exponentially slower with each extra input, whereas <code>algorithm_u</code> runs almost as fast for double and quadruple the input size.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T17:32:44.360", "Id": "103286", "Score": "3", "body": "There is a problem with that implementation / algorithm. `algorithm_u(range(1,14), 3)` should contain `[[2, 3, 11, 12], [5, 6, 7, 8, 9], [1, 4, 10, 13]]`, but it doesn't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-24T19:04:36.180", "Id": "148414", "Score": "1", "body": "Confirmed with moose that something's off here. `pretty_print(list(algorithm_u([\"W\", \"X\", \"Y\", \"Z\"], 2)))` should contain `[['W', 'X'], ['Y', 'Z']]` but doesn't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-13T03:49:49.357", "Id": "151020", "Score": "0", "body": "Edited to fix the bug discovered by @moose and Brad Beattie. There were missing yield statements, as pointed out by melashot, that caused some solutions to be ignored." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-13T03:52:07.177", "Id": "151021", "Score": "0", "body": "Thank you @BradBeattie for providing a smaller failing case. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-13T03:53:55.433", "Id": "151022", "Score": "0", "body": "@melashot, I could not approve your edit in time. It helped point the way toward fixing the bug. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-14T20:18:34.763", "Id": "304771", "Score": "0", "body": "Where is this referred to as “Algorithm U”? As far as I can tell, it's only described in the answer to exercise 17 in section 7.2.1.5." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-18T08:07:01.963", "Id": "1944", "ParentId": "1526", "Score": "23" } }, { "body": "<p>Based on an answer in an all partitions question (<a href=\"https://stackoverflow.com/questions/19368375/set-partitions-in-python/61141601\">https://stackoverflow.com/questions/19368375/set-partitions-in-python/61141601</a>): This can be done with simple recursion, no need for itertools, no need for a complicated algorithm. I am surprised this was not suggested. It should be just as efficient as Knuth's algorithm as well as it goes through every combination only once.</p>\n\n<pre><code>def subsets_k(collection, k): yield from partition_k(collection, k, k)\ndef partition_k(collection, min, k):\n if len(collection) == 1:\n yield [ collection ]\n return\n\n first = collection[0]\n for smaller in partition_k(collection[1:], min - 1, k):\n if len(smaller) &gt; k: continue\n # insert `first` in each of the subpartition's subsets\n if len(smaller) &gt;= min:\n for n, subset in enumerate(smaller):\n yield smaller[:n] + [[ first ] + subset] + smaller[n+1:]\n # put `first` in its own subset \n if len(smaller) &lt; k: yield [ [ first ] ] + smaller\n</code></pre>\n\n<p>Test:</p>\n\n<pre><code>something = list(range(1,5))\nfor n, p in enumerate(subsets_k(something, 1), 1):\n print(n, sorted(p))\nfor n, p in enumerate(subsets_k(something, 2), 1):\n print(n, sorted(p))\nfor n, p in enumerate(subsets_k(something, 3), 1):\n print(n, sorted(p)) \nfor n, p in enumerate(subsets_k(something, 4), 1):\n print(n, sorted(p))\n</code></pre>\n\n<p>Yields correctly:</p>\n\n<pre><code>1 [[1, 2, 3, 4]]\n\n1 [[1], [2, 3, 4]]\n2 [[1, 2], [3, 4]]\n3 [[1, 3, 4], [2]]\n4 [[1, 2, 3], [4]]\n5 [[1, 4], [2, 3]]\n6 [[1, 3], [2, 4]]\n7 [[1, 2, 4], [3]]\n\n1 [[1], [2], [3, 4]]\n2 [[1], [2, 3], [4]]\n3 [[1], [2, 4], [3]]\n4 [[1, 2], [3], [4]]\n5 [[1, 3], [2], [4]]\n6 [[1, 4], [2], [3]]\n\n1 [[1], [2], [3], [4]]\n</code></pre>\n\n<p>Compared to the Knuth implementation above (modified for Python3 - <code>xrange</code> changed to <code>range</code>):</p>\n\n<pre><code>if __name__ == '__main__':\n import timeit\n print(timeit.timeit(\"for _ in subsets_k([1, 2, 3, 4, 5], 3): pass\", globals=globals()))\n print(timeit.timeit(\"for _ in algorithm_u([1, 2, 3, 4, 5], 3): pass\", globals=globals()))\n</code></pre>\n\n<p>Results in more than twice as fast code:</p>\n\n<pre><code>20.724652599994442\n41.03094519999286\n</code></pre>\n\n<p>Sometimes a simple approach is the best one. It would be interesting to know if optimizations can be applied to Knuth variation to fix this, or if this simple algorithm is the best one.</p>\n\n<p>Update: the Knuth timing information above is both wrong and misleading!!!</p>\n\n<p>The <code>t</code> implementation compiles a whole list and does not return a generator. Whereas the Knuth version has a generator. To make a fair test comparison, one must enumerate all the elements otherwise the Knuth implementation is just running to the first <code>yield</code> returning the generator and timing this... <code>for _ in generator: pass</code> would have been sufficient to have a real test comparison.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T13:48:48.547", "Id": "240277", "ParentId": "1526", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-29T17:44:53.210", "Id": "1526", "Score": "20", "Tags": [ "python", "algorithm", "combinatorics" ], "Title": "Finding all k-subset partitions" }
1526
<p>Here is the database query needed to create the database:</p> <pre><code>create table Area ( AreaId int primary key identity(1,1), Name nvarchar(64) not null ) create table Level ( LevelId int primary key identity(1,1), Name nvarchar(32) not null, Principle nvarchar(512) not null ) create table Subject ( SubjectId int primary key identity(1,1), AreaId int foreign key references Area(AreaId), LevelId int foreign key references Level(LevelId), Name nvarchar(32) not null, Abbreviation nvarchar(16) ) create table StaffType ( StaffTypeId int primary key identity(1,1), Name nvarchar(64) not null ) create table Staff ( StaffId int primary key identity(1,1), StaffTypeId int foreign key references StaffType(StaffTypeId), Name nvarchar(128) not null, LastNameFather nvarchar(256) not null, LastNameMother nvarchar(256) not null, DateOfBirth datetime, PlaceOfBirth nvarchar(256), Sex nvarchar(8) not null, Carnet nvarchar(64), Telephone nvarchar(64), MobilePhone nvarchar(64), Address nvarchar(256), FatherName nvarchar(256), MotherName nvarchar(256), FatherContactNumber nvarchar(64), MotherContactNumber nvarchar(64), FatherPlaceOfWork nvarchar(64), MotherPlaceOfWork nvarchar(64), DateOfHiring datetime, YearsOfService int, Formation nvarchar(128) ) create table Grade ( GradeId int primary key identity(1,1), Name nvarchar(32) not null, LevelId int foreign key references Level(LevelId), Observation nvarchar(256) ) create table GradeInstance ( GradeInstanceId int primary key identity(1,1), StaffId int foreign key references Staff(StaffId), GradeId int foreign key references Grade(GradeId), Name nvarchar(32) not null, Year datetime ) create table Student ( StudentId int primary key identity(1,1), RUDE int, Name nvarchar(64) not null, LastNameFather nvarchar(256) not null, LastNameMother nvarchar(256) not null, DateOfBirth datetime not null, PlaceOfBirth nvarchar(128), Sex nvarchar(8), Carnet nvarchar(32), Telephone nvarchar(64), MobilePhone nvarchar(64), Address nvarchar(256), FatherName nvarchar(512), MotherName nvarchar(512), FatherMobilePhone nvarchar(64), MotherMobilePhone nvarchar(64), FatherProfession nvarchar(64), MotherProfession nvarchar(64), FatherPlaceOfWork nvarchar(256), MotherPlaceOfWork nvarchar(256), Observations nvarchar(3000) ) create table StudentInstance ( StudentInstanceId int primary key identity(1,1), GradeInstanceId int foreign key references GradeInstance(GradeInstanceId), StudentId int foreign key references Student(StudentId) ) create table StudentGradeReport ( StudentGradeReportId int primary key identity(1,1), StudentInstanceId int foreign key references StudentInstance(StudentInstanceId), SubjectId int foreign key references Subject(SubjectId), FirstTrimester int, SecondTrimester int, ThirdTrimester int, FinalGrade int ) </code></pre> <p>If you find an attribute that <em>should</em> be null checked, please disregard it. I've gone over this with the client and they want certain things to left blank if so chosen by the end user.</p> <p>My main concern when designing this database was how to associate a student with a grade here and now, yet keep a record for previous years and manage to see what grade he got back in 2009. See?</p> <p>I think I've done a good job but you never know - the hivemind here will probably find a flaw and I'd love some feedback.</p>
[]
[ { "body": "<p>Here are some observations:</p>\n\n<ol>\n<li>Beware of storing calculated information in the database, especially time-sensitive values like <code>YearsOfService</code>. You must ensure to have a (yearly?) process update this column based on the current date and <code>DateOfHiring</code>. What happens if that process fails? How do you catch it later? What happens if you restore from an old backup? Is it worth storing, or could you recalculate it when needed with little cost?</li>\n<li>The <code>Staff</code> and <code>Student</code> tables are nearly identical. Could you benefit from a <code>Person</code> table to allow a more generic data-entry form? It may not be worth it since they would probably create a new record if a student were to become a staff member.</li>\n<li>I find it much easier to analyze a schema with a couple rows of sample data per table, except for the obvious tables like <code>Student</code>. I assume <code>Level</code> is grade level (1st, 2nd, etc), but I'm not sure.</li>\n<li>I think <code>StudentInstance</code> and <code>StudentGradeReport</code> should be merged. Each row tracks the scores for a student plus grade plus year, or in your case, student plus grade-instance.</li>\n<li><code>GradeInstance</code> is a joining table for <code>Grade</code>, <code>Staff</code>, and year. The use of the word \"instance\" here works somewhat but I think could be replaced with something more meaningful, maybe even <code>GradeYear</code>.</li>\n<li>In the U.S. we call <code>Level</code> a grade, and <code>Grade</code> a class, at least that's what I get from your table definitions. Again, sample data would help. You might be missing an actual table for <code>Year</code> to which you can relate the <code>Grade</code>s that are taught that year?</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T02:23:17.373", "Id": "1533", "ParentId": "1528", "Score": "5" } }, { "body": "<p>Additional Observations:</p>\n\n<ol>\n<li>Consider a new lookup table <code>Phonetype</code> (e.g. Mobile, Home, Work, etc.). </li>\n<li>Create <code>PersonPhone</code> table that will have the <code>PhoneTypeId</code>, <code>PersonId</code>, and <code>PersonType</code> (student, faculty, parent, etc.) field and also a linking table between Phone and Person</li>\n<li>With today's modern and extended families, a Father/Mother field will not suffice. Consider renaming to Guardian1/Guardian2. </li>\n<li>Create a relationship list table (e.g. Mother, Father, Grandmother) </li>\n<li>Create a <code>StudentRelationLink</code> table that can specify the student's legal guardians as well as other important people for the student (e.g. Emergency Contacts)</li>\n<li>Is it necessary to have the last name of the father and mother on the Staff?</li>\n<li>A Profession look-up might be beneficial on the student's parents </li>\n<li>I assume this product will be web-based and multiple users could modify records simultaneously. You might want to add fields to each table to maintain concurrency. (e.g. <code>Created</code>, <code>LastModified</code>)</li>\n<li>I don't see any tables that enforce permissions on your application. This might be okay for a small scope, but when your product grows and more people start to use, you may want to give them read-only access or deny them access all together to certain areas of the program</li>\n</ol>\n\n<hr>\n\n<h2>NOTE:</h2>\n\n<p>Creating school management software from the ground-up is a daunting task. That being said, you've got to start somewhere and, as long as your client is happy, you should see pay checks for many years to come :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T12:30:02.333", "Id": "2681", "Score": "2", "body": "Some great points, but I'd remove mother/father/guardians entirely and create a new \"Guardians\" table. What if a child has amicably divorced parents who have remarried and now are all considered responsible for the child? Guardian3 and Guardian4? What if siblings are at the same school? Will you repeat the data? Splitting it into a separate Guardians table and a join table is a more flexible solution." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T13:37:07.850", "Id": "2682", "Score": "0", "body": "That makes more sense. Remove Guardians off of the Student table and consider using the StudentRelationLink table for marking a student's guardians. Also, in StudentRelationLink , you can add useful fields like CanReceiveMail, CanPickUpFromSchool, IsEmergencyContact, IsGuardian, etc." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T13:39:08.423", "Id": "2683", "Score": "0", "body": "Also, while you're at it, you might to consider stripping out the address from student too and putting that in a separate table. Students from split families will have multiple addresses and you list one as the Primary Household. Also, as Ant mentioned, student's can have siblings who may (or may not) have the same address." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-30T08:34:48.193", "Id": "1543", "ParentId": "1528", "Score": "8" } }, { "body": "<p>Your data needs to be more</p>\n\n<h1><a href=\"http://www.learn.geekinterview.com/data-warehouse/data-types/what-is-atomic-data.html\" rel=\"nofollow\">ATOMIC</a> AND HOMOGENEOUS</h1>\n\n<p>This table</p>\n\n<blockquote>\n<pre><code>create table StudentGradeReport\n(\n StudentGradeReportId int primary key identity(1,1),\n StudentInstanceId int foreign key references StudentInstance(StudentInstanceId),\n SubjectId int foreign key references Subject(SubjectId),\n FirstTrimester int,\n SecondTrimester int,\n ThirdTrimester int,\n FinalGrade int\n)\n</code></pre>\n</blockquote>\n\n<p>doesn't look right to me.</p>\n\n<p>I think that you want something more like this</p>\n\n<pre><code>CREATE TABLE StudentGradeReport\n(\n TableID INT PRIMARY KEY IDENTITY(1,1),\n StudentInstanceID INT FOREIGN KEY REFERENCES, StudentInstance(StudentInstanceID),\n SubjectID INT FOREIGN KEY REFERENCES Subject(SubjectID)\n Term NVARCH(2), -- this will tell us T1, T2, T3 or F\n SchoolYear INT,\n UpdateDate DATETIME,\n UserChangeID INT NOT NULL\n)\n-- the UserChangeID would be a foreign key to the Staff table(or User Table), \n-- assuming they are the only people that can change these things. \n-- this way you can keep track of who is changing things.\n</code></pre>\n\n<p>This seems like the right way to create this table. </p>\n\n<p>You want your data to be <a href=\"http://www.learn.geekinterview.com/data-warehouse/data-types/what-is-atomic-data.html\" rel=\"nofollow\"><strong>atomic</strong></a> in all of your tables, but not redundant.</p>\n\n<p>In your version of this table you had redundant data, you would fill in <code>FirstTrimester</code> with a <code>1</code> (<em>true</em>) and then the other 3 with a <code>0</code> (<em>false</em>) that is very redundant.</p>\n\n<p>The data that would go into that table would have to be updated or overwritten if they wanted to change something or there was a mistake. This isn't good for keeping track of changes. In the table that I gave you have the ability to add a new row of data and then keeping track of who made the change, this way you can keep track of who changed what and when.</p>\n\n<p>Having your data in the table that I provided it is going to be a whole lot easier to pull reports from. you can pull data from</p>\n\n<ul>\n<li>a specific student</li>\n<li>a specific subject</li>\n<li>a Specific school year</li>\n<li>a range of school years</li>\n<li>all changes made by a specific user</li>\n</ul>\n\n<p>I hope that looking at my answer helps you to see how the rest of your tables need to be more <strong><a href=\"http://www.learn.geekinterview.com/data-warehouse/data-types/what-is-atomic-data.html\" rel=\"nofollow\">ATOMIC</a></strong>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T06:07:18.847", "Id": "36180", "ParentId": "1528", "Score": "9" } }, { "body": "<p>How about having more generic tables.</p>\n\n<ul>\n<li><p><code>PERSON</code> with a field <code>type_of_person</code> where <code>1 = parent</code>, <code>2 = parent</code> (for divorced families), <code>3 = personnel</code>, <code>4 = student</code> etc that way you keep all the basic information in one table. </p></li>\n<li><p>Afterwards create a table with addressing information that will be connected with only adult records of the table \"PERSON\"</p></li>\n<li><p>Finally create a table with member specific data. If the member is of <code>type = 1 or 2</code> (parent) maybe keep some personal information, like profession (he may be a doctor, a policeman or a fireman that you may need to call in case of emergency), special requirements,notes whatever. If it is <code>type 3 = personnel</code> (wages, timetables, tax info etc). If it is <code>4 = student</code> you can store grades, year, special info,...whatever.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T11:10:03.540", "Id": "59234", "Score": "3", "body": "Don't put everything in one para. Use some bullets or points to break down your points and make it more readable." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T08:26:23.260", "Id": "36184", "ParentId": "1528", "Score": "1" } }, { "body": "<ol>\n<li>Staff - \"YearsOfService\" isnt necessary as it can be aggregated from the DateOfHiring attribute.</li>\n<li>Staff - Is \"PlaceOfBirth\" even interesting to know? Would this field be useful as something more than just trivia?</li>\n<li>Staff - \"Sex\" could preferably be changed into \"Gender\"</li>\n</ol>\n\n<p>I think your <code>Grade</code> and <code>GradeInstance</code> is weird. A <code>GradeInstance</code> has a <code>Staff</code> and a <code>Grade</code>? And then your <code>StudentInstance</code> has a <code>GradeInstance</code>?</p>\n\n<p>I also think that keeping track of <code>First/Second/Third trimester</code> in your <code>StudentGradeReport</code> table is bad because you would need to update every <code>StudentGradeReport</code> record as soon as this changes. This could possibly be done by keeping another table called <code>Trimesters</code>, which has first, second, third as columns, and a <code>daterange</code> as tuples and then aggregate from the current date</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T14:32:27.623", "Id": "59261", "Score": "0", "body": "PlaceOfBirth is something that is used in background checks and stuff like that, so this is not just trivia. in a school I would want that school to have as much background on their teachers as possible" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T14:38:48.183", "Id": "59265", "Score": "0", "body": "Didn't know that. And this is in the US? Not sure if we do it (probably to some extent)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T14:48:35.437", "Id": "59269", "Score": "0", "body": "probably more for a credit check type of thing...lol but that is what I would assume. and this Database layout has been approved by the Customer already so I imagine that is a field that the customer wants." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T09:58:58.983", "Id": "36196", "ParentId": "1528", "Score": "3" } } ]
{ "AcceptedAnswerId": "1543", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-29T20:55:06.960", "Id": "1528", "Score": "7", "Tags": [ "sql", "sql-server" ], "Title": "Database schema for a school" }
1528
<p>I am creating a form class for validating form data, and would like some advice on how to refactor it for best practices. Keep in mind that this is a rough draft.</p> <p>Basically, there is a form abstract class (<code>lev_form</code>), which you would extend. In the extended classes, you would write a <code>__construct</code> method that creates all of the form fields, and form field validations. You could then instantiate that extended class, and run its <code>validate_form()</code> method to validate <code>$_POST</code> and <code>$_FILES</code> data against all of the child form fields, and their child form field validations.</p> <p>It somewhat mimics the way jQuery form validation is operated, and the eventual plan is to give the class the ability to print out a jQuery validation class for the form, based on the same data that the backend validation uses.</p> <p>Here is the form class:</p> <pre><code>&lt;?php abstract class lev_form { protected $fields = array(); abstract public function __construct() { // set up form fields and field vlaidations here } protected function create_field($name, $label) { lev::load_library('lev_forms/lev_field'); $this-&gt;fields[] = new lev_field($name, $label); } // validates POST and FILES data public function validate_form() { try { foreach($this-&gt;fields as $field_object) { $field_object-&gt;validate_field(); } } catch (Exception $e) { return $e-&gt;getMessage(); } return true; } // validates form using jQuery public function print_jquery_validator($selector) { } } ?&gt; </code></pre> <p>Here is the class for form fields:</p> <pre><code>&lt;?php class lev_field { protected $name; protected $label; protected $validations = array(); public function __construct($name, $label) { $this-&gt;name = $name; $this-&gt;label = $label; } public function create_validation($type, $argument = null, $message = null) { lev::load_library('lev_forms/lev_field_validation'); $this-&gt;validations[] = new lev_field_validation($type, $argument, $message, $this-&gt;name, $this-&gt;label); } public function validate_field() { foreach ($this-&gt;validation as $validation_object) { $validation_object-&gt;validate(); } } } ?&gt; </code></pre> <p>And here is the form field validation class:</p> <pre><code>&lt;?php class lev_field_validation { protected $type; protected $argument; protected $message; protected $field_name; protected static $default_validation_error_messages = array( 'required' =&gt; '[field_label] is a required field.', 'minlength' =&gt; '[field_label] must be at least [validation_argument] characters in length.', 'maxlength' =&gt; '[field_label] must be at most [validation_argument] characters in length.', 'min' =&gt; '[field_label] must be at least [validation_argument].', 'max' =&gt; '[field_label] must be at most [validation_argument].', 'email' =&gt; '[field_label] must be a valid email address.', 'url' =&gt; '[field_label] must be a valid URL.', 'date' =&gt; '[field_label] must be a valid date.', 'number' =&gt; '[field_label] must be a numeric value.', 'digits' =&gt; '[field_label] must only contain digits.', 'boolean' =&gt; '[field_label] must be true or false.', 'equalto' =&gt; '[field_label] must be equal to [validation_argument].', 'file_accept_extensions' =&gt; '[field_label] must be a valid file type.', 'file_max_size' =&gt; '[field_label] must have a file size no greater than [validation_argument] bytes.' ); public function __construct($type, $argument, $message, $field_name, $field_label) { $this-&gt;type = $type; $this-&gt;argument = $argument; $this-&gt;field_name = $field_name; if ($message) { $this-&gt;message = $message; } else if (array_key_exists($type, self::$default_validation_error_messages)) { $this-&gt;message = preg_replace(array('\[field_label\]', '\[validation_argument\]'), array($field_label, $argument), self::$default_validation_error_messages[$type]); } else { trigger_error('No set error message or default error message for form validation "' . $type . '"', E_USER_ERROR); } } public function validate() { $this-&gt;error_check_validation(); $this-&gt;check_validation(); } protected function error_check_validation() { if (array_search($this-&gt;field_name, $_POST) === true) { if ($this-&gt;type == 'file_accept_extensions' || $this-&gt;type == 'file_max_size') trigger_error('Use of invalid form validation "' . $this-&gt;type . '" on non-file field.', E_USER_ERROR); } else if (array_search($this-&gt;field_name, $_FILES) === true) { if ($this-&gt;type != 'file_accept_extensions' &amp;&amp; $this-&gt;type != 'file_max_size') trigger_error('Use of invalid form validation "' . $this-&gt;type . '" on file field. You may only use this validation on non-file fields.', E_USER_ERROR); } else { trigger_error('Form field "' . $this-&gt;field_name . '" not found in $_POST or $_FILES array even though it exists in this form\'s class.', E_USER_ERROR); } } protected function check_validation() { switch ($validation-&gt;type) { case 'required': if (!$this-&gt;required()) throw new Exception($this-&gt;message); break; case 'callback': if ($_POST[$this-&gt;field_name] !== '' &amp;&amp; $this-&gt;argument($_POST[$this-&gt;field_name])) throw new Exception($this-&gt;message); break; case 'minlength': if ($_POST[$this-&gt;field_name] !== '' &amp;&amp; strlen($_POST[$this-&gt;field_name]) &lt; $this-&gt;argument) throw new Exception($this-&gt;message); break; case 'maxlength': if ($_POST[$this-&gt;field_name] !== '' &amp;&amp; strlen($_POST[$this-&gt;field_name]) &gt; $this-&gt;argument) throw new Exception($this-&gt;message); break; case 'min': if ($_POST[$this-&gt;field_name] !== '' &amp;&amp; $_POST[$this-&gt;field_name] &gt; $this-&gt;argument) throw new Exception($this-&gt;message); break; case 'max': if ($_POST[$this-&gt;field_name] !== '' &amp;&amp; $_POST[$this-&gt;field_name] &lt; $this-&gt;argument) throw new Exception($this-&gt;message); break; case 'email': if ($_POST[$this-&gt;field_name] !== '' &amp;&amp; !filter_var($_POST[$this-&gt;field_name], FILTER_VALIDATE_EMAIL)) throw new Exception($this-&gt;message); break; case 'url': if ($_POST[$this-&gt;field_name] !== '' &amp;&amp; !filter_var($_POST[$this-&gt;field_name], FILTER_VALIDATE_URL)) throw new Exception($this-&gt;message); break; case 'date': if ($_POST[$this-&gt;field_name] !== '' &amp;&amp; !strtotime($_POST[$this-&gt;field_name])) throw new Exception($this-&gt;message); break; case 'number': if ($_POST[$this-&gt;field_name] !== '' &amp;&amp; !is_numeric($_POST[$this-&gt;field_name])) throw new Exception($this-&gt;message); break; case 'digits': if ($_POST[$this-&gt;field_name] !== '' &amp;&amp; !is_int($_POST[$this-&gt;field_name]) &amp;&amp; $_POST[$this-&gt;field_name] &gt;= 0) throw new Exception($this-&gt;message); break; case 'boolean': if ($_POST[$this-&gt;field_name] !== '' &amp;&amp; !filter_var($_POST[$this-&gt;field_name], FILTER_VALIDATE_BOOLEAN)) throw new Exception($this-&gt;message); break; case 'equalto': if ($_POST[$this-&gt;field_name] !== '' &amp;&amp; $_POST[$this-&gt;field_name] !== $_POST[$this-&gt;argument]) throw new Exception($this-&gt;message); break; case 'file_accept_extensions': $extension = preg_replace('/.+?\.(.+)$/', '$1', $_FILES[$this-&gt;field_name]['name']); if (array_search($extension, $this-&gt;argument) === false) throw new Exception($this-&gt;message); break; case 'file_max_size': if (filesize($_FILES[$this-&gt;field_name]['tmp_name']) &gt; $this-&gt;argument) throw new Exception($this-&gt;message); break; default: trigger_error('Validation "' . $this-&gt;type . '" does not exist. This validation was called by field "' . $this-&gt;field_name . '".', E_USER_ERROR); } return false; } protected function required() { if ($this-&gt;argument &amp;&amp; !$_POST[$this-&gt;argument]) return true; return ($_POST[$this-&gt;field_name] === '') ? false : true; } } ?&gt; </code></pre>
[]
[ { "body": "<p>I jumped straight down to <code>lev_field_validation</code> as it's the most interesting class.</p>\n\n<ol>\n<li>Whenever I see a giant <code>switch()</code> block, I immediately suspect there are a lot of subclasses trying to break out. Each validation type should be a different subclass with an appropriate override of <code>check_validation()</code> (and <code>error_check_validation()</code> in a couple cases).</li>\n<li>You repeat <code>$_POST[$this-&gt;field_name] !== ''</code> twelve times which is a sure sign that this should be encapsulated in its own method. For one thing, you should check if the field exists using <code>array_key_exists()</code> before grabbing its value.</li>\n<li>The idiom <code>$x ? false : true</code> can be replaced by <code>!$x</code>. The second line of <code>required()</code> thus becomes <code>return $_POST[$this-&gt;field_name] !== '';</code>.</li>\n<li>Add some high-level comments explaining what is going on overall. For example, given its name I would expect <code>required()</code> to tell me if the value is required, yet it appears to mean that the value was passed in and must be validated. Shouldn't a \"> 5\" validation fail if I don't provide a value? If not, explain why or at least point that out.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T09:30:57.377", "Id": "3007", "Score": "0", "body": "Or before the switch he could do `$empty = empty($_POST[$this->field_name])` and then for each check do `iF(!$empty &&)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T02:40:12.047", "Id": "3122", "Score": "0", "body": "great suggestions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T01:56:48.380", "Id": "1532", "ParentId": "1530", "Score": "2" } }, { "body": "<ul>\n<li>The lack of comments is definitely a concern.</li>\n<li>The code under the case statements is relatively unreadable, and contains a great deal of duplication. Think about how to rewrite this without so much duplicated code. The previous response suggests subclassing, I would suggest avoiding OO entirely.</li>\n<li>The fact that you've opted to use OO is measurably adding a lot of pretty pointless bloat to your real code. Consider implementing the same thing without OO and comparing the results as a personal exercise.</li>\n<li>Architectural concern: what if the user wants to perform custom validation?</li>\n<li>Your code is not internationalisation aware. While it's good to see that you have a dedicated structure for most of the messages you have written, the triggererror() lines contain user-oriented strings right in to your code, which prevents easy internationalisation.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T02:37:36.120", "Id": "3120", "Score": "0", "body": "first comments lie. they become stale after refactoring. they become a maintainence concern in of themselves. turning this into procedural code not only clutters up the namespace with function names which in large projects with many developers can become an issue, it stops the code from being able to be autoloaded. meaning, you would have to include the file containing above anywhere that you would like to use it, or even worse, include it in every instance of your script. encapsulating it in a class allows me to autoload the class only when it is needed without adding extra lines of code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T02:39:38.413", "Id": "3121", "Score": "0", "body": "ideally i would use small enough functions, and good enough function names, so that the public routines would be expressive enough to read without any comments at all." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T02:20:49.513", "Id": "1797", "ParentId": "1530", "Score": "1" } } ]
{ "AcceptedAnswerId": "1532", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-29T22:40:21.557", "Id": "1530", "Score": "2", "Tags": [ "php", "validation", "form" ], "Title": "Form validator class and child classes" }
1530
<blockquote> <p><strong>Exercise 1.31</strong></p> <p>a. The sum procedure is only the simplest of a vast number of similar abstractions that can be captured as higher-order procedures.51 Write an analogous procedure called product that returns the product of the values of a function at points over a given range. Show how to define factorial in terms of product. Also use product to compute approximations to using the pi / 4 = (2/3) * (4/3) * (4/5) * (6/5) * (6/7) * (8/7) ...</p> <p>b. If your product procedure generates a recursive process, write one that generates an iterative process. If it generates an iterative process, write one that generates a recursive process.</p> </blockquote> <p>I wrote the following:</p> <p>Recursive:</p> <pre><code>(define (product term a next b) (cond ((&gt; a b) 1) (else (* (term a) (product term (next a) next b))))) </code></pre> <p>Iterative: </p> <pre><code>(define (i-product term a next b) (cond ((&gt; a b) null) (else (define (iter a result) (cond ((&gt; a b) result) (else (iter (next a) (* (term a) result))))) (iter a 1)))) </code></pre> <p>Multiply-integers [test - does (product ...) work?]</p> <pre><code>(define (identity x) x) (define (inc x) (+ 1 x)) (define (multiply-integers a b) (i-product identity a inc b)) </code></pre> <p>Compute pi:</p> <pre><code>(define (square x) (* x x)) (define (compute-pi steps) (define (next n) (+ n 2.0)) (* 8.0 (* steps 2) (/ (i-product square 4.0 next (* (- steps 1) 2)) (i-product square 3.0 next (* steps 2))))) </code></pre> <p>Factorial:</p> <pre><code>(define (factorial n) (define (next n) (+ n 1)) (i-product identity 1 next n)) </code></pre> <p>What do you think of my solution?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T02:52:18.823", "Id": "2665", "Score": "0", "body": "I meant to post this at codereview.stackexchange.com - can it be migrated?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T03:07:21.597", "Id": "2666", "Score": "0", "body": "@Joshua: Yes. Click \"flag\", \"it needs ♦ moderator attention\", then \"other\", and fill in the textbox requesting this. :-) (I've also requested a migration for you in the mod chat room, in case they monitor that more frequently. ;-))" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T03:47:38.640", "Id": "2674", "Score": "0", "body": "It turned out that the mod chat room was indeed monitored more frequently (thanks Shog9!), but, in future, you can flag your post yourself anyway. SO mods are meant to be pretty active, and should see your flag pretty much straight away. :-)" } ]
[ { "body": "<p>Since your definitions have only two <code>cond</code> clauses, you may replace <code>cond</code> with <code>if</code>. Your iterative definition is a departure from the example of <code>sum</code>. It should return 1 (product identity) when <code>a</code> is greater than <code>b</code>, not null. This makes the outer <code>cond</code> unnecessary.</p>\n\n<p>Your definition of <code>compute-pi</code> suffers from imprecision of float operations (it fails to produce meaningful values for n > 85). It would be better to convert to float after computing the approximating fraction.</p>\n\n<pre><code>(define (product term a next b)\n (if (&gt; a b)\n 1\n (* (term a) (product term (next a) next b))))\n\n(define (i-product term a next b)\n (define (iter a result)\n (if (&gt; a b)\n result\n (iter (next a) (* (term a) result))))\n (iter a 1))\n\n(define (compute-pi steps)\n (define (next n) (+ n 2))\n (* 8.0 (* steps 2) (/ (i-product square 4 next (* (- steps 1) 2)) \n (i-product square 3 next (* steps 2)))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T13:05:46.967", "Id": "1579", "ParentId": "1534", "Score": "1" } } ]
{ "AcceptedAnswerId": "1579", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-30T02:49:42.020", "Id": "1534", "Score": "0", "Tags": [ "lisp", "scheme" ], "Title": "Writing a product() function analogous to sum" }
1534
<p>Given the following recursive definition of sum:</p> <blockquote> <pre><code>(define (sum term a next b) (if (&gt; a b) 0 (+ (term a) (sum term (next a) next b)))) </code></pre> </blockquote> <p>And the task: </p> <blockquote> <p><strong>Exercise 1.30</strong></p> <p>The sum procedure above generates a linear recursion. The procedure can be rewritten so that the sum is performed iteratively. Show how to do this by filling in the missing expressions in the following definition:</p> <pre><code>(define (sum term a next b) (define (iter a result) (if &lt;??&gt; &lt;??&gt; (iter &lt;??&gt; &lt;??&gt;))) (iter &lt;??&gt; &lt;??&gt;)) </code></pre> </blockquote> <p>I wrote the following code. What do you think?</p> <pre><code>(define (i-sum term a next b) (define (iter a result) (if (&gt; a b) result (iter (next a) (+ result (term a))))) (iter a 0)) (define (identity x) x) (define (inc x) (+ 1 x)) (define (sum-integers a b) (i-sum identity a inc b)) </code></pre>
[]
[ { "body": "<p>I believe your answer is correct, although I'm not sure why you need the <code>identity</code>, <code>inc</code>, and <code>sum-integers</code> procedure on the bottom for your solution.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T02:51:02.693", "Id": "2671", "Score": "0", "body": "Not homework - personal growth exercise :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T02:57:29.853", "Id": "2672", "Score": "0", "body": "@Joshua: Haha okay, just checking. :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T03:22:44.467", "Id": "2673", "Score": "0", "body": "They're there for testing purposes - I suppose maybe I should have removed them before posting the question?...hmm" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T02:04:30.507", "Id": "1536", "ParentId": "1535", "Score": "2" } } ]
{ "AcceptedAnswerId": "1536", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-30T01:48:08.220", "Id": "1535", "Score": "0", "Tags": [ "recursion", "lisp", "scheme", "sicp" ], "Title": "Iterative sum using recursion" }
1535
<p>As an answer to this problem:</p> <blockquote> <p><strong>Exercise 1.29</strong></p> <p>Simpson's Rule is a more accurate method of numerical integration than the method illustrated above. Using Simpson's Rule, the integral of a function f between a and b is approximated as (h / 3) * (y_0 + 4y_1 + 2y_2 + 4y_3 + 2y_4 + ... + 2y_(n-2) + 4y_(n-1) + y_n</p> <p>where h = (b - a)/n, for some even integer n, and yk = f(a + kh). (Increasing n increases the accuracy of the approximation.) Define a procedure that takes as arguments f, a, b, and n and returns the value of the integral, computed using Simpson's Rule. Use your procedure to integrate cube between 0 and 1 (with n = 100 and n = 1000), and compare the results to those of the integral procedure shown above.</p> </blockquote> <p>I wrote the following solution:</p> <pre><code>(define (sum term a next b) (define (iter a result) (if (&gt; a b) result (iter (next a) (+ (term a) result))) ) (iter a 0)) (define (simpsons-rule f a b n) (let ((h (/ (- b a) n))) (define (y_k k) (f (+ a (* k h)))) (define (even n) (= (remainder n 2) 0)) (define (term n) (* (if (even n) 2.0 4.0) (y_k n))) (define (next n) (+ n 1)) (* (/ h 3.0) (+ (y_k 0.0) (sum term 0.0 next (- n 1.0)) (y_k n))))) (define (cube x) (* x x x)) </code></pre> <p>What do you think?</p>
[]
[ { "body": "<p>When you call <code>sum</code>, make sure you start with 1 (and not 0). Otherwise, you get an error of + 2 y_0 h / 3. In case of <code>(simpsons-rule cube 1 2 1000)</code>, this error is 0.000666....</p>\n\n<p>Another way to rewrite the series is to group even and odd terms together, excluding the first and last terms.</p>\n\n<p>(h / 3) * (y_0 + y_n + 4 * (y_1 + y_3 + ... + y_n-1) + 2 * (y_2 + y_4 + ... + y_n-2))</p>\n\n<p>This gives us another possible implementation:</p>\n\n<pre><code>(define (simpsons-rule f a b n)\n (define h (/ (- b a) n))\n (define (y-k k) (f (+ a (* k h))))\n (define (next n) (+ n 2))\n (* (/ h 3.0) (+ (y-k 0) (y-k n) (* 4 (sum y-k 1 next (- n 1))) (* 2 (sum y-k 2 next (- n 2))))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T13:41:59.990", "Id": "1580", "ParentId": "1538", "Score": "2" } } ]
{ "AcceptedAnswerId": "1580", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-30T04:07:50.277", "Id": "1538", "Score": "2", "Tags": [ "lisp", "scheme", "sicp", "numerical-methods" ], "Title": "Integral using Simpson's Rule" }
1538
<p>Given this task:</p> <blockquote> <p><strong>Exercise 1.32</strong></p> <p>a. Show that sum and product (exercise 1.31) are both special cases of a still more general notion called accumulate that combines a collection of terms, using some general accumulation function:</p> <p>(accumulate combiner null-value term a next b)</p> <p>Accumulate takes as arguments the same term and range specifications as sum and product, together with a combiner procedure (of two arguments) that specifies how the current term is to be combined with the accumulation of the preceding terms and a null-value that specifies what base value to use when the terms run out. Write accumulate and show how sum and product can both be defined as simple calls to accumulate.</p> <p>b. If your accumulate procedure generates a recursive process, write one that generates an iterative process. If it generates an iterative process, write one that generates a recursive process.</p> </blockquote> <p>I wrote the following solution:</p> <p>Recursive:</p> <pre><code>(define (accumulate combiner null-value term a next b) (if (&gt; a b) null-value (combiner (term a) (accumulate combiner null-value term (next a) next b)))) </code></pre> <p>Iterative:</p> <pre><code>(define (i-accumulate combiner null-value term a next b) (define (iter a result) (if (&gt; a b) result (iter (next a) (combiner (term a) result)))) (iter a null-value)) </code></pre> <p>Sum/Product using iterative accumulate:</p> <pre><code>(define (sum term a next b) (i-accumulate + 0 term a next b)) (define (product term a next b) (i-accumulate * 1 term a next b)) </code></pre> <p>What do you think?</p>
[]
[ { "body": "<p>Since the only parameter that changes in your recursive definition is <code>a</code>, you can write an inner definition like so:</p>\n\n<pre><code>(define (accumulate combiner null-value term a next b)\n (define (rec a)\n (if (&gt; a b)\n null-value\n (combiner (term a) (rec (next a)))))\n (rec a))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T14:04:15.847", "Id": "1583", "ParentId": "1539", "Score": "1" } } ]
{ "AcceptedAnswerId": "1583", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-30T04:22:13.963", "Id": "1539", "Score": "0", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Show that sum and product are both examples of accumulation" }
1539
<p>Given the following task:</p> <blockquote> <p><strong>Exercise 1.33</strong></p> <p>You can obtain an even more general version of accumulate (exercise 1.32) by introducing the notion of a filter on the terms to be combined. That is, combine only those terms derived from values in the range that satisfy a specified condition. The resulting filtered-accumulate abstraction takes the same arguments as accumulate, together with an additional predicate of one argument that specifies the filter. Write filtered-accumulate as a procedure. Show how to express the following using filtered-accumulate:</p> <p>a. the sum of the squares of the prime numbers in the interval a to b (assuming that you have a prime? predicate already written)</p> <p>b. the product of all the positive integers less than n that are relatively prime to n (i.e., all positive integers i &lt; n such that GCD(i,n) = 1).</p> </blockquote> <p>I wrote this code:</p> <p>(Utility functions)</p> <pre><code>(define (gcd a b) (if (= b 0) a (gcd b (remainder a b)))) (define (square x) (* x x)) (define (divisible? b a) (= (remainder b a) 0)) (define (smallest-divisor n) (find-divisor n 2)) (define (find-divisor n test-divisor) (define (next x) (if (= x 2) 3 (+ x 2))) (cond ((&gt; (square test-divisor) n) n) ((divisible? n test-divisor) test-divisor) (else (find-divisor n (next test-divisor))))) (define (prime? x) (= (smallest-divisor x) x)) (define (inc x) (+ x 1)) (define (identity x) x) </code></pre> <p>Recursive:</p> <pre><code>(define (filtered-accumulate combiner filter null-value term a next b) (if (&gt; a b) null-value (combiner (if (filter a) (term a) null-value) (filtered-accumulate combiner filter null-value term (next a) next b) ))) </code></pre> <p>Iterative:</p> <pre><code>(define (i-filtered-accumulate combiner filter null-value term a next b) (define (iter a result) (if (&gt; a b) result (iter (next a) (combiner result (if (filter a) (term a) null-value))))) (iter a null-value)) </code></pre> <p>Sum of primes between <code>a</code> and <code>b</code>:</p> <pre><code>(define (sum-of-primes-between a b) (filtered-accumulate + prime? 0 identity a inc b)) </code></pre> <p>Product of relative primes less than <code>n</code>:</p> <pre><code>(define (product-of-relative-primes-less-than n) (define (relprime-n i) (= (gcd i n) 1)) (filtered-accumulate * relprime-n 1 identity 1 inc n)) </code></pre> <p>What do you think?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T00:26:22.550", "Id": "2766", "Score": "0", "body": "idk if you consider it contrary to this exercises purpose, or maybe efficiency is it a premium, but you might consider just writing a standalone `filter` function and composing them. `filter` is a worthwhile function in its own write" } ]
[ { "body": "<p>Since you're recursing only on <code>a</code> and possibly <code>result</code>, you can use an inner <code>define</code> that only changes these arguments.</p>\n\n<p>When an item matches a filter condition, you can ignore it by recursing on the remaining items. You need not give it a <code>null-value</code> result. Putting these ideas together, we get:</p>\n\n<pre><code>(define (filtered-accumulate combiner filter? null-value term a next b)\n (define (rec a)\n (cond\n ((&gt; a b) null-value)\n ((filter? a) (combiner (term a) (rec (next a))))\n (else (rec (next a)))))\n (rec a))\n\n(define (i-filtered-accumulate combiner filter? null-value term a next b)\n (define (iter a result)\n (if (&gt; a b)\n result\n (iter (next a) (if (filter? a) (combiner (term a) result) result))))\n (iter a null-value))\n</code></pre>\n\n<p>The problem asks for a sum of square of primes, like so (note the negated filter):</p>\n\n<pre><code>(define (sum-of-square-of-primes-between a b)\n (i-filtered-accumulate + prime? 0 square a inc b))\n</code></pre>\n\n<p>You can check for relative primes starting with 2:</p>\n\n<pre><code>(define (product-of-relative-primes-less-than n)\n (define (relative-prime-n? i) (= (gcd i n) 1))\n (i-filtered-accumulate * relative-prime-n? 1 identity 2 inc n))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T00:23:20.460", "Id": "2765", "Score": "0", "body": "Adeel - that is not how filters typically work. generally those terms for which the filter function is TRUE are the ones that stay. those that make the function false are filtered out. http://docs.python.org/library/functions.html#filter http://zvon.org/other/haskell/Outputprelude/filter_f.html" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T01:46:49.130", "Id": "2768", "Score": "0", "body": "@jon_darkstar: I stand corrected." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T19:57:11.187", "Id": "1590", "ParentId": "1541", "Score": "1" } }, { "body": "<p>There are a few ways to address this</p>\n\n<ol>\n<li><p>Write a <code>filter-accumulate</code> function like you are working on</p></li>\n<li><p>Have seperate <code>filter</code> and <code>accumulate</code> functions and compose them (<code>filter</code> first)</p></li>\n<li><p>Just use <code>accumulate</code> and work the filtering into your <code>combine</code> function (treat term like identity element when conditions not met). Consider 'automating' this with a function that takes <code>filter</code> and <code>combine</code> functions and puts them together.</p></li>\n</ol>\n\n<p>example of third method for (a)</p>\n\n<pre><code>(accumulate (lambda (x y) (if (prime? b)\n (a)\n (+ a (square b))))\n (range A B)\n 0)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T00:38:13.710", "Id": "1593", "ParentId": "1541", "Score": "1" } }, { "body": "<p>'Accumulate' is usually called 'foldl'. So, your function is just</p>\n\n<pre><code>foldl f v $ filter g xs\n</code></pre>\n\n<p>in Haskell. Also, your algorithm is quite inefficent. If I was to find prime numbers, I would sieve them with prime divisors below the square root of current number. Here is an example:</p>\n\n<pre><code>primes = (2 :) $ flip filter [3..] $ \\n -&gt; flip all (flip takeWhile primes $ \\i -&gt; i * i &lt;= n) $ \\x -&gt; n `mod` x /= 0\n\nmain = print $ take 10 $ primes\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>[2,3,5,7,11,13,17,19,23,29]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-15T16:10:37.130", "Id": "1912", "ParentId": "1541", "Score": "-1" } } ]
{ "AcceptedAnswerId": "1590", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-30T05:07:05.873", "Id": "1541", "Score": "1", "Tags": [ "primes", "lisp", "scheme", "sicp" ], "Title": "Filtered-Accumulate" }
1541
<p>Some days ago I made you a question and I got some really useful answers. I will make a summary to those of you who didn't read and I will explain my new doubts and where I have problems now.</p> <p><strong>Explanation</strong></p> <p>I have been working on a program, simulating a small database, that first of all read information from txt files and store them in the computer memory and then, I can make queries taking normal tables and/or transposed tables. The problem is that the performance is not good enough yet. It works slower than what I expect. I have improved it but I think I should improve it more. I have specific points where my program doesn't have a good performance.</p> <p><strong>Current problem</strong></p> <p>The first problem that I have now (where my program is slower) is that I spend more time to, for example table with 100,000 columns &amp; 100 rows (0.325 min, I've improved this thanks to your help) than 100,000 rows &amp; 100 columns (1.61198 min, the same than before). But on the other hand, access time to some data is better in the second case (in a determined example, 47 seconds vs. 6079 seconds in the first case) any idea why??</p> <p><strong>Explanation</strong></p> <p>Now let me remind you how my code works (with an atached summary of my code)</p> <p>First of all I have a .txt file simulating a database table with random strings separated with "|". Here you have an example of table (with 7 rows and 5 columns). I also have the transposed table</p> <p><em><strong>NormalTable.txt</em></strong></p> <pre><code>42sKuG^uM|24465\lHXP|2996fQo\kN|293cvByiV|14772cjZ`SN| 28704HxDYjzC|6869xXj\nIe|27530EymcTU|9041ByZM]I|24371fZKbNk| 24085cLKeIW|16945TuuU\Nc|16542M[Uz\|13978qMdbyF|6271ait^h| 13291_rBZS|4032aFqa|13967r^\\`T|27754k]dOTdh|24947]v_uzg| 1656nn_FQf|4042OAegZq|24022nIGz|4735Syi]\|18128klBfynQ| 6618t\SjC|20601S\EEp|11009FqZN|20486rYVPR|7449SqGC| 14799yNvcl|23623MTetGw|6192n]YU\Qe|20329QzNZO_|23845byiP| </code></pre> <p><em><strong>TransposedTable.txt</em></strong> (This is new from the previous post)</p> <pre><code>42sKuG^uM|28704HxDYjzC|24085cLKeIW|13291_rBZS|1656nn_FQf|6618t\SjC|14799yNvcl| 24465\lHXP|6869xXj\nIe|16945TuuU\Nc|4032aFqa|4042OAegZq|20601S\EEp|23623MTetGw| 2996fQo\kN|27530EymcTU|16542M[Uz\|13967r^\\`T|24022nIGz|11009FqZN|6192n]YU\Qe| 293cvByiV|9041ByZM]I|13978qMdbyF|27754k]dOTdh|4735Syi]\|20486rYVPR|20329QzNZO_| 14772cjZ`SN|24371fZKbNk|6271ait^h|24947]v_uzg|18128klBfynQ|7449SqGC|23845byiP| </code></pre> <p><strong>Explanation</strong></p> <p>This information in a .txt file is read by my program and stored in the computer memory. Then, when making queries, I will access to this information stored in the computer memory. Loading the data in the computer memory can be a slow process, but accessing to the data later will be faster, what really matters me. </p> <p>Here you have the part of the code that read this information from a file and store in the computer.</p> <p><em><strong>Code that reads data from the Table.txt file and store it in the computer memory</em></strong></p> <pre><code>int h; do { cout&lt;&lt; "Do you want to query the normal table or the transposed table? (1- Normal table/ 2- Transposed table):" ; cin&gt;&gt;h; }while(h!=1 &amp;&amp; h!=2); string ruta_base("C:\\Users\\Raul Velez\\Desktop\\Tables\\"); if(h==1) { ruta_base +="NormalTable.txt"; // Folder where my "Table.txt" is found } if(h==2) { ruta_base +="TransposedTable.txt"; } string temp; // Variable where every row from the Table.txt file will be firstly stored vector&lt;string&gt; buffer; // Variable where every different row will be stored after separating the different elements by tokens. vector&lt;ElementSet&gt; RowsCols; // Variable with a class that I have created, that simulated a vector and every vector element is a row of my table ifstream ifs(ruta_base.c_str()); while(getline( ifs, temp )) // We will read and store line per line until the end of the ".txt" file. { size_t tokenPosition = temp.find("|"); // When we find the simbol "|" we will identify different element. So we separate the string temp into tokens that will be stored in vector&lt;string&gt; buffer // --- NEW PART ------------------------------------ const char* p = temp.c_str(); char* p1 = strdup(p); char* pch = strtok(p1, "|"); while(pch) { buffer.push_back(string(pch)); pch = strtok(NULL,"|"); } free(p1); ElementSet sss(0,buffer); buffer.clear(); RowsCols.push_back(sss); // We store all the elements of every row (stores as vector&lt;string&gt; buffer) in a different position in "RowsCols" // --- NEW PART END ------------------------------------ } Table TablesStorage(RowsCols); // After every loop we will store the information about every .txt file in the vector&lt;Table&gt; TablesDescriptor vector&lt;Table&gt; TablesDescriptor; TablesDescriptor.push_back(TablesStorage); // In the vector&lt;Table&gt; TablesDescriptor will be stores all the different tables with all its information DataBase database(1, TablesDescriptor); </code></pre> <p><strong>Information already given in the previous post</strong></p> <p>After this, comes the access to the information part. Let's suppose that I want to make a query, and I ask for input. Let's say that my query is row "n", and also the consecutive tuples "numTuples", and the columns "y". (We must say that the number of columns is defined by a decimal number "y", that will be transformed into binary and will show us the columns to be queried, for example, if I ask for columns 54 (00110110 in binary) I will ask for columns 2, 3, 5 and 6). Then I access to the computer memory to the required information and store it in a vector shownVector. Here I show you the part of this code.</p> <p><strong>Problem</strong> In the loop <em>if(h == 2)</em> where data from the transposed tables are accessed, performance is poorer ¿why?</p> <p><em><strong>Code that access to the required information upon my input</em></strong></p> <pre><code>int n, numTuples; unsigned long long int y; cout&lt;&lt; "Write the ID of the row you want to get more information: " ; cin&gt;&gt;n; // We get the row to be represented -&gt; "n" cout&lt;&lt; "Write the number of followed tuples to be queried: " ; cin&gt;&gt;numTuples; // We get the number of followed tuples to be queried-&gt; "numTuples" cout&lt;&lt;"Write the ID of the 'columns' you want to get more information: "; cin&gt;&gt;y; // We get the "columns" to be represented ' "y" unsigned int r; // Auxiliar variable for the columns path int t=0; // Auxiliar variable for the tuples path int idTable; vector&lt;int&gt; columnsToBeQueried; // Here we will store the columns to be queried get from the bitset&lt;500&gt; binarynumber, after comparing with a mask vector&lt;string&gt; shownVector; // Vector to store the final information from the query bitset&lt;5000&gt; mask; mask=0x1; clock_t t1, t2; t1=clock(); // Start of the query time bitset&lt;5000&gt; binaryNumber = Utilities().getDecToBin(y); // We get the columns -&gt; change number from decimal to binary. Max number of columns: 5000 // We see which columns will be queried for(r=0;r&lt;binaryNumber.size();r++) // { if(binaryNumber.test(r) &amp; mask.test(r)) // if both of them are bit "1" { columnsToBeQueried.push_back(r); } mask=mask&lt;&lt;1; } do { for(int z=0;z&lt;columnsToBeQueried.size();z++) { ElementSet selectedElementSet; int i; i=columnsToBeQueried.at(z); Table&amp; selectedTable = database.getPointer().at(0); // It simmulates a vector with pointers to different tables that compose the database, but our example database only have one table, so don't worry ElementSet selectedElementSet; if(h == 1) { selectedElementSet=selectedTable.getRowsCols().at(n); shownVector.push_back(selectedElementSet.getElements().at(i)); // We save in the vector shownVector the element "i" of the row "n" } if(h == 2) { selectedElementSet=selectedTable.getRowsCols().at(i); shownVector.push_back(selectedElementSet.getElements().at(n)); // We save in the vector shownVector the element "n" of the row "i" } n=n+1; t++; } }while(t&lt;numTuples); t2=clock(); // End of the query time showVector().finalVector(shownVector); float diff ((float)t2-(float)t1); float microseconds = diff / CLOCKS_PER_SEC*1000000; cout&lt;&lt;"Time: "&lt;&lt;microseconds&lt;&lt;endl; </code></pre> <p><em><strong>Class definitions</strong></em></p> <p>Here I attached some of the class definitions so that you can compile the code, and understand better how it works:</p> <pre><code>class ElementSet { private: int id; vector&lt;string&gt; elements; public: ElementSet(); ElementSet(int, vector&lt;string&gt;); const int&amp; getId(); void setId(int); const vector&lt;string&gt;&amp; getElements(); void setElements(vector&lt;string&gt;); }; class Table { private: vector&lt;ElementSet&gt; RowsCols; public: Table(); Table(vector&lt;ElementSet&gt;); const vector&lt;ElementSet&gt;&amp; getRowsCols(); void setRowsCols(vector&lt;ElementSet&gt;); }; class DataBase { private: int id; vector&lt;Table&gt; pointer; public: DataBase(); DataBase(int, vector&lt;Table&gt;); const int&amp; getId(); void setId(int); const vector&lt;Table&gt;&amp; getPointer(); void setPointer(vector&lt;Table&gt;); }; class Utilities { public: Utilities(); static bitset&lt;500&gt; getDecToBin(unsigned long long int); }; </code></pre> <p><strong>Summary of my problems</strong></p> <ul> <li>Why the load of the data is different depending on the table format???</li> <li>Why the access to the information also depends on the table (and the performance is in the opposite way than the table data load?</li> </ul>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T12:23:00.473", "Id": "2971", "Score": "1", "body": "It does not sound like a codereview question." } ]
[ { "body": "<p>If you want to optimize your code, I would first suggest you to profile your code (some for windows can be found here : <a href=\"https://stackoverflow.com/questions/67554/whats-the-best-free-c-profiler-for-windows-if-there-are\">https://stackoverflow.com/questions/67554/whats-the-best-free-c-profiler-for-windows-if-there-are</a>). </p>\n\n<p>Programmer are usualy very poor at finding bottleneck in code and profiler will help you to find where 20% of your code run 80% of the time.</p>\n\n<p>Then with thoses information, we will be able to give you a better kind of help.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T22:00:06.937", "Id": "1832", "ParentId": "1556", "Score": "3" } }, { "body": "<p>First of all before optimization you must to correct some lines such as:</p>\n\n<pre><code>for(int z=0;z&lt;columnsToBeQueried.size();z++)\n</code></pre>\n\n<p>You must write something as:</p>\n\n<pre><code>/*int size = columnsToBeQueried.size(); \nfor(int z=0;z&lt;size;z++)*/\n</code></pre>\n\n<p>because as I think that is count every time the size of the columnsToBeQueried and the same</p>\n\n<pre><code>binaryNumber.size()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-18T21:26:27.410", "Id": "1961", "ParentId": "1556", "Score": "1" } }, { "body": "<p>Do you really ask why transpose table operation takes different time or do you ask for improving performance?</p>\n\n<p>Both questions are related in this case and i'll try to answer them.</p>\n\n<p>Consider this:</p>\n\n<pre><code>selectedElementSet=selectedTable.getRowsCols().at(n);\n</code></pre>\n\n<p>What is going on under the cover? The vector is copied. That means all strings in vector are copied. In transposed table there 100 000 strings and in normal one there is 100. What to do to improve perfomance? </p>\n\n<pre><code>const ElementSet&amp; selectedElementSet=selectedTable.getRowsCols().at(n);\n</code></pre>\n\n<p>As simple as that. No more copies. </p>\n\n<p>After making this change i highly recommend to read more on C++ and stl library. You'll better understand how it works and would be able to eliminate more \"under the cover\" problems with your code.</p>\n\n<p>And, of course, profiler is your best friend with performance issues.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T10:36:25.990", "Id": "18594", "ParentId": "1556", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-30T16:00:50.470", "Id": "1556", "Score": "2", "Tags": [ "c++", "optimization" ], "Title": "Optimizing my code that simulates a database" }
1556
<p>I'm working with the following code which adjusts an int based on multiple elements of an integer array. I am wondering if there's a cleaner, easier-to-read construct for this:</p> <pre><code>int Blue = 0; int[] Adjustments = new int[24]; // ... populate Adjustments if (Adjustments[0] == 255) Blue = 128; else if (Adjustments[0] == 0) Blue = 0; if (Adjustments[1] == 255) Blue += 64; else if (Adjustments[1] == 0) Blue += 0; if (Adjustments[2] == 255) Blue += 32; else if (Adjustments[2] == 0) Blue += 0; if (Adjustments[3] == 255) Blue += 16; else if (Adjustments[3] == 0) Blue += 0; if (Adjustments[4] == 255) Blue += 8; else if (Adjustments[4] == 0) Blue += 0; if (Adjustments[5] == 255) Blue += 4; else if (Adjustments[5] == 0) Blue += 0; if (Adjustments[6] == 255) Blue += 2; else if (Adjustments[6] == 0) Blue += 0; if (Adjustments[7] == 255) Blue += 1; else if (Adjustments[7] == 0) Blue += 0; </code></pre> <p>Any suggestions? <hr> <strong>Edit</strong></p> <p>Here is the revised version based on suggestions provided:</p> <pre><code>Blue = 0; Green = 0; Red = 0; int[] Adjustments = new int[24]; // ... populate Adjustments int[] AdjustmentStops = new[] { 128, 64, 32, 16, 8, 4, 2, 1 }; for (int i = 0; i &lt; 8; i++) { Blue += Adjustments[i] == 255 ? AdjustmentStops[i] : 0; Green += Adjustments[i + 8] == 255 ? AdjustmentStops[i] : 0; Red += Adjustments[i + 12] == 255 ? AdjustmentStops[i] : 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T16:45:00.760", "Id": "2915", "Score": "1", "body": "You could just write `1 << (7-i)` instead of `AdjustmentStops[i]` and get rid of the array, but it’s up to you to decide whether you find that too unreadable." } ]
[ { "body": "<p>How about the following?</p>\n\n<pre><code>int Blue = 0;\nint[] Adjustments = new int[ 24 ];\nint[] BlueAdditions = new int[] { 128, 64, 32, 16, 8, 4, 2, 1 };\n// ... populate Adjustments\n\nfor ( int i = 0; i &lt; 8; ++i )\n{\n if ( Adjustments[ i ] == 255 )\n {\n Blue += BlueAdditions[ i ];\n }\n}\n</code></pre>\n\n<p>Why do you do <code>Blue += 0</code>? That's pretty pointless, so I removed those.</p>\n\n<p>Furthermore, why is Adjustments 24 items long? I'm guessing you use the other items at a later moment, if you don't, you can remove the magic number <code>8</code> and change it to <code>Adjustments.Length</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T18:04:19.600", "Id": "2723", "Score": "0", "body": "This code is something I inherited; I suspect at one time the `+= 0` parts had a different amount and have never been omitted. Your idea of an array holding the adjustment stops is great." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T18:05:32.173", "Id": "2724", "Score": "0", "body": "Adjustments is 24 elements because there are also red and green values adjusted later, but I only included that which I think got the point across. :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T18:10:45.067", "Id": "2725", "Score": "0", "body": "@JYelton: In that case I would opt to encapsulate this code with an adjustments array of 8 long, and run it for red, green and blue separatly." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T17:52:19.083", "Id": "1559", "ParentId": "1557", "Score": "2" } }, { "body": "<p>At the risk of being 'clever':</p>\n\n<pre><code>int Blue = 0;\nint[] Adjustments = new int[24];\n// ... populate Adjustments \n\nfor (int blueIndex=0; blueIndex&lt;8; blueIndex++)\n{\n if (Adjustments[blueIndex] == 255)\n {\n Blue |= (1 &lt;&lt; (7 - blueIndex));\n }\n}\n</code></pre>\n\n<p>Since in effect you're setting bits anyway I think using bitwise operations is idiomatic here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T19:42:04.290", "Id": "2726", "Score": "0", "body": "I was curious about a way that implemented the bit position somehow, this does just that." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T22:20:21.320", "Id": "2731", "Score": "1", "body": "but you want bitwise OR dont you? `|=`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T23:23:38.840", "Id": "2735", "Score": "0", "body": "@jon_darkstar: You're right :) Edited." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T00:43:24.347", "Id": "2738", "Score": "0", "body": "you want these 1's AND those 1's, so why shouldn't it work? =P" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T01:45:37.313", "Id": "2740", "Score": "1", "body": "@jon_darkstar - Bitwise `AND` doesn't have the same meaning as \"and\" in English. Bitwise AND says, \"make the result true if both inputs are true,\" while in English it means \"both statements are true\". For example, \"He gave me the apples and oranges\" means that you received the apples and the oranges while \"He gave me the apples `AND` oranges\" means you received nothing because nothing is both an apple and an orange, barring genetic hybrids." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T02:23:41.577", "Id": "2742", "Score": "0", "body": "was only joking dave. give me a LITTLE credit" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T21:11:43.537", "Id": "2760", "Score": "1", "body": "While I like this solution, I opted for Steven Jeuris' because if (for some reason) the values change it will be easier to modify. Awesome work though." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T19:04:27.647", "Id": "1560", "ParentId": "1557", "Score": "7" } }, { "body": "<pre><code>Blue = 0; Red = 0; Green = 0;\nfor(int i = 0; i &lt; 8; i++)\n{\n Blue |= (Adjustments[i] / 255) * (1 &lt;&lt; (i-7));\n Red |= (Adjustments[i+8] / 255) * (1 &lt;&lt; (i-7));\n Green |= (Adjustments[i+16] / 255) * (1 &lt;&lt; (i-7));\n}\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>Blue = 0; Red = 0; Green = 0;\na = 1;\nfor(int i = 7; i &gt;= 0; i--)\n{\n Blue |= (Adjustments[i] / 255) * a;\n Red |= (Adjustments[i+8] / 255) * a;\n Green |= (Adjustments[i+16] / 255) * a;\n a = a &lt;&lt; 1;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T02:24:55.553", "Id": "2743", "Score": "0", "body": "bet theres a nice way to do this with slices and reduce (or is it aggregate in c#/LINQ)? ill poke around a little and see if i can figure it out" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T22:11:04.930", "Id": "1563", "ParentId": "1557", "Score": "2" } }, { "body": "<p>Although perhaps less efficient, any time I see an array being used as a half-assed object, I'm inclined to make an object.</p>\n\n<pre><code>struct ColorAdjustment {\n public int Red;\n public int Blue;\n public int Green; \n}\n</code></pre>\n\n<p>Then make an array of 8 of those.</p>\n\n<p>But since you're only checking two values (255 or 0) a set of bools would be even better.\nBut since you're just doing bit math, @jon_darkstar's answer is even better still because it just does that math directly.</p>\n\n<p>But best of all would probably be to use a BitArray or to do bit boolean logic on a 24-bit value (or an Int32, if you don't mind wasted space) to indicate the state of adjustments, as:</p>\n\n<pre><code>Int24 adjustments = 0xBEAF;\nfor(int i = 0; i &lt; 8; i++) {\n if((adjustments &amp;&amp; (1 &lt;&lt; i)) != 0)\n ...do blue stuff...\n if((adjustments &amp;&amp; (1 &lt;&lt; (i + 8))) != 0)\n ...do red stuff...\n...\n</code></pre>\n\n<p>Edit:\nHah, and I just realized I ran the full gamut from clear, object based code to fiddly bit-based code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T22:33:34.670", "Id": "1618", "ParentId": "1557", "Score": "-1" } } ]
{ "AcceptedAnswerId": "1559", "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T16:22:16.147", "Id": "1557", "Score": "5", "Tags": [ "c#", "array", "integer" ], "Title": "Adjusting integer based on multiple elements in int array" }
1557
<p>I have a simplified model that looks like this:</p> <pre><code>class Player &lt; ActiveRecord::Base has_many :picks def pick_for_game(game) id = game.instance_of?(Game) ? game.id : game pick = picks.find {|pick| pick.game_id == id} if !pick pick = picks.build(:game_id =&gt; id) end pick end end </code></pre> <p>The <code>pick_for_game</code> method usually is called a bunch of times when an action is executed. What would be a good way to make this code work efficiently with a list of games?</p>
[]
[ { "body": "<p>You can use <code>find_or_initialize_by</code> dynamic finder, see a guide <a href=\"http://edgeguides.rubyonrails.org/active_record_querying.html#dynamic-finders\" rel=\"noreferrer\">here</a></p>\n\n<p>This would be equivalent to your code:</p>\n\n<pre><code>def pick_for_game(game)\n game_id = game.instance_of?(Game) ? game.id : game\n picks.find_or_initialize_by_game_id(game_id)\nend\n</code></pre>\n\n<p>Hope it helps you!.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T14:21:38.617", "Id": "2749", "Score": "1", "body": "This is why I love ruby and rails. You can write such elegant and simple code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-30T20:41:09.987", "Id": "1561", "ParentId": "1558", "Score": "7" } }, { "body": "<p>Expanding on @jpemberthy: Shouldn't we duck type?</p>\n\n<pre><code>def pick_for_game(game)\n game = game.id if game.respond_to? :id\n picks.find_or_initialize_by_game_id(game)\nend\n</code></pre>\n\n<p>or be brazen:</p>\n\n<pre><code>def pick_for_game(game)\n picks.find_or_initialize_by_game_id(begin game.id rescue game end)\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T19:52:20.187", "Id": "226520", "ParentId": "1558", "Score": "3" } } ]
{ "AcceptedAnswerId": "1561", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-03-30T17:51:04.763", "Id": "1558", "Score": "6", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Find associated object if exists, otherwise generate it" }
1558
<p>This function will read an expression (made up of tokens) from the vector of tokens passed into it. It will remove the tokens that make up the expression from the vector and return them.</p> <p>A token is added to the expression if</p> <ul> <li>it is the first token</li> <li>it has an operator before it</li> </ul> <p>Brackets are handled in parseBracketTokens (which calls this function)</p> <pre><code>RawExpression *parseExpressionTokens( vector&lt;Token*&gt; &amp;tokens, bool brackets = false) { // This is a vector of elements that make up an expression vector&lt;RawExpressionElement*&gt; elements; while(tokens.size() &gt; 0) { // Operands must be at the start of an expression or after an operator if(tokenIsOperand(tokens[0])) { if(elements.size() == 0 || eElementIsRelationalOperator(elements.back())) { elements.push_back(makeEElementFromToken(tokens[0])); removeToken(tokens, 0); continue; } // This token is part of the next expression, break from the loop break; } if(tokenIsRelationalOperator(tokens[0])) { // Make sure we have an operand left of it if(tokens[0]-&gt;type == TOKEN_MINUS) { if(elements.size() == 0 || !eElementIsOperand(elements.back())) { // handle the minus number or symbol :O } } if(elements.size() != 0 &amp;&amp; eElementIsOperand(elements.back())) { elements.push_back(makeEElementFromToken(tokens[0])); removeToken(tokens, 0); continue; } throw(string("Operator has bad lhand:") + tokenToString(tokens[0])); } // A closing bracket marks the end of an expression if(tokens[0]-&gt;type == TOKEN_CLOSEBRACKET) { if(!brackets) throw(string("Unmatched closing bracket")); break; } // Handle brackets and function calls if(tokens[0]-&gt;type == TOKEN_OPENBRACKET) { // Check if it follows an identifier (if so, its a function call) if(elements.size() != 0 &amp;&amp; elements.back()-&gt;e_type == REE_IDENTIFIER) { RawExpression *e = parseBracketTokens(tokens); string id = ((IdentifierREElement*)elements.back())-&gt;id; removeExpressionElement(elements, elements.size()-1); elements.push_back(new FunctionCallREElement(id, e)); continue; } // This is not a function call if(elements.size() == 0 || !eElementIsOperand(elements.back())) { RawExpression *e = parseBracketTokens(tokens); elements.push_back(e); continue; } // This is part of another expression break; } // Parse Identifiers if(tokens[0]-&gt;type == TOKEN_IDENTIFIER) { elements.push_back(makeEElementFromToken(tokens[0])); removeToken(tokens, 0); continue; } // Unknown token, throw an error throw(string("Unexpected token in expression:") + tokenToString(tokens[0])); } // Make sure expression doesn't end with an operator. if(elements.size() &gt; 0 &amp;&amp; !eElementIsOperand(elements.back())) throw(string("Operator missing rhand value")); return new RawExpression(elements); } </code></pre> <p>I would like to split this code up into something like </p> <pre><code>if(processOperand(tokens)) continue; if(processRelationalOperator(tokens)) continue; if(precessBracket(tokens)) continue; if(processIdentifier(tokens)) continue; </code></pre> <p>But the fact that it has to <code>continue</code> or <code>break</code> in some cases leaves me questioning the best was to approach this.</p> <p>I think I might have to define a new type something like <code>{ NOT_RELEVANT, PART_OF_EXPRESSION, END_OF_EXPRESSION }</code></p> <p>and then do this</p> <pre><code>ExpressionElement *e; // Use this an out ptr in the function call below result = processOperand(tokens, e); if(result == END_OF_EXPRESSION) break; else if(result == PART_OF_EXPRESSION) addItToExpression(e); // else its NOT_RELAVANT so try parsing the next type </code></pre> <p>But it seems like a bad idea to define a new type for this.</p> <p>What do you think?</p>
[]
[ { "body": "<p>My first thought is that parsers should be implemented as table driven state machines for exactly the reason you see in the code :-)</p>\n\n<p>Actually, I think breaking this into a set of separate functions is one good approach, and adding a new enum to support it makes it very clear the state of the expression after each step.</p>\n\n<p>Another option I would consider is determining the paths through the code and possibly doing some optimizations around them at the expense of clarity. There appear to be several places where once you first entered a conditional block, you have committed to not doing any other code in the loop. Re-arranging these may eliminate some of the separate continue/break statements and allow easier refactoring.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T12:37:00.220", "Id": "1604", "ParentId": "1564", "Score": "8" } }, { "body": "<p>About refactoring this concrete routine (not algorithm itself):</p>\n\n<ul>\n<li>Replace <code>elements.size() == 0</code> by <code>elements.empty()</code>; it is faster.</li>\n<li>Replace whole <code>while</code> cycle with <code>for_each</code></li>\n<li>Normalize tokens identification ( now some tokens are identified by separate routines, but some are identified via <code>if(type == blabl)</code> )</li>\n<li><p>Move logic after each token identifying <code>if</code> to separate routines:</p>\n\n<pre><code>class TokenToElements{\n typedef vector&lt;RawExpressionElement *&gt; el_vec_t;\n el_vec_t &amp;elements;\npublic:\n TokenToElements( el_vec_t &amp;e ):elements( e ){};\n\n enum TokenType{\n TK_OPERAND,\n TK_REL_OP,\n TK_CLOSEBRACKET,\n TK_OPENBRACKET,\n TK_IDENTIFIER,\n TK_UNKNOWN\n };\n\n TokenType get_token_type( Token *token ){\n if ( tokenIsOperand( token ) ) return TK_OPERAND;\n if ( tokenIsRelationOperator( token ) ) return TK_REL_OP;\n if ( token-&gt;type == TOKEN_CLOSEBRACKET ) return TK_CLOSEBRACKET;\n if ( token-&gt;type == TOKEN_OPENBRACKET ) return TK_OPENBRACKET;\n if ( token-&gt;type == TOKEN_IDENTIFIER ) return TK_IDENTIFIER;\n return TK_UNKNOWN;\n };\n\n void do_operand( Token *token ){ ... };\n void do_relation_operator( Token *token ){ ... };\n void do_closebraket( Token *token ){ ... };\n void do_openbraket( Token *token ){ ... };\n void do_identifier( Token *token ){ ... };\n\n void opearator()( Token *token ){\n switch( get_token_type( token ) ){\n case TK_OPERAND:\n do_operand( token );\n break;\n case TK_REL_OP:\n do_relation_operator( token );\n break;\n case TK_CLOSEBRACKET:\n do_closebraket( token );\n break;\n case TK_OPENBRACKET:\n do_openbraket( token );\n break;\n case TK_IDENTIFIER:\n do_identifier( token );\n break;\n default:\n throw std::runtime_error( \"Unexpected token in expression:\" + tokenToString( token ) );\n };\n };\n};\n\nRawExpression *parseExpressionTokens(\n vector&lt;Token*&gt; &amp;tokens, bool brackets = false) {\n\n // This is a vector of elements that make up an expression\n vector&lt;RawExpressionElement*&gt; elements;\n\n std::for_each( tokens.begin(), tokens.end(), TokenToElements( elements ) );\n};\n</code></pre>\n\n<p>Another solution is return pointer to callback function from <code>get_token_type</code> and call it instead of <code>switch</code>. Code of <code>TokenToElement::operator()</code> will be even shorter:</p>\n\n<pre><code>typedef void (TokenToElement::*hndl_fun_t)( Token *);\n\nvoid operator()( Token * token ){\n hndl_fun_t hndl = get_token_handler( token )\n (this-&gt;*hdnl)( token );\n};\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T11:44:23.990", "Id": "3173", "Score": "0", "body": "This wont work. I need to know if the next token is part of the current expression. If it is not I need to leave the loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-15T08:00:25.840", "Id": "3189", "Score": "1", "body": "you have 'elements' array in every of your routines in 'TokenToElements' functor :) so your logic from *monster function* can be copied without problems." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T11:34:49.507", "Id": "1879", "ParentId": "1564", "Score": "6" } } ]
{ "AcceptedAnswerId": "1604", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-30T23:01:48.203", "Id": "1564", "Score": "9", "Tags": [ "c++" ], "Title": "Monster token parser function" }
1564
<p>I'm a little unsure as to what code belongs in the services and what belongs in the controllers.</p> <p>Lets say I'm creating a website that requires a fine grained level of permissions (e.g. a user has permissions based on their user level (if they're currently logged in) determining whether they can view, edit, add entities and each entity has it's own set of requirements).</p> <p>The process is pretty much the same for all entities:</p> <ul> <li>Get the current user, either a registered one or an anonymous one</li> <li>Get the requested entity <ul> <li>Check that it is not null</li> <li>Check it isn't locked by the system</li> </ul></li> <li>Check that the user has permissions to view/edit on the entity, as well as all parent entities</li> </ul> <p>So, what should go where? </p> <p>Right now, my controller makes a call to the service to get the entity and passes in the user (or null for anonymous).</p> <p>The service makes a call to the repository which gets the entity by the id. Then it makes sure that the user has permission to view it. The code is basically:</p> <pre><code>// Controller public ActionResult Get(int id) { string error; var entity = EntityService.Get(id, GetUser(), out error); if(entity == null) // Display error else // Display entity } // Service public Entity Get(int id, User user, out string error) { var entity = Repository.Get(id); // null check // permissions check // if it passes, return the entity, otherwise assign error and return null } </code></pre> <p>I don't really like this way of doing it because if I need to do something like redirect the user or display a custom view, I can't just return an error string, I need an enum or something to tell me exactly why the <code>Get</code> failed so I can handle the case properly. Plus (and I'm not sure if this is actually considered a bad thing) whatever is going on in the services method is hidden from the controller.</p> <p>Any suggestions on a better design?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T14:47:42.217", "Id": "8630", "Score": "0", "body": "Clarifying question: are these WCF services or Web/ASMX services? Are they also written in C# or are they in another language?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T15:34:51.113", "Id": "8631", "Score": "0", "body": "Sorry, my terminology is probably incorrect. When I say services project, I mean a project that implements the service layer of an application. It's just a C# class library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T17:17:45.977", "Id": "8634", "Score": "0", "body": "Makes sense. I agree, services is an overloaded word in programming." } ]
[ { "body": "<p>My first instinct is to suggest using built-in ASP.NET Roles. This is handled at the ASP.NET level, so in general you can redirect to the appropriate View. You may have roles for 'Anon' 'Read' and 'ReadWrite' and possibly more. This will help with the first pass authorization, not at the specific database record level, but at a high level based on user type, aka role. However, its not required and the per record, per user access will work just as well.</p>\n\n<p>If you have specific access requirements on a 'per record, per user' basis, you have a couple options.</p>\n\n<p><strong>A)</strong> Do what you're doing now, pass the User object to the Services layer, and let the services sort it out and return an appropriate error code. In this case, the service probably selects all of the data required to service the request, so if you expect a high level of authorization failures, this is probably not ideal because you'll waste a lot of database IO on requests that are going to fail. If in your list views, you arleady eliminate records the user doesn't have access to, and are your record level security is to prevent people from Uri snoopting (/Entity/Detail/#### for example) this might be sufficient.</p>\n\n<p><strong>B)</strong> Implement a method or two in your services layer which accepts a UserID and an EntityID. It then does the minimum database selection to determin if the UserID provided has access to the EntityID and it simply returns true/false. This is a good option if you expect that high number of requests for entities will fail authorization, since in the failed instances, you'll only select a few bits of data from the database and not the entire request; however, for requests that are permitted, you end up doing two selections. Only you can decide if this is worth it or not. But it does make the code a bit more simple:</p>\n\n<pre><code>if(! services.UserEntityAccess(userID, entityID))\n{\n return View(\"NoAccessView\");\n}\n\nreturn View(services.ReadEntity(entityID));\n</code></pre>\n\n<p><strong>C)</strong> Hybrid of A and B, when you initialize a new instance of your service layer, make sure that your User object is a parameter in the constructor of the service, then your service can is always operating from within the \"context\" of a specific user. This is probably the way I would go, and internally, you can decide which of option A or B works best, based mostly on how many failed authorizations you expect, the advantage here is that if you guess wrong, it's easy to change, because its handeled internally to the class, and you wont need to change any calling code.</p>\n\n<pre><code>public ActionResult Get(int id)\n{\n var svc = new ServicesLayer(GetUser());\n var entResponse = svc.GetEntity(id);\n\n if (entResponse.Error != null)\n { \n return View(\"ErrorView\",entResponse.Error);\n }\n\n return View(entResponse.Entity);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T17:36:44.780", "Id": "2784", "Score": "0", "body": "This is a great answer, thanks. I'm leaning towards Option C, but I'd like to see if anyone else has any other suggestions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T16:44:31.830", "Id": "1610", "ParentId": "1567", "Score": "1" } }, { "body": "<p>You can <em>probably</em> refactor a lot of the repetitive functionality to Action Filters. For example, when you are checking for permissions you could use an AuthorizationFilter, that checks for the permission before the Action event executes, and if it is not satisfied, a <code>RedirectToAction</code> is called. The reason I said probably, is because it depends on you being able to manage permissions on a controller action level instead of an individual entity level, and there wasn't enough information in your question to know this for sure. Refactoring these concerns to action filters that return redirect results will help you to determine the cause of failures (invalid, unauthorized, etc), because you will redirect the user to a different page depending on which condition failed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T06:00:12.260", "Id": "1632", "ParentId": "1567", "Score": "1" } }, { "body": "<p>Could be wrong but I'm thinking you are taking to issue the controller/service pattern in general, not just for Roles.\nFor all of my projects except the most trivial I end up with a Policy (basically bl) layer between the controller and the service. The controller action instantiates a policy class and executes it, inside the policy it calls services to get data etc... Dependency inject everything into your policy so you can mock those services. Your controllers end up very small which is the way I like them!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-04T16:36:05.587", "Id": "2891", "Score": "0", "body": "So the policy is responsible for filtering out the valid/invalid results by handling all the permissions check? Is its only purpose to keep that logic outside of the service class? That seems like a nice and clean idea. Thanks for the suggestion." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-04T20:02:34.630", "Id": "2892", "Score": "0", "body": "I always see these MVC patterns discussed where they have 1 model class that pulls data and they use it in their controller and bang we have a web page. In reality, lets say using a PRG pattern, creating timecards with state by state OT rules and approval chains, that simple model doesn't last a minute. In this application I have shared Policy (BL layer), individual policies that call the shared, and throw in a low level service layer, called by either shared or individual. It's essentially a 3 layer Model..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-04T16:32:34.750", "Id": "1643", "ParentId": "1567", "Score": "1" } } ]
{ "AcceptedAnswerId": "1643", "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T01:12:51.827", "Id": "1567", "Score": "4", "Tags": [ "asp.net-mvc-3", "vb.net" ], "Title": "Is this a proper use of a services project and an ASP.NET MVC controller?" }
1567
<p>Given the following exercise:</p> <blockquote> <p>Exercise 1.37. a. An infinite continued fraction is an expression of the form</p> <p><img src="https://i.stack.imgur.com/mrsXH.gif" alt="infinite continued fraction"></p> <p>As an example, one can show that the infinite continued fraction expansion with the Ni and the Di all equal to 1 produces 1/, where is the golden ratio (described in section 1.2.2). One way to approximate an infinite continued fraction is to truncate the expansion after a given number of terms. Such a truncation -- a so-called k-term finite continued fraction -- has the form</p> <p><img src="https://i.stack.imgur.com/4Zv6G.gif" alt="k term finite continued fraction"></p> <p>Suppose that n and d are procedures of one argument (the term index i) that return the Ni and Di of the terms of the continued fraction. Define a procedure cont-frac such that evaluating (cont-frac n d k) computes the value of the k-term finite continued fraction. Check your procedure by approximating 1/ using</p> <pre><code>(cont-frac (lambda (i) 1.0) (lambda (i) 1.0) k) </code></pre> <p>for successive values of k. How large must you make k in order to get an approximation that is accurate to 4 decimal places?</p> <p>b. If your cont-frac procedure generates a recursive process, write one that generates an iterative process. If it generates an iterative process, write one that generates a recursive process.</p> </blockquote> <p>I wrote the following two functions:</p> <p>Recursive:</p> <pre><code>(define (cont-frac n_i d_i k) (define (recurse n) (define (next n) (+ n 1)) (if (= n k) (/ (n_i k) (d_i k)) (/ (n_i n) (+ (d_i n) (recurse (next n)))))) (recurse 1)) </code></pre> <p>Iterative:</p> <pre><code>(define (i-cont-frac n_i d_i k) (define (iterate result n) (define (next n) (- n 1)) (if (= n 1) (/ (n_i n) result) (iterate (+ (d_i (next n)) (/ (n_i n) result)) (next n)))) (iterate (d_i k) k)) </code></pre> <p>What do you think of my solution?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T02:33:22.897", "Id": "2744", "Score": "0", "body": "this portion of the book - http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-12.html#%_sec_1.3.3" } ]
[ { "body": "<p>Your solutions look good. </p>\n\n<p>I don't see any significantly different way to do the recursive solution. My preferences for whitespace (mostly concerning the <code>if</code>) are a little different. Also, I wouldn't define a function for <code>next</code> in this situation. If for some reason you don't want to simply put <code>(+ n 1)</code> as an argument a <code>let</code> expression would be more applicable.</p>\n\n<pre><code>(define (cont-frac n_i d_i k)\n (define (recurse n)\n (if (= n k) \n (/ (n_i k) (d_i k)) \n (/ (n_i n) (+ (d_i n) (recurse (+ n 1)))) ))\n (recurse 1))\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>(define (cont-frac n_i d_i k)\n (define (recurse n)\n (if (= n k) \n (/ (n_i k) (d_i k)) \n (let ((next_n (+ n 1)))\n (/ (n_i n) (+ (d_i n) (recurse next_n)))) ))\n (recurse 1))\n</code></pre>\n\n<p>PS - write a function for the <code>nth_odd_square</code> and try this</p>\n\n<pre><code>(/ 4.0 (+ 1 (i-cont-frac nth_odd_square (lambda (i) 2.0) 500000)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T05:33:35.393", "Id": "1571", "ParentId": "1568", "Score": "1" } }, { "body": "<p>Note that your definitions of <code>cont-frac</code> and <code>i-cont-frac</code> accept as arguments the functions <code>n</code> and <code>d</code>, and not <code>n_i</code> or <code>d_i</code> (which, I assume, would be specific values of <code>n</code> and <code>d</code> at index <code>i</code>). I would avoid this confusion by naming the arguments properly.</p>\n\n<p>The definition of <code>i-cont-frac</code> could be improved by rewriting the base case. When the iterant is zero, the result should be zero as well.</p>\n\n<p>One could also abstract out the idea of an initial and a terminal value of the iterant, and the initial value of the result. Here's an implementation of these ideas:</p>\n\n<pre><code>(define (cont-frac n d k)\n (define initial-result 0)\n (define initial-i 0)\n (define terminal-i k)\n (define (recurse i)\n (if (= i terminal-i)\n initial-result\n (let\n ((next-i (+ i 1)))\n (/ (n next-i) (+ (d next-i) (recurse next-i))))))\n (recurse initial-i))\n\n(define (i-cont-frac n d k)\n (define initial-result 0)\n (define initial-i k)\n (define terminal-i 0)\n (define (iterate result i)\n (if (= i terminal-i)\n result\n (let\n ((next-i (- i 1)))\n (iterate (/ (n i)\n (+ (d i) result))\n next-i))))\n (iterate initial-result initial-i))\n</code></pre>\n\n<p>Note the difference in the <code>initial-i</code>, <code>terminal-i</code> and <code>next-i</code> values in these definitions. This is in line with how recursion and iteration work in these functions.</p>\n\n<p>Notice that the recursive definition needs to use <code>let</code> in order to get the next value of <code>i</code> to allow for the 1-indexed nature of the functions <code>n</code> and <code>d</code> and to return the correct value of zero when <code>k</code> is zero. If we assume that <code>k</code> is never zero, we may rewrite a simplified version of the recursive definition like so:</p>\n\n<pre><code>(define (cont-frac n d k)\n (define initial-result 0)\n (define initial-i 1)\n (define terminal-i k)\n (define (recurse i)\n (define (next i) (+ i 1))\n (/ (n i) (+ (d i) (if (= i terminal-i) initial-result (recurse (next i))))))\n (recurse initial-i))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T12:42:46.963", "Id": "1578", "ParentId": "1568", "Score": "1" } } ]
{ "AcceptedAnswerId": "1578", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-31T02:12:19.007", "Id": "1568", "Score": "0", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Infinite Continued Fraction - iterative and recursive" }
1568
<p>Given the following task:</p> <blockquote> <p>Exercise 1.38. In 1737, the Swiss mathematician Leonhard Euler published a memoir De Fractionibus Continuis, which included a continued fraction expansion for e - 2, where e is the base of the natural logarithms. In this fraction, the Ni are all 1, and the Di are successively 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, .... Write a program that uses your cont-frac procedure from exercise 1.37 to approximate e, based on Euler's expansion.</p> </blockquote> <p>I wrote this solution:</p> <pre><code>(define (i-cont-frac n d k) (define (iterate result i) (define (next n) (- n 1)) (if (= i 0) result (iterate (/ (n i) (+ (d i) result)) (next i)))) (iterate 0 k)) (define (divisible? a b) (= (remainder a b) 0)) (define (compute-e k) (define (n i) 1) (define (d i) (cond ((= i 1) 1) ((= i 2) 2) ((divisible? (- i 1) 3) (* (/ (- i 1) 3.0) 2.0)) (else 1.0))) (+ 2 (cont-frac n d k))) </code></pre> <p>What do you think?</p>
[]
[ { "body": "<p>Your definition of <code>d</code> is not quite right. It produces incorrect results for some values of <code>i</code> and it has two special cases which are not necessary. A possible definition is:</p>\n\n<pre><code> (define (d i)\n (cond\n ((divisible? (+ i 1) 3) \n (* (/ (+ i 1) 3) 2))\n (else 1)))\n</code></pre>\n\n<p>This is because i is 1-indexed (series begins with i = 1). If you want a decimal instead of a fraction as your result, change the multiplier to 2.0 and the else value to 1.0.</p>\n\n<p>Another way to write <code>d</code> is:</p>\n\n<pre><code> (define (d i)\n (let\n ((d-value (* (/ (+ i 1) 3) 2)))\n (if (integer? d-value) d-value 1)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T11:55:38.683", "Id": "1576", "ParentId": "1569", "Score": "2" } } ]
{ "AcceptedAnswerId": "1576", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-31T02:52:45.587", "Id": "1569", "Score": "1", "Tags": [ "programming-challenge", "mathematics", "scheme", "sicp" ], "Title": "Compute e using Euler's expansion" }
1569
<p>There are two aspects to this question that are inter-related.</p> <ol> <li>Change I've made to the <code>trie</code> module in python (<a href="http://pypi.python.org/pypi/trie" rel="nofollow">PyPI</a>, <a href="https://github.com/dhain/trie" rel="nofollow">GitHub</a>) to make it serialisable (and deserialisable).</li> </ol> <p>The change I made is <a href="https://github.com/stephenpaulger/trie/commit/0246526ac75766a57f866d7ed44bef97850a762c" rel="nofollow">visible on GitHub</a>. I added two functions to the <code>Node</code> class used in serialisation.</p> <pre><code>def __getstate__(self): return (self.parent, self.key, self.nodes, self.value) def __setstate__(self, state): (self.parent, self.key, self.nodes, self.value) = state if type(self.value) == object: self.value = Node.no_value </code></pre> <p>The <code>Node</code> class uses an instance of <code>object</code> to signify that there is no value for that <code>Node</code>. If you serialise and deserialise a <code>Trie</code> of <code>Nodes</code> then the values are set to different instances of <code>object</code>, this is why I added a check for the type being <code>object</code> and replacing it with <code>Node.no_value</code>.</p> <p>Is this a reasonable way of doing things? Is anyone likely to want to store an actual instance of <code>object</code>?</p> <ol start="2"> <li>Is there a better way of signifying that a <code>Node</code> has no value, that is more robust to serialisation?</li> </ol>
[]
[ { "body": "<p>Use None rather then Node.no_value.</p>\n\n<p>None is the typical value to use for the absence of value. However, its possible that you actually want to store None in your trie, so that doesn't work.</p>\n\n<p>Checking the type of the object is not really a good plan because somebody could decide to store plain objects in your trie. I would add another value, a boolean \"self.value is Node.no_value\", to the tuple in <strong>setstate</strong>. By checking that I could be sure that it works correctly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T12:27:14.450", "Id": "1577", "ParentId": "1574", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-31T09:09:14.720", "Id": "1574", "Score": "2", "Tags": [ "python", "trie" ], "Title": "Serialising missing values in trie" }
1574
<p>I'm creating a gradebook. Many students earn a grade in many standards each. I'm hoping to get help analyzing the code below for efficient use of asynchronous result fetching. <code>ofy</code> is an <code>Objectify</code> object, which is basically just a convenience wrapper over the async fetching capabilities of AppEngine.</p> <pre><code>public List&lt;StandardScoreDAO&gt; getStandardScores( ArrayList&lt;Long&gt; studentIdLongs, ArrayList&lt;Long&gt; standardIdLongs) { ObjectifyService.register(StandardScoreDAO.class); Objectify ofy = ObjectifyService.begin(); List&lt;Iterator&lt;StandardScoreDAO&gt;&gt; results = new ArrayList&lt;Iterator&lt;StandardScoreDAO&gt;&gt;(); for (Long studentId : studentIdLongs) { for (Long standardId : standardIdLongs) { results.add(ofy.query(StandardScoreDAO.class) .filter("measuredUserId =", studentId) .filter("standardId =", standardId) .iterator()); } } ArrayList&lt;StandardScoreDAO&gt; ret = new ArrayList&lt;StandardScoreDAO&gt;(); for (Iterator&lt;StandardScoreDAO&gt; i : results) { while (i.hasNext()) { ret.add(i.next()); } } return ret; } </code></pre> <p>As you can see, if there are 100 studentIds and 100 standardIds, this is 10,000 queries. AppEngine will only run 10 in parallel. Aiee! I don't know if it's at all realistic to expect this to finish in 30 seconds (testing soon), but I wonder if anyone sees a much better way to organize this.</p>
[]
[ { "body": "<p>With Objectify, you have the option to use the \"in\" operator in a query. Moreover, it becomes clear from the second block of nested loops that you are only looking for the intersection of the two sets of measuredUserIds and standardIds. So, a single statement should do the trick:</p>\n\n<pre><code>public List&lt;StandardScoreDAO&gt; getStandardScores(\n ArrayList&lt;Long&gt; studentIdLongs, ArrayList&lt;Long&gt; standardIdLongs) {\n ObjectifyService.register(StandardScoreDAO.class);\n Objectify ofy = ObjectifyService.begin();\n\n Iterator&lt;StandardScoreDAO&gt; i = ofy.query(StandardScoreDAO.class)\n .filter(\"measuredUserId in\", studentIdLongs)\n .filter(\"standardId in\", standardIdLongs)\n .iterator();\n\n List&lt;StandardScoreDAO&gt; ret = new LinkedList&lt;StandardScoreDAO&gt;();\n\n while (i.hasNext()) {\n ret.add(i.next());\n }\n\n return ret;\n}\n</code></pre>\n\n<p>If you access a list merely by iteration (and not by random access or by index), and do not know its size on creation, LinkedList might give you a performance benefit.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T12:55:44.387", "Id": "3159", "Score": "0", "body": "Are Objectify's \"in\" operators immune from the 30-sub-query limit? With JDO, for example, I couldn't use `studentIdLongs.contains(:measuredUserId) && standardIdLongs.contains(:standardId)` because it generates many more than 30 sub-queries. Thanks for the tip on `LinkedList` - that makes sense!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T07:50:58.000", "Id": "1848", "ParentId": "1581", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T13:50:47.757", "Id": "1581", "Score": "2", "Tags": [ "java", "google-app-engine" ], "Title": "Querying the same fields for many different values on AppEngine" }
1581
<p>I've been working on a Stack Overflow like pager for my personal use and I've gotten everything working pretty good. Some of my logic is a bit suspect though, especially the logic in the Pager class itself. I thought I'd try posting this code on here just to see what sort of responses I got. I included my test cases as well. Some of the test names might be weird, but I'll go back and fix that later. </p> <pre><code> public class Pager { public int TotalPages { get; private set; } public int SelectedItem { get; private set; } public int PageNumbersToShow { get; set; } public string CssClass { get; set; } public Pager(int selectedItem, int totalPages, int pageNumbersToShow = 5) { this.SelectedItem = selectedItem; this.TotalPages = totalPages; this.PageNumbersToShow = pageNumbersToShow; this.CssClass = "pager fl"; } public override string ToString() { var finalString = new StringBuilder(); var pagerDiv = new TagBuilder("div"); pagerDiv.AddCssClass(CssClass); //prev 1 2 (3) //prev 1 (2) 3 next // (1) 2 3 next if (TotalPages &lt;= PageNumbersToShow) { for (int i = 1; i &lt;= TotalPages; i++) { finalString.Append(new PageNumber(i, (SelectedItem == i)).ToString()); } } //Greater than pagesize and selected page is less than pagesize // prev (1) 2 3 4 5 ... 11 next // prev 1 (2) 3 4 5 ... 11 next if (SelectedItem &lt; PageNumbersToShow &amp;&amp; TotalPages &gt; PageNumbersToShow) { for (int i = 1; i &lt;= PageNumbersToShow; i++) { finalString.Append(new PageNumber(i, (SelectedItem == i)).ToString()); } finalString.Append(new PageNumber().ToString()); finalString.Append(new PageNumber(TotalPages).ToString()); } //prev 1 ... 7 8 9 10 (11) //prev 1 ... 7 (8) 9 10 11 next if (SelectedItem &gt; PageNumbersToShow &amp;&amp; TotalPages - (PageNumbersToShow - 1) &lt; SelectedItem) { finalString.Append(new PageNumber(1).ToString()); finalString.Append(new PageNumber().ToString()); for (int i = (TotalPages - PageNumbersToShow) + 1; i &lt;= TotalPages; i++) { finalString.Append(new PageNumber(i, (SelectedItem == i)).ToString()); } } //prev 1 ... 4 5 (6) 7 8 ... 11 next if (SelectedItem &gt;= PageNumbersToShow &amp;&amp; TotalPages - (PageNumbersToShow - 1) &gt;= SelectedItem) { finalString.Append(new PageNumber(1).ToString()); finalString.Append(new PageNumber().ToString()); var middle = (PageNumbersToShow / 2); for (int i = SelectedItem - middle; i &lt;= SelectedItem + middle; i++) { finalString.Append(new PageNumber(i, (SelectedItem == i)).ToString()); } finalString.Append(new PageNumber().ToString()); finalString.Append(new PageNumber(TotalPages).ToString()); } /* Add Previous and Next Link */ if (SelectedItem != 1) { finalString.Insert(0, new PageNumber(SelectedItem - 1, "prev").ToString()); } if (SelectedItem != TotalPages) { finalString.Append(new PageNumber(SelectedItem + 1, "next").ToString()); } /* Copy final string into div inner HTML */ pagerDiv.InnerHtml = finalString.ToString(); return pagerDiv.ToString(); } private class PageNumber { private const string cssClass = "page-numbers"; private const string href = "?page={0}"; private TagBuilder link = new TagBuilder("a"); private TagBuilder span = new TagBuilder("span"); public bool Current { get; private set; } public int Page { get; private set; } public PageNumber(int Page, bool Current = false) { this.Current = Current; this.Page = Page; span.AddCssClass(cssClass); span.SetInnerText(Page.ToString()); } public PageNumber(int Page, string spanText) { this.Page = Page; span.AddCssClass(cssClass + " " + spanText); span.SetInnerText(spanText + " "); } public PageNumber() { span.AddCssClass(cssClass + " " + "dots"); span.SetInnerText("..."); } public override string ToString() { if (Current) { span.AddCssClass("current"); return span.ToString(); } else { if (span.ToString().Contains("dots")) { return span.ToString(); } link.MergeAttribute("href", string.Format(href, Page)); link.MergeAttribute("title", string.Format("go to page {0}", Page)); link.InnerHtml = span.ToString(); return link.ToString(); } } } } [TestClass] public class PagerTests { // (1) [TestMethod] public void Should_Only_Print_Out_One_Span_If_Number_Of_Pages_Is_One() { //Arrange var pager = new Pager(1, 1); //Act var result = pager.ToString(); //Assert result.ShouldEqual(@"&lt;div class=""pager fl""&gt;&lt;span class=""current page-numbers""&gt;1&lt;/span&gt;&lt;/div&gt;"); } // (1) 2 3 next [TestMethod] public void Should_Not_Print_Out_Previous_If_Selected_Page_Is_First_In_List_Smaller_Than_Five() { //Arrange StringBuilder expectedValue = new StringBuilder(); var pager = new Pager(1, 3); //Act var result = pager.ToString(); //Assert expectedValue.Append(@"&lt;div class=""pager fl""&gt;"); expectedValue.Append(@"&lt;span class=""current page-numbers""&gt;1&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=2"" title=""go to page 2""&gt;&lt;span class=""page-numbers""&gt;2&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=3"" title=""go to page 3""&gt;&lt;span class=""page-numbers""&gt;3&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=2"" title=""go to page 2""&gt;&lt;span class=""page-numbers next""&gt;next &lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;/div&gt;"); result.ShouldEqual(expectedValue.ToString()); } // prev 1 2 (3) [TestMethod] public void Should_Not_Print_Out_Next_Link_When_Selected_Page_Is_Last_In_List_Smaller_Than_Five() { //Arrange StringBuilder expectedValue = new StringBuilder(); var pager = new Pager(3, 3); //Act var result = pager.ToString(); //Assert expectedValue.Append(@"&lt;div class=""pager fl""&gt;"); expectedValue.Append(@"&lt;a href=""?page=2"" title=""go to page 2""&gt;&lt;span class=""page-numbers prev""&gt;prev &lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=1"" title=""go to page 1""&gt;&lt;span class=""page-numbers""&gt;1&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=2"" title=""go to page 2""&gt;&lt;span class=""page-numbers""&gt;2&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""current page-numbers""&gt;3&lt;/span&gt;"); expectedValue.Append(@"&lt;/div&gt;"); result.ShouldEqual(expectedValue.ToString()); } // prev 1 (2) 3 next [TestMethod] public void Should_Print_Out_Both_Next_And_Previous_When_Selected_Is_Not_First_Or_Last_In_List_Smaller_Than_Five() { //Arrange StringBuilder expectedValue = new StringBuilder(); var pager = new Pager(2, 3); //Act var result = pager.ToString(); //Assert expectedValue.Append(@"&lt;div class=""pager fl""&gt;"); expectedValue.Append(@"&lt;a href=""?page=1"" title=""go to page 1""&gt;&lt;span class=""page-numbers prev""&gt;prev &lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=1"" title=""go to page 1""&gt;&lt;span class=""page-numbers""&gt;1&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""current page-numbers""&gt;2&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=3"" title=""go to page 3""&gt;&lt;span class=""page-numbers""&gt;3&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=3"" title=""go to page 3""&gt;&lt;span class=""page-numbers next""&gt;next &lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;/div&gt;"); result.ShouldEqual(expectedValue.ToString()); } // (1) 2 3 4 5 ... 11 next [TestMethod] public void List_Greater_Than_Five_Pages_Generates_Dot_Dot_Dot_Last_Link_With_Page_One_Selcted() { //Arrange StringBuilder expectedValue = new StringBuilder(); var pager = new Pager(1, 11); //Act var result = pager.ToString(); //Assert expectedValue.Append(@"&lt;div class=""pager fl""&gt;"); expectedValue.Append(@"&lt;span class=""current page-numbers""&gt;1&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=2"" title=""go to page 2""&gt;&lt;span class=""page-numbers""&gt;2&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=3"" title=""go to page 3""&gt;&lt;span class=""page-numbers""&gt;3&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=4"" title=""go to page 4""&gt;&lt;span class=""page-numbers""&gt;4&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=5"" title=""go to page 5""&gt;&lt;span class=""page-numbers""&gt;5&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""page-numbers dots""&gt;...&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=11"" title=""go to page 11""&gt;&lt;span class=""page-numbers""&gt;11&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=2"" title=""go to page 2""&gt;&lt;span class=""page-numbers next""&gt;next &lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;/div&gt;"); result.ShouldEqual(expectedValue.ToString()); } // prev 1 ... 3 4 (5) 6 7 ... 11 next [TestMethod] public void List_Greater_Than_Five_Give_Prev_One_Dot_Dot_Dot_Four_Numbers_Dot_Dot_Dot_Last_Next() { //Arrange StringBuilder expectedValue = new StringBuilder(); var pager = new Pager(5, 11); //Act var result = pager.ToString(); //Assert expectedValue.Append(@"&lt;div class=""pager fl""&gt;"); expectedValue.Append(@"&lt;a href=""?page=4"" title=""go to page 4""&gt;&lt;span class=""page-numbers prev""&gt;prev &lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=1"" title=""go to page 1""&gt;&lt;span class=""page-numbers""&gt;1&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""page-numbers dots""&gt;...&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=3"" title=""go to page 3""&gt;&lt;span class=""page-numbers""&gt;3&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=4"" title=""go to page 4""&gt;&lt;span class=""page-numbers""&gt;4&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""current page-numbers""&gt;5&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=6"" title=""go to page 6""&gt;&lt;span class=""page-numbers""&gt;6&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=7"" title=""go to page 7""&gt;&lt;span class=""page-numbers""&gt;7&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""page-numbers dots""&gt;...&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=11"" title=""go to page 11""&gt;&lt;span class=""page-numbers""&gt;11&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=6"" title=""go to page 6""&gt;&lt;span class=""page-numbers next""&gt;next &lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;/div&gt;"); result.ShouldEqual(expectedValue.ToString()); } // prev 1 ... 7 8 9 10 (11) [TestMethod] public void When_List_Is_Greater_Than_Five_And_Selected_Is_The_Last_Item() { //Arrange StringBuilder expectedValue = new StringBuilder(); var pager = new Pager(11, 11); //Act var result = pager.ToString(); //Assert expectedValue.Append(@"&lt;div class=""pager fl""&gt;"); expectedValue.Append(@"&lt;a href=""?page=10"" title=""go to page 10""&gt;&lt;span class=""page-numbers prev""&gt;prev &lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=1"" title=""go to page 1""&gt;&lt;span class=""page-numbers""&gt;1&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""page-numbers dots""&gt;...&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=7"" title=""go to page 7""&gt;&lt;span class=""page-numbers""&gt;7&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=8"" title=""go to page 8""&gt;&lt;span class=""page-numbers""&gt;8&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=9"" title=""go to page 9""&gt;&lt;span class=""page-numbers""&gt;9&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=10"" title=""go to page 10""&gt;&lt;span class=""page-numbers""&gt;10&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""current page-numbers""&gt;11&lt;/span&gt;"); expectedValue.Append(@"&lt;/div&gt;"); result.ShouldEqual(expectedValue.ToString()); } // prev 1 ... 7 (8) 9 10 11 next [TestMethod] public void When_List_Is_Greater_Than_Five_And_Within_PageSize_Of_End_Of_List_And_Last_Item_Is_Not_Selected() { //Arrange StringBuilder expectedValue = new StringBuilder(); var pager = new Pager(8, 11); //Act var result = pager.ToString(); //Assert expectedValue.Append(@"&lt;div class=""pager fl""&gt;"); expectedValue.Append(@"&lt;a href=""?page=7"" title=""go to page 7""&gt;&lt;span class=""page-numbers prev""&gt;prev &lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=1"" title=""go to page 1""&gt;&lt;span class=""page-numbers""&gt;1&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""page-numbers dots""&gt;...&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=7"" title=""go to page 7""&gt;&lt;span class=""page-numbers""&gt;7&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""current page-numbers""&gt;8&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=9"" title=""go to page 9""&gt;&lt;span class=""page-numbers""&gt;9&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=10"" title=""go to page 10""&gt;&lt;span class=""page-numbers""&gt;10&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=11"" title=""go to page 11""&gt;&lt;span class=""page-numbers""&gt;11&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=9"" title=""go to page 9""&gt;&lt;span class=""page-numbers next""&gt;next &lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;/div&gt;"); result.ShouldEqual(expectedValue.ToString()); } //prev 1 ... 5 6 (7) 8 9 ... 11 next [TestMethod] public void When_Selected_Is_One_Less_Than_Page_Size() { //Arrange StringBuilder expectedValue = new StringBuilder(); var pager = new Pager(7, 11); //Act var result = pager.ToString(); //Assert expectedValue.Append(@"&lt;div class=""pager fl""&gt;"); expectedValue.Append(@"&lt;a href=""?page=6"" title=""go to page 6""&gt;&lt;span class=""page-numbers prev""&gt;prev &lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=1"" title=""go to page 1""&gt;&lt;span class=""page-numbers""&gt;1&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""page-numbers dots""&gt;...&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=5"" title=""go to page 5""&gt;&lt;span class=""page-numbers""&gt;5&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=6"" title=""go to page 6""&gt;&lt;span class=""page-numbers""&gt;6&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""current page-numbers""&gt;7&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=8"" title=""go to page 8""&gt;&lt;span class=""page-numbers""&gt;8&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=9"" title=""go to page 9""&gt;&lt;span class=""page-numbers""&gt;9&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""page-numbers dots""&gt;...&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=11"" title=""go to page 11""&gt;&lt;span class=""page-numbers""&gt;11&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=8"" title=""go to page 8""&gt;&lt;span class=""page-numbers next""&gt;next &lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;/div&gt;"); result.ShouldEqual(expectedValue.ToString()); } //prev 1 ... 8 9 (10) 11 12 ... 15 next [TestMethod] public void When_Selected_Is_Exactly_Total_Pages_Minus_Page_Size() { //Arrange StringBuilder expectedValue = new StringBuilder(); var pager = new Pager(10, 15); //Act var result = pager.ToString(); //Assert expectedValue.Append(@"&lt;div class=""pager fl""&gt;"); expectedValue.Append(@"&lt;a href=""?page=9"" title=""go to page 9""&gt;&lt;span class=""page-numbers prev""&gt;prev &lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=1"" title=""go to page 1""&gt;&lt;span class=""page-numbers""&gt;1&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""page-numbers dots""&gt;...&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=8"" title=""go to page 8""&gt;&lt;span class=""page-numbers""&gt;8&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=9"" title=""go to page 9""&gt;&lt;span class=""page-numbers""&gt;9&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""current page-numbers""&gt;10&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=11"" title=""go to page 11""&gt;&lt;span class=""page-numbers""&gt;11&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=12"" title=""go to page 12""&gt;&lt;span class=""page-numbers""&gt;12&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;span class=""page-numbers dots""&gt;...&lt;/span&gt;"); expectedValue.Append(@"&lt;a href=""?page=15"" title=""go to page 15""&gt;&lt;span class=""page-numbers""&gt;15&lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;a href=""?page=11"" title=""go to page 11""&gt;&lt;span class=""page-numbers next""&gt;next &lt;/span&gt;&lt;/a&gt;"); expectedValue.Append(@"&lt;/div&gt;"); result.ShouldEqual(expectedValue.ToString()); } } </code></pre>
[]
[ { "body": "<p>It's a little wonky to have a</p>\n\n<pre><code>public int PageNumbersToShow { get; set; }\n</code></pre>\n\n<p>Then do all dis bizness in the toString() method</p>\n\n<pre><code>if (TotalPages &lt;= PageNumbersToShow) {\n\n for (int i = 1; i &lt;= TotalPages; i++) {\n finalString.Append(new PageNumber(i, (SelectedItem == i)).ToString());\n }\n\n }\n</code></pre>\n\n<p>You've created a class to encapsulate a PageNumber. It would make more sense to have the Pager hold a list of these.</p>\n\n<p>If you're thinking along these lines already, then a Pager is really just a <a href=\"http://en.wikipedia.org/wiki/Composite_pattern\">Composite</a> of PageNumbers. </p>\n\n<p>Don't do so much business logic processing in your toString() methods and constructors. Most of that logic should be in utility methods devoted to their particular tasks. For example</p>\n\n<pre><code> if (Current) {\n span.AddCssClass(\"current\");\n return span.ToString();\n } else {\n\n if (span.ToString().Contains(\"dots\")) {\n return span.ToString();\n }\n</code></pre>\n\n<ol>\n<li>What if I wanna add another CSS class later? </li>\n<li>What if I decide to change from to <li> like a reasonable person?</li>\n<li>What if I wanna add javascript events?</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T04:55:55.243", "Id": "1597", "ParentId": "1585", "Score": "7" } }, { "body": "<p>I'm using something like below paired with a separate html rendering helper method. I thought it was pretty clean but I'm sure it's not perfect.</p>\n\n<pre><code>#region IPagedList\n\n/// &lt;remarks&gt;\n/// Represents a subset of a collection of objects that can be individually accessed by index and containing metadata about the superset collection of objects this subset was created from.\n/// &lt;/remarks&gt;\n/// &lt;typeparam name=\"T\"&gt;The type of object the collection should contain.&lt;/typeparam&gt;\n/// &lt;seealso cref=\"IList{T}\"/&gt;\npublic interface IPagedList\n{\n /// &lt;summary&gt;\n /// Total number of subsets within the superset.\n /// &lt;/summary&gt;\n /// &lt;value&gt;\n /// Total number of subsets within the superset.\n /// &lt;/value&gt;\n int PageCount { get; }\n\n /// &lt;summary&gt;\n /// Total number of objects contained within the superset.\n /// &lt;/summary&gt;\n /// &lt;value&gt;\n /// Total number of objects contained within the superset.\n /// &lt;/value&gt;\n int TotalItemCount { get; }\n\n /// &lt;summary&gt;\n /// Zero-based index of this subset within the superset.\n /// &lt;/summary&gt;\n /// &lt;value&gt;\n /// Zero-based index of this subset within the superset.\n /// &lt;/value&gt;\n int PageIndex { get; }\n\n /// &lt;summary&gt;\n /// Maximum size any individual subset.\n /// &lt;/summary&gt;\n /// &lt;value&gt;\n /// Maximum size any individual subset.\n /// &lt;/value&gt;\n int PageSize { get; }\n}\n\n#endregion\n\n#region PagedList\n\n/// &lt;summary&gt;\n/// Represents a subset of a collection of objects that can be individually accessed by index and containing metadata about the superset collection of objects this subset was created from.\n/// &lt;/summary&gt;\n/// &lt;typeparam name=\"T\"&gt;The type of object the collection should contain.&lt;/typeparam&gt;\n/// &lt;seealso cref=\"IPagedList{T}\"/&gt;\n/// &lt;seealso cref=\"List{T}\"/&gt;\npublic class PagedList&lt;T&gt; : List&lt;T&gt;, IPagedList\n{\n /// &lt;summary&gt;\n /// Default CTOR\n /// &lt;/summary&gt;\n public PagedList()\n : this(new List&lt;T&gt;(), 0, 0, 20)\n { }\n\n\n /// &lt;summary&gt;\n /// Initializes a new instance of a type deriving from &lt;see cref=\"BasePagedList{T}\"/&gt; and sets properties needed to calculate position and size data on the subset and superset.\n /// &lt;/summary&gt;\n /// &lt;param name=\"index\"&gt;The index of the subset of objects contained by this instance.&lt;/param&gt;\n /// &lt;param name=\"pageSize\"&gt;The maximum size of any individual subset.&lt;/param&gt;\n /// &lt;param name=\"totalItemCount\"&gt;The size of the superset.&lt;/param&gt;\n public PagedList(IEnumerable&lt;T&gt; list, int totalItemCount, int pageIndex, int pageSize)\n : base(list == null ? new List&lt;T&gt;() : list) \n {\n if (pageIndex &lt; 0)\n throw new ArgumentOutOfRangeException(\"index\", pageIndex, \"PageIndex cannot be below 0.\");\n if (pageSize &lt; 1)\n throw new ArgumentOutOfRangeException(\"pageSize\", pageSize, \"PageSize cannot be less than 1.\");\n\n // set source to blank list if superset is null to prevent exceptions\n this.PageCount = CalcNumberOfPages(totalItemCount, pageSize);\n this.TotalItemCount = totalItemCount;\n this.PageSize = pageSize;\n this.PageIndex = pageIndex;\n }\n\n\n /// &lt;summary&gt;\n /// Calculates the number of pages in a set.\n /// &lt;/summary&gt;\n /// &lt;param name=\"totalItemCount\"&gt;Total number of items in the set&lt;/param&gt;\n /// &lt;param name=\"pageSize\"&gt;Number of items in a page&lt;/param&gt;\n /// &lt;returns&gt;Number of pages (int).&lt;/returns&gt;\n protected int CalcNumberOfPages(int totalItemCount, int pageSize)\n {\n return (totalItemCount % pageSize == 0) ? (totalItemCount / pageSize) : totalItemCount / pageSize + 1;\n }\n\n\n #region IPagedList&lt;T&gt; Members\n\n /// &lt;summary&gt;\n /// Total number of subsets within the superset.\n /// &lt;/summary&gt;\n public int PageCount { get; protected set; }\n\n /// &lt;summary&gt;\n /// Total number of objects contained within the superset.\n /// &lt;/summary&gt;\n public int TotalItemCount { get; protected set; }\n\n /// &lt;summary&gt;\n /// Zero-based index of this subset within the superset.\n /// &lt;/summary&gt;\n public int PageIndex { get; protected set; }\n\n /// &lt;summary&gt;\n /// Maximum size any individual subset.\n /// &lt;/summary&gt;\n public int PageSize { get; protected set; }\n\n /// &lt;summary&gt;\n /// Returns true if this is the first subset within the superset.\n /// &lt;/summary&gt;\n public bool IsFirstPage\n {\n get { return PageIndex &lt; 1; }\n }\n\n /// &lt;summary&gt;\n /// Returns true if this is the last subset within the superset.\n /// &lt;/summary&gt;\n public bool IsLastPage\n {\n get { return PageIndex + 1 == PageCount; }\n }\n\n #endregion\n}\n\n#endregion\n\n#region Extensions\n\n/// &lt;summary&gt;\n/// Container for extension methods designed to simplify the creation of instances of &lt;see cref=\"PagedList{T}\"/&gt;.\n/// &lt;/summary&gt;\n/// &lt;remarks&gt;\n/// Container for extension methods designed to simplify the creation of instances of &lt;see cref=\"PagedList{T}\"/&gt;.\n/// &lt;/remarks&gt;\npublic static class PagedListExtensions\n{\n /// &lt;summary&gt;\n /// Creates a subset of this collection of objects that can be individually accessed by index and containing metadata about the collection of objects the subset was created from.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;The type of object the collection should contain.&lt;/typeparam&gt;\n /// &lt;param name=\"superset\"&gt;The collection of objects to be divided into subsets. If the collection implements &lt;see cref=\"IQueryable{T}\"/&gt;, it will be treated as such.&lt;/param&gt;\n /// &lt;param name=\"index\"&gt;The index of the subset of objects to be contained by this instance.&lt;/param&gt;\n /// &lt;param name=\"pageSize\"&gt;The maximum size of any individual subset.&lt;/param&gt;\n /// &lt;returns&gt;A subset of this collection of objects that can be individually accessed by index and containing metadata about the collection of objects the subset was created from.&lt;/returns&gt;\n /// &lt;seealso cref=\"PagedList{T}\"/&gt;\n public static PagedList&lt;T&gt; ToPagedList&lt;T&gt;(this IEnumerable&lt;T&gt; list, int totalItemCount, int pageIndex, int pageSize)\n {\n return new PagedList&lt;T&gt;(list, totalItemCount, pageIndex, pageSize);\n }\n}\n\npublic static class PageQuery\n{\n public static PagedList&lt;T&gt; Paginate&lt;T&gt;(this IQueryable&lt;T&gt; query, int pageIndex, int pageSize, int totalItemCount)\n {\n return query.Skip(Math.Max(pageSize * pageIndex, 0)).Take(pageSize).ToPagedList(totalItemCount, pageIndex, pageSize);\n }\n}\n\n#endregion\n</code></pre>\n\n<p>Then to page a dataset with Linq to SQL you call it like:</p>\n\n<pre><code> int rowCount = (from o in dc.Table\n select o).Count();\n\n return (from o in dc.Table\n orderby o.LastName\n select o).Paginate(pageNum, pageSize, rowCount);\n</code></pre>\n\n<p>Then to render the pager html something like this:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Renders a paging control. This has to be used in strongly typed pages that use PagedList&lt;Entity&gt;\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;&lt;/typeparam&gt;\n /// &lt;param name=\"page\"&gt;&lt;/param&gt;\n /// &lt;param name=\"routeName\"&gt;&lt;/param&gt;\n /// &lt;param name=\"routeValues\"&gt;&lt;/param&gt;\n public static void Pager&lt;T&gt;(this HtmlHelper&lt;T&gt; page, string routeName, object routeValues) where T : class, IPagedList\n {\n RouteValueDictionary routeDictionary = (routeValues == null) ? new RouteValueDictionary() : new RouteValueDictionary(routeValues);\n\n HtmlTextWriter writer = new HtmlTextWriter(page.ViewContext.HttpContext.Response.Output);\n\n if (writer != null)\n {\n int lowerBound = (page.ViewData.Model.PageIndex) - 10;\n lowerBound = lowerBound &lt; 0 ? 0 : lowerBound;\n\n int upperBound = (page.ViewData.Model.PageIndex) + 10;\n upperBound = upperBound &gt; page.ViewData.Model.PageCount ? page.ViewData.Model.PageCount : upperBound;\n\n writer.Write(\"&lt;div class=\\\"pager\\\"&gt;\");\n\n string pageNumberParam;\n\n for (int pageNum = lowerBound + 1; pageNum &lt;= upperBound; pageNum++)\n {\n pageNumberParam = string.Empty;\n\n if (pageNum != page.ViewData.Model.PageIndex + 1)\n {\n VirtualPathData vPathData = RouteTable.Routes.GetVirtualPath(page.ViewContext.RequestContext, routeName, routeDictionary);\n\n pageNumberParam += vPathData.VirtualPath.Contains('?') ? \"&amp;pageNum=\" : \"?pageNum=\";\n pageNumberParam += (pageNum - 1).ToString();\n\n writer.AddAttribute(HtmlTextWriterAttribute.Href, vPathData.VirtualPath + pageNumberParam);\n writer.AddAttribute(HtmlTextWriterAttribute.Alt, \"Page \" + pageNum);\n writer.RenderBeginTag(HtmlTextWriterTag.A);\n }\n\n writer.AddAttribute(\n HtmlTextWriterAttribute.Class,\n pageNum == page.ViewData.Model.PageIndex + 1 ? \"pageLinkCurrent\" : \"pageLink\"\n );\n\n writer.RenderBeginTag(HtmlTextWriterTag.Span);\n writer.Write(pageNum);\n writer.RenderEndTag();\n\n if (pageNum != page.ViewData.Model.PageIndex + 1)\n {\n writer.RenderEndTag();\n }\n writer.Write(\" \");\n }\n\n writer.Write(\"&lt;br /&gt; (\");\n writer.Write(page.ViewData.Model.TotalItemCount);\n writer.Write(\" items in \");\n writer.Write(page.ViewData.Model.PageCount);\n writer.Write(\" pages) \");\n\n writer.Write(\"&lt;/div&gt;\");\n }\n\n }\n</code></pre>\n\n<p>I think a similar pattern was in the 2nd last issue of MSDN mag too...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T23:11:34.023", "Id": "1887", "ParentId": "1585", "Score": "3" } }, { "body": "<p>instead of this malarky....</p>\n\n<pre><code>finalString.Append(new PageNumber(TotalPages).ToString());\n</code></pre>\n\n<p>why not something that manages the pagenumbering so you have a simple interface...</p>\n\n<pre><code>pages.AddPage(pageNumber);\n</code></pre>\n\n<p>and</p>\n\n<pre><code>pages.AddPage(2).Select();\n</code></pre>\n\n<p>then at the end... </p>\n\n<pre><code>finalString = pages.ToString();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T23:45:56.063", "Id": "1888", "ParentId": "1585", "Score": "4" } } ]
{ "AcceptedAnswerId": "1597", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-31T16:19:07.987", "Id": "1585", "Score": "8", "Tags": [ "c#", "asp.net" ], "Title": "Stack Overflow like pager" }
1585
<p>I had this as an interview question, and the interviewer pointed this out. Here's what I wrote:</p> <pre><code>//C# Syntax here public string Reverse(string s) { char[] arr = s.ToCharArray(); int idx = 0; int endIdx = s.Length - 1; for(; idx &lt; endIdx; ++idx, --endIdx) { char temp = arr[idx]; arr[idx] = arr[endIdx]; arr[endIdx] = temp; } return arr.ToString(); } </code></pre> <p>However, the interviewer was asking if I should have changed it to this:</p> <pre><code>//C# Syntax here public string Reverse(string s) { char[] arr = s.ToCharArray(); int idx = 0; int endIdx = s.Length - 1; while(idx &lt; endIdx) { char temp = arr[idx]; arr[idx] = arr[endIdx]; arr[endIdx] = temp; ++idx; --endIdx; } return arr.ToString(); } </code></pre> <p>Personally, I like the first version, because it puts all of the machinery which controls the loop into the loop statement. One can insert <code>continue</code> or <code>break</code> or <code>return</code> statements into the loop without it breaking things.</p> <p>However, some programmers dislike putting that stuff into the <code>for</code>, because they think it's being too "clever".</p> <p>What do you consider best-practice for this?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T16:15:19.683", "Id": "2752", "Score": "4", "body": "I think this would be a better question for codereview.stackexchange.com or stackoverflow." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T16:18:03.363", "Id": "2753", "Score": "1", "body": "@whatisname: Maybe code review. I don't think it works on SO because it's subjective." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T02:49:34.853", "Id": "2773", "Score": "0", "body": "@Brian: I disagree with that tag -- this particular example is using C# as the language, but I'm asking about any language where `for` exists in the form taken from C." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T10:49:34.307", "Id": "3093", "Score": "0", "body": "IMHO you was posted this correctly to Programmers. ;p As you noted the example code isn't really meant to be reviewed, but just an example." } ]
[ { "body": "<p>I would argue against changing it. This seems to be exactly what for-loops were invented for. Also, why not put the initialization in the for loop?</p>\n\n<p>I would have also preferred</p>\n\n<pre><code>for(int idx=0; idx &lt; endIdx; ++idx, --endIdx) {\n</code></pre>\n\n<p>if only so that I don't have to scan up and down the page looking for the initialization of <code>idx</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T16:19:31.863", "Id": "2754", "Score": "3", "body": "Because this was on a whiteboard, and I was running out of space :P (And because that makes the FOR line long)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T16:21:19.803", "Id": "2755", "Score": "1", "body": "@Billy ONeal: Ok, whiteboard space constraints are fair ;)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T04:10:57.450", "Id": "2817", "Score": "5", "body": "Why not: `for (int idx = 0, endIdx = s.Length-1; idx < endIdx; ++idx, --endIdx) { ... }`? That way you get **all** the loop controls in the loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T11:08:25.973", "Id": "3094", "Score": "1", "body": "@Billy ONeal: I prefer having all loop counters/conditionals inside the for-loop, and if that makes the for-loop line too long, I'd break them into three lines." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T16:18:17.417", "Id": "1587", "ParentId": "1586", "Score": "14" } }, { "body": "<p>I personally would go with the <code>while</code> loop. I'm not against <code>for</code> loops at all, but yours is different than most, and caused me to reread to catch up. I am used to seeing, as I imagine most people are, <code>for</code> loops with an initializer and only one statement to iterate:</p>\n\n<p><code>for (int i = startValue; i &lt; endValue; i++) {...}</code></p>\n\n<p>To me, you're already initializing outside of the loop statement (as you said, you prefer to keep things in the loop statement), so you may as well use a <code>while</code> so people expect initialization to be elsewhere. Same with using this construct:</p>\n\n<p><code>++idx, --endIdx</code> </p>\n\n<p>I'm not <em>expecting</em> this sort of thing in a <code>for</code> loop. I would be more aware something like this might happen in a <code>while</code> loop.</p>\n\n<p>Summary: I personally think the <code>while</code> loop is more readable, because I have certain expectations for <code>for</code> loops. If this is true of the other people who will read/maintain the code, I don't know.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T20:06:54.453", "Id": "2758", "Score": "0", "body": "Do you have rationale other than \"this is the one I like\"?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T21:19:40.950", "Id": "2761", "Score": "1", "body": "I feel like it adheres better to user expectations, where \"users\" in this case are other people who will work with the code. Now yes, I base that on what I personally expect, as detailed in my answer. The `for` loop you have was more difficult for me to read, because it did things I don't normally see in `for` loops, but more frequently see in `while` loops. So yes, it's pretty subjective, but not just because I fancy `while` loops or have a thing against the word \"for\" or something :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T02:51:41.793", "Id": "2774", "Score": "0", "body": "Okay, that's reasonable. +1." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T20:02:46.787", "Id": "1591", "ParentId": "1586", "Score": "12" } }, { "body": "<p>Personally, I can't really warm up to either version. I guess that to me, reversing a sequence is <em>so</em> obviously a fold, that anything which <em>doesn't</em> implement it as a fold looks just plain weird.</p>\n\n<p>I would have expected to see something much more like this:</p>\n\n<pre><code>public static string Reverse(this string s)\n{\n return s.Aggregate(\"\", (acc, el) =&gt; el + acc);\n}\n</code></pre>\n\n<p>I.e. implemented as a left fold.</p>\n\n<p>After all, reversing any sequence (not just strings) is really just the same as </p>\n\n<pre><code>foldl (flip (:)) []\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T02:40:24.657", "Id": "2769", "Score": "0", "body": "That performs horribly though (in the first case -- you've turned a constant time algorithm into an O(N^2) one, with a memory allocation for the whole string for each character!)). I don't know what `fold1` is. (Nor have I ever heard of the concept)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T02:47:41.873", "Id": "2770", "Score": "0", "body": "More to the point, this doesn't answer my question -- I'm not asking about this specific implementation of reverse, I'm asking about the general case of embedding logic more complicated than \"n + 1\" in a for loop condition." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T02:48:08.877", "Id": "2771", "Score": "0", "body": "Err.. where I said \"constant time\" above I meant \"linear time\"." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T22:12:00.257", "Id": "2793", "Score": "0", "body": "In a functional language, a fold or more explicit recursion, would often replace a loop. Single-Linked-Lists are also very common in functional languages, where a string would be a linked-list of char. And actually, a properly done functional algorithm would still be O(n), since you'd go over the list, building a new list in reverse order as you went." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T22:14:52.733", "Id": "2794", "Score": "0", "body": "Such as: `reverse first :: rest = (reverse rest) :: first` And pretend I added the case for empty list. `::` is the \"cons\" operator. Check out F# for functional programming in .NET." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T22:19:15.210", "Id": "2795", "Score": "0", "body": "Also, technically, the loop example is still faster because you're performing an in-place swap. So the mutable loop code take n/2 time while the recursion takes n time. There may be a clever way to do it functionally that I'm not aware of that evens it up." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T18:57:27.650", "Id": "2880", "Score": "0", "body": "@CodexArcanum: The linked list solution is still O(n^2), because to do the append the list must be transversed to find the last element (unless you're keeping around a pointer to the last element, which this implementation doesn't seem to do). Linked list is a horrendously bad data structure in any case -- I still wonder why a better compromise like C++'s `deque` isn't a common primitive available in more languages.." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T01:56:32.910", "Id": "1594", "ParentId": "1586", "Score": "0" } }, { "body": "<p>I honestly don't think it matters. For a function this simple, I can think of several similar implementations:</p>\n\n<ul>\n<li>Have an index to the front and to the back in a for loop</li>\n<li>Have an index to the front and to the back in a while loop</li>\n<li>Have a single index, and calculate the offset from the end of the loop each time round the loop</li>\n<li>All of the possibilities above, but increment/decrement a pointer to char, rather than an index into an array (at least in C, can you do this in C# ?)</li>\n</ul>\n\n<p>And probably several more. I think that the right answer is whatever seems most readable (unless it's EGREGIOUSLY inefficient), and if you think it may be called in an inner loop leave a comment saying (a) don't do that and (b) suggest what changes you'd think about making then, but you'd most likely need to be sure, the function is too simple for your common sense to be much guide about what's faster.</p>\n\n<p>I agree your answer has the potential problems the interviewer described, and his has the potential problems you described. I think either is more than fine, so long as you can see the potential issues, I don't think they can be improved into a single \"best\" answer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T16:49:15.137", "Id": "2783", "Score": "0", "body": "\"can you do this in C#\" <-- Not really. It's possible but you'll have to go into \"unsafe code\" -- which means your code won't run several places, i.e. Silverlight, because unsafe code requires full trust. Again though, **I'm not talking about this specific case of `reverse`**. I'm talking about the general case -- this is just the algorithm I happened to be talking about when the general question came up." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T11:40:06.697", "Id": "1603", "ParentId": "1586", "Score": "0" } }, { "body": "<p>I was going to write this as a comment but got out of space, so...</p>\n\n<p>In general lines, I agree with Peter Leppert; I think the while is more idiomatic here.</p>\n\n<p>Of course C for syntax allows you to use the first case, and in simple functions I don't think it really matters, but then, C allows you implementing mostly any function in the header of a for loop with an empty body, and that doesn't makes it a good idea ;-). </p>\n\n<p>Your for header was</p>\n\n<pre><code>for(; idx &lt; endIdx; ++idx, --endIdx)\n</code></pre>\n\n<p>just because you got out of space in the whiteboard. In a computer it would have been more like the following:</p>\n\n<pre><code>for(int idx = 0, endIdx = s.Length - 1; idx &lt; endIdx; ++idx, --endIdx)\n</code></pre>\n\n<p>Ok, fair enough. Now you find you need another control variable for a new functionality: </p>\n\n<pre><code>for(int idx = 0, endIdx = s.Length - 1, otherVar = FunctionCall(param1, param2); idx &lt; endIdx &amp;&amp; otherVar &lt; AnotherFunctionCall(param1); ++idx, --endIdx, otherVar += 5)\n</code></pre>\n\n<p>What now, uh? It gets ugly very quickly. This doesn't scale up, so, where do you put the line? Character limit in header? Only two control variables? </p>\n\n<p>That's why I would only do the classic for loop:</p>\n\n<pre><code>for (int i = 0; i &lt; maxI; i++)\n{\n ...\n}\n</code></pre>\n\n<p>and use a while for everything else.</p>\n\n<p>Anyway, with that question the interviewer was probably trying to see how you think rather than testing your programming capabilities.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T19:00:49.767", "Id": "2881", "Score": "0", "body": "But if you limit the for loop to that only, then there's little reason for it to exist at all -- `foreach` handles that. (i.e. `foreach(var idx = Enumerable.Range(0, maxI)) { ... }`) (That syntax isn't 100% correct but it gets the idea)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T20:45:02.510", "Id": "3071", "Score": "0", "body": "@Billy Oneal: Sorry, you're right, I was thinking in C++ where we still don't have a for each, so I didn't use the best example. However, it still applies if you don't want to process every item in the list, or need to do so in specific order (i.e. traverse a list backwards)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T20:31:12.530", "Id": "60911", "Score": "0", "body": "@BillyONeal, @JaimePardos is probably correct that the interviewer just wanted to see your thought process on tackling this problem. IMHO, I like the `for` for the simple reason that it's easier to read and you don't have to worry about setting the start and end index for each loop." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T00:46:34.827", "Id": "1628", "ParentId": "1586", "Score": "0" } }, { "body": "<p>That code looks pretty complex for the trivial task it does.</p>\n\n<ol>\n<li>No need to convert the string to a char array. By not calling ToCharArray() <a href=\"http://weblogs.asp.net/justin_rogers/archive/2004/06/10/153175.aspx\">you get rid of an extra copy of data</a>.</li>\n<li>Poorly named variables IMHO. (The convention for index is <code>i</code>.)</li>\n<li>No need to substract from the end index. (which I prefer to call <code>length</code> as a convention)</li>\n<li>You shouldn't call <code>ToString()</code>, but use the constructor of string. Your code outputs the typename instead of the reversed string.</li>\n</ol>\n\n<p>Altogether:</p>\n\n<pre><code>public string Reverse( string s )\n{\n int length = s.Length;\n char[] reversed = new char[ length ];\n\n for ( int i = 0; i &lt; length; ++i )\n {\n reversed[ i ] = s[ length - 1 - i ];\n }\n\n return new string( reversed );\n}\n</code></pre>\n\n<p>And of course, the proper solution would be using <a href=\"http://msdn.microsoft.com/en-us/library/bb358497.aspx\"><code>Reverse()</code></a> from <code>IEnumerable</code>. But that wasn't part of the question perhaps.</p>\n\n<pre><code>return new string( s.Reverse().ToArray() );\n</code></pre>\n\n<hr>\n\n<p>An interesting article which compares different reverse string implementations <a href=\"http://weblogs.asp.net/justin_rogers/archive/2004/06/10/153175.aspx\">can be found here</a>.</p>\n\n<p>It's a pity you got referred to here from Programmers.SE, IMHO you do touch some points which are perfectly discussable on Programmers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T04:58:10.580", "Id": "3003", "Score": "0", "body": "1. Yes there is. Just because you did it a different way doesn't mean you didn't do it. 2. I strongly disagree. Single letter variable names make me cringe. The counter is primarily an array index, and it's name reflects that. 3. Okay, I agree that's nicer. 4. Why does it matter? 5. **READ THE QUESTION. I'm not talking about this specific implementation of `Reverse`. I'm talking about use of logic in `for` loops. Reverse is the algorithm I happened to be using as an example when the question came up, but critiquing how I threw this together in 30 seconds is not the point.**" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T05:25:59.443", "Id": "3004", "Score": "4", "body": "1. By not calling `ToCharArray()` you [get rid of an extra copy of data](http://weblogs.asp.net/justin_rogers/archive/2004/06/10/153175.aspx). 2. The name of a variable should be only as important as the scope it is in. The for loop indexer is a perfect example of a small scope. If you don't like `i`, I'd still prefer `index` over `idx`, but I know of practically noone who doesn't use `i`. 4. Your code outputs the typename instead of the reversed string. 5. When you post on Code Review, expect a code review. If you want to discuss a general topic go to Programmers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T18:07:24.663", "Id": "3018", "Score": "2", "body": "I didn't post to code review. I posted to programmers. It got moved here. (Sorry for shouting last night -- I was half asleep and not thinking straight.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T01:44:43.777", "Id": "60944", "Score": "0", "body": "This answer is buggy. It does not accomplish the required task: to reverse the String. What it does do, is reverse the string twice, leaving the string in its original state. The condition of the loop should be something like `i < (length / 2)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T11:55:44.597", "Id": "60968", "Score": "0", "body": "@rolfl? Huh? No it doesn't? `length / 2` only reverses half of the string. Perhaps you are confused because I mention the `return new string( s.Reverse().ToArray() );` in the end? This is a separate solution from the one above, reusing already built-in framework code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T12:16:45.490", "Id": "60971", "Score": "0", "body": "@StevenJeuris - For a string of lenght 4, you start at i=0, and you swap `reversed[0]` and `reversed[3]`, then `reversed[1]` and `reversed[2]`, then `reversed[2]` and `reversed[1]` and finally `reversed[3]` and `reversed[0]`. You have double-reversed it, hence made no change..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T13:11:53.183", "Id": "60977", "Score": "2", "body": "Sorry @rolfl but this answer is not wrong. Once an index is set in the `reversed` array it is not modified again. The for-loop reads from `s` and writes to `reversed`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T13:12:00.800", "Id": "60978", "Score": "1", "body": "@rolfl I don't swap anything (as in the OPs solution). I iterate across all chars in reverse order, for simplicity reasons. Performance wise one might be better than the other, but I'd need to run into a performance issue prior to refactoring that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T13:13:13.467", "Id": "60979", "Score": "0", "body": "Ahh... thanks all.. down-vote removed. In my head I had it that you were reversing the chars 'in place', but they are coming from different arrays." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T13:25:14.973", "Id": "60980", "Score": "0", "body": "Agree with 2. Really poor variable names all through from OP." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-07T10:44:58.927", "Id": "1713", "ParentId": "1586", "Score": "11" } }, { "body": "<p>The primary consideration when deciding what to put in the for-loop header should be whether the for-loop header conveys the structure of the loop. The three elements (initializer; condition; update) should form a coherent story.</p>\n\n<p>I would express your function like this:</p>\n\n<pre><code>public string Reverse(string s)\n{\n char[] arr = s.ToCharArray();\n for (int i = 0, j = s.Length - 1; i &lt; j; ++i, --j)\n {\n char swap = arr[i];\n arr[i] = arr[j];\n arr[j] = swap;\n }\n return arr.ToString();\n}\n</code></pre>\n\n<p>From just the for-loop header, a reasonably experienced programmer can recognize the idiom for stepping two array indices until they meet in the middle. By convention, <code>i</code> and <code>j</code> are array indices; you don't need the <code>…Idx</code> Hungarian suffix.</p>\n\n<p>In comparison, the interviewer's proposal looks unstructured. I feel like I have to mentally decompile it back into the for-loop above to understand what is going on.</p>\n\n<p>I've also renamed <code>temp</code> to <code>swap</code> as a silent \"comment\".</p>\n\n<hr>\n\n<p>You might be wondering, to what extreme can you pack logic into the for-loop header? In practice, I've never seen more a good for-loop header that involved more than two variables. The probable explanation is that the condition usually involves a binary comparison operator. A third variable would therefore usually be \"off-topic\" for the header.</p>\n\n<p>Two other guidelines you might want to use are:</p>\n\n<ul>\n<li>If you can fill in all three parts of the header (initializer; condition; update), then a for-loop is probably appropriate.</li>\n<li>If the loop body surreptitiously updates the iteration variable, such that the header tells a misleading or incomplete story, then the iteration should probably <em>not</em> be done using a for-loop.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T21:44:59.180", "Id": "36998", "ParentId": "1586", "Score": "3" } }, { "body": "<p>Although both for and while are loops and both will work but as a general guideline, for loop is better suited in this case because</p>\n\n<ul>\n<li>When we know the number of iterations in advance, we should use for loop as it allows initiation, condition and increment to be done in one line.</li>\n<li>Index variable (idx in this case), is more appropiately scoped, why should we increase the scope of idx when this is meant only to be used within the loop.</li>\n<li>Unlike while loop, statements like continue, etc. (if required) can be used without any issues.</li>\n</ul>\n\n<p>While loop should be usually used if we don't know number of iterations in advance.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T22:32:23.600", "Id": "37000", "ParentId": "1586", "Score": "0" } }, { "body": "<p>All things aside, I believe that these two pieces of code function differently. The first is predecrement, the second is post.</p>\n\n<p>I would agree that for loops make this specific application more obfuscated (not by much, but it is certainly less clear). I recommend using for loops primarily for iterating linearly through a collection with the intent of going from some start to an end, where both of these points are known/fixed before the loop starts.</p>\n\n<p>I think that the for loop is a completely valid approach for something like this though. If you find yourself making a for loop and placing an if statement nearly in the beginning of it, then you may want to consider using a while loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T04:51:24.687", "Id": "60949", "Score": "0", "body": "Erm, no, both cases are preincrement." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T00:32:00.700", "Id": "37006", "ParentId": "1586", "Score": "-2" } }, { "body": "<p>I think it's important to go back to the context that this was an interview question. </p>\n\n<p>When I interview people, I try to ask questions that don't have one \"right\" answer - that's more like a trivia test, which is actually fairly useless to me. Instead, I'll ask a question that requires more of an opinion response, watch the candidate, and look for them to apply logical thinking to the problem. </p>\n\n<p>If you can justify that it should be a for loop, and your code is readable, good answer. If you can justify that it should be a while loop, and your code is readable, that's also a good answer. But if you say \"it should be a for loop because that's the right way,\" that's just spewing out dogma and doesn't demonstrate independent thought. It's a less mature answer. Not that it's wrong, but if I'm trying to figure out if you're a starting programmer or an experienced engineer, it's a clue.</p>\n\n<p>By the way, another really good answer is to say \"In my code I'd use Reverse() on the array, because it's already tested.\" An employer generally does not want to pay you to reinvent the wheel, and as an interviewer I'd appreciate the depth of your experience that shows.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T14:45:48.780", "Id": "37045", "ParentId": "1586", "Score": "0" } }, { "body": "<p>@Billy ONeal : I strongly believe that this is a matter of taste. Robert C. Martin states in <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow\">Clean Code</a> that software developers like to use obfuscated code to \"show off\" and I agree with him. I also liked to do that until I started to work on my first complex project and I realized that extra mind mappings are not necessary.</p>\n\n<p>That been said, my option will be to use the <code>while()</code> loop; I think that we can go here with the same principle which is applied to a method: the loop should do one thing and one thing only (personal opinion extrapolated from <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow\">Clean Code</a>). So, if I look at a piece of code after 4 hours of endless debugging, it might feel easier to read (I only formatted the code for easier reading):</p>\n\n<pre><code> //top-down reading per loop\n while (UnswitchedCharactersExist())\n {\n SwitchCharacters(arr, idx, endIdx);\n IncrementStartIndex();\n DecrementEndIndex();\n }\n</code></pre>\n\n<p>than:</p>\n\n<pre><code> //read the initializer, the condition, the code block and go back up for the update\n //after that read the condition, the code block and go back up for the update\n for(; UnswitchedCharactersExist(); IncrementStartIndex(), DecrementEndIndex())\n {\n SwitchCharacters(arr, idx, endIdx); \n }\n</code></pre>\n\n<p>My 2 cents on the subject.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-19T11:38:27.260", "Id": "37734", "ParentId": "1586", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-31T16:13:57.610", "Id": "1586", "Score": "18", "Tags": [ "c#", "strings", "interview-questions", "comparative-review" ], "Title": "Reversing a string" }
1586
<p>I want to write my own version of <code>HttpUtility.ParseQueryString</code>, because it is not included in the .NET Framework Client Profile. My code is pretty straightforward and simple, but I'm looking at the code of <code>HttpUtility.ParseQueryString</code> with Reflector, and is about 200 lines including the code of the called methods. </p> <p>I don't want to just steal the code specially because there are parts that I have no idea what they are for. Is my code OK or am I missing something (I don't care about performance here)?</p> <pre><code>Dictionary&lt;string, string&gt; GetParams(string str) { int questionMarkIndex = str.IndexOf('?'); if (questionMarkIndex != -1) { string paramsString = str.Substring(questionMarkIndex + 1); string[] keyValues = paramsString.Split(new char[] { '&amp;' }, StringSplitOptions.RemoveEmptyEntries); Dictionary&lt;string, string&gt; result = new Dictionary&lt;string, string&gt;(); foreach (string keyValue in keyValues) { string[] splitKeyValue = keyValue.Split(new char[] { '=' }); if (splitKeyValue.Length == 2 &amp;&amp; !string.IsNullOrWhiteSpace(splitKeyValue[0])) { string unencodedKey = Uri.UnescapeDataString(splitKeyValue[0]); string unencodedValue = Uri.UnescapeDataString(splitKeyValue[1]); result[unencodedKey] = unencodedValue; } } return result; } else return new Dictionary&lt;string, string&gt;(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T20:24:32.597", "Id": "2759", "Score": "0", "body": "Should I assume my code is OK from not getting any answer?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-02T06:22:11.750", "Id": "2798", "Score": "0", "body": "Good catch with with the + symbol, I've run into that same issue in the Java libraries: I wonder if that can be considered a bug in `Uri.UnescapeDataString`. I had fun coming up with a regex solution for this, glad you liked it. Certainly go with what is easier for you to read and maintain. But I also encourage you to delve into regex land: looking back on string processing code I've written in the past, I can see how much time and effort I could have saved myself. Plus it's fun!" } ]
[ { "body": "<p>I figure <code>HttpUtility.ParseQueryString</code> is just incredibly robust, and you likely are missing something. But I can't spot anything in particular and it's likely that without deep research you won't be able to cover all the cases which were clearly studied and thought out in Microsoft's implementation. However, I think your implementation can be refactored to be easier to read and maintain by using regular expressions instead of brute force string splitting. I present the following in F# which hopefully you can translate easily enough to C# (the key functionality relies on the same .NET libraries available in both languages). I'm still new to regex writing myself, so I'm sure it's not as robust as it could be, but it seems to work well for all the typical cases I tested (generally assumes query string is not malformed, allows no query string, allows empty values but not empty keys, accounts for possible # delimiter after query string part):</p>\n\n<pre><code>open System\nopen System.Text.RegularExpressions\nlet uriParams uri =\n let matches = Regex.Matches(uri, @\"[\\?&amp;](([^&amp;=]+)=([^&amp;=#]*))\", RegexOptions.Compiled)\n seq { //create a sequence of key, value tuples extracted from the matches\n for m in matches do \n yield Uri.UnescapeDataString(m.Groups.[2].Value), Uri.UnescapeDataString(m.Groups.[3].Value)\n } |&gt; dict // convert the sequence of key, value tuples into an immutable IDictionary\n</code></pre>\n\n<p><strong>Update</strong></p>\n\n<p>I went ahead and translated to C#:</p>\n\n<pre><code>using System;\nusing System.Text.RegularExpressions;\nusing System.Collections.Generic;\n\n...\n\nstatic Dictionary&lt;string, string&gt; GetParams(string uri)\n{\n var matches = Regex.Matches(uri, @\"[\\?&amp;](([^&amp;=]+)=([^&amp;=#]*))\", RegexOptions.Compiled);\n var keyValues = new Dictionary&lt;string, string&gt;(matches.Count);\n foreach (Match m in matches)\n keyValues.Add(Uri.UnescapeDataString(m.Groups[2].Value), Uri.UnescapeDataString(m.Groups[3].Value));\n\n return keyValues;\n}\n</code></pre>\n\n<p><strong>Update 2</strong></p>\n\n<p>Here's a more functional C# version:</p>\n\n<pre><code>using System;\nusing System.Text.RegularExpressions;\nusing System.Collections.Generic;\nusing System.Linq;\n\n...\n\nstatic Dictionary&lt;string, string&gt; GetParams(string uri)\n{\n var matches = Regex.Matches(uri, @\"[\\?&amp;](([^&amp;=]+)=([^&amp;=#]*))\", RegexOptions.Compiled);\n return matches.Cast&lt;Match&gt;().ToDictionary(\n m =&gt; Uri.UnescapeDataString(m.Groups[2].Value),\n m =&gt; Uri.UnescapeDataString(m.Groups[3].Value)\n );\n}\n</code></pre>\n\n<p><strong>Edit</strong></p>\n\n<p>I updated the regex to address the very important consideration of the # delimiter that @Visionary pointed out. That is probably the biggest thing missing from your own implementation functionality-wise. Also, here is a list of some cases I tested (using the F# version):</p>\n\n<pre><code>uriParams \"http://www.foo.com\" // []\nuriParams \"http://www.foo.com?\" // []\nuriParams \"http://www.foo.com?q=\" // [(\"q\",\"\")]\nuriParams \"http://www.foo.com?q=search&amp;doit=no\" // [(\"q\",\"search\"), (\"doit\",\"no\")]\nuriParams \"http://www.foo.com?q=search&amp;doit=no&amp;go=further\" // [(\"q\",\"search\"), (\"doit\",\"no\"), (\"go\",\"further\")]\nuriParams \"http://www.foo.com?q=&amp;doit=no\" // [(\"q\",\"\"), (\"doit\",\"no\")]\nuriParams \"http://www.foo.com?q=&amp;doit=no&amp;=&amp;test&amp;good=true\" //[(\"q\",\"\"), (\"doit\",\"no\"), (\"good\",\"true\")]\nuriParams \"http://www.foo.com?q=search&amp;doit=no#validationError\" // [(\"q\",\"search\"), (\"doit\",\"no\")]\nuriParams \"http://www.foo.com?q=search&amp;doit=no#validationError=true\" // [(\"q\",\"search\"), (\"doit\",\"no\")]\nuriParams \"http://www.foo.com?q=se%20arch&amp;do%20it=no\" // [(\"q\",\"se arch\"), (\"do it\",\"no\")]\nuriParams \"http://www.foo.com?q=search&amp;doit=#validationError\" // [(\"q\",\"search\"), (\"doit\",\"\")]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T04:34:14.747", "Id": "2777", "Score": "0", "body": "Nice implementation. But don't forget RFC3986: # may also be a delimiter http://tools.ietf.org/html/rfc3986" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-27T19:27:57.390", "Id": "248850", "Score": "1", "body": "Thanks, i joined this community just to thank you! The Uri parse query string was not working for me. You can always depend on RegEx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-30T01:14:29.637", "Id": "249349", "Score": "0", "body": "Awesome @Radmation, glad to help!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T20:43:24.860", "Id": "1592", "ParentId": "1588", "Score": "15" } } ]
{ "AcceptedAnswerId": "1592", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-31T18:12:19.840", "Id": "1588", "Score": "12", "Tags": [ "c#", "url" ], "Title": "Get params from a URL" }
1588
<p>Given the following task from <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-14.html" rel="nofollow">SICP</a></p> <blockquote> <p><strong>Exercise 2.1</strong></p> <p>Define a better version of make-rat that handles both positive and negative arguments. Make-rat should normalize the sign so that if the rational number is positive, both the numerator and denominator are positive, and if the rational number is negative, only the numerator is negative.</p> </blockquote> <p>And these prerequisite functions:</p> <pre><code>(define (gcd a b) (if (= b 0) a (gcd b (remainder a b)))) (define (numer a) (car a)) (define (denom a) (cdr a)) (define (print-rat a) (newline) (display (numer a)) (display "/") (display (denom a))) (define (add-rat a b) (make-rat (+ (* (numer a) (denom b)) (* (numer b) (denom a))) (* (denom a) (denom b)))) (define (sub-rat a b) (make-rat (- (* (numer a) (denom b)) (* (numer b) (denom a))) (* (denom a) (denom b)))) (define (mul-rat a b) (make-rat (* (numer a) (numer b)) (* (denom a) (denom b)))) (define (div-rat a b) (make-rat (* (numer a) (denom b)) (* (numer b) (denom a)))) </code></pre> <p>I wrote this version of (make-rat ... ). What do you think?</p> <pre><code>(define (make-rat n d) (define (sign n d) (if (&gt; (* n d) 0) + -)) (let* ((abs-n (abs n)) (abs-d (abs d)) (div (gcd abs-n abs-d))) (cons ((sign n d) (/ abs-n div)) (/ abs-d div)))) </code></pre>
[]
[ { "body": "<p>To normalize a fraction, one needs to do two things:</p>\n\n<ol>\n<li>fix the signs of numerator and denominator; and</li>\n<li>reduce them to their lowest terms.</li>\n</ol>\n\n<p>Your implementation does these two things just fine. However, there is an easier way. To do (1), simply negate both numerator and denominator if the denominator is negative. To do (2), divide by the greatest common divisor.</p>\n\n<p>One could combine the two steps above. Divide the numerator and denominator by the greatest common divisor with its sign fixed to be the same as the denominator's sign. Implementation follows:</p>\n\n<pre><code>(define (make-rat n d)\n (let\n ((div ((if (&lt; d 0) - +) (abs (gcd n d)))))\n (cons (/ n div) (/ d div))))\n</code></pre>\n\n<p>If <code>gcd</code> always returns a positive number (which your implementation does not), you may remove the call to <code>abs</code> above.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-02T03:08:13.913", "Id": "1620", "ParentId": "1596", "Score": "2" } } ]
{ "AcceptedAnswerId": "1620", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-01T04:39:54.070", "Id": "1596", "Score": "2", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Make a version of make-rat that handles positive and negative arguments" }
1596
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-14.html" rel="nofollow">SICP</a>:</p> <blockquote> <p><strong>Exercise 2.2</strong></p> <p>Consider the problem of representing line segments in a plane. Each segment is represented as a pair of points: a starting point and an ending point. Define a constructor make-segment and selectors start-segment and end-segment that define the representation of segments in terms of points. Furthermore, a point can be represented as a pair of numbers: the x coordinate and the y coordinate. Accordingly, specify a constructor make-point and selectors x-point and y-point that define this representation. Finally, using your selectors and constructors, define a procedure midpoint-segment that takes a line segment as argument and returns its midpoint (the point whose coordinates are the average of the coordinates of the endpoints). To try your procedures, you'll need a way to print points:</p> <pre><code>(define (print-point p) (newline) (display "(") (display (x-point p)) (display ",") (display (y-point p)) (display ")")) </code></pre> </blockquote> <p>I wrote the following solution:</p> <pre><code>(define (make-segment a b) (cons a b)) (define (start-segment l) (car l)) (define (end-segment l) (cdr l)) (define (make-point x y) (cons x y)) (define (x-point p) (car p)) (define (y-point p) (cdr p)) (define (sum . l) (if (zero? (length l)) 0 (+ (car l) (apply sum (cdr l))))) (define (average . l) (/ (apply sum l) (length l))) (define (midpoint seg) (make-point (average (x-point (start-segment seg)) (x-point (end-segment seg))) (average (y-point (start-segment seg)) (y-point (end-segment seg))))) (define (print-point p) (newline) (display "(") (display (x-point p)) (display ",") (display (y-point p)) (display ")")) (define seg-1 (make-segment (make-point 3 4) (make-point 8 10))) (print-point (midpoint seg-1)) </code></pre> <p>What do you think?</p>
[]
[ { "body": "<p>Your definitions of <code>make-segment</code> and <code>make-point</code> can be simply bound to <code>cons</code>; you may do the same for accessors.</p>\n\n<pre><code>(define make-segment cons)\n(define start-segment car)\n(define end-segment cdr)\n\n(define make-point cons)\n(define x-point car)\n(define y-point cdr)\n</code></pre>\n\n<p>Your definition of <code>sum</code> is similar to how <code>+</code> works. You may use <code>+</code> instead in your definition of <code>average</code>.</p>\n\n<pre><code>(define (average . l) (/ (apply + l) (length l)))\n</code></pre>\n\n<p>Notice the repetition of code in your definition of <code>midpoint</code>--you create a new point out of the averages of each coordinate of the two end-points that describe the line segment. You may abstract out the calculation of averages either by writing your own helper function or by using the built-in <code>map</code> function, like so:</p>\n\n<pre><code>(define point-&gt;coordinate-accessors (list x-point y-point))\n(define (midpoint seg)\n (apply make-point (map (lambda (point-&gt;coordinate)\n (average (point-&gt;coordinate (start-segment seg))\n (point-&gt;coordinate (end-segment seg))))\n point-&gt;coordinate-accessors)))\n</code></pre>\n\n<p>This definition is general enough to handle midpoint calculation in as many dimensions as handled by <code>make-point</code> and <code>point-&gt;coordinate-accessors</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T19:54:43.227", "Id": "1614", "ParentId": "1598", "Score": "2" } } ]
{ "AcceptedAnswerId": "1614", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-01T04:58:39.810", "Id": "1598", "Score": "2", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Midpoint of a segment" }
1598
<p>I had a job to remove all kinds of comments from the Lua file. I tried to find a usable Python script to this on the net, but Google did not help. </p> <p>Therefore, I made one. This script recognizes all types of comments such as single and multi-Line comments.</p> <p>I would welcome your opinion.</p> <pre><code># written in Python 3.2 import codecs import re inputFilePath = 'testfile.lua' inputLuaFile = codecs.open( inputFilePath, 'r', encoding = 'utf-8-sig' ) inputLuaFileDataList = inputLuaFile.read().split( "\r\n" ) inputLuaFile.close() outputFilePath = 'testfile_out.lua' outputLuaFile = codecs.open( outputFilePath, 'w', encoding = 'utf-8' ) outputLuaFile.write( codecs.BOM_UTF8.decode( "utf-8" ) ) def create_compile( patterns ): compStr = '|'.join( '(?P&lt;%s&gt;%s)' % pair for pair in patterns ) regexp = re.compile( compStr ) return regexp comRegexpPatt = [( "oneLineS", r"--[^\[\]]*?$" ), ( "oneLine", r"--(?!(-|\[|\]))[^\[\]]*?$" ), ( "oneLineBlock", r"(?&lt;!-)(--\[\[.*?\]\])" ), ( "blockS", r"(?&lt;!-)--(?=(\[\[)).*?$" ), ( "blockE", r".*?\]\]" ), ( "offBlockS", r"---+\[\[.*?$" ), ( "offBlockE", r".*?--\]\]" ), ] comRegexp = create_compile( comRegexpPatt ) comBlockState = False for i in inputLuaFileDataList: res = comRegexp.search( i ) if res: typ = res.lastgroup if comBlockState: if typ == "blockE": comBlockState = False i = res.re.sub( "", i ) else: i = "" else: if typ == "blockS": comBlockState = True i = res.re.sub( "", i ) else: comBlockState = False i = res.re.sub( "", i ) elif comBlockState: i = "" if not i == "": outputLuaFile.write( "{}\n".format( i ) ) </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:46:27.847", "Id": "2861", "Score": "0", "body": "Link to a site with comment examples is missing." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:46:58.877", "Id": "2862", "Score": "1", "body": "Any reason why you have to do this in Python? There are several Lua parsers in Lua." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:48:56.643", "Id": "2863", "Score": "1", "body": "Closing Lua comment symbol does not have to have `--` attached. `--[[ ]]` is perfectly valid" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:51:14.907", "Id": "2864", "Score": "0", "body": "Maybe I missed it, but I think that you do not support for `--[=[ ]=]` \"long bracket\" comments, which may contain any number of `=` as long as they are balanced. See manual: http://www.lua.org/manual/5.1/manual.html#2.1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-01T11:47:55.020", "Id": "4285", "Score": "0", "body": "I agree with Winston, using regexes for parsing a non-trivial programming language is prone to fail, unless using it on a very strict set of files of regular syntax (proprietary code)... At the very least, context is missing, nested comments aren't handled, you don't seem to match comments like -- [huhu] and so on." } ]
[ { "body": "<p>Firstly, I think you have some subtle bugs. </p>\n\n<ul>\n<li>What if -- appears inside a string?\nIn that case it should not be a\ncomment.</li>\n<li>What if someone ends a block and starts another one on the same line: --]] --[[</li>\n<li>You split on '\\r\\n', if you run this on a linux system you won't have those line seperators</li>\n</ul>\n\n<p>Secondly, some your variable names could use help. </p>\n\n<ul>\n<li>The python style guide recommonds\nunderscore_style not camelCase for\nlocal variable names.</li>\n<li>You use some abbreviations in your names, I don't think that's a good idea. e.g. res or comRegexPatt</li>\n<li>You have an i, the name of which gives very little hint what it is doing</li>\n</ul>\n\n<p>Your regular expressions look convoluted. I think this a symptom of the fact that the problem is not best solved by a regular expression. This will be even more so if you fix the string problem. </p>\n\n<p>The way I'd solve this problem: I'd write a class CodeText which holds the actual code in question and then write code like this:</p>\n\n<pre><code>def handle_code(code_text):\n while code_text.text_remaining:\n if code_text.matches('--'):\n handle_comment(code_text)\n elif code_text.matches('\"'):\n handle_string(code_text)\n else:\n code_text.accept()\n\ndef handle_string(code_text):\n while not code_text.matches('\"'):\n code_text.accept()\n\ndef handle_comment(code_text):\n if code_text.matches('[['):\n handle_block_comment(code_text)\n else:\n while not code_text.matches('\\n'):\n code_text.reject()\n\n def handle_comment_block(code_text):\n while not code_text.match(\"--]]\"):\n code_text.reject() \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T14:02:43.780", "Id": "1606", "ParentId": "1601", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-01T09:43:43.037", "Id": "1601", "Score": "4", "Tags": [ "python" ], "Title": "Lua comment remover" }
1601
<p>I am new to using classes heavily, and was wondering if going so far as to create a class specifically for templates was going to far. Here is a simplified version of my class template. Yes, I know I the use of <code>unset</code> is not necessary, but I like it there so don't give me any grief for it.</p> <pre><code>class template{ private $templateString = ""; private $templatePlaceholderStrings = array(); private $templatePlaceholderValueStrings = array(); function fillTemplateString($string){ $this-&gt;templateString = $string; unset($string); } function fillTemplatePlaceholderStrings($array){ $this-&gt;templatePlaceholderStrings = $array; unset($array); } function filltemplatePlaceholderValueStrings($array){ $this-&gt;templatePlaceholderValueStrings = $arrray; unset($array); } function buildTemplate(){ return preg_replace($this-&gt;templatePlaceholderStrings, $this-&gt;templatePlaceholderValueStrings, $this-&gt;templateString); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-02T01:29:06.547", "Id": "2797", "Score": "1", "body": "Could you clarify the usage of this class? It looks to me like a base class to be extended." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T18:00:16.933", "Id": "2916", "Score": "0", "body": "I could bet i saw this class somewhere... I can't just remember where." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T09:11:06.350", "Id": "3005", "Score": "0", "body": "@Charlie Pigerelli: http://stackoverflow.com/questions/5513258/php-is-creating-a-class-for-templates-to-much" } ]
[ { "body": "<p>Philosophically I would try to use built-in classes as much as possible, and this seems like the beginnings of the <a href=\"http://www.php.net/manual/en/class.messageformatter.php\" rel=\"nofollow\">MessageFormatter</a> class. </p>\n\n<p>As a side note, you seem to have a typo:</p>\n\n<pre><code>function filltemplatePlaceholderValueStrings($array){\n $this-&gt;templatePlaceholderValueStrings = $arrray;\n unset($array);\n}\n</code></pre>\n\n<p>(Taking an argument of 2 r's and setting a variable of three r's ... not sure if that was an error in your code, or an error in pasting it in here, but thought I should point it out).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T13:23:29.820", "Id": "1633", "ParentId": "1605", "Score": "0" } }, { "body": "<p>This definitely wouldn't be going too far. Any business logic that your program has to capture is best kept in a class. Preferably, the class would have automated tests running against it as well to ensure that it is functioning properly.</p>\n\n<p>In your example, the class isn't doing anything drastically different than what the preg_replace method does itself. Rather than simply duplicating the built-in functionality of this method, I would suggest trying to think of what business goal you are trying to achieve and create methods that more closely mirror it.</p>\n\n<pre><code>class template {\n private $_templateText;\n\n // Initialize the template with this method, as an instance of \n // template doesn't make much sense without some text.\n public static function factory($templateText) {\n $template = new template();\n $template-&gt;_templateText = $templateText;\n\n return $template;\n }\n\n // This can be called as many times as needed. Alternatively, you could add a \n // method that would take two arrays, with the idea that the two array's keys\n // are coupled and paired off. If you choose to couple the two arrays, I would\n // recommend avoiding passing them in to two different methods. Make the coupling\n // as obvious as possible by passing them in to the same method.\n public function replacePlaceholderTextWithString($placeholderText, $string) {\n // ...\n }\n\n // This could have some additional error handling code that would verify that\n // all placeholder text has been replaced and throw an exception if it hasn't.\n // Otherwise, it would simply format the template text based on what had\n // previously been passed in to replacePlaceholderTextWithString(...)\n public function getFormattedTemplateText() {\n // ...\n }\n}\n</code></pre>\n\n<p>Lastly, I would add that a big advantage to using your own class for this is that you are able to change how you would like to implement this functionality in the future. You could change from using preg_replace to using the MessageFormatter, or any number of other solutions. It adds a great deal of flexibility and provides you the opportunity to put automated tests around it that can quickly notify you when it no longer works as expected.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T18:04:25.637", "Id": "2917", "Score": "0", "body": "`andMostOfAllTryToAvoidSuchFunctionsNamePlease()`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-04T12:48:31.420", "Id": "1641", "ParentId": "1605", "Score": "2" } }, { "body": "<p>As a suggestion for a personal exercise, consider implementing this without using any of PHP's object oriented features. Then compare the two solutions side by side.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T02:09:22.333", "Id": "1796", "ParentId": "1605", "Score": "-1" } } ]
{ "AcceptedAnswerId": "1641", "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T13:00:09.917", "Id": "1605", "Score": "3", "Tags": [ "php", "classes" ], "Title": "PHP, Is creating a class for templates to much?" }
1605
<p>In <a href="https://stackoverflow.com/questions/5489626/c-f0-vs-perl-f0/5489809#5489809">response</a> to the SO question <em><a href="https://stackoverflow.com/questions/5489626/c-f0-vs-perl-f0">C: f>0 vs Perl: $f>0?</a></em>, the use of overflow to terminate the loop is referred to as "poor programming practice". Paraphrased:</p> <blockquote> <p>Your c code is actually exiting because of poor programming practice. You're relying on <code>fib</code> being a <code>long long int</code>, which has an upper limit of 9.22337204 × 10^18. When you loop around to the 93rd iteration <code>fib</code> becomes 1.22001604 × 10^19, which overflows and becomes negative.</p> </blockquote> <p>Substantially the same code:</p> <pre><code>cat &gt;fib.c &lt;&lt;EOF #include &lt;stdio.h&gt; int main(){ for (long long int temp, i=1, prev=0, fib=1; fib&gt;0 ; i++, temp=fib, fib+=prev, prev=temp) printf("%lli: %lli\n", i, fib); } EOF gcc -std=c99 -ofib fib.c ./fib </code></pre> <p>The code was intended to be a one time "throw-away" program which was evidenced by the use of single letter variable names in the original version. The use of the overflow being indicated by <code>fib</code> becoming negate was used to terminate the loop.</p> <p>Without knowing in advance what the maximum number of iterations the hardware architecture could handle what would be good "programming practice" to terminate the loop knowing that <code>long long int</code> is limited yet desiring as many values as possible? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-08T12:14:24.840", "Id": "108889", "Score": "0", "body": "Use `LLONG_MAX` or `ULLONG_MAX` from `<<limits.h>`." } ]
[ { "body": "<p>Good programming practice is knowing that your loop is going to exit. In your case, the exit condition is <code>fib &lt;= 0</code>. Thinking about the algorithm, is <code>fib</code> ever going to be non-positive?</p>\n\n<p>You want to exit after some sort of condition. For sequences like this you usually terminate the loop after either a fixed number of iterations (i.e. \"generate the first 50 Fibonacci numbers\") or when your values get big enough (i.e. \"generate all Fibonacci numbers smaller than 50000\").</p>\n\n<p>If you really do want to generate an infinite number of values in an infinite sequence, you need to take your variable types into consideration. Obviously you wouldn't use a boolean value, because its range is tiny. Similarly, even <code>long long int</code> isn't enough because it's finitely bounded. If you want to go beyond the range of your variable types, you need to come up with custom variables or find a library that provides that functionality. For C, you would probably use <a href=\"http://gmplib.org/\" rel=\"nofollow\">GMP</a>.</p>\n\n<p>In this case, your loop only exits because of inherent software limitations. It does not give the same results on different platforms, nor would it give the same results for different implementations with different languages (as you saw when you tried to code the same thing in Perl). This would be considered a poor programming practice, as the results are fairly non-deterministic and lead to confusion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T16:09:35.747", "Id": "2782", "Score": "0", "body": "Since the desire was not for a pre-known fixed number of values nor a pre-determined range of results, I have added \"knowing that long long int is limited yet desiring as many values as possible\" for clarification." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T15:55:16.987", "Id": "1609", "ParentId": "1607", "Score": "4" } }, { "body": "<p>Use unsigned rather than signed because once there is overflow the effect is undefined.\nWhereas with unsigned there is no overflow but modulo arithmetic plus it produces an additional value. </p>\n\n<pre><code>cat &gt;fib2.c &lt;&lt;EOF\n// Fibinocci numbers\n#include &lt;stdio.h&gt;\nint main(){\n for (unsigned long long ii=1, fib=1, prev=0, temp;\n fib&gt;=prev; // Wrap indicates max value per implementation\n ii++, temp=fib, fib+=prev, prev=temp)\n printf(\"%llu: %llu\\n\", ii, fib);\n }\nEOF\ngcc -std=c99 -ofib2 fib2.c\n./fib2\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-08T07:48:39.177", "Id": "139209", "Score": "0", "body": "[Relevant explanation](http://stackoverflow.com/q/18195715/1157100)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T17:48:18.587", "Id": "1680", "ParentId": "1607", "Score": "7" } } ]
{ "AcceptedAnswerId": "1680", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-01T14:23:04.167", "Id": "1607", "Score": "7", "Tags": [ "c", "integer", "fibonacci-sequence" ], "Title": "Terminating a C loop when maximum hardware limit reached" }
1607
<p>I am hoping the code is readable as is. I can probably just print the XML using streams but I have other reasons for using the library.</p> <p>Please offer any inputs on how to improve program design/structure.</p> <p>The header file </p> <pre><code>#ifndef GEN_XML #define GEN_XML #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;sstream&gt; typedef std::string stringType; typedef std::vector&lt;stringType&gt; stringVector; typedef std::vector&lt;int&gt; integerVector; class gen_xml { private: int previousTime; int tempTime; public: stringVector text_file; integerVector time_ms; stringVector text_info; public: gen_xml():previousTime(1),tempTime(2) {}; virtual int validate(int argc,char* argv[]); virtual void showInput(int argc,char* argv[]); virtual bool validateFileExtention(stringType fname,stringType ext); virtual int getAbsoluteTime(stringType value); virtual void getData(char* argv[]); virtual stringType toString(int num); virtual void generateXML(stringVector text_file,integerVector time_ms,char* FileName); }; #endif // GEN_XML </code></pre> <p>The CPP file</p> <pre><code>#include "tinyxml.h" #include "tinystr.h" #include "gen_xml.h" using namespace std; int main(int argc,char* argv[]) { gen_xml req; if(req.validate(argc,argv)) { req.getData(argv); req.generateXML(req.text_info,req.time_ms,argv[2]); } cout&lt;&lt;"Done"&lt;&lt;endl; return 0; } void gen_xml::generateXML(stringVector text_file,integerVector time_ms,char* FileName) { TiXmlDeclaration* declaration = new TiXmlDeclaration("1.0", "UTF-8", "no");//Create DTD TiXmlDocument* doc = new TiXmlDocument; doc-&gt;LinkEndChild(declaration); TiXmlElement* msg; TiXmlElement * root = new TiXmlElement( "tags" ); doc-&gt;LinkEndChild( root ); for(int i=0; i&lt;(int)text_file.size(); i++) { TiXmlElement * msgs = new TiXmlElement( "metatag" ); msgs-&gt;SetAttribute("event", "onCuePoint"); msgs-&gt;SetAttribute("overwrite", "true"); root-&gt;LinkEndChild( msgs ); msg = new TiXmlElement( "name" ); msg-&gt;LinkEndChild( new TiXmlText("CuePoint"+toString(i) )); msgs-&gt;LinkEndChild( msg ); msg = new TiXmlElement( "timestamp" ); msg-&gt;LinkEndChild( new TiXmlText(toString((int)time_ms.at(i)))); msgs-&gt;LinkEndChild( msg ); msg= new TiXmlElement( "parameters" ); msgs-&gt;LinkEndChild( msg ); TiXmlElement * _params = new TiXmlElement( "textinfo" ); _params-&gt;LinkEndChild(new TiXmlText( text_info.at(i))); msg-&gt;LinkEndChild( _params ); msg= new TiXmlElement( "type" ); msg-&gt;LinkEndChild( new TiXmlText("navigation")); msgs-&gt;LinkEndChild( msg ); } doc-&gt;SaveFile( FileName ); } string gen_xml::toString(int num) { stringstream abc; string value; abc&lt;&lt;num; value=abc.str(); return value; } int gen_xml::validate(int argc,char* argv[]) { fstream filestr; string temp; bool result; if(argc&gt;3) { cerr&lt;&lt;"Input Arguments Exceeded"&lt;&lt;endl; return 0; } if(validateFileExtention(argv[1],".txt")&amp;&amp;validateFileExtention(argv[2],".xml")) { filestr.open(argv[1]); if (filestr.is_open()) { filestr.close(); result=true; } else { cout &lt;&lt; "Error opening file"; result=false; } } return result; } void gen_xml::getData(char* argv[]) { fstream filestr; string temp; filestr.open(argv[1]); while( getline( filestr, temp )) { text_file.push_back( temp ); } //cout&lt;&lt;(int)text_file.at(0).size()&lt;&lt;endl; //getAbsoluteTime(text_file.at(0).substr(0,12)); for(int i=0; i&lt;(int)text_file.size(); i++) { time_ms.push_back(getAbsoluteTime(text_file.at(i).substr(0,12))); temp=text_file.at(i).substr(13,(int)text_file.at(i).size()-14); text_info.push_back(temp); } filestr.close(); } int gen_xml::getAbsoluteTime(string value) { int hours,minutes,milliseconds; int absTime; (stringstream)value.substr(3,2)&gt;&gt;hours; (stringstream)value.substr(6,2)&gt;&gt;minutes; (stringstream)value.substr(9,3)&gt;&gt;milliseconds; absTime=60*1000*(hours*60+minutes)+ milliseconds; //-- stupid fix for a tool... dont ask why tempTime=absTime/1000; if(previousTime==tempTime) { absTime=(tempTime+1)*1000; } previousTime=tempTime; //-- return absTime; } bool gen_xml::validateFileExtention(string name,string ext) { string str (name); string str2 (ext); size_t found; bool res; int num_periods = count(name.begin(), name.end(), '.'); found=str.find(str2); if ((found!=string::npos)&amp;&amp;(num_periods==1)) { //cout &lt;&lt; "file extention"&lt;&lt;str2&lt;&lt;"found at: " &lt;&lt;int(found) &lt;&lt; endl; res=true; } else { // cout&lt;&lt;"file name incorrect"&lt;&lt;endl; res=false; } return res; } void gen_xml::showInput(int argc,char* argv[]) { cout&lt;&lt;"argc = "&lt;&lt;argc&lt;&lt;"\t"; for (int i = 0; i&lt;argc; i++) { cout&lt;&lt;"argv["&lt;&lt;i&lt;&lt;"] = "&lt;&lt; argv[i]&lt;&lt;"\n"; } } </code></pre>
[]
[ { "body": "<p>I would remove the validate method and do some modifications:</p>\n\n<p>About <code>validate</code>:</p>\n\n<ul>\n<li>Check <code>argc</code> and <code>argv</code> outside the class, just provide the <code>filename</code> to the <code>getData</code> method.</li>\n<li>You also need to check when <code>argc</code> is less than 2, the user may forget to supply the <code>filename</code>.</li>\n<li>Opening the file in the validate method and closing it again does not guarantee that it will be still available when you call <code>getData</code>, so it is better to open the file only there and handle any errors there.</li>\n</ul>\n\n<p>About <code>getData</code>:</p>\n\n<ul>\n<li>I would rename it to <code>loadData</code>.</li>\n<li>For each line loaded you insert a value in time_ms and text_info vectors, call <code>reserve</code> before the loop to pre-allocate the needed memory.</li>\n<li>No need to call close on the stream, it will close when its scopes end.</li>\n</ul>\n\n<p>About <code>validateFileExtention</code>:</p>\n\n<ul>\n<li>Use <code>rfind</code> instead of <code>find</code> and just grab the last \".\" from the string.</li>\n<li>I would instead create a function to copy the <code>fileExtension</code> and check both extensions at once, instead of finding the extension each time.</li>\n<li>I would also not even bother about file extension at all. I would just let the parser validate it.</li>\n</ul>\n\n<p>About <code>generateXML</code>:</p>\n\n<ul>\n<li>Memory leak: you never delete doc. Also, if you need it just inside the method, why you use dynamic memory? Just create it on stack.</li>\n<li>Also, check if tinyxml deletes everything that you insert on the document. If not, you will have to handle this too.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-01T20:16:56.393", "Id": "1615", "ParentId": "1608", "Score": "5" } }, { "body": "<p><strong>Header file:</strong></p>\n\n<ul>\n<li><p>Since your variables and functions are in camelCase, your own types, especially <code>gen_xml</code>, should be in PascalCase. It shouldn't be easy to mix up all of these based on their naming conventions.</p></li>\n<li><p>If you aren't using a particular library in a header file, don't include it. Header files should include as few things as possible because anything including <em>those</em> header files will also be exposed to those libraries. If any libraries are just needed in the implementation file, then keep them there.</p>\n\n<p>You're only using <code>&lt;string&gt;</code> and <code>&lt;vector&gt;</code> in the header file, so move the rest of the libraries to the implementation file.</p></li>\n<li><p>The <code>typedef</code>s in the header file don't seem too useful, and they don't really save any keystrokes. If a type is not very long and you cannot give it a shorter (and distinctive) name, then you don't need to use a <code>typedef</code>.</p></li>\n<li><p>You shouldn't have any <code>public</code> data members in a <code>class</code>. All such data members should be <code>private</code>. If you <em>must</em> allow them to be changed outside the class after object-construction), then have setters for any individual ones.</p></li>\n<li><p>I don't think any of these functions need to be <code>virtual</code>. There's no inheritance or polymorphism being used in this program.</p></li>\n<li><p><code>showInput()</code> should be <code>const</code> since it's not modifying any data members.</p></li>\n</ul>\n\n<p><strong>Implementation file:</strong></p>\n\n<ul>\n<li><p>The final output in <code>main()</code> doesn't look necessary. If you're executing this on the command line, you'll already receive a prompt for the next command. Plus, it's a little misleading if the file failed to open in the first place.</p></li>\n<li><p><code>validate()</code> isn't a very descriptive name as it doesn't specify <em>what</em> it's validating.</p>\n\n<p>It appears to be checking two different things: the number of command line arguments and the file extensions. You should probably have <code>main()</code> validate the former and <code>validate()</code> the latter, then terminate if any of them fails. You should also rename <code>validate()</code> to something more descriptive, such as <code>validateFilename()</code>.</p></li>\n<li><p><code>showInput()</code> should be displaying data members, not command line arguments. Otherwise, it has no business being a member function.</p></li>\n<li><p>This cast to <code>int</code> is useless:</p>\n\n<blockquote>\n<pre><code>for(int i=0; i&lt;(int)text_file.size(); i++)\n</code></pre>\n</blockquote>\n\n<p>The function <code>size()</code> already returns an <code>std::size_type</code>, which is an integer type. You don't necessarily need to loop towards an <code>int</code> value; any integer type will do.</p>\n\n<p>Moreover, don't use C-style casting in C++ unless it's absolutely necessary. For such casts, use the C++-style cast <code>static_cast&lt;&gt;()</code>.</p>\n\n<pre><code>static_cast&lt;SomeType&gt;(someVariable);\n</code></pre></li>\n<li><p><code>getAbsoluteTime()</code>'s argument, <code>value</code>, should probably be passed by <code>const&amp;</code> as it isn't being modified within the function.</p></li>\n<li><p>If you have C++11, use <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/to_string\" rel=\"nofollow\"><code>std::to_string()</code></a> instead of your own <code>toString()</code> function.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-07T20:17:01.417", "Id": "52721", "ParentId": "1608", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-01T15:14:14.773", "Id": "1608", "Score": "4", "Tags": [ "c++", "xml" ], "Title": "Generating XML file from text input" }
1608
<p>I am trying to cycle through a few of these blocks. They basically narrow down a number of people that fulfill a bunch of attributes.</p> <p>I apologize if this seems really messy, but my database is really taking a toll processing this, and I know there's a better way. I'm just lost on strategy right now.</p> <pre><code>def count_of_distribution #beginning with an array.. array_of_users = [] # any matching zip codes? .. # zip_codes @zip_codes = self.distributions.map(&amp;:zip_code).compact unless @zip_codes.nil? || @zip_codes.empty? @matched_zips = CardSignup.all.map(&amp;:zip_code) &amp; @zip_codes @matched_zips.each do |mz| CardSignup.find(:all, :conditions =&gt; ["zip_code = ?", mz]).each do |cs| array_of_users &lt;&lt; cs.id end end end # any matching interests?.. # interest @topics = self.distributions.map(&amp;:me_topic).compact unless @topics.nil? || @topics.empty? @matched_topics = MeTopic.all.map(&amp;:name) &amp; @topics @matched_topics.each do |mt| MeTopic.find(:all, :conditions =&gt; ["name = ?", mt]).each do |mt2| mt2.users.each do |u| array_of_users &lt;&lt; u.card_signup.id if u.card_signup end end end end # any matching sexes?.. # sex @sexes = self.distributions.map(&amp;:sex).compact unless @sexes.nil? || @sexes.empty? @matched_sexes = CardSignup.all.map(&amp;:sex) &amp; @sexes @matched_sexes.each do |ms| CardSignup.find(:all, :conditions =&gt; ["sex = ?", ms]).each do |cs| array_of_users &lt;&lt; cs.id end end end total_number = array_of_users.compact.uniq return total_number end </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T19:38:43.747", "Id": "2785", "Score": "0", "body": "It would help if you explained a bit about self.distributions and CardSignup etc. contain." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T19:43:45.460", "Id": "2787", "Score": "0", "body": "Distributions are a selection of characteristics for an email to go to.. Examples include age, interests, sex, etc. And CardSignups are the subscription, so when you sign up you fill out your age, interests, sex. etc. So I'm basically trying to find all the CardSignup attributes that match the Distribution attributes." } ]
[ { "body": "<p>The first thing I notice is that you're calling <code>map.{}.compact</code> when you probably could be calling <code>select{}</code>, that is, you want to select from self.distribution. So that would replace 6 method calls with 3.</p>\n\n<p>If you use select, it always returns an array and never a nil, so instead of <code>unless X.nil or X.empty</code>, you could use <code>if X.any?</code>, which would replace 6 method calls with three.</p>\n\n<p>If you aren't using <code>@matched_zips</code> outside of this context, it makes no sense to assign a variable here. Instead of assigning, you could just use <code>(CardSignup.all.map(&amp;:zip_code) &amp; @zip_codes).each do</code>, which would spare you three variable assignments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T19:48:06.750", "Id": "2789", "Score": "0", "body": "Thanks philosodad ;) That's a tough call because I need to compare to arrays to see which one matches, but select will just pull the objects and not the array of attributes." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T21:35:16.013", "Id": "2792", "Score": "0", "body": "So you want all the `:zipcode` from distribution such that `:zipcode` is not nil? Why? For the purposes of comparison with your other array, the `nil` values will be dropped anyway... unless you allow nil values in your `CardSignup` array as well." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T19:37:59.020", "Id": "1612", "ParentId": "1611", "Score": "6" } }, { "body": "<p>Another thing that can be fixed is your return call. So instead of </p>\n\n<pre><code>def count_of_distribution \n # ... your code ...\n\n total_number = array_of_users.compact.uniq\n\n return total_number\nend\n</code></pre>\n\n<p>You could remove the <code>total_number</code> variable and instead write:</p>\n\n<pre><code>def count_of_distribution \n # ... your code ...\n\n array_of_users.compact.uniq\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T18:48:35.150", "Id": "1787", "ParentId": "1611", "Score": "4" } }, { "body": "<p>In addition to the things already mentioned I noticed was that you're setting a lot of instance variables. Obviously I don't know how and where you're going to use them, but my first instinct is that this is a sign of bad design.</p>\n\n<p>Generally a method which is called primarily for its return value, should avoid side effects (like setting instance variables) when possible.</p>\n\n<p>Another point: You might consider using a set instead of an array. This way you don't need to call <code>uniq</code> on it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-24T13:58:53.457", "Id": "2068", "ParentId": "1611", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-01T19:12:21.093", "Id": "1611", "Score": "3", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Counting subscribers with matching ZIP code, interests, and sex" }
1611
<p>Having fancy animations in WPF is quite nice so I tried to implement a generic fading animation for <code>UIElements</code> which I use for the Popups in my application. I was wondering if there was anything wrong with it, and thought about posting it here yesterday. There were indeed many things wrong at that time and I have improved the code greatly since then (I think) but there probably are still some issues with it now.</p> <p>One of the first flaws I came across was that by temporarily changing the <code>RenderTransform</code> the original can get messed up if the same animation is started while another one is still playing because the <code>Completed</code> event of he first would never be called and the original <code>RenderTransform</code> is merged with a half-animated transform that comes from my disrupted animation.</p> <p>To prevent this I now have a <code>HashSet</code> which is checked for the <code>UIElement</code> in question and no animation will be started if another one is still in progress, not sure if that is the best approach here.</p> <pre><code>namespace HB.Animation { public enum Direction { Up, Down, Left, Right } public enum AnimationType { In, Out } public abstract class UIElementAnimationBase { private static readonly HashSet&lt;UIElement&gt; _animatedElements = new HashSet&lt;UIElement&gt;(); private AnimationType _type = AnimationType.In; /// &lt;summary&gt; /// Gets or sets the type of the animation. Default is In. /// &lt;/summary&gt; public AnimationType Type { get { return _type; } set { _type = value; } } private UIElement _target = null; /// &lt;summary&gt; /// Gets or sets the target of the animation. /// &lt;/summary&gt; public UIElement Target { get { return _target; } set { _target = value; } } private TimeSpan _duration = TimeSpan.FromSeconds(0.3); /// &lt;summary&gt; /// Gets or sets the duration of the animation. Default is 0.3 seconds. /// &lt;/summary&gt; public TimeSpan Duration { get { return _duration; } set { _duration = value; } } public event EventHandler Completed; protected void OnCompleted() { _animatedElements.Remove(Target); if (Completed != null) { Completed(this, null); } } public void BeginAnimation() { if (_animatedElements.Contains(Target)) { return; } else { _animatedElements.Add(Target); } BeginAnimationDetail(); } protected abstract void BeginAnimationDetail(); } public class FadeAnimation : UIElementAnimationBase { private Direction _direction = Direction.Down; /// &lt;summary&gt; /// Gets or sets the direction of the animation. Default is Down. /// &lt;/summary&gt; public Direction Direction { get { return _direction; } set { _direction = value; } } private double _distance = 50; /// &lt;summary&gt; /// Gets or sets the distance of the target travels in the animation. Default is 50. /// &lt;/summary&gt; public double Distance { get { return _distance; } set { _distance = value; } } private FillBehavior _opacityBehavior = FillBehavior.HoldEnd; /// &lt;summary&gt; /// Gets or sets the fill behavior of the opacity sub-animation. Default is HoldEnd. /// &lt;/summary&gt; public FillBehavior OpacityBehavior { get { return _opacityBehavior; } set { _opacityBehavior = value; } } public FadeAnimation(UIElement target) { Target = target; } public FadeAnimation(UIElement target, AnimationType type, Direction direction) : this(target) { Type = type; Direction = direction; } protected override void BeginAnimationDetail() { Transform tempTrans = Target.RenderTransform; TranslateTransform trans; EasingMode easing; double opacityTarget; double translateOrigin; double translateTarget; DependencyProperty translateProperty; switch (Type) { case AnimationType.In: easing = EasingMode.EaseOut; opacityTarget = 1; translateTarget = 0; switch (Direction) { case Direction.Up: trans = new TranslateTransform(0, -Distance); translateProperty = TranslateTransform.YProperty; break; case Direction.Down: trans = new TranslateTransform(0, Distance); translateProperty = TranslateTransform.YProperty; break; case Direction.Left: trans = new TranslateTransform(-Distance, 0); translateProperty = TranslateTransform.XProperty; break; case Direction.Right: trans = new TranslateTransform(Distance, 0); translateProperty = TranslateTransform.XProperty; break; default: throw new InvalidOperationException(); } break; case AnimationType.Out: easing = EasingMode.EaseIn; opacityTarget = 0; trans = new TranslateTransform(0, 0); switch (Direction) { case Direction.Up: translateTarget = -Distance; translateProperty = TranslateTransform.YProperty; break; case Direction.Down: translateTarget = Distance; translateProperty = TranslateTransform.YProperty; break; case Direction.Left: translateTarget = -Distance; translateProperty = TranslateTransform.XProperty; break; case Direction.Right: translateTarget = Distance; translateProperty = TranslateTransform.XProperty; break; default: throw new InvalidOperationException(); } break; default: throw new InvalidOperationException(); } TransformGroup group = new TransformGroup(); if (tempTrans != null) group.Children.Add(tempTrans); group.Children.Add(trans); Target.RenderTransform = group; DoubleAnimation animTranslate = new DoubleAnimation(translateTarget, (Duration)Duration); animTranslate.EasingFunction = new CubicEase() { EasingMode = easing }; DoubleAnimation animFade = new DoubleAnimation(opacityTarget, (Duration)Duration) { FillBehavior = OpacityBehavior }; animTranslate.Completed += delegate { Target.RenderTransform = tempTrans; OnCompleted(); }; Target.BeginAnimation(UIElement.OpacityProperty, animFade); trans.BeginAnimation(translateProperty, animTranslate); } } } </code></pre> <p>Here is a usage example:</p> <pre><code>private void DisplayMode_QuickSelect_Executed(object sender, ExecutedRoutedEventArgs e) { Popup popup = FindResource("DisplayModePopup") as Popup; FadeAnimation anim = new FadeAnimation(popup.Child) { Duration = Settings.BalloonAnimationDuration }; if (popup.IsOpen) { anim.Type = HB.Animation.AnimationType.Out; anim.Completed += delegate { popup.IsOpen = false; }; } else { popup.Child.Opacity = 0; popup.IsOpen = true; } anim.BeginAnimation(); } </code></pre>
[]
[ { "body": "<p>I would focus on <code>BeginAnimationDetail</code> method. </p>\n\n<ul>\n<li><p><strong>Variable names</strong>. I would rename at least these variables - <code>tempTrans</code> and <code>trans</code>. <code>tempTrans</code> name doesn't give me any idea what is this variable about. I would name it <code>originalTransform</code> for example - it will be enough to understand why do you add it to another transform and later resetting control's transform to this one. From <code>tempTrans</code> name it is unclear how will you use it. </p></li>\n<li><p>In the beginning of that method you have several variables defined and then for ~60 lines (two <code>switch</code> statements) you're setting some values to those variables. Besides the fact that some part of code is repeated there, I find it very difficult to read when variables are assigned far from the line when they were defined. I would rewrite method in order to avoid it. Algorithm could be: </p>\n\n<ul>\n<li><p>Calculate positions of <code>in</code> and <code>out</code> points. <code>In = {0, 0}</code>, <code>Out</code> depends on <code>Direction</code> and <code>Distance</code>. </p></li>\n<li><p>Decide at which point animation will start and at which point it will finish.</p></li>\n<li><p>Create animations and start them.</p></li>\n</ul></li>\n</ul>\n\n<p>Result (it is around two times shorter): </p>\n\n<pre><code> protected override void BeginAnimationDetail()\n {\n var inPoint = new Point(0, 0);\n Point outPoint;\n\n switch (Direction)\n {\n case Direction.Up:\n outPoint = new Point(0, -Distance);\n break;\n case Direction.Down:\n outPoint = new Point(0, Distance);\n break;\n case Direction.Left:\n outPoint = new Point(-Distance, 0);\n break;\n case Direction.Right:\n outPoint = new Point(Distance, 0);\n break;\n default:\n throw new InvalidOperationException();\n }\n\n Transform originalTransform = Target.RenderTransform;\n\n var easing = Type == AnimationType.In ? EasingMode.EaseOut : EasingMode.EaseIn;\n double opacityTarget = Type == AnimationType.In ? 1 : 0;\n Point from = Type == AnimationType.In ? outPoint : inPoint;\n Point to = Type == AnimationType.In ? inPoint : outPoint;\n\n var animatedTranslate = new TranslateTransform(from.X, from.Y);\n\n var group = new TransformGroup();\n if (originalTransform != null) group.Children.Add(originalTransform);\n group.Children.Add(animatedTranslate);\n Target.RenderTransform = group;\n\n var animFade = new DoubleAnimation(opacityTarget, Duration) {FillBehavior = OpacityBehavior};\n animFade.Completed += delegate\n {\n Target.RenderTransform = originalTransform;\n OnCompleted();\n };\n\n Target.BeginAnimation(UIElement.OpacityProperty, animFade);\n animatedTranslate.BeginAnimation(TranslateTransform.XProperty, new DoubleAnimation(to.X, Duration) {EasingFunction = new CubicEase {EasingMode = easing}});\n animatedTranslate.BeginAnimation(TranslateTransform.YProperty, new DoubleAnimation(to.Y, Duration) {EasingFunction = new CubicEase {EasingMode = easing}});\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-02T00:47:15.553", "Id": "2796", "Score": "0", "body": "Thank you for this great response! I suspected that there would be a better way to handle those switches and variable initializations, very intelligent how you did that; also interesting how somewhat doing \"more\" by considering both axes is actually a lot shorter." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T22:50:37.603", "Id": "1619", "ParentId": "1617", "Score": "5" } }, { "body": "<p>Nowadays using auto-implemented properties is the way to go. </p>\n\n<pre><code>/// &lt;summary&gt; \n/// Gets or sets the type of the animation. Default is In.\n/// &lt;/summary&gt;\npublic AnimationType Type { get; set; } = AnimationType.In;\n</code></pre>\n\n<p>looks neater than </p>\n\n<blockquote>\n<pre><code>private AnimationType _type = AnimationType.In;\n/// &lt;summary&gt;\n/// Gets or sets the type of the animation. Default is In.\n/// &lt;/summary&gt;\npublic AnimationType Type\n{\n get { return _type; }\n set { _type = value; }\n} \n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>Using C# 6 (VS 2015) we can simplify the null check in the <code>OnCompleted()</code> method like so </p>\n\n<pre><code>protected void OnCompleted()\n{\n _animatedElements.Remove(Target);\n\n Completed?.Invoke(this, null);\n} \n</code></pre>\n\n<hr>\n\n<p>If we take advantage of the result of the <code>HashSet.Add()</code> method we can simplify the <code>BeginAnimation()</code> method like so </p>\n\n<pre><code>public void BeginAnimation()\n{\n if (_animatedElements.Add(Target))\n {\n BeginAnimationDetail();\n }\n} \n</code></pre>\n\n<p>but I would throw a <code>NullReferenceException</code> if <code>Target == null</code> so it will be thrown from that <code>public</code> method instead of the <code>protected abstract void BeginAnimationDetail()</code> method. IMO this is neccessary because the <code>Target</code> property is public hence it can by error be set to <code>null</code>. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-18T09:50:58.083", "Id": "114358", "ParentId": "1617", "Score": "3" } } ]
{ "AcceptedAnswerId": "1619", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-01T21:30:39.930", "Id": "1617", "Score": "4", "Tags": [ "c#", "wpf", "easing" ], "Title": "Custom UIElement Animations" }
1617
<p>I don't really have any specific questions for this thread. I have been working on an independent project recently and have been learning everything from the web. Just yesterday I became aware of templating and the idea of separating business and presentational logic.</p> <p>I would be very thankful for any comments regarding possible re-factorings, security vulnerabilities, improved design philosophies, etc. The purpose of this thread is mostly a sanity check and to be sure my current design and methodology is sound.</p> <p><strong>index.php</strong></p> <pre><code>&lt;?php require('db.php'); $resultsPerPage = 15; $submissionCount = mysql_num_rows(mysql_query("SELECT id FROM $submissionsTableName")); $pageCount = ceil($submissionCount / $resultsPerPage); if (isset($_GET['sort'])) if ($_GET['sort'] == 'hot' || $_GET['sort'] == 'new' || $_GET['sort'] == 'top') $sort = $_GET['sort']; else header('Location: 404.php'); else $sort = 'hot'; switch ($sort) { case 'hot': $sortAlgorithm = 'submissions.id * (submissions.upvote - submissions.downvote)'; break; case 'new': $sortAlgorithm = 'submissions.id'; break; case 'top': $sortAlgorithm = '(submissions.upvote - submissions.downvote)'; break; } if (isset($_GET['page'])) if ($_GET['page'] &lt;= $pageCount &amp;&amp; $_GET['page'] &gt;= 1) $page = $_GET['page']; else header('Location: 404.php'); else $page = 1; $startRow = ($page - 1) * $resultsPerPage; if (isset($_GET['search'])) { $searchArgs = explode(' ', $_GET['search']); $argCount = count($searchArgs); $searchSQL = '\'' . $searchArgs[0] . '\''; for ($i = 1; $i &lt; $argCount; $i++) { $searchSQL .= ', \'' . $searchArgs[$i] . '\''; } $submissionQuery = mysql_query("SELECT submissions.* FROM submissions, tags, tagmap WHERE tagmap.tagID = tags.id AND (tags.text IN ($searchSQL)) AND submissions.id = tagmap.submissionID ORDER BY $sortAlgorithm DESC LIMIT $startRow, $resultsPerPage"); } else { $submissionQuery = mysql_query("SELECT id, category, title, author, date, upvote, downvote FROM $submissionsTableName ORDER BY $sortAlgorithm DESC LIMIT $startRow, $resultsPerPage"); } $outcomeCount = mysql_num_rows($submissionQuery); $submissions = array(); while ($row = mysql_fetch_assoc($submissionQuery)) { $upvote = "upvote"; $downvote = "downvote"; $rowIP = $_SERVER['REMOTE_ADDR']; $userIPRow = mysql_fetch_assoc(mysql_query("SELECT type FROM $votingIPsTableName WHERE submissionID = $row[id] AND commentID = 0 AND IPAddress = '$rowIP'")); if ($userIPRow['type'] == 'upvote active') $upvote = 'upvote active'; else if ($userIPRow['type'] == 'downvote active') $downvote = 'downvote active'; $votes = $row['upvote'] - $row['downvote']; $tagsQuery = mysql_query("SELECT tags.text FROM tags INNER JOIN tagmap ON tags.id = tagmap.tagID WHERE tagmap.submissionID = $row[id]"); $tags = array(); while ($tag = mysql_fetch_assoc($tagsQuery)) { $tags[] = $tag['text']; } $commentsQuery = mysql_query("SELECT id FROM $commentsTableName WHERE submissionID = $row[id]"); $commentCount = mysql_num_rows($commentsQuery); $submissions[] = array('submission' =&gt; $row, 'upvote' =&gt; $upvote, 'votes' =&gt; $votes, 'downvote' =&gt; $downvote, 'tags' =&gt; $tags, 'commentCount' =&gt; $commentCount); } // Divider $index_view = new Template('index_view.php', array( 'header' =&gt; new Template('header.php'), 'menu' =&gt; new Template('menu.php'), 'submissions' =&gt; new Template('submissions.php', array('submissions' =&gt; $submissions)), 'pagination' =&gt; new Template('pagination.php', array('page' =&gt; $page, 'pageCount' =&gt; $pageCount, 'resultsPerPage' =&gt; $resultsPerPage, 'outcomeCount' =&gt; $outcomeCount, 'submissionCount' =&gt; $submissionCount, 'sort' =&gt; $sort)), 'footer' =&gt; new Template('footer.php') )); $index_view-&gt;render(); ?&gt; </code></pre> <p><strong>submissions.php</strong></p> <pre><code>&lt;div id="submissions"&gt; &lt;?php foreach ($this-&gt;submissions as $row): ?&gt; &lt;div class="submission" id="submission&lt;?php echo $row['submission']['id']; ?&gt;"&gt; &lt;div class="voteblock"&gt; &lt;a class="&lt;?php echo $row['upvote']; ?&gt;" title="Upvote"&gt;&lt;/a&gt; &lt;div class="votes"&gt;&lt;?php echo $row['votes']; ?&gt;&lt;/div&gt; &lt;a class="&lt;?php echo $row['downvote']; ?&gt;" title="Downvote"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="submissionblock"&gt; &lt;h3&gt;&lt;a href="s/&lt;?php echo $row['submission']['id']; ?&gt;.php"&gt;&lt;?php echo $row['submission']['title']; ?&gt;&lt;/a&gt; (&lt;?php echo $row['submission']['category']; ?&gt;) - &lt;?php echo $row['commentCount']; ?&gt; comments&lt;/h3&gt; &lt;div class="tags"&gt; &lt;?php foreach ($row['tags'] as $tag): echo $tag . ' '; endforeach; ?&gt; &lt;/div&gt; &lt;span class="date"&gt;&lt;?php echo $row['submission']['date']; ?&gt;&lt;/span&gt; by &lt;span class="author"&gt;&lt;?php echo $row['submission']['author']; ?&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endforeach; ?&gt; &lt;/div&gt; </code></pre> <p><strong>index_view.php</strong></p> <pre><code>&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;title&gt;Website&lt;/title&gt; &lt;meta http-equiv="content-type" content="text/html; charset=UTF-8" /&gt; &lt;link href="styles.css" rel="stylesheet" type="text/css"/&gt; &lt;link href="favicon.png" rel="shortcut icon" /&gt; &lt;/head&gt; &lt;body&gt; &lt;?php $this-&gt;header-&gt;render(); $this-&gt;menu-&gt;render(); $this-&gt;submissions-&gt;render(); $this-&gt;pagination-&gt;render(); $this-&gt;footer-&gt;render(); ?&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="vote.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="prettydate.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>Well, it's good that you thought of it. And you are definitely moving in the right direction. Your code seems to be fine, but still not very readable and not very structured. Try to organize your code to classes or smaller functions. E.g. this:</p>\n\n<pre><code>if (isset($_GET['sort']))\n if ($_GET['sort'] == 'hot' || $_GET['sort'] == 'new' || $_GET['sort'] == 'top')\n $sort = $_GET['sort'];\n else\n header('Location: 404.php');\nelse\n $sort = 'hot';\n\nswitch ($sort) {\n case 'hot':\n $sortAlgorithm = 'submissions.id * (submissions.upvote - submissions.downvote)';\n break;\n case 'new':\n $sortAlgorithm = 'submissions.id';\n break;\n case 'top':\n $sortAlgorithm = '(submissions.upvote - submissions.downvote)';\n break;\n}\n</code></pre>\n\n<p>Should be in function <code>get_sort_algorith()</code>, or even in class Request, or it's subclass. This might seem useless right now, but having code in a function or class makes debugging easier and makes this code re-usable in another parts of the project.</p>\n\n<p>Have you heard/tried any MVC frameworks and/or about MVC design pattern? This pattern describes splitting code to Model (=data &amp; database access), View (=html templates) &amp; Controller (code that manipulates data and calls views for output). </p>\n\n<p>Here are some useful links that might help you:</p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">Wikipedia's MVC article</a></li>\n<li><a href=\"http://codeigniter.com/user_guide/overview/mvc.html\" rel=\"nofollow\">CodeIgniter User Guide chapter on MVC</a></li>\n<li><a href=\"http://codeigniter.com/\" rel=\"nofollow\">and CodeIgniter framework</a> </li>\n</ul>\n\n<p>Some other notes:</p>\n\n<pre><code>header('Location: 404.php');\n</code></pre>\n\n<p>This probably won't give you what you want. This wold be 301 redirect, not a 404 error. You'd better use <code>header(\"HTTP/1.0 404 Not Found\");</code> and configure your webserver to map error 404 to 404.php. In apache this could be done with <code>ErrorDocument 404 /404.php</code></p>\n\n<pre><code>if (isset($_GET['search'])) {\n $searchArgs = explode(' ', $_GET['search']);\n $argCount = count($searchArgs);\n $searchSQL = '\\'' . $searchArgs[0] . '\\'';\n\n for ($i = 1; $i &lt; $argCount; $i++) {\n $searchSQL .= ', \\'' . $searchArgs[$i] . '\\'';\n }\n</code></pre>\n\n<p>SQL injection here. Assume what will happen if someone will make request with <code>search='; DROP TABLE users</code>. ALWAYS escape what you are getting from outside of your app.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-04T01:23:58.587", "Id": "2886", "Score": "2", "body": "Frameworks are a very good way to learn MVC, because good ones will force you to use it. You have to invest a little more time reading before you can hack away, but it is well worth it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-02T20:11:25.297", "Id": "1625", "ParentId": "1621", "Score": "7" } }, { "body": "<h2><strong>Use sql binding</strong></h2>\n\n<p>Additive to the answer above, look into sql binding. After going through the learning cycle myself (unfettered user input into sql, sql escaping, and finally sql binding), neither of the first two should be used for anything that touches user input and then goes to any database that you like. At all.</p>\n\n<p>In other words, the sooner you start using binding with your sql, the better off you'll be.\nPDO ( <a href=\"http://php.net/manual/en/book.pdo.php\" rel=\"nofollow\">http://php.net/manual/en/book.pdo.php</a> ) is something you'll want to get somewhat familiar with, but the uh, api I guess for PDO is rather complex, so what I have done is implemented a wrapper that allows me to work like this:</p>\n\n<p>$datum = query_item('select id from users where user_id = :id', array(':id'=>5));\n$row_array = query_row('select * from users where user_id = :id', array(':id'=>5));\n$iterable_resultset = query('select * from users where user_id = :id', array(':id'=>5));</p>\n\n<p>In other words, a simplified query wrapper function to make all your sql easily bindable.</p>\n\n<p>The functions are based in part on the code here:</p>\n\n<p><a href=\"https://github.com/tchalvak/ninjawars/blob/master/deploy/lib/data/lib_db.php\" rel=\"nofollow\">https://github.com/tchalvak/ninjawars/blob/master/deploy/lib/data/lib_db.php</a></p>\n\n<p>Anyway, the point is, look into sql binding, you'll be glad you did every time you hear about <a href=\"http://www.scmagazineus.com/oracles-mysqlcom-hacked-via-sql-injection/article/199419/\" rel=\"nofollow\">-other- people's sql-injection problems.</a></p>\n\n<h2><strong>Use templating principles</strong></h2>\n\n<p>One thing I notice with your code (submissions.php and index_view.php for example) is that you're using naked php in your html. That will tend to get complicated when you end up using three or four languages/principles (php, html, javascript, css) in the same page. Let me tell you, the code that I hate, the code that I cringe when I see I have to debug it, that's javascript code with php intermixed on a html page working with css. What you want to work on is separation of concerns. When it comes to php, understanding that and harnessing the benefits of that, at least when you're new to php, will be greatly increased by using a template engine for a while, at least until you understand php enough to decide when and whether you want to skip the templating agent.</p>\n\n<p>1/4 of the benefit of a templating engine will be simplified syntax, and 3/4 of the benefit will be separation of concerns. Using an MVC pattern, which @rvs mentioned, gives a similar benefit, but getting to know a template engine library will be helpful if you end up doing cleanup on someone else's code and can't fully rewrite an existing system (story of my life as a php developer).</p>\n\n<p>So I suggest getting to know smarty ( <a href=\"http://www.smarty.net/\" rel=\"nofollow\">http://www.smarty.net/</a> ). In the beginning it should be easy to just include smarty as a lib in projects and using the templates there.</p>\n\n<h2>In lieu of a templating engine</h2>\n\n<p>Let's suppose you don't want to get into the complexity of template engines and template engine syntax for the moment, you should still work towards <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow\">separation of concerns</a>. The simple way to do this in php is just avoid any php except echos in your html. Do all of your logic -outside- of your html, and just pass variables to echo or loop over and then echo into where-ever the html is. It'll make your php code and your html code much easier to debug and much easier to redesign.</p>\n\n<p>Sql binding and separation of concerns, those are the biggest things I've learned make my life easier when developing php.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T03:42:22.543", "Id": "1696", "ParentId": "1621", "Score": "1" } } ]
{ "AcceptedAnswerId": "1625", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-02T05:55:12.787", "Id": "1621", "Score": "4", "Tags": [ "php" ], "Title": "Site design for upvote/downvote submissions" }
1621
<p>You may see full code <a href="https://github.com/agladysh/luatexts/blob/9d47f9c7ef1c1e5a9ade29fda0526e392bc7ddeb/src/c/luatexts.c" rel="nofollow">here</a> (note that the link points to the specific commit).</p> <p>Language is "clean C" (that is, a subset of C89, C99 and C++98 — it is intended to compile under all of these standards). The code must be portable between x86 and x86_64.</p> <p>UTF-8 handling implemented based on information <a href="http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8" rel="nofollow">here</a> and tested with data in <a href="http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt" rel="nofollow">this</a> file.</p> <p>First and foremost I'm interested in correctness. But I'm a bit worried about the length and readability of the code and its speed (I did not profile this thing yet though, so that particular worry is not motivated). I will accept any comments, including constructive nitpicks.</p> <p>The function itself:</p> <pre><code>/* * *Increments* len_bytes by the number of bytes read. * Fails on invalid UTF-8 characters. */ static int ltsLS_eatutf8char(lts_LoadState * ls, size_t * len_bytes) { unsigned char b = 0; signed char expected_length = 0; int i = 0; const unsigned char * origin = ls-&gt;pos; /* Check if we have any data in the buffer */ if (!ltsLS_good(ls) || ltsLS_unread(ls) &lt; 1) { ls-&gt;unread = 0; ls-&gt;pos = NULL; return LUATEXTS_ECLIPPED; } /* We have at least one byte in the buffer, let's check it out. */ b = *ls-&gt;pos; /* We did just eat a byte, no matter what happens next. */ ++ls-&gt;pos; --ls-&gt;unread; /* Get an expected length of a character. */ expected_length = utf8_char_len[b]; /* Check if it was a valid first byte. */ if (expected_length &lt; 1) { ls-&gt;unread = 0; ls-&gt;pos = NULL; return LUATEXTS_EBADUTF8; } /* If it was a single-byte ASCII character, return right away. */ if (expected_length == 1) { *len_bytes += expected_length; return LUATEXTS_ESUCCESS; } /* * It was a multi-byte character. Check if we have enough bytes unread. * Note that we've eaten one byte already. */ if (ltsLS_unread(ls) + 1 &lt; expected_length) { ls-&gt;unread = 0; ls-&gt;pos = NULL; return LUATEXTS_ECLIPPED; /* Assuming it is buffer's fault. */ } /* Let's eat the rest of characters */ for (i = 1; i &lt; expected_length; ++i) { b = *ls-&gt;pos; /* We did just eat a byte, no matter what happens next. */ ++ls-&gt;pos; --ls-&gt;unread; /* Check if it is a continuation byte */ if (utf8_char_len[b] != -1) { ls-&gt;unread = 0; ls-&gt;pos = NULL; return LUATEXTS_EBADUTF8; } } /* All bytes are correct, let's check out for overlong forms */ if ( expected_length == 2 &amp;&amp; ( (origin[0] &amp; 0xFE) == 0xC0 ) ) { ls-&gt;unread = 0; ls-&gt;pos = NULL; return LUATEXTS_EBADUTF8; } else if ( expected_length == 3 &amp;&amp; ( origin[0] == 0xE0 &amp;&amp; (origin[1] &amp; 0xE0) == 0x80 ) ) { ls-&gt;unread = 0; ls-&gt;pos = NULL; return LUATEXTS_EBADUTF8; } else if ( expected_length == 4 &amp;&amp; ( origin[0] == 0xF0 &amp;&amp; (origin[1] &amp; 0xF0) == 0x80 ) ) { ls-&gt;unread = 0; ls-&gt;pos = NULL; return LUATEXTS_EBADUTF8; } else if ( expected_length == 5 &amp;&amp; ( origin[0] == 0xF8 &amp;&amp; (origin[1] &amp; 0xF8) == 0x80 ) ) { ls-&gt;unread = 0; ls-&gt;pos = NULL; return LUATEXTS_EBADUTF8; } else if ( expected_length == 6 &amp;&amp; ( origin[0] == 0xFC &amp;&amp; (origin[1] &amp; 0xFC) == 0x80 ) ) { ls-&gt;unread = 0; ls-&gt;pos = NULL; return LUATEXTS_EBADUTF8; } /* No overlongs, check for surrogates. */ if ( expected_length == 3 &amp;&amp; ( origin[0] == 0xED &amp;&amp; (origin[1] &amp; 0xE0) == 0xA0 ) ) { ls-&gt;unread = 0; ls-&gt;pos = NULL; return LUATEXTS_EBADUTF8; } /* * Note: Not checking for U+FFFE or U+FFFF. * * Chapter 3 of version 3.2 of the Unicode standard, Paragraph C5 says * "A process shall not interpret either U+FFFE or U+FFFF as an abstract * character", but table 3.1B includes them among * the "Legal UTF-8 Byte Sequences". * * We opt to pass them through. */ /* Phew. All done, the UTF-8 character is valid. */ *len_bytes += expected_length; return LUATEXTS_ESUCCESS; } </code></pre> <p>The function relies on this lookup table:</p> <pre><code>static const signed char utf8_char_len[256] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0 }; </code></pre> <p>The function works on <code>lts_LoadState</code> buffer "stream iterator", which should be prepared by caller. Relevant pieces of code:</p> <pre><code>typedef struct lts_LoadState { const unsigned char * pos; size_t unread; } lts_LoadState; static void ltsLS_init( lts_LoadState * ls, const unsigned char * data, size_t len ) { ls-&gt;pos = (len &gt; 0) ? data : NULL; ls-&gt;unread = len; } #define ltsLS_good(ls) \ ((ls)-&gt;pos != NULL) #define ltsLS_unread(ls) \ ((ls)-&gt;unread) </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T07:16:52.050", "Id": "2846", "Score": "2", "body": "This could be a lot simpler. Compare to the functions [pg_utf8_islegal](http://git.postgresql.org/gitweb?p=postgresql.git;a=blob;f=src/backend/utils/mb/wchar.c;h=5b0cf628fe9a470ce450d2f34c0de421352e7c43;hb=HEAD#l1266) and [pg_utf_mblen](http://git.postgresql.org/gitweb?p=postgresql.git;a=blob;f=src/backend/utils/mb/wchar.c;h=5b0cf628fe9a470ce450d2f34c0de421352e7c43;hb=HEAD#l457) from PostgreSQL. A nice thing about these functions is that they aren't tangled up in a framework, so they're easier to understand by themselves and easier to reuse." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:16:09.740", "Id": "2853", "Score": "0", "body": "@Joey: Ah, where were you when I asked this question... http://stackoverflow.com/questions/5517205/how-to-read-utf-8-string-given-its-length-in-characters-in-plain-c89 :-)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:36:49.233", "Id": "2858", "Score": "0", "body": "@Joey: If you will post an answer for the linked question, I'll accept it for the sake of future readers. (I'm not sure that I want to rewrite my code though — too much of wasted work, need to think more about it...)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T05:26:02.750", "Id": "76867", "Score": "0", "body": "For the future readers: here is probably the simplest implementation: http://bjoern.hoehrmann.de/utf-8/decoder/dfa/" } ]
[ { "body": "<p>One obvious issue - the longest valid Unicode character is represented by 4 bytes in UTF-8. Although it is possible to extend the logic to 5 or 6 bytes, there is no need since Unicode is a 21-bit codeset.</p>\n\n<p>Be careful about using version 3.2 of the Unicode standard; the current version is 6.0. Granted, they keep them as backwards compatible as possible, but it is as well to use the latest version. Paragraph C5 in 6.0.0 bears no resemblance to the paragraph you quote. The bytes 0xC0, 0xC1, and 0xF5..0xFF cannot appear in valid UTF-8.</p>\n\n<p>In view of that, you can modify your lookup table to:</p>\n\n<pre><code>static const signed char utf8_char_len[256] =\n{\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n};\n</code></pre>\n\n<p>The zeroes for the forbidden bytes will trigger an early exit.</p>\n\n<p>The loadstate structure is odd; you have to have something else that keeps a record of where the start of the buffer is. However, since the code zaps the loadstate on encountering an error, there has to be another place where the information is stored, so maybe it isn't too critical.</p>\n\n<p>A good compiler might well optimize:</p>\n\n<pre><code> if (expected_length == 1)\n {\n *len_bytes += expected_length;\n return LUATEXTS_ESUCCESS;\n }\n</code></pre>\n\n<p>so that it is the same as:</p>\n\n<pre><code> if (expected_length == 1)\n {\n *len_bytes++;\n return LUATEXTS_ESUCCESS;\n }\n</code></pre>\n\n<p>The overlong and surrogate testing is interesting. Table 3.7 from Chapter 3 of the 6.0.0 Unicode standard lists:</p>\n\n<pre><code>Table 3-7. Well-Formed UTF-8 Byte Sequences\nCode Points First Byte Second Byte Third Byte Fourth Byte\nU+0000..U+007F 00..7F\nU+0080..U+07FF C2..DF 80..BF\nU+0800..U+0FFF E0 A0..BF 80..BF\nU+1000..U+CFFF E1..EC 80..BF 80..BF\nU+D000..U+D7FF ED 80..9F 80..BF\nU+E000..U+FFFF EE..EF 80..BF 80..BF\nU+10000..U+3FFFF F0 90..BF 80..BF 80..BF\nU+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF\nU+100000..U+10FFFF F4 80..8F 80..BF 80..BF\n</code></pre>\n\n<p>You need to do some extra testing for 0xF4 as the first byte; your code allows through quite a lot of invalid characters. Otherwise, the tests you have do work, allowing through the surrogates, which you test for separately.</p>\n\n<p>The test for the surrogates is incorrect. The bit masking operation is wrong, allowing through many surrogates. I think you could write:</p>\n\n<pre><code>if (expected_length == 3 &amp;&amp; (origin[0] == 0xED &amp;&amp; (origin[1] &amp; 0xE0) != 0x80))\n</code></pre>\n\n<p>The conditions for overlong forms and surrogates can be reduced to:</p>\n\n<pre><code>/* All bytes are correct; check out for overlong forms and surrogates */\nif ((expected_length == 2 &amp;&amp; ((origin[0] &amp; 0xFE) == 0xC0)) ||\n (expected_length == 3 &amp;&amp; (origin[0] == 0xE0 &amp;&amp; (origin[1] &amp; 0xE0) == 0x80)) ||\n (expected_length == 4 &amp;&amp; (origin[0] == 0xF0 &amp;&amp; (origin[1] &amp; 0xF0) == 0x80)) ||\n (expected_length == 4 &amp;&amp; (origin[0] == 0xF4 &amp;&amp; (origin[1] &gt; 0x8F))) ||\n (expected_length == 3 &amp;&amp; (origin[0] == 0xED &amp;&amp; (origin[1] &amp; 0xE0) != 0x80)))\n{\n ls-&gt;unread = 0;\n ls-&gt;pos = NULL;\n return LUATEXTS_EBADUTF8;\n}\n</code></pre>\n\n<p>This is vastly shorter and therefore more readable than the original. The near symmetry of the terms is made evident by the layout. It is wider than 80 characters; if that's a problem, I'd shorten the name <code>expected_length</code> (to maybe <code>exp_len</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T11:57:03.650", "Id": "2848", "Score": "0", "body": "@Jonathan: Thank you for in-depth review. I'll leave comments below:" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:01:12.163", "Id": "2849", "Score": "1", "body": "1. On 5 and 6 byte characters. This file http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt (which is widely quoted and which I considered as an authoritative source) includes tests for such characters (2.1.5, 2.1.6, 2.2.5, 2.2.6), implying that they are legal. Well, I guess, to make code simpler, I will drop support for them by modifying the lookup table as you suggest." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:02:20.943", "Id": "2850", "Score": "0", "body": "1.1. If someone can suggest a test-suite that I can reuse (directly or as an inspiration), please do: http://stackoverflow.com/questions/5519315/a-test-data-set-for-auto-testing-utf-8-string-validator" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:05:29.847", "Id": "2851", "Score": "0", "body": "2. Regarding U+FFFF and U+FFFE: so, according to 6.0 standard, are they legal or not? What I tried to google up left me confused on that point." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:10:58.873", "Id": "2852", "Score": "0", "body": "3. On loadstate: the function we discuss operates on user-provided read-only string buffer of given length. The `lts_LoadState` structure is a thin abstraction over this; it can be considered as a half-baked \"stream iterator\". User knows the start of his buffer, so we don't have to -- reading in reverse direction is not needed or supported." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:19:36.210", "Id": "2854", "Score": "0", "body": "4. On `*len_bytes += expected_length` vs `*len_bytes++`. I think that the former is arguably more readable, as it has a little bit more semantic information about what is going on. Maybe I'm wrong." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:21:58.347", "Id": "2855", "Score": "0", "body": "5. On overlongs and surrogates: thank you! With your permission I will reuse this code snippet. (I wish I had better tests :-) )" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:22:48.640", "Id": "2856", "Score": "0", "body": "@Jonathan: That's all comments I have now. Thank you again for excellent review!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:59:49.080", "Id": "2865", "Score": "0", "body": "On #3: I updated the question to clarify this point." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T14:10:39.990", "Id": "2871", "Score": "0", "body": "@Alexander: regarding §1 - the Unicode 5.1.0 chapter 3 says \"D92 UTF-8 encoding form: The Unicode encoding form that assigns each Unicode scalar value to an unsigned byte sequence of one to four bytes in length\" and also \"As a consequence of the well-formedness conditions specified in Table 3-7, the following byte values are disallowed in UTF-8: C0–C1, F5–FF.\" If MGK's page still suggests the 5 and 6 byte encodings are valid UTF-8, then it is due for update." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T14:16:13.997", "Id": "2872", "Score": "0", "body": "@Alexander: Quoting section D95 of the Unicode 5.1.0 chapter 3: \"While there is obviously no need for a byte order signature when using UTF-8, there are occasions when processes convert UTF-16 or UTF-32 data containing a byte order mark into UTF-8. When represented in UTF-8, the byte order mark turns into the byte sequence `<EF BB BF>`. Its usage at the beginning of a UTF-8 data stream is neither required nor recommended by the Unicode Standard, but its presence does not affect conformance to the UTF-8 encoding scheme.\" See also: http://www.unicode.org/faq/utf_bom.html#BOM" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T14:27:18.883", "Id": "2873", "Score": "0", "body": "@Alexander: if you download the code chart from http://www.unicode.org/charts/ for U+FFFF (enter FFFF in the box at the top), you will find that U+FFFE and U+FFFF are both guaranteed to be 'not a character'. The value U+FFFE is not a character so that the byte sequences 0xFF 0xFE and 0xFE 0xFF at the start of a sequence of bytes are unambiguous indicators of the byte-order of UTF-16LE vs UTF-16BE (though, if followed by two 0x00 0x00 bytes, 0xFF 0xFE could indicate UTF-32LE)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T14:37:40.933", "Id": "2875", "Score": "0", "body": "@Alexander: it is mildly surprising that you only scan through the buffer to identify the bytes used by a UTF-8 character without converting the value into a UTF-32 Unicode code point. I took the code at face value; it is not required. I also note that I get a warning from GCC (4.6.0) set ultra-fussy - a signed/unsigned comparison warning when you check there are enough bytes in the buffer. (The 'static function defined but not used' warnings I get are an artefact of the minimal code that I've got.)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T14:44:52.523", "Id": "2877", "Score": "0", "body": "@Jonathan: Regarding scanning through the buffer: after I scanned the buffer and confirmed that it contains the expected string of given length in characters, I push the string to Lua state, and let user deal with it as he pleases. I have to calculate byte length and do the validation myself, since stock Lua is not aware of UTF-8 (but deals just fine with binary data in strings)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T14:48:21.163", "Id": "2878", "Score": "0", "body": "@Jonathan: On U+FFFE, U+FFFF. I guess I should not fail only if they are the very first characters in the string. Now the question is does \"string length in characters\" include these two or not... Would it be too bad if I just unconditionally fail when I detect them? It is guaranteed by the format that UTF-8 string that I traverse is not at the start of a file." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T14:49:44.327", "Id": "2879", "Score": "0", "body": "@Jonathan: Thanks for the note on warning, I'll fix it." } ], "meta_data": { "CommentCount": "16", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T04:07:22.390", "Id": "1631", "ParentId": "1624", "Score": "8" } } ]
{ "AcceptedAnswerId": "1631", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-02T14:02:20.753", "Id": "1624", "Score": "7", "Tags": [ "c++", "c", "portability", "utf-8" ], "Title": "UTF-8 character reader function" }
1624
<p>I've had a go at writing something that generates a random maze using disjoint sets using the grouping class I found <a href="http://code.activestate.com/recipes/387776-grouping-objects-into-disjoint-sets/" rel="nofollow">here</a>.</p> <p>The way I'm generating the maze is by generating all the cells, with each cell having a wall to the right of it and beneath it. Each wall can either be active or not.</p> <p>I pick wall at random and look at the pair of cells on either side of it to see if they are in the same group (connected), if they are, I leave the wall, if they aren't, I destroy the wall, and join the groups the neighbouring cells belonged to.</p> <p>This will continue until all the cells are connected. I'm then trying to print the maze, probably in a really horrible way.</p> <p>I'd really like to get some feedback on anything I could be doing better. Is it possible to make the code more efficient? If I do a 1000*1000 maze, it takes a very long time to calculate.</p> <pre><code>import random from grouper import Grouper import sys X = 20 Y = 20 class Cell(): """Represents a cell in the maze, with an x and y coordinate and its right hand wall and downwards wall. """ def __init__(self, x, y): self.x, self.y = x, y self.right_wall = self.down_wall = None class Wall(): """Represents a wall in the maze with its two neighbouring cells. """ def __init__(self): self.neighbours = None self.active = True def popchoice(seq): """Takes an iterable and pops a random item from it. """ return seq.pop(random.randrange(len(seq))) # A mapping of coord tuple to Cell object cells = {} # A list of all the non-edge walls walls = [] # Generate cells for y in range(Y): for x in range(X): cells[(x, y)] = Cell(x, y) # Generate walls and add to the neighbouring cells for y in range(Y): for x in range(X): current_cell = cells[(x,y)] down_wall = Wall() current_cell.down_wall = down_wall right_wall = Wall() current_cell.right_wall = right_wall if y != Y-1: down_wall.neighbours = (current_cell, cells[(x,y+1)]) walls.append(down_wall) if x != X-1: right_wall.neighbours = (current_cell, cells[(x+1,y)]) walls.append(right_wall) # Get a list of all the cell objects to give to the Grouper cell_list = [cells[key] for key in cells] maze = Grouper(cell_list) for _ in range(len(walls)): # Pop a random wall from the list and get its neighbours wall = popchoice(walls) cell_1, cell_2 = wall.neighbours # If the cells on either side of the wall aren't already connected, # destroy the wall if not maze.joined(cell_1, cell_2): wall.active = False maze.join(cell_1, cell_2) # Draw the maze maze_map = [] x_max = (X*2)+1 y_max = (Y*2)+1 # Make an empty maze map with True for wall and False for space # Make top wall maze_map.append([True for _ in range(x_max)]) for y in range(1, y_max): # Make rows with left side wall maze_map.append([True]+[False for _ in range(1, x_max)]) # Add the down and right walls from each cell to the map for coords, cell in cells.items(): x, y = coords # Add the intersection wall for each cell (down 1 right 1) maze_map[(y*2)+2][(x*2)+2] = True if cell.right_wall.active: maze_map[(y*2)+1][(x*2)+2] = True if cell.down_wall.active: maze_map[(y*2)+2][(x*2)+1] = True def output(string): sys.stdout.write(string) # Print the map for row in maze_map: for tick in row: if tick: output('X'), else: output('.'), output('\n') </code></pre> <p>It gives a maze like this:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>XXXXXXXXXXXXXXXXXXXXX X.......X...X.X.X...X XXX.XXXXXXX.X.X.X.XXX X.X...............X.X X.XXXXXXXXX.XXXXX.X.X X...X...X.X.X.......X X.XXXXX.X.X.XXXXXXXXX X.X.X.....X...X...X.X X.X.XXX.XXX.XXXXX.X.X X.X...X.........X...X X.XXX.XXX.X.XXX.X.XXX X...X.X.X.X.X.X.X.X.X XXX.X.X.XXX.X.XXX.X.X X.................X.X XXXXX.XXX.XXXXX.X.X.X X...X.X.X.X...X.X.X.X XXX.XXX.X.XXX.X.XXX.X X.X...X...X.....X...X X.X.X.XXX.X.X.XXX.X.X X...X.....X.X.....X.X XXXXXXXXXXXXXXXXXXXXX </code></pre> </blockquote>
[]
[ { "body": "<pre><code>import random\nfrom grouper import Grouper\nimport sys\n\nX = 20\nY = 20\n\nclass Cell():\n</code></pre>\n\n<p>Either put object as the base class, or don't include the (). It doesn't really matter, but I think this is ugly.</p>\n\n<pre><code> \"\"\"Represents a cell in the maze, with an x and y coordinate and its\n right hand wall and downwards wall.\n\n \"\"\"\n def __init__(self, x, y):\n self.x, self.y = x, y\n self.right_wall = self.down_wall = None\n\nclass Wall():\n \"\"\"Represents a wall in the maze with its two neighbouring cells.\n \"\"\"\n def __init__(self):\n self.neighbours = None\n self.active = True\n\ndef popchoice(seq):\n \"\"\"Takes an iterable and pops a random item from it.\n \"\"\"\n return seq.pop(random.randrange(len(seq)))\n</code></pre>\n\n<p>Call it pop_choice so that you don't have guess where one word begins and the other exists. Also it takes a sequence not an iterable</p>\n\n<pre><code># A mapping of coord tuple to Cell object \ncells = {}\n</code></pre>\n\n<p>I recommend looking at numpy. It has an array type. Basically, you can create an array like: cells = numpy.array( (Y,X), object) which will provide an efficent 2d array structure. That would be nicer to work with and faster then the dictionary you are using.</p>\n\n<pre><code># A list of all the non-edge walls\nwalls = []\n\n# Generate cells\nfor y in range(Y):\n for x in range(X):\n cells[(x, y)] = Cell(x, y)\n</code></pre>\n\n<p>You shouldn't do logic and loops in module scope. They are slower there then in functions.</p>\n\n<pre><code># Generate walls and add to the neighbouring cells\nfor y in range(Y):\n for x in range(X):\n current_cell = cells[(x,y)]\n down_wall = Wall()\n current_cell.down_wall = down_wall\n right_wall = Wall()\n current_cell.right_wall = right_wall\n if y != Y-1:\n down_wall.neighbours = (current_cell, cells[(x,y+1)])\n walls.append(down_wall)\n\n if x != X-1:\n right_wall.neighbours = (current_cell, cells[(x+1,y)])\n walls.append(right_wall)\n</code></pre>\n\n<p>You create Walls in every case, but only sometimes add them to walls. This suggests either a bug or a misnamed walls variable.</p>\n\n<pre><code># Get a list of all the cell objects to give to the Grouper \ncell_list = [cells[key] for key in cells]\n</code></pre>\n\n<p>If using dict, this is the same as <code>cell_list = cells.values()</code> If you use numpy arrays like I suggest its <code>cell_list = cells.flatten()</code></p>\n\n<pre><code>maze = Grouper(cell_list)\n</code></pre>\n\n<p>This variable really isn't holding the maze. Calling it maze is misleading</p>\n\n<pre><code>for _ in range(len(walls)):\n # Pop a random wall from the list and get its neighbours\n wall = popchoice(walls)\n cell_1, cell_2 = wall.neighbours\n # If the cells on either side of the wall aren't already connected,\n # destroy the wall\n if not maze.joined(cell_1, cell_2):\n wall.active = False\n maze.join(cell_1, cell_2)\n</code></pre>\n\n<p>Do it like this instead:</p>\n\n<pre><code>random.shuffle(walls)\nfor wall in walls:\n cell_1, cell_2 = wall.neighbours \n ...\n</code></pre>\n\n<p>That'll be more efficient and is clearer.</p>\n\n<pre><code># Draw the maze\n\nmaze_map = []\n\nx_max = (X*2)+1\ny_max = (Y*2)+1\n</code></pre>\n\n<p>Its not clear why you need x_max, a comment would be helpful explaining that</p>\n\n<pre><code># Make an empty maze map with True for wall and False for space\n# Make top wall\nmaze_map.append([True for _ in range(x_max)])\nfor y in range(1, y_max):\n # Make rows with left side wall\n maze_map.append([True]+[False for _ in range(1, x_max)])\n</code></pre>\n\n<p>Here is another case that can really use numpy's ndarrays:</p>\n\n<pre><code>maze_map = numpy.zeros( (x_max, y_max), bool)\nmaze_map[0,:] = True\nmaze_map[:,0] = True\n</code></pre>\n\n<p>That does the same as all your maze_map code so far. Also, calling maze_map, blocked or something would make it clearer why you are putting True/False in it.</p>\n\n<pre><code># Add the down and right walls from each cell to the map\nfor coords, cell in cells.items():\n x, y = coords\n # Add the intersection wall for each cell (down 1 right 1)\n maze_map[(y*2)+2][(x*2)+2] = True\n if cell.right_wall.active:\n maze_map[(y*2)+1][(x*2)+2] = True\n if cell.down_wall.active:\n maze_map[(y*2)+2][(x*2)+1] = True\n</code></pre>\n\n<p>The formula being used to figure out which cells are being reference is kinda hard to figure out. </p>\n\n<pre><code>def output(string):\n sys.stdout.write(string)\n\n\n\n# Print the map\nfor row in maze_map:\n for tick in row:\n if tick: output('X'),\n else: output('.'),\n output('\\n')\n</code></pre>\n\n<p>The following might be a clearer version for drawing:</p>\n\n<pre><code>def output(blocked):\n sys.stdout.write(\".*\"[blocked])\n\nfor x in range(2*X+1):\n output(True)\nsys.stdout.write('\\n')\n\nfor y in range(Y):\n output(True)\n for x in range(X):\n cell = cells[(x,y)]\n output(False)\n output(cell.right_wall.active)\n sys.stdout.write('\\n')\n output(True)\n for x in range(X):\n cell = cells[(x,y)]\n output(cell.down_wall.active)\n output(True)\n sys.stdout.write('\\n')\n</code></pre>\n\n<p>I think its a bit clearer because it doesn't have formulas like 2*x+1. It needs more comment but I trust you can handle that.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>For numpy, use it like this:</p>\n\n<pre><code>cells = numpy.empty( (X,Y), object)\n# object is the python object type, not the object you want to put into it\n# python's default is to use a number types which are more efficient\n# but we aren't storing numbers\nfor x, y in numpy.ndindex(X, Y):\n cell[index] = Cell(x,y)\n</code></pre>\n\n<p>Speed:</p>\n\n<p>The biggest time-consumer in the code is the grouper code. That code has opted to implemented the simpler rather then more efficient algorithm for the task. You should really implememt the union-find algorithm. That algorithm is crazy efficient, running in for what is all intents and purposes constant time. </p>\n\n<p>Memory:</p>\n\n<p>If memory is a concern, add <strong>slots</strong> to your classes. Look up the documentation for how to do it. However, I wouldn't bother unless you are really running out of memory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:40:35.997", "Id": "2859", "Score": "0", "body": "Thank you so much for the amazing review! I've implemented all of your suggestions: [here](http://bit.ly/i8Y3y5). I didn't quite understand how to use numpy arrays. I wanted to make an empty array to append my cells to, but it wouldn't let me make an array without giving it an object. I've also been trying to make the script more efficient. Here's the result of cProfile with the version linked above: [benchmark](http://paste.pocoo.org/show/364695/). I then tried a different way of making the walls: [script](http://bit.ly/dH6Cn4) + [benchmark](http://paste.pocoo.org/show/364710/). A bit faster." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T12:45:39.647", "Id": "2860", "Score": "0", "body": "Is there a way to make the script use less memory? Are all the objects it's generating the problem?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T13:52:44.913", "Id": "2868", "Score": "1", "body": "@Acrorn, I've responded to your additional questions in the edit" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T13:53:54.460", "Id": "2869", "Score": "1", "body": "@Acorn, as an aside you should checkout http://code.google.com/p/jrfonseca/wiki/Gprof2Dot, it draws a graph showing what your code is doing and make it much easier to see where performance problems lie." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T13:55:16.843", "Id": "2870", "Score": "1", "body": "http://imagebin.org/146412 for an example" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T14:33:55.780", "Id": "2874", "Score": "0", "body": "Thanks for the tips! I tried using this algorithm instead: http://code.activestate.com/recipes/215912-union-find-data-structure/ .. but it took almost exactly the same amount of time as with the other one. Is it not the algorithm you were referring to? Here's the current code: https://gist.github.com/900361" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T19:09:15.373", "Id": "2882", "Score": "0", "body": "Impressive Winston (my +1 was already casted some time ago)!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T19:16:58.810", "Id": "2883", "Score": "1", "body": "@Acorn, I've reworked your code into a version as optimized as I can do: http://pastebin.com/J5Ny83vU The union-find code is taking up the bulk of the running time. The only thing left would be to implement the union-find algorithm in C and use it as an extension module." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T20:06:59.587", "Id": "2884", "Score": "0", "body": "Wow! I'm in awe! It's going to take me a while to get my head around what you've done, especially seeing as I don't have any numpy experience.. but a huge thanks none the less! `77.107 CPU seconds` down to `28.843 CPU seconds` :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T20:19:31.540", "Id": "2885", "Score": "0", "body": "@Acron, yeah numpy takes some practice to get used to. But it can offload a lot of work out of python making it much faster." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T00:11:53.520", "Id": "1627", "ParentId": "1626", "Score": "4" } } ]
{ "AcceptedAnswerId": "1627", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-02T23:00:42.540", "Id": "1626", "Score": "7", "Tags": [ "python" ], "Title": "Generating a random maze using disjoint sets" }
1626
<p>I'm currently working on a project where I am trying to predict a presidential election based on the population density and region of a voter. I wrote a few MATLAB functions to parse the data, but it takes about a minute to run, which seems long. My languages of choice are usually Java or Python and I feel like this calculation would only top a few seconds in those languages.</p> <p>Quick side note: although this is for a school project, it is a simulation class, not a programming class. The code works, which is what is required, the efficiency of the code is personal interest.</p> <p><strong>Main test script</strong> </p> <pre><code>%test metrics printf("starting test\n"); p0 = parsePopMap("density2010.png"); %not shown because this returns quickly [vm,rp,dp] = metrics(p0); printf("republican:%d\ndemocrat:%d\n",rp,dp) </code></pre> <p><strong>metrics.m</strong></p> <pre><code>%generate matrix determining republican vote function [voteMatrix,republicanPixels,democratPixels] = metrics(popGraph) voteMatrix = zeros(rows(popGraph),columns(popGraph)); republicanPixels=0; democratPixels=0; printf("loading regions\n"); %regions is a matrix of size == popGraph, has values from 1-6 %so that any regions(row,column) returns the region of the country load regions; %based on the printout, this happens within seconds printf("calculating votes\n"); %suspected bottleneck for r = [1:rows(popGraph)] for c = [1:columns(popGraph)] pixelRegion = regions(r,c); if (pixelRegion == 6) voteMatrix(r,c)=-1; %because it is water else vote = voteFromLocation(pixelRegion,popGraph(r,c)); voteMatrix(r,c) = vote; if vote&gt;.5 republicanPixels +=1; else democratPixels +=1; end end endfor endfor </code></pre> <p><strong>voteFromLocation.m</strong></p> <pre><code>function vote = voteFromLocation(region,popDens) % array is percent for urban, suburban, rural % probability area will vote republican voteAverage = [ [.375,.51,.79];%pacific coast [.40,.54,.765];%midwest [.30,.47,.48];%Northeast [.485,.625,.725];%south [.46,.62,.795]];%Mountains/plains voteDelta = [ [.05,.06,.1];%pacific coast [.04,.04,.07];%midwest [.12,.06,.10];%northeast [.09,.07,.27];%south [.12,.08,.21]];%mountains/plains %represents the max value of that demographic ruralThresh = 900; %so &lt;=900 is rural subThresh = 1100; % 900&lt;x&lt;=1100 is suburban %urban is anything above 1100 demo = -1; if(popDens&lt;=ruralThresh) demo = 3; elseif(popDens&lt;=subThresh) demo = 2; else demo = 1; end mean = voteAverage(region,demo); stdDev = voteDelta(region,demo); probVoteRep = (mean + stdDev * randn()); vote = probVoteRep; </code></pre> <p>I believe the source of the bottleneck is the <code>for</code> loops of <code>metrics.m</code>. Most matrix processing I've seen uses different approaches, which I believe may be faster.</p>
[]
[ { "body": "<p>Replacing loops in MATLAB with equivalent matrix operations (a technique commonly referred to as <em>vectorization</em>) often, but not always, leads to improvements in performance. However, this frequently results in code that may be difficult for others to read, so it is advisable to use the profiler to identify bottlenecks and then try vectorizing only those sections of code where performance really matters. You could do something like this (outside the loop):</p>\n\n<pre><code>voteMatrix(regions == 6) = -1\n</code></pre>\n\n<p>This is equivalent to the first <code>if</code> condition in your loop. Try to do the same to the <code>else</code> condition. (Hint: you'll need to update your <code>voteFromLocation</code> method to handle arrays in the same manner.)</p>\n\n<p>It's been a long time since I last used MATLAB, so my syntax may not be very accurate, but you get the general idea.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T09:33:35.040", "Id": "24835", "Score": "0", "body": "@Matt Wow, thanks! Your edit makes the answer much better. I wish I could vote you up!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-20T10:18:56.810", "Id": "1999", "ParentId": "1634", "Score": "5" } }, { "body": "<p>The most useful advice, that I can give you, is using the Profiler of Matlab. It lets you measure where a program spends time and what portions of your code you should improve. Besides, see Programming Fundamentals/Performance/Techniques for Improving Performance in the Matlab Help documentation for more information about it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T23:34:17.843", "Id": "21309", "Score": "1", "body": "The MATLAB profiler really is a very nice little tool." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-03T22:06:09.720", "Id": "2806", "ParentId": "1634", "Score": "2" } }, { "body": "<p>You are without doubt correct in suspecting that the bottleneck is in the double loop over the regions matrix.</p>\n\n<p>The sub2ind function is worth knowing about, because it allows you to write something like this:</p>\n\n<pre><code>% load or pass in popGraph, regions, voteAverage, voteDelta\n\n% assert 2 == ndims(popGraph)\n% assert 2 == ndims(regions)\n% assert all(size(popGraph) == size(regions))\n\n[nRows, nCols] = size(popGraph)\n\nisRural = popGraph &lt;= ruralThresh\nisUrban = popGraph &gt;= subThresh\nisSuburban = ~isRural &amp;&amp; ~isUrban\nisSea = 6 == regions\n\ndemo = ones(nRows, nCols)\ndemo(isRural) = 3\ndemo(isSuberban) = 2\ndemo(isUrban) = 1\n\nindices = sub2ind(demo, regions)\n\nmeanvalue = voteAverage(indices)\nstdvalue = voteDelta(indices)\n\nprobVoteRep = meanvalue + stdvalue * randn(nRows, nCols)\nprobVoteRep(isSea) = -1 \n\nrepublicanPixels = zeros(nRows, nCols)\ndemocratPixels = zeros(nRows, nCols)\n\nrepublicanPixels(probVoteRep &gt; 0.5) = 1\ndemocratPixels( probVoteRep &lt;= 0.5) = 1\n</code></pre>\n\n<p>(NOTE: I have not run this code, so it will probably not work without modification).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T21:02:19.003", "Id": "21304", "Score": "0", "body": "It's generally faster to use `zeros(nRows, nCols)` than using `ones`, but in the case above you could just comment the call to `demo(isUrban) = 1` because you already initialized the whole array to ones." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T23:30:59.407", "Id": "21308", "Score": "1", "body": "I used demo = ones(nRows, nCols) because the variable demo was going to be used as an index, and, for quick-and-dirty scripts like this, it feels better to use a valid default value. I would have used nan(nRows, nCols) if correctness was more important, justifying a fail-fast approach). Also, I included the redundant assignment to demo(isUrban) for pedagogical reasons, on the assumption that reasonable readability trumps nth-degree efficiency in this case." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T18:15:46.593", "Id": "12398", "ParentId": "1634", "Score": "5" } } ]
{ "AcceptedAnswerId": "1999", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-04T01:12:00.667", "Id": "1634", "Score": "4", "Tags": [ "optimization", "matrix", "matlab" ], "Title": "Presidential election predictor using matrix-processing" }
1634
<p>Given the following exercise:</p> <blockquote> <p><strong>Exercise 2.5</strong></p> <p>Show that we can represent pairs of nonnegative integers using only numbers and arithmetic operations if we represent the pair a and b as the integer that is the product 2^a * 3^b. Give the corresponding definitions of the procedures cons, car, and cdr.</p> </blockquote> <p>I wrote the following:</p> <pre><code>(define (cons a b) (* (expt 2 a) (expt 3 b))) (define (car x) (if (= 0 (remainder x 3)) (car (/ x 3)) (/ (log x) (log 2)))) (define (cdr x) (if (= 0 (remainder x 2)) (cdr (/ x 2)) (/ (log x) (log 3)))) </code></pre> <p>What do you think?</p>
[]
[ { "body": "<p>Your definition of <code>cons</code> is perfect.</p>\n\n<p>Your definitions of <code>car</code> and <code>cdr</code> contain the <code>log</code> operation, which is a floating-point operation. Not only are its results imprecise, it is not needed to solve this problem. Furthermore, notice that the two definitions look very similar to each other. Whenever one sees a repeated pattern, one ought to consider factoring it out.</p>\n\n<p>To address the above two concerns, one may write a helper function, <code>log-x</code>, which is a specialized log function that takes integer parameters <code>x</code> and <code>n</code> and returns integer p such that x ^ p * y = n, where x does not divide y. Then, <code>car</code> and <code>cdr</code> may call <code>log-x</code>, with <code>x</code> being 2 and 3 respectively.</p>\n\n<p>In the following implementation, I have renamed the definitions so they do not conflict with primitives.</p>\n\n<pre><code>(define (cons-np a b)\n (* (expt 2 a) (expt 3 b)))\n\n(define (log-x x n)\n (if (= (remainder n x) 0)\n (+ 1 (log-x x (/ n x)))\n 0))\n\n(define (car-np np)\n (log-x 2 np))\n\n(define (cdr-np np)\n (log-x 3 np))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T08:59:42.067", "Id": "1656", "ParentId": "1635", "Score": "4" } } ]
{ "AcceptedAnswerId": "1656", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-04T01:40:50.313", "Id": "1635", "Score": "2", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Represent pairs of nonnegative integers using 2^a * 3^b" }
1635
<p>Given the following exercise:</p> <blockquote> <p><strong>Exercise 2.6</strong></p> <p>In case representing pairs as procedures wasn't mind-boggling enough, consider that, in a language that can manipulate procedures, we can get by without numbers (at least insofar as nonnegative integers are concerned) by implementing 0 and the operation of adding 1 as</p> <pre><code>(define zero (lambda (f) (lambda (x) x))) (define (add-1 n) (lambda (f) (lambda (x) (f ((n f) x))))) </code></pre> <p>This representation is known as Church numerals, after its inventor, Alonzo Church, the logician who invented the calculus.</p> <p>Define one and two directly (not in terms of zero and add-1). (Hint: Use substitution to evaluate (add-1 zero)). Give a direct definition of the addition procedure + (not in terms of repeated application of add-1).</p> </blockquote> <p>I wrote this solution. I'm not 100% certain what the correct answer is, and I'm not sure the best way to check my solution so it's possible that I have made a mistake in my answer. Please let me know what you think.</p> <pre><code>;given definitions (define zero (lambda (f) (lambda (x) x))) (define (add-1 n) (lambda (f) (lambda (x) (f ((n f) x))))) ; exercise 2.6: define one and two directly - ; not in terms of zero or add-1 (define one (lambda (f) (lambda (x) (f (f x))))) (define two (lambda (f) (lambda (x) (f ((f (f x)) x))))) (define (church-plus a b) (define (church-num n) (cond ((= 0 a) (lambda (x) x)) ((= 1 a) (lambda (f) (lambda (x) (f ((n f) x))))) (else (church-num (- n 1))))) (church-num (+ a b))) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T20:58:54.840", "Id": "64377", "Score": "0", "body": "I see that you can define 'inc' as `function inc(n,f,x) {n(f(x))}` and `function inc(n,f,x) {f(n(x))}`. Right?" } ]
[ { "body": "<p>Church defined numerals as the repeated application of a function. The first few numerals are defined thus:</p>\n\n<pre><code>(define zero (lambda (f) (lambda (x) x)))\n(define one (lambda (f) (lambda (x) (f x))))\n(define two (lambda (f) (lambda (x) (f (f x)))))\n</code></pre>\n\n<p>... and so on.</p>\n\n<p>To see how <code>one</code> is derived, begin by defining <code>one</code> as <code>(add-1 zero)</code> and then perform the applications in order as shown in the steps below (I have written each function to be applied and its single argument on separate lines for clarity):</p>\n\n<pre><code>;; Givens\n(define add-1 (lambda (n) (lambda (f) (lambda (x) (f ((n f) x))))))\n(define zero (lambda (f) (lambda (x) x)))\n\n(define one\n (add-1 ;; substitute with definition of add-1\n zero))\n\n(define one\n ((lambda (n) ;; apply this function to argument zero\n (lambda (f) (lambda (x) (f ((n f) x)))))\n zero))\n\n(define one\n (lambda (f) (lambda (x) (f ((zero ;; substitute with definition of zero\n f) x)))))\n\n(define one\n (lambda (f) (lambda (x) (f (((lambda (f) ;; apply this function to argument f\n (lambda (x) x))\n f)\n x)))))\n\n(define one\n (lambda (f) (lambda (x) (f ((lambda (x) ;; apply this function to argument x\n x)\n x)))))\n\n(define one\n (lambda (f) (lambda (x) (f x)))) ;; we're done!\n</code></pre>\n\n<p>You may try your hand at <code>two</code> in a similar fashion. =)</p>\n\n<p>By definition, Church numerals are the repeated application of a function. If this function were the integer increment function and the initial argument were 0, then we could generate all natural numbers 0, 1, 2, 3, .... This is an important insight.</p>\n\n<p>Thus, a Church numeral is a function that takes one argument, the increment function, and returns a function that also takes one argument, the additive identity. Thus, if we were to apply a Church numeral to the integer increment function <code>(lambda (n) (+ 1 n))</code> (or simply <code>add1</code> in Scheme), which we then apply to the integer additive identity <code>0</code>, we would get an integer equivalent to the Church numeral as a result. In code:</p>\n\n<pre><code>(define (church-numeral-&gt;int cn)\n ((cn add1) 0))\n</code></pre>\n\n<p>A few tests:</p>\n\n<pre><code>&gt; (church-numeral-&gt;int zero)\n0\n&gt; (church-numeral-&gt;int one)\n1\n&gt; (church-numeral-&gt;int two)\n2\n&gt; (church-numeral-&gt;int (add-1 two))\n3\n&gt; (church-numeral-&gt;int (add-1 (add-1 two)))\n4\n</code></pre>\n\n<p>A Church-numeral addition should take two Church numerals as input, and not integers, as in your code.</p>\n\n<p>We use the insight above about increment functions and additive identities to notice that integer addition is simply repeated incrementing. If we wish to add integers <code>a</code> and <code>b</code>, we begin with the number <code>b</code> and increment it <code>a</code> times to get <code>a + b</code>.</p>\n\n<p>The same applies to Church numerals. Instead of using integer increment function and integer additive identity, we use the Church increment function <code>add-1</code> and we begin with a Church numeral as the additive identity. Thus, we can implement Church-numeral addition as:</p>\n\n<pre><code>(define (plus cn-a cn-b)\n ((cn-a add-1) cn-b))\n</code></pre>\n\n<p>A few examples:</p>\n\n<pre><code>(define three (plus one two))\n(define four (plus two two))\n(define five (plus two three))\n(define eight (plus three five))\n</code></pre>\n\n<p>... and associated tests:</p>\n\n<pre><code>&gt; (church-numeral-&gt;int three)\n3\n&gt; (church-numeral-&gt;int four)\n4\n&gt; (church-numeral-&gt;int five)\n5\n&gt; (church-numeral-&gt;int eight)\n8\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T07:37:50.553", "Id": "2927", "Score": "0", "body": "Thanks for this detailed answer - I need to take some time to understand it :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T08:02:51.580", "Id": "2928", "Score": "0", "body": "How would you define plus without using add-1? I tried substitution but I'm finding it harder than I expected." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T12:16:55.603", "Id": "2932", "Score": "0", "body": "nm - got an answer that seems to work - thanks!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T13:44:41.567", "Id": "2935", "Score": "0", "body": "@jaresty: You don't need to avoid the use of add-1 in your definition of plus. You simply need to avoid its \"repeated application.\" In other words, the definition of plus cannot be recursive." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T10:44:41.890", "Id": "1661", "ParentId": "1636", "Score": "2" } } ]
{ "AcceptedAnswerId": "1661", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-04T02:07:06.193", "Id": "1636", "Score": "2", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Church Numerals - implement one, two, and addition" }
1636
<p>From the Extended Exercise beginning in section <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-14.html" rel="nofollow">2.1.4</a>, you can find exercise 2.8:</p> <blockquote> <p>Exercise 2.8. Using reasoning analogous to Alyssa's, describe how the difference of two intervals may be computed. Define a corresponding subtraction procedure, called sub-interval.</p> </blockquote> <p>I wrote the following:</p> <pre><code>(define (sub-interval x y) (make-interval (- (lower-bound x) (upper-bound y)) (- (upper-bound x) (lower-bound y)))) </code></pre> <p>What do you think?</p>
[]
[ { "body": "<p>Looks great. Don't forget to define <code>lower-bound</code> and <code>upper-bound</code> as <code>car</code> and <code>cdr</code> respectively.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T11:05:23.070", "Id": "1662", "ParentId": "1638", "Score": "1" } } ]
{ "AcceptedAnswerId": "1662", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-04T02:29:41.437", "Id": "1638", "Score": "1", "Tags": [ "scheme", "sicp", "interval" ], "Title": "Interval Subtraction" }
1638
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-14.html" rel="nofollow">2.11</a></p> <blockquote> <p>Exercise 2.11. In passing, Ben also cryptically comments: ``By testing the signs of the endpoints of the intervals, it is possible to break mul-interval into nine cases, only one of which requires more than two multiplications.'' Rewrite this procedure using Ben's suggestion.</p> </blockquote> <p>I wrote the following:</p> <pre><code>(define (negative? . n) (or (= 0 (length n)) (and (&gt; 0 (car n)) (apply negative? (cdr n))))) (define (positive? . n) (or (= 0 (length n)) (and (&gt;= (car n) 0) (apply positive? (cdr n))))) (define (straddles-zero? x) (and (&gt;= 0 (lower-bound x)) (&gt;= (upper-bound x) 0))) (define (fast-mul-interval x y) (let* ((u-x (upper-bound x)) (u-y (upper-bound y)) (l-x (lower-bound x)) (l-y (lower-bound y))) (cond ; same sign - max is neg, or min is pos ((positive? l-y l-x) (make-interval (* l-x l-y) (* u-x u-y))) ((negative? u-y u-x) (make-interval (* u-x u-y) (* l-x l-y))) ; x and y have opposite signs ((and (positive? l-x) (negative? u-y)) (make-interval (* u-x l-y) (* l-x u-y))) ((and (positive? l-y) (negative? u-x)) (make-interval (* l-x u-y) (* u-x l-y))) ; x straddles zero ((straddles-zero? x) (if (straddles-zero? y) (make-interval (min (* l-x u-y) (* l-y u-x)) (max (* l-x l-y) (* u-x u-y))) (if (negative? u-y) (make-interval (* u-x l-y) (* l-x l-y)) (make-interval (* l-x u-y) (* u-x u-y))))) ((straddles-zero? y) (if (negative? u-x) (make-interval (* u-y l-x) (* l-y l-x)) (make-interval (* l-y u-x) (* u-y u-x))))))) </code></pre> <p>What do you think?</p> <hr> <p>The new version is here:</p> <pre><code>(define (fast-mul-interval x y) (let ((l-x (lower-bound x)) (u-x (upper-bound x)) (l-y (lower-bound y)) (u-y (upper-bound y))) (cond ((&gt; l-x 0) ;x &gt; 0 (cond ((&gt; l-y 0) ;y &gt; 0 (make-interval (* l-x l-y) (* u-x u-y)) ) ((&lt; u-y 0) ;y &lt; 0 (make-interval (* u-x l-y) (* l-x u-y)) ) (else ;y contains 0 (make-interval (* u-x l-y) (* u-y u-x)) )) ) ((&gt; l-y 0) ;y &gt; 0 (if (&lt; u-x 0) ; x &lt; 0 (make-interval (* u-y l-x) (* l-y u-x)) ; x contains 0 (make-interval (* l-x u-y) (* u-x l-y)) ) ) ((&lt; u-x 0) ;x &lt; 0 (if (&lt; u-y 0) ; y &lt; 0 (make-interval (* u-x u-y) (* l-x l-y)) ; y contains 0 (make-interval (* u-y u-x) (* l-y u-x)) ) ) ((&lt; u-y 0) ;y &lt; 0 and x contains 0 (make-interval (* u-y u-x) (* l-x u-y)) ) (else ;x and y both contain 0 (let ((p1 (* l-x l-y)) (p2 (* l-x u-y)) (p3 (* u-x u-y)) (p4 (* u-x l-y))) (make-interval (min p1 p2 p3 p4) (max p1 p2 p3 p4))) )))) </code></pre>
[]
[ { "body": "<p>Your logic is correct.</p>\n\n<p>You may use <code>let</code> instead of <code>let*</code> since the value of one binding does not depend on the value of another binding.</p>\n\n<p>Since efficiency is important, you can cut back on the number of comparisons as well. For example, if <code>u-x</code> is negative, then <code>l-x</code> is also negative and need not be tested. For this reason, the functions <code>negative?</code>, <code>positive?</code> and <code>straddles-zero?</code> are not necessary. Instead, you can simply use nested <code>if</code>s:</p>\n\n<pre><code>(if (&lt; u-x 0)\n ; x is in R &lt; 0\n (if (&lt; u-y 0)\n ; y is in R &lt; 0\n ...\n (if (&lt; l-y 0)\n ; y contains 0\n ...\n ; y is in R &gt;= 0\n ... ))\n (if (&lt; l-x 0)\n ; x contains 0\n ...\n ; x is in R &gt;= 0\n ... ))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-07T00:51:45.097", "Id": "3669", "Score": "0", "body": "You can simplify that further by using `cond`, if I'm not mistaken." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T23:30:20.217", "Id": "1691", "ParentId": "1639", "Score": "1" } } ]
{ "AcceptedAnswerId": "1691", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-04T04:59:02.780", "Id": "1639", "Score": "1", "Tags": [ "scheme", "sicp", "interval" ], "Title": "A more efficient mul-interval" }
1639
<p>Since I did not get a satisfactory answer <a href="https://stackoverflow.com/questions/5531130/an-efficient-way-to-shuffle-a-json-array-in-java">here</a> (and I really needed to get it going on this weekend), I decided to implement my own Fisher–Yates shuffle, porting the code I found in other SO posts. I know my programming technique is far from optimal, so I decided to post this here.</p> <p>What do you think? Can it be improved?</p> <pre><code>public static JSONArray shuffleJsonArray (JSONArray array) throws JSONException { // Implementing Fisher–Yates shuffle Random rnd = new Random(); for (int i = array.length() - 1; i &gt;= 0; i--) { int j = rnd.nextInt(i + 1); // Simple swap Object object = array.get(j); array.put(j, array.get(i)); array.put(i, object); } return array; } </code></pre>
[]
[ { "body": "<p>It runs in <span class=\"math-container\">\\$O(n)\\$</span> time so I'm not sure there's a way to improve this. It looks like you've implemented the algorithm pretty well, according the <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow noreferrer\">Fisher-Yates shuffle</a>.</p>\n\n<p>You might consider not using <code>Object</code> if you can use the type that's stored in the array instead.</p>\n\n<p>I also thought I read somewhere that it should be safe to loop to <span class=\"math-container\">\\$n/2\\$</span> instead of <span class=\"math-container\">\\$n\\$</span> (because you're swapping with elements from <span class=\"math-container\">\\$1 \\cdots n\\$</span> so in theory, you shouldn't need to swap every element), but I don't have hard proof of that, so you take your chances ;)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-04T15:30:06.590", "Id": "2888", "Score": "0", "body": "Thanks for looking at it. I based it on that wikipedia page and a couple of posts in SO. I will keep in mind the n/2 loops to change it if needed. Lastly, I wrote it using `JSONObject` instead of `Object` but then I changed it to make it more reusable. What would be the advantage of using `JSONObject` instead?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-04T15:36:49.153", "Id": "2890", "Score": "0", "body": "@Aleadam: I don't know the JSONArray datatype well, I guess I was trying to suggest to use Java generics so you don't have to use `Object`, but I don't know if you can do that with JSONArray." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-17T20:58:49.777", "Id": "19021", "Score": "0", "body": "I also think that there is no faster way for shuffling an array. Every try in doing it faster (O(log n) or O(sqrt n)) would result in a poorly shuffled array." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-04-04T15:15:10.623", "Id": "1642", "ParentId": "1640", "Score": "2" } } ]
{ "AcceptedAnswerId": "1642", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-04T06:08:39.277", "Id": "1640", "Score": "3", "Tags": [ "java", "array", "json", "shuffle" ], "Title": "Shuffling a JSON array in Java" }
1640
<p>I've just tried to do some code for <code>TreeMap</code>. The <code>TreeMap</code> concept can be found <a href="http://hcil.cs.umd.edu/trs/91-03/91-03.html" rel="nofollow">here</a>. As an exercise I've tried to find the solution without reading the article.</p> <p>Then, I came across this code. The main problem is that I missed the algorithm, my code is not so simple, elegant, short and clean. And I used OOP because I didn't know how to do without it (at university I learned no C, no functional programming, only OOP).</p> <p>Another issue is that I wanted to make a list of rectangles with no dependencies from the render engine (no matplotlib, maybe I'm writing something for openGL and pyqt), so I need some Rectangle with coordinates normalized between 0 and 1.</p> <p>This is my code, which I'm no proud of: it is too verbose, redundant and not KISS, and maybe it could also be a bit more readable:</p> <pre><code>class Rectangle(object): def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width self.height = height def __repr__(self): return "Rect - x:{0}, y:{1}, width:{2}, height:{3}".format(self.x, self.y, self.width, self.height) class Node(object): iter_method = iter size_method = int def __init__(self, content, depth=0): self.depth = depth self.childs = [] try: self.value = Node.size_method(content) except TypeError: self.childs = [Node(x, depth+1) for x in Node.iter_method(content)] self.value = sum(child.value for child in self.childs) @property def leaf(self): return len(self.childs)&gt;0 def __repr__(self): s = "{0}Node:{1}".format('\t'*self.depth, self.value) if self.leaf: s += '\n'+'\n'.join(str(child) for child in self.childs) return s class TreeMap(object): def __init__(self, root): self.root = root self.rects = [] self.build(self.root, Rectangle(0,0,1,1)) def build(self, node, rect, horizzontal=True): node.rect = rect self.rects.append( rect ) sizes = [child.value for child in node.childs] total_size = node.value if horizzontal: x = 0.0 for child in node.childs: y = rect.y w = (child.value*rect.width) / float(total_size) h = rect.height self.build(child, Rectangle(x,y,w,h), not horizzontal) x += w else: y = 0.0 for child in node.childs: x = rect.x h = (child.value*rect.height) / float(total_size) w = rect.width self.build(child, Rectangle(x,y,w,h), not horizzontal) x += w import unittest class Test_TreeMap(unittest.TestCase): def test_build_depth0(self): nodes = (2,1,(2,2)) known = (1, 1), (2.0/7, 1), (1.0/7, 1), (4.0/7, 1), (4.0/7, 0.5), (4.0/7, 0.5) Node.iter_method = iter Node.size_method = int root = Node(nodes) t = TreeMap(root) widths = tuple((rect.width, rect.height) for rect in t.rects) self.assertEqual(known, widths) unittest.main() </code></pre>
[]
[ { "body": "<p><strong>repr</strong> shouldn't be used as a general pretty print method. It should give a short description of an object, preferably one which looks like code. </p>\n\n<p>Its best to use correct english in variable names, i.e. children not childs.</p>\n\n<p>Rather then combining a lot of strings, use StringIO</p>\n\n<p>The TreeMap.build method is mostly concerned with a node. It should really be on the node class. The only interaction it has with TreeMap is the rectangles. But since you store those on the object anyway, we will provide a seperate iteration for those.</p>\n\n<p>Once we've moved build into Node, TreeMap doesn't do anything, so we eliminate it.</p>\n\n<p>There doesn't seem to be a really good reason for a Node to worry about its own depth.</p>\n\n<p>I don't like the Node constructor. I don't think that a constructor should be concerned with conversion from a seperate format like that. Format conversions should be done in other functions. Since iter_method and size_method are only for that conversion, they should be arguments there</p>\n\n<p>The tricky bit is the Node.build function. You have two for loops which look pretty much the same. We can combine them by pulling the bits of logic unique to each direction out. </p>\n\n<p>My results:</p>\n\n<pre><code>from StringIO import StringIO\n\nclass Rectangle(object):\n\n def __init__(self, x, y, width, height):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n\n def __repr__(self):\n return \"Rectangle({0},{1},{2},{3})\".format(\n self.x, self.y, self.width, self.height)\n\n def slice(self, horizontal, start, length):\n if horizontal:\n return Rectangle(self.x + start, self.y, length, self.height)\n else:\n return Rectangle(self.x, self.y + start, self.width, length)\n\n\nclass Node(object):\n\n def __init__(self, children, value):\n self.children = children\n self.value = value\n\n @classmethod\n def from_nested_tuple(class_, data):\n return class_.from_data(data, iter, int)\n\n @classmethod\n def from_data(class_, data, iter_method, size_method):\n try:\n iterable = iter_method(data)\n except TypeError:\n value = size_method(data)\n return class_([], value)\n else:\n children = [ class_.from_data(item, iter_method, size_method)\n for item in iterable]\n return Node(children, sum(child.value for child in children))\n\n def __repr__(self):\n return \"Node&lt; {}, {} children&gt;\".format( self.value, len(self.children))\n\n def _pretty_print(self, output, depth):\n output.write('\\t' * depth)\n output.write('Node: {}'.format(self.value))\n output.write('\\n')\n for child in self.children:\n child.pretty_print(output, depth + 1)\n\n\n def pretty_print(self):\n output = StringIO()\n self._pretty_print(output, 0)\n return output.get_value()\n\n def build(self, rect, horizontal=True):\n self.rect = rect\n\n sizes = [child.value for child in self.children]\n total_size = self.value\n\n if horizontal:\n space = rect.width\n else:\n space = rect.height\n\n position = 0.0\n for child in self.children:\n length = child.value * space\n child.build( rect.slice(horizontal, position, length), \n not horizontal)\n position += length\n\n def rectangles(self):\n yield self.rect\n for child in self.children:\n for rect in child.rectangles():\n yield rect\n\n\n\nimport unittest \n\nclass Test_TreeMap(unittest.TestCase):\n\n def test_build_depth0(self):\n nodes = (2,1,(2,2))\n\n known = (1, 1), (2.0/7, 1), (1.0/7, 1), (4.0/7, 1), (4.0/7, 0.5), (4.0/7, 0.5)\n\n Node.iter_method = iter\n Node.size_method = int\n root = Node.from_nested_tuple(nodes)\n root.build( Rectangle(0,0,1,1) )\n\n widths = tuple((rect.width, rect.height) for rect in root.rectangles())\n self.assertEqual(known, widths)\nunittest.main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T12:22:09.123", "Id": "2910", "Score": "0", "body": "going farther in the project moving the recursion to contructor the tree in a separate method (from_data) and not in constructor is revealed a very useful advice!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-04T20:44:59.493", "Id": "1645", "ParentId": "1644", "Score": "7" } } ]
{ "AcceptedAnswerId": "1645", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-04T18:13:32.763", "Id": "1644", "Score": "5", "Tags": [ "python", "tree" ], "Title": "TreeMap implementation" }
1644
<p>SICP exercise 2.18 asks the following:</p> <blockquote> <p>Exercise 2.18. Define a procedure reverse that takes a list as argument and returns a list of the same elements in reverse order:</p> </blockquote> <pre><code>(reverse (list 1 4 9 16 25)) (25 16 9 4 1) </code></pre> <p>I wrote this iterative function:</p> <pre><code>(define (reverse n) (define (iter a b) (if (null? a) b (iter (cdr a) (cons (car a) b)))) (iter n null)) </code></pre> <p>I could not think of a way to do this recursively. Is there a better way to write this function? Is it possible to do it recursively?</p>
[]
[ { "body": "<p>Not much different from yours, and kind of sloppy with the list mechanics (id generally prefer to use <code>cons</code> over <code>append</code>)</p>\n\n<pre><code>&gt; (define (rev l)\n (if (null? (cdr l))\n l\n (append (rev (cdr l)) (list (car l)))))\n&gt; (rev '(1 2 3 4))\n(4 3 2 1)\n</code></pre>\n\n<p>This, on the other hand, i like</p>\n\n<pre><code>(define (rev l) (foldr (lambda (a b) (append b (list a))) l '()))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T06:28:42.873", "Id": "2893", "Score": "0", "body": "Interesting. I didn't know about append - how is it different from cons?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T06:32:56.737", "Id": "2894", "Score": "0", "body": "gives a proper null-terminated list when both arguments are proper lists" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T06:40:12.703", "Id": "2895", "Score": "0", "body": "there might be a way with just car/cons/cdr to do the same, but i played around for a while had a hard time making the list come out properly. if you can find a way to tweak mine like that plz let me know" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T15:36:59.013", "Id": "2912", "Score": "0", "body": "@jaresty: `append` is O(n) on the lengths of all the given lists except the last. `cons` is O(1)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T06:13:23.493", "Id": "1650", "ParentId": "1648", "Score": "0" } }, { "body": "<p>Here's a recursive definition of reverse (named <code>rev</code>) that uses primitives (<code>car</code>/<code>cdr</code>/<code>cons</code>) and an inner definition of <code>snoc</code> (reverse <code>cons</code>):</p>\n\n<pre><code>(define (rev lis)\n (define (snoc elem lis)\n (if (null? lis)\n (cons elem lis)\n (cons (car lis) (snoc elem (cdr lis)))))\n (if (null? lis)\n lis\n (snoc (car lis) (rev (cdr lis)))))\n</code></pre>\n\n<p>Obviously, this definition is not meant to be efficient. =)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T07:47:09.463", "Id": "1654", "ParentId": "1648", "Score": "1" } } ]
{ "AcceptedAnswerId": "1654", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-05T05:24:34.233", "Id": "1648", "Score": "2", "Tags": [ "recursion", "lisp", "scheme", "sicp" ], "Title": "Design a procedure to reverse a list" }
1648
<blockquote> <p><strong>Exercise 2.20</strong></p> <p>The procedures +, *, and list take arbitrary numbers of arguments. One way to define such procedures is to use define with dotted-tail notation. In a procedure definition, a parameter list that has a dot before the last parameter name indicates that, when the procedure is called, the initial parameters (if any) will have as values the initial arguments, as usual, but the final parameter's value will be a list of any remaining arguments.</p> <p>For instance, given the definition</p> <pre><code>(define (f x y . z) &lt;body&gt;) </code></pre> <p>the procedure f can be called with two or more arguments. If we evaluate</p> <pre><code>(f 1 2 3 4 5 6) </code></pre> <p>then in the body of f, x will be 1, y will be 2, and z will be the list (3 4 5 6). Given the definition</p> <pre><code>(define (g . w) &lt;body&gt;) </code></pre> <p>the procedure g can be called with zero or more arguments. If we evaluate</p> <pre><code>(g 1 2 3 4 5 6) </code></pre> <p>then in the body of g, w will be the list</p> <pre><code>(1 2 3 4 5 6) </code></pre> <p>Use this notation to write a procedure same-parity that takes one or more integers and returns a list of all the arguments that have the same even-odd parity as the first argument. For example,</p> <pre><code>(same-parity 1 2 3 4 5 6 7) (1 3 5 7) (same-parity 2 3 4 5 6 7) (2 4 6) </code></pre> </blockquote> <p>I wrote the following:</p> <pre><code>(define (same-parity n . l) (define (even? n) (= (remainder n 2) 0)) (define (odd? n) (not (even? n))) (define (rec n . l) (define (include-and-go) (cons (car l) (apply rec (cons n (cdr l))))) (define (exclude-and-go) (apply rec (cons n (cdr l)))) (if (null? l) null (if (or (and (even? (car l)) (even? n)) (and (odd? (car l)) (odd? n))) (include-and-go) (exclude-and-go)))) (cons n (apply rec (cons n l)))) </code></pre> <p>Is there a better way?</p>
[]
[ { "body": "<p>If one were to abstract out the filter function (named <code>filt</code> here), it would greatly simplify writing <code>same-parity</code>:</p>\n\n<pre><code>(define (filt test? lis)\n (cond\n ((null? lis) lis)\n ((test? (car lis)) (cons (car lis) (filt test? (cdr lis))))\n (else (filt test? (cdr lis)))))\n\n(define (same-parity n . lis)\n (filt (if (odd? n) odd? even?) lis))\n</code></pre>\n\n<p>The filter function is common enough that it is part of the Scheme standard and is appropriately named <code>filter</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T08:06:45.773", "Id": "1655", "ParentId": "1649", "Score": "2" } }, { "body": "<p>You should write a filter, its a standard part of the toolkit. its not to hard. Adeel's is good. It can also be written from fold if you'd like to.</p>\n\n<p>Once you have filter, do the following.</p>\n\n<pre><code>(define (parity-match n . l)\n (if (odd? n)\n (filter odd? l)\n (filter even? l)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T08:59:44.207", "Id": "1657", "ParentId": "1649", "Score": "1" } } ]
{ "AcceptedAnswerId": "1655", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-05T06:05:56.427", "Id": "1649", "Score": "1", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Filter a list of integers by parity" }
1649
<blockquote> <p><strong>Exercise 2.23</strong></p> <p>The procedure for-each is similar to map. It takes as arguments a procedure and a list of elements. However, rather than forming a list of the results, for-each just applies the procedure to each of the elements in turn, from left to right. The values returned by applying the procedure to the elements are not used at all -- for-each is used with procedures that perform an action, such as printing. For example,</p> <pre><code>(for-each (lambda (x) (newline) (display x)) (list 57 321 88)) 57 321 88 </code></pre> <p>The value returned by the call to for-each (not illustrated above) can be something arbitrary, such as true. Give an implementation of for-each.</p> </blockquote> <p>I wrote the following:</p> <pre><code>(define (for-each l f) (f (car l)) (when (&gt; (length l) 1) (for-each (cdr l) f))) </code></pre> <p>Is this a good answer?</p>
[]
[ { "body": "<p>No. Your function needs to handle the empty list too. If your implementation supports <code>unless</code>, use this:</p>\n\n<pre><code>(define (for-each f l)\n (unless (null? l)\n (f (car l))\n (for-each f (cdr l))))\n</code></pre>\n\n<p>Otherwise, the R5RS-compatible version would be:</p>\n\n<pre><code>(define (for-each f l)\n (cond ((not (null? l))\n (f (car l))\n (for-each f (cdr l)))))\n</code></pre>\n\n<p>Granted, the implicit <code>begin</code> behaviour of <code>cond</code> is not explained until Chapter 3. So if you want to avoid using that, here's a similar version that uses <code>let</code> to simulate <code>begin</code>:</p>\n\n<pre><code>(define (for-each f l)\n (cond ((not (null? l))\n (let ()\n (f (car l))\n (for-each f (cdr l))))))\n</code></pre>\n\n<p>Now, here, too, the <code>let</code> body is an implicit <code>begin</code>. If you want to work around <em>that</em>, too, then bind the result of the side-effect to a dummy variable:</p>\n\n<pre><code>(define (for-each f l)\n (cond ((not (null? l))\n (let ((unused (f (car l))))\n (for-each f (cdr l))))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-05T06:47:13.960", "Id": "1652", "ParentId": "1651", "Score": "3" } }, { "body": "<p>The solution below relies on neither unless nor begin. This seems somewhat desirable because neither of these procedures has been introduced in the text at this point.</p>\n\n<pre><code>(define (for-each proc items)\n (if (null? items)\n #t\n (if ((lambda (x) #t) (proc (car items)))\n (for-each proc (cdr items)))))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-11T00:17:40.040", "Id": "126800", "Score": "0", "body": "It's true that `begin` isn't introduced until chapter 3. However, `(let () ...)` (since `let`'s body has an implicit `begin`) is a better workaround for that than using the `(lambda (x) #t)` hack that you have, since the latter doesn't make clear that `(proc (car items))` is evaluated purely for side effects." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T21:20:48.840", "Id": "43252", "ParentId": "1651", "Score": "2" } } ]
{ "AcceptedAnswerId": "1652", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-05T06:23:34.690", "Id": "1651", "Score": "1", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "A definition of for-each" }
1651
<p>I don't see any way to refactor this, but something tells me I'm missing something.</p> <pre><code>if val.instance_of?(Hash) then @fields.has_key?(key) ? @fields[key].merge!(val) : @fields.merge!({key =&gt; val}) elsif val.instance_of?(Array) then @fields.has_key?(key) ? @fields[key].push(val) : @fields.merge!({key =&gt; Array.new.push(val)}) else @fields.has_key?(key) ? @fields[key] &lt;&lt; val : @fields.merge!({key =&gt; val}) end </code></pre> <p>The point of the method is to take a hash and insert a value of different types if the key doesn't exist:</p> <p>{:key => "value}, {:key = ["value"]}, or {:key => {:k => "value"}}</p> <p>or append if it does:</p> <p>{:key=> "value1value2"}, {:key => [["value1"], ["value2"]], {:key => {:k1 => "value1", :k2 => "value2"}}</p> <p>it does work as intended, so my issue is thinking that there is likely an easier way to do it.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T12:16:06.380", "Id": "2909", "Score": "2", "body": "Could you explain what you want the code to do? I have a feeling that it does not do what you want in all cases (for example because `push` and `<<` do the same thing on arrays, but you seem to use them as if they were different), but of course I can't tell for sure unless you specify what you want." } ]
[ { "body": "<p>There are some obvious targets for refactoring, such as <code>Array.new.push(val)</code> instead of <code>[val]</code>, but to me this entire code block stinks. The most obvious <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow\">smell</a> is the type checking necessitated by a lack of duck typing.</p>\n\n<p>Can you explain more about the tensions that lead to this design? I suspect the best solution is further up the context stack than what you have provided.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-06T18:48:20.093", "Id": "1683", "ParentId": "1663", "Score": "6" } }, { "body": "<p>There are several options for refactoring your code.\nIn any case we must get value for given key. </p>\n\n<ol>\n<li>If value not exist (same as nil by default in a hash) we must set value as result value ( standart behavior for hash).</li>\n<li>If value exist we should do something based on existing or given value class. IMHO \"case\" operator looking very good for this. In \"when\" option we can set one or more classes to redefine standart behavior.</li>\n</ol>\n\n<p>Code wrapped into class for easy explore it in irb. It just sample for presentation</p>\n\n<pre><code>class MyHash &lt; Hash\n def []=(key,val)\n super(key, \n case (old = self[key]).class\n when Array, String\n old + val\n when Hash, MyHash\n old.merge(val)\n else\n val \n end\n )\n end\nend\n</code></pre>\n\n<p>Ok, now some testing in irb:</p>\n\n<p>Strings</p>\n\n<pre><code> &gt; mh = MyHash.new()\n =&gt; {}\n\n &gt; mh[:k1] = \"str1\"\n =&gt; \"str1\"\n\n &gt; mh\n =&gt; {:k1=&gt;\"str1\"}\n\n &gt; mh[:k1] = \"str2\"\n =&gt; \"str2\"\n\n &gt; mh\n =&gt; {:k1=&gt;\"str1str2\"}\n</code></pre>\n\n<p>Arrays</p>\n\n<pre><code>&gt; mh[:k2] = [1]\n =&gt; [1] \n\n &gt; mh\n =&gt; {:k1=&gt;\"str1str2\", :k2=&gt;[1]} \n\n &gt; mh[:k2] = [2]\n =&gt; [2] \n\n &gt; mh\n =&gt; {:k1=&gt;\"str1str2\", :k2=&gt;[1, 2]} \n</code></pre>\n\n<p>Hashes</p>\n\n<pre><code> &gt; mh[:k3] = {1=&gt;:a}\n =&gt; {1=&gt;:a} \n\n &gt; mh\n =&gt; {:k1=&gt;\"str1str2\", :k2=&gt;[1, 2], :k3=&gt;{1=&gt;:a}} \n\n &gt; mh[:k3] = {2=&gt;:b}\n =&gt; {2=&gt;:b} \n\n &gt; mh\n =&gt; {:k1=&gt;\"str1str2\", :k2=&gt;[1, 2], :k3=&gt;{1=&gt;:a, 2=&gt;:b}} \n</code></pre>\n\n<p>This code have many issues, behavior when old and new value have different class, Arrays result should be array of array etc. but as stated above it is just sample.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T22:50:12.993", "Id": "1833", "ParentId": "1663", "Score": "3" } } ]
{ "AcceptedAnswerId": "1833", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-05T11:56:53.763", "Id": "1663", "Score": "3", "Tags": [ "ruby" ], "Title": "Add data of unknown type to a hash" }
1663
<p>I have a list of map entries, and I need an iterable that returns the keys. </p> <p>Of course, we could be naive and copy over into a new collection of the desired type, but that's inefficient.</p> <p>So let's see if we can provide a view of the existing structure using generics. Yes, I was able to do that, but it's not perfect: it gives unchecked conversions when it's passed to a function expecting Iterable&LT;K&GT;. Could it be improved to avoid these warnings?</p> <p>Perhaps it could implement Iterable&LT;K&GT; similar to the commented out line which is the path I attempted but couldn't complete. Can you figure out the similar but correct (no warnings on usage) generic implementation?</p> <p>This should help demonstrate how the ListKeyIterable is used:</p> <pre><code>List&amp;LT; Map.Entry &amp;LT; Long,String &amp;GT; &amp;GT; list; void traverse( Iterable&amp;LT;Long&amp;GT; ) {} traverse( new ListKeyIterable&amp;LT;List&amp;LT;Map.Entry&amp;LT;Long,String&amp;GT;&amp;GT;&amp;GT;( list ); </code></pre> <p>Here is the working code, but it gives unchecked conversion warning on the call to traverse().</p> <pre><code>class ListKeyIterable&amp;LT;T extends List&amp;LT;? extends Map.Entry&amp;LT;?,?&amp;GT;&amp;GT;&amp;GT; implements Iterable //class ListKeyIterable&amp;LT;T extends List&amp;LT;? extends Map.Entry&amp;LT;K,?&amp;GT;&amp;GT;&amp;GT; implements Iterable&amp;LT;K&amp;GT; { T list; public ListKeyIterable( T list ) { this.list = list; } class ListKeyIterator&amp;LT;K&amp;GT; implements Iterator&amp;LT;K&amp;GT; { Iterator&amp;LT;Map.Entry&amp;LT;K,?&amp;GT;&amp;GT; iterator; public ListKeyIterator( Iterator&amp;LT;Map.Entry&amp;LT;K,?&amp;GT;&amp;GT; iterator ) { this.iterator = iterator; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public K next() { return iterator.next().getKey(); } @Override public void remove() { throw new RuntimeException( "ValueListIterator remove() not implemented." ); } } @Override public Iterator iterator() { return new ListKeyIterator( list.iterator() ); } //@Override public &amp;LT;K&amp;GT; Iterator&amp;LT;K&amp;GT; iterator() { return new ListKeyIterator( list.iterator() ); } } </code></pre>
[]
[ { "body": "<p>Just parameterize with both types:</p>\n\n<pre><code>class ListKeyIterable&lt;K,T extends List&lt;? extends Map.Entry&lt;K,?&gt;&gt;&gt; implements Iterable&lt;K&gt;;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T22:12:00.157", "Id": "2920", "Score": "0", "body": "Yes, that's the ticket. Caller needs to of course specify both now: traverse( new ListKeyIterable<Long,List<Map.Entry<Long,String>>>( list );" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T22:07:51.313", "Id": "1670", "ParentId": "1668", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-05T21:30:23.580", "Id": "1668", "Score": "2", "Tags": [ "java", "iterator" ], "Title": "Can you make this Key-interable view of a List of Maps better?" }
1668
<p>I'm changing code that writes data to a DB, so I have a dump (a text file) of an earlier run to compare against, to ensure that my changes don't screw things up. Here goes:</p> <pre><code>def dbcheck(cursor): dbresult = list() cursor.execute("SELECT COLUMN FROM TABLE") for item in cursor.fetchall(): line = item[0] + "\n" dbresult.append(line) with open(dbdump) as f: for n, line in enumerate(f): if line != dbresult[n]: print("DB content does not match original data!") </code></pre> <p>This code runs fine, but I'm worried that <code>dbresult</code> can grow really large, so am looking for a less risky way of doing this. I'm also curious of what else can be improved.</p> <p>[<strong>sidenote</strong>] I left out exception handling for the sake of simplicity/clarity.</p>
[]
[ { "body": "<p>Use zip to iterate over both iterators at the same time. It'll only use the memory needed to hold a single entry from each at a time.</p>\n\n<pre><code>def dbcheck(cursor):\n cursor.execute(\"SELECT COLUMN FROM TABLE\")\n with open(dbdump) as f:\n for item, line in zip(cursor, f):\n if line != item[0] + '\\n':\n print(\"DB content does not match original data!\")\n</code></pre>\n\n<p>If using python 2.x use <code>itertools.izip</code> instead of <code>zip</code>. zip puts everything in a huge list which won't be very efficient.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T23:34:58.390", "Id": "2921", "Score": "0", "body": "Looks more elegant, however wasn't there talk about stuff like zip and lambda not being very Pythonic?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T23:36:51.667", "Id": "2922", "Score": "0", "body": "Aren't you missing `cursor.fetchall()`?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T00:31:21.957", "Id": "2923", "Score": "0", "body": "@Tshepange, fetchall() returns the entire result of the query as a list. But you can also iterate over the cursor directly to get the results. Since you want to iterate over all the rows in the table, this is what you want." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T00:37:57.923", "Id": "2924", "Score": "0", "body": "I've never heard zip accused of not being pythonic, lambda and reduce, yes. But zip belongs with enumerate, itertools and all that perfectly pythonic stuff." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T00:42:53.830", "Id": "2925", "Score": "1", "body": "And to be clear, it is not as though certain features of python are unpythonic and should be avoided. The goal of pythonicity is readable code. Some features tend to produce unreadable code and thus get a bad rap." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T07:21:13.493", "Id": "2926", "Score": "0", "body": "\"It'll only use the memory needed to hold a single entry from each at a time.\" - Under Python 3, yes, under Python 2 it will return one megalist." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T12:16:06.350", "Id": "2931", "Score": "0", "body": "@Lennart, yes I'll add that to the answer" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T22:39:42.003", "Id": "1671", "ParentId": "1669", "Score": "4" } }, { "body": "<p>This should do it:</p>\n\n<pre><code>def dbcheck(cursor):\n cursor.execute(\"SELECT COLUMN FROM TABLE\")\n with open(dbdump) as f:\n for item in cursor:\n if f.readline() != item + '\\n'\n print(\"DB content does not match original data!\")\n</code></pre>\n\n<p>No need to read either the whole column nor the whole file before iterating.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T07:15:26.573", "Id": "1674", "ParentId": "1669", "Score": "5" } }, { "body": "<p>You can use itertools.izip to avoid reading all of both sets of data before iterating. Also, this version breaks immediately on finding a problem:</p>\n\n<pre><code>import itertools as it\ndef dbcheck(cursor):\n with open(dbdump) as f:\n cursor.execute(\"SELECT COLUMN FROM TABLE\")\n for fline, dbrec in it.izip(f, cursor):\n if fline.strip() != dbrec[0]:\n print(\"DB content does not match original data!\")\n break\n</code></pre>\n\n<p>Here is a version that reports the line number of the file, along with the mismatched data, and continues for all lines in the file. Also note that it's not calling print as a function, but rather using parenthesis to group the expression creating the string to print (in Python 3.x it is calling print as a function):</p>\n\n<pre><code>import itertools as it\ndef dbcheck(cursor):\n with open(dbdump) as f:\n cursor.execute(\"SELECT COLUMN FROM TABLE\")\n for lineno, fline, dbrec in it.izip(it.count(), f, cursor):\n if fline.strip() != dbrec[0]:\n print(\"Line %d: File: %s, DB: %s\" % \n (lineno, \n fline.strip(), \n dbrec[0].strip()))\n</code></pre>\n\n<p>Also, in Python 3, the \"zip\" function is the same as itertools.zip, I think.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T00:01:25.893", "Id": "2947", "Score": "1", "body": "2 issues: the very last line, why strip `brec`, and why call it `brec` :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T00:06:10.757", "Id": "2948", "Score": "1", "body": "Why introduce a variable, `res`? Can't we just play with `cursor`?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T00:42:32.553", "Id": "2949", "Score": "0", "body": "@Tshepang, thanks for the catch. brec in the second example should have been dbrec. I've edited the example to use the correct name." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T00:44:09.073", "Id": "2950", "Score": "1", "body": "@Tshepang, I'm stripping both the line entry and the database value assuming: 1. whitespace on the ends isn't important, and 2. there will be additional whitespace on both the file line and the database record. The file line will have the end-of-line characters, and the database record may have padding, since some drivers pad the values to the full column width." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T00:45:46.073", "Id": "2951", "Score": "0", "body": "@Tshepang, I use \"res\" as the resultset from the cursor only because it's more difficult to format the \"for\" construct with the execute() inline. It could be done, of course, but at some point naming a subexpression is as clear as anonymous composition." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T09:57:56.573", "Id": "2965", "Score": "1", "body": "@TheUNIXMan: I don't understand what you say, but can't you do `it.izip(it.count(), f, cursor)` instead of introducing res?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T18:14:20.247", "Id": "3138", "Score": "0", "body": "It depends on what \"cursor\" is, I guess. If it's a result from a query, you can do that. If it's a database connection, you'll have to execute the query on it, giving you a result that you can then iterate over." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T20:42:34.760", "Id": "3148", "Score": "1", "body": "Which DB driver allows you to run execute using a Connection object?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T20:53:18.770", "Id": "3149", "Score": "1", "body": "Well, now that's an interesting question... Apparently I'm not sure. I suppose you do need a cursor if I'm reading the DB API (http://www.python.org/dev/peps/pep-0249/) right. I've been using SQL Alchemy (http://www.sqlalchemy.org/) more lately which has different semantics. So iterating over a cursor is perfectly fine with the DB API. I'll update the example there." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-06T21:54:55.243", "Id": "1689", "ParentId": "1669", "Score": "1" } } ]
{ "AcceptedAnswerId": "1674", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-05T22:02:19.110", "Id": "1669", "Score": "5", "Tags": [ "python" ], "Title": "Reducing memory usage when comparing two iterables" }
1669
<p>I was wondering if my code will produce a true singleton. I am creating an Android app, and all activities should access my API through one instance of the <code>SyncApi</code> class.</p> <pre><code>public class Api { private static SyncApi api = null; static { synchronized (api) { if (api == null) { api = new ApiFActory().getSyncApi(); } } } public static SyncApi getInstance() { return api; } } </code></pre> <p>Use of the class would look like:</p> <pre><code>SyncApi api = Api.getInstance(); api.logOn("jjnguy", "pa55w0rd"); </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T09:24:07.117", "Id": "2930", "Score": "2", "body": "If you don’t want laziness, why not initialise the `SyncApi` instance directly in the declaration? No need for the `static` constructor. Java guarantees that initialisation of static members will only happen once." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T12:25:47.090", "Id": "2933", "Score": "0", "body": "@Konrad, ah! Well that helps then. I was worried that the initialization could (in rare multi-threaded cases) happen more than once." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-24T23:17:35.430", "Id": "3373", "Score": "9", "body": "I'd just like to point out that Singletons are considered an anti-pattern mostly now due to the difficulty in testing. Also you haven't made the constructor private so this isn't actually a Singleton." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-27T06:16:51.103", "Id": "25958", "Score": "0", "body": "Here synchronization may not works correctly, all is explained in Effective Java from Joshua Bloch, or some sample in Wikipedia" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T14:11:32.823", "Id": "32851", "Score": "1", "body": "@Athas Singletons are considered an anti-pattern because it takes this nice concept of encapsulation and controlled flow of data and says \"hey, let's go back to having global variables now.\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T12:22:47.003", "Id": "45256", "Score": "0", "body": "Why why why you init a `static` variable to null ? It will be null - will be even if not static - bad idiom" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T14:12:39.423", "Id": "74737", "Score": "0", "body": "`synchronized (null)` is mutch more effective way to create a NPE and prevent the loading of the class. BTW: The NPE will be absolutly thread-save." } ]
[ { "body": "<p>In Java there’s an established idiom for creating a <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\">thread-safe singleton</a>, due to Bill Pugh:</p>\n\n<pre><code>public class Api {\n private Api() { }\n\n private static class SingletonHolder { \n public static final SyncApi INSTANCE = new ApiFactory().getSyncApi();\n }\n\n public static SyncApi getInstance() {\n return SingletonHolder.INSTANCE;\n }\n}\n</code></pre>\n\n<p>This implementation is both <em>lazy</em> and completely <em>thread-safe</em>, without the need to explicit synchronization and checking. This has the advantage that it eliminates the possibility of subtle race conditions and redundant locking.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T20:51:06.293", "Id": "57543", "Score": "0", "body": "How is the `SyncApi` class defined? I believe this implementation can be broken if `Api` and/or `SyncApi` are not `final`. One could extend these classes and create objects in ways completely uncontrolled by this code. Every instance of `SyncApi`'s subclass would obviously be an instance of `SyncApi` as well. The enum-based solution is not affected by this because all enums are implicitly final." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T08:39:26.987", "Id": "57748", "Score": "0", "body": "@Tom Actually I just copied & pasted OP’s code to some extent, I was actually meaning the two classes to be one (i.e. `SyncApi` = `Api`), then this code is safe (`Api` cannot be extended)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T12:16:14.827", "Id": "57771", "Score": "0", "body": "OK, I missed the `private` constructor being the only one. `final` wouldn't hurt for clarity though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T12:28:37.603", "Id": "437299", "Score": "1", "body": "**Don’t use this code** — use the enum-based safe singleton idiom given in the answer by user aivikiss." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T09:15:52.413", "Id": "1675", "ParentId": "1673", "Score": "42" } }, { "body": "<p>The best and simple method was gived by Joshua Bloch in <em>《Effective Java 2th edition》</em></p>\n\n<pre><code>public enum Api {\n INSTANCE;\n}\n</code></pre>\n\n<p>you can use it like this</p>\n\n<pre><code>Api api = Api.INSTANCE;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T15:32:41.887", "Id": "2982", "Score": "1", "body": "This is not at all a singleton." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T15:43:11.413", "Id": "2983", "Score": "0", "body": "Yeah, sorry. Enums are different from singletons." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T18:46:20.353", "Id": "2991", "Score": "20", "body": "Why? Enums are classes, are they not? If you define additional non-static methods on the Api class above, it will behave exactly like a singleton, because it IS a singleton." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T02:21:09.363", "Id": "3025", "Score": "0", "body": "@rom, good point. I'd like to see this example expanded upon." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T15:08:14.313", "Id": "1715", "ParentId": "1673", "Score": "36" } }, { "body": "<p>If you want thread-safe and lazy, I completely agree with the <a href=\"https://codereview.stackexchange.com/questions/1673/is-my-code-a-safe-singleton/1675#1675\">answer</a> provided by Konrad Rudolph.</p>\n\n<p>If you want just thread-safe without laziness (which is also very common), then you can initialize INSTANCE in the upper class, not from inner one.</p>\n\n<p>Here is a good article with many tests and examples:<br>\n<a href=\"http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html\" rel=\"nofollow noreferrer\">http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html</a></p>\n\n<p>But both approaches don't give you an absolute singleton, since different ClassLoaders will create different instances. It might look like a nearly impossible case, but in my experience I faced a bug which was cause by such a situation.</p>\n\n<p>Here is an article about absolute singletons:<br>\n<a href=\"http://surguy.net/articles/communication-across-classloaders.xml\" rel=\"nofollow noreferrer\">http://surguy.net/articles/communication-across-classloaders.xml</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T12:40:06.690", "Id": "45257", "Score": "0", "body": "Yes - he must use an enum to have an absolute singleton" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T15:13:51.780", "Id": "1861", "ParentId": "1673", "Score": "3" } }, { "body": "<p>Well, this is definitely not a Singleton, because this code is legal:\n<code>Api.api=new Api();</code></p>\n\n<p>You should <em>at least</em> define api variable as final and at least private constructor to avoid instantiation. </p>\n\n<p>See @Konrad Rudolph's for proposed solution.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-08T21:01:37.730", "Id": "12403", "ParentId": "1673", "Score": "3" } }, { "body": "<p>I agree with all the other answers but your problem, as you state it, is not to have a single API instance but to have a single SyncApi instance.</p>\n\n<p>You will have no way to prevent a user from doing:</p>\n\n<pre><code>SyncApi api = new ApiFActory().getSyncApi();\n</code></pre>\n\n<p>You have to make SyncApi a Singleton or encapsulate it's usage in your Api class and not give access to it outside your Api...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T11:46:52.397", "Id": "20505", "ParentId": "1673", "Score": "2" } }, { "body": "<p>Your setting your api to null did not help you spot your NullPointerException</p>\n\n<pre><code>synchronized (api) // api == null, you should use Api.class\n</code></pre>\n\n<p>As to the singleton please, please, <em>please</em> use an enum. <a href=\"https://stackoverflow.com/a/71399/281545\">It is the recommended pattern since java 5</a>. Now, <a href=\"https://stackoverflow.com/questions/12883051/enum-and-singletons-top-level-vs-nested-enum\">if you want lazy loading</a> :</p>\n\n<pre><code>public class Api {\n\n private Api() {}\n\n private enum SingletonHolder {\n INSTANCE;\n\n private static final Api singleton = new Api();\n\n Api getSingleton() {\n return singleton;\n }\n }\n\n public Api api() {\n Api.SingletonHolder.INSTANCE.getSingleton();\n }\n}\n</code></pre>\n\n<p>Call :</p>\n\n<pre><code> api().logOn(\"jjnguy\", \"pa55w0rd\");\n</code></pre>\n\n<p>You may dispose of <code>getSingleton()</code> and access <code>singleton</code> directly inside <code>Api</code></p>\n\n<pre><code>public class Api {\n\n private Api() {/*your costly init here*/}\n\n private enum SingletonHolder {\n INSTANCE;\n private static final Api singleton = new Api();\n }\n\n public Api api() {\n return Api.SingletonHolder.singleton;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-01T12:46:44.107", "Id": "117748", "Score": "1", "body": "you do not need to use `static` and `final` keywords in enum class declaration as enum classes are already provide `static` and `final`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-01T13:31:03.600", "Id": "117755", "Score": "0", "body": "@EnesUnal: correct (see also http://stackoverflow.com/a/253282/281545), edited" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-21T12:42:05.950", "Id": "28781", "ParentId": "1673", "Score": "3" } }, { "body": "<pre><code>public class Singleton {\n private static Singleton instance = null;\n\n public static Singleton getInstance(){\n if(null == instance){\n synchronized(Singleton.class){\n //double check\n if(null == instance){\n instance = new Singleton();\n }\n } \n }\n return instance;\n }\n\n}\n</code></pre>\n\n<p>This can be used to ensure only single instance is created. Or just use Enums.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T03:40:52.250", "Id": "66477", "Score": "4", "body": "`if(null == instance)` Yoda-style, this sounds like." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T03:38:17.487", "Id": "35470", "ParentId": "1673", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T03:56:45.273", "Id": "1673", "Score": "41", "Tags": [ "java", "android", "singleton" ], "Title": "Is my code a 'safe' singleton?" }
1673
<p>Is there a better way of doing this?</p> <pre><code>File.open( "/etc/my.cnf" ) do |f| f.grep( /^testdir/ ) do |line| test1 = line.chop.gsub(/ /,"") test2 = test1.sub(/.*=/, "") RETURN_PATH = "#{test2}/test_ups" end end </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T14:30:28.310", "Id": "2936", "Score": "3", "body": "What's wrong with this one? What do you want to improve? Define *better*." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T14:33:36.767", "Id": "2937", "Score": "0", "body": "It works fine but still wants to know if any other efficient way is available." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T14:47:35.530", "Id": "2938", "Score": "2", "body": "I'm ok with these kinds of questions on SO as long as there is a good definition of better. Like Douglas suggests, the people at codereview.SE have less strict standards for questions having definite answers (they will comment any code on any aspect), and they need the questions to take the site out of beta (I hope they make it, seems like a very good addition to SE)." } ]
[ { "body": "<p>Aside from not using a constant for <code>RETURN_PATH</code> (which is obviously wrong and will cause Ruby to warn you), it seems reasonable enough to me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T18:34:06.550", "Id": "1682", "ParentId": "1677", "Score": "3" } }, { "body": "<p>Here's my refactoring, I'll explain below what I've done:</p>\n\n<pre><code>path = File.readlines(\"/etc/my.cnf\").find { |line| line =~ /^testdir/ }.chomp.gsub(/( )|(.*=)/, '')\n@return_path = File.join(path, 'test_ups') # &gt;&gt; \"/tmp/test_ups\"\n</code></pre>\n\n<p>Firstly you can use File.readlines to return an Array of lines from your file, we then use your regex to match a single line beginning with testdir, we then remove the \\r\\n with chomp - notice I changed <code>chop</code> for <code>chomp</code> because it is safer (Refer to <a href=\"http://www.ruby-doc.org/core/classes/String.html#M001188\" rel=\"nofollow\">Ruby#String</a>) and then clean it up with a single regex and <code>gsub</code>. Lastly we return your path in the instance variable <code>@return_path</code> rather than a constant.</p>\n\n<p>I've made a few assumptions when writing this, including my.cnf being the standard MySQL conf file - you may need to adapt this to suit.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T04:53:11.490", "Id": "1758", "ParentId": "1677", "Score": "3" } }, { "body": "<p>I'm not sure what the semantics of your code are, but on the assumption that you are munging things that look like paths to files, I would commend to you the <a href=\"http://ruby-doc.org/core/classes/File.html\" rel=\"nofollow\">File.basename</a> method (and friends) that might express more cleanly your intent. Note: there is no need to actually access the file to get the basename. It is a simple string operation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-29T00:25:23.810", "Id": "2152", "ParentId": "1677", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-06T14:29:19.257", "Id": "1677", "Score": "2", "Tags": [ "ruby", "mysql", "ruby-on-rails", "parsing" ], "Title": "Extracting and mangling a parameter from a MySQL configuration file" }
1677
<p>Which one of the following is preferrable and why when writing C macro?</p> <p><strong>Type 1</strong></p> <pre><code>#define I2C_START() I2C_WAIT_IDLE(); SSP1CON2bits.SEN = 1 </code></pre> <p><strong>Type 2</strong></p> <pre><code>#define I2C_START() \ do \ { \ I2C_WAIT_IDLE(); \ SSP1CON2bits.SEN = 1; \ }while(0) </code></pre> <p>One of my colleagues prefers <strong>Type 1</strong> while I prefer <strong>Type 2</strong>. So when both of us work in a project, both of the types are seen throughout the project.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-16T04:20:20.290", "Id": "3214", "Score": "0", "body": "http://c-faq.com/cpp/multistmt.html explains it in detail." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-08T17:28:13.567", "Id": "70750", "Score": "1", "body": "This question appears to be off-topic because it is about best practice regarding a specific language feature. See [help/on-topic]." } ]
[ { "body": "<p>I prefer the second one because it can be used with normal compound stamens without modifications or accidentally being used incorrectly.</p>\n<pre><code>if (condition)\n I2c_START; \n</code></pre>\n<p>Type 1: FAIL<br />\nType 2: OK</p>\n<p>Of course with good coding standards that can be avoided (always use '{' '}' on if). But every now and then people can be lazy (or just careless) and the second version prevents accidents from happening.</p>\n<p>The best solution is not to use macros. Use functions and let the compiler work out when to inline.</p>\n<h3>Edited:</h3>\n<p>For billy: (Type 3) no do while</p>\n<pre><code>#define I2C_START() \\\n{ \\\n I2C_WAIT_IDLE(); \\\n SSP1CON2bits.SEN = 1; \\\n}\n</code></pre>\n<p>Unfortunately this fails if you use the else part of the if statement:<br />\nThe trailing semi-colon (on type 3) marks the end of the <code>if statement</code> thus else is not syntactically allowed. At least this gives you a compilation error unlike above. But Type 2 still works as expected.</p>\n<pre><code>if (condition)\n I2C_START();\nelse\n std::cout &lt;&lt; &quot;FAIL this test\\n&quot;;\n</code></pre>\n<p>Type 1: FAIL<br />\nType 2: OK<br />\nType 3: FAIL</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T04:23:59.140", "Id": "2958", "Score": "0", "body": "Well, you really don't need the \"do\" and \"while (0)\" bits for type 2 to prevent this though. A plain block will do just fine." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T07:17:37.780", "Id": "2959", "Score": "1", "body": "It's syntax thing. Having only {} block will expand to if (...) { ... }; and spare ; is not good." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T01:54:50.130", "Id": "3024", "Score": "0", "body": "@blaze, really? You're worried about a semicolon that only the compiler will see, and ignore?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T10:01:59.317", "Id": "3090", "Score": "6", "body": "@AShelly: if (foo) do { bar; } while 0; else { mmm; } = ok. if (foo) {bar} ; else {mmm;} = syntax error on else, because spare ; terminated if-statement. Oops :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T19:09:58.347", "Id": "3109", "Score": "0", "body": "Ok, good point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-28T18:34:16.550", "Id": "3503", "Score": "0", "body": "@Billy ONeal: Added explanation of why `do while(0)` required." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-06T19:10:08.530", "Id": "1686", "ParentId": "1679", "Score": "15" } }, { "body": "<p>The Linux Kernel Newbies FAQ has an <a href=\"http://kernelnewbies.org/FAQ/DoWhile0\">entry on this</a>, since Linux uses it extensively. It's the syntax-safe way of defining these kinds of macros.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-22T09:30:19.240", "Id": "43100", "Score": "0", "body": "It would be good if you could actually put the content in your answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-02T02:19:37.770", "Id": "43718", "Score": "0", "body": "It's a long FAQ entry, sorry." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T00:56:48.260", "Id": "1692", "ParentId": "1679", "Score": "6" } }, { "body": "<p>The second form is the safest without having to think too much about the consequences way.</p>\n\n<p>but for what you are using it for? neither really need to be used. It should be a function. I'm taking it this is PIC code.... the overhead of the function call won't cost you that much.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T11:42:20.090", "Id": "3008", "Score": "0", "body": "yes it is pic. we typically write macros for 2/3 lines of register access." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T04:46:43.233", "Id": "1725", "ParentId": "1679", "Score": "4" } }, { "body": "<p>I something similar to type two but without the do while as in:</p>\n\n<pre><code>#define I2C_START() \\\ndo \\\n{ \\\n I2C_WAIT_IDLE(); \\\n SSP1CON2bits.SEN = 1; \\\n}while(0)\n</code></pre>\n\n<p>The do while could be difficult to understand for an inexperienced coder. I also always use {} even for onliner <code>if</code> statements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T12:22:45.133", "Id": "3614", "Score": "0", "body": "any inexperience coder should learn what do{}while(0) does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-06T05:39:14.823", "Id": "3654", "Score": "0", "body": "Yes. But by keeping it obvious and simple you avoid problems with people that have not or do not want to learn." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T11:26:30.023", "Id": "2251", "ParentId": "1679", "Score": "0" } } ]
{ "AcceptedAnswerId": "1686", "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T16:56:46.907", "Id": "1679", "Score": "7", "Tags": [ "c", "macros" ], "Title": "'do { statement; } while(0)' against 'statement' when writing C macro?" }
1679
<p>I've written the code below to do some work on machine learning in R. I'm not overly happy with some bits of it, and I suspect I could improve it quite a bit. Bits I'm specifically interested in looking at are how to deal with appending to vectors in the loop, and whether I can combine all of the functions <code>kf.knn</code>, <code>kf.svm</code> etc into one function with various arguments.</p> <pre><code>library(class) library(nnet) library(epibasix) library(CVThresh) library(e1071) df &lt;- read.table("semeion.data.data") df$digit &lt;- replicate(nrow(df), 42) df$digit[which(as.logical(df$V266), arr.ind=TRUE)] = 9 df$digit[which(as.logical(df$V265), arr.ind=TRUE)] = 8 df$digit[which(as.logical(df$V264), arr.ind=TRUE)] = 7 df$digit[which(as.logical(df$V263), arr.ind=TRUE)] = 6 df$digit[which(as.logical(df$V262), arr.ind=TRUE)] = 5 df$digit[which(as.logical(df$V261), arr.ind=TRUE)] = 4 df$digit[which(as.logical(df$V260), arr.ind=TRUE)] = 3 df$digit[which(as.logical(df$V259), arr.ind=TRUE)] = 2 df$digit[which(as.logical(df$V258), arr.ind=TRUE)] = 1 df$digit[which(as.logical(df$V257), arr.ind=TRUE)] = 0 data &lt;- df[,c(0:256,267)] squareTable &lt;- function(x,y) { x &lt;- factor(x) y &lt;- factor(y) commonLevels &lt;- sort(unique(c(levels(x), levels(y)))) x &lt;- factor(x, levels = commonLevels) y &lt;- factor(y, levels = commonLevels) table(x,y) } kf.knn &lt;- function(data, k, nearest) { N &lt;- nrow(data) data &lt;- data[sample(1:N),] folds.index &lt;- cvtype(N, cv.bsize=1, cv.kfold=k, FALSE)$cv.index total = 0 for (i in 1:k) { test &lt;- data[folds.index[i,], 0:256] test.labels &lt;- data[as.array(folds.index[i,]), 257] rest &lt;- as.array(folds.index[-i,]) train &lt;- data[rest, 0:256] train.labels &lt;- data[rest, 257] knnpredict &lt;- knn(train, test, train.labels, nearest) t &lt;- table(as.factor(test.labels), as.factor(knnpredict)) kap &lt;- epiKappa(t) total &lt;- total + kap$kappa } return(total / k) } kf.nnet &lt;- function(data, k, hidden) { N &lt;- nrow(data) data &lt;- data[sample(1:N),] folds.index &lt;- cvtype(N, cv.bsize=1, cv.kfold=k, FALSE)$cv.index total = 0 for (i in 2:k) { test &lt;- data[folds.index[i,], 0:256] test.labels &lt;- data[as.array(folds.index[i,]), 257] rest &lt;- as.array(folds.index[-i,]) train &lt;- data[rest, 0:256] train.labels &lt;- data[rest, 257] train$label &lt;- as.factor(train.labels) nnetwork &lt;- nnet(label ~ ., data=train, size=hidden, MaxNWts = 10000, maxit=200, linout=TRUE) nnetpredict &lt;- predict(nnetwork, test, "class") table &lt;- squareTable(as.factor(test.labels), as.factor(nnetpredict)) print(table) kap &lt;- epiKappa(table) total &lt;- total + kap$kappa } return(total / k) } kf.svm &lt;- function(data, k) { N &lt;- nrow(data) data &lt;- data[sample(1:N),] folds.index &lt;- cvtype(N, cv.bsize=1, cv.kfold=k, FALSE)$cv.index total = 0 for (i in 2:k) { test &lt;- data[folds.index[i,], 0:256] test.labels &lt;- data[as.array(folds.index[i,]), 257] rest &lt;- as.array(folds.index[-i,]) train &lt;- data[rest, 0:256] train.labels &lt;- data[rest, 257] train$label &lt;- as.factor(train.labels) svmmodel &lt;- svm(label ~ ., data=train, cost=8, gamma=0.001, cross=2) svmpredict &lt;- predict(svmmodel, test) t &lt;- table(as.factor(test.labels), as.factor(svmpredict)) print(t) kap &lt;- epiKappa(t) total &lt;- total + kap$kappa } return(total / k) } result &lt;- vector("numeric", 1) n &lt;- vector("numeric", 1) for (i in 2:10) { avg &lt;- kf.nnet(data, 5, i) result &lt;- append(result, avg) n &lt;- append(n, i) cat("!!!!!!!", i, avg, "\n") } result &lt;- result[2:length(result)] n &lt;- n[2:length(n)] df &lt;- data.frame(kappa = result, n=n) plot(df$n, df$res) print(df) </code></pre>
[]
[ { "body": "<p>You can avoid appending to vectors (which can cause re-allocation of space and can considerably slow things down in principle; though in your case of only a length 10 vector that shouldn't be noticeable) if you allocate them to the needed size initially and then assign within them.</p>\n\n<pre><code>result &lt;- vector(\"numeric\", 10)\n# or even: result &lt;- numeric(10)\nn &lt;- vector(\"numeric\", 10)\n\nfor (i in 2:10)\n{\n avg &lt;- kf.nnet(data, 5, i)\n result[i] &lt;- avg\n n[i] &lt;- i\n cat(\"!!!!!!!\", i, avg, \"\\n\")\n}\n</code></pre>\n\n<p>I'm not clear what you are asking about combing function; you can add an additional argument which is a character vector which then the code just has a series of if/elseif's checking that parameter to see which algorithm to use, if that is what you mean.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T17:00:27.203", "Id": "36975", "ParentId": "1681", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-06T18:07:25.917", "Id": "1681", "Score": "5", "Tags": [ "r", "clustering", "machine-learning" ], "Title": "Performing machine learning" }
1681
<p>Of course the recursive version is trivial:</p> <pre><code>hanoi n = solve n 1 2 3 solve 0 _ _ _ = [] solve n from help to = (solve (n-1) from to help) ++ [(from,to)] ++ (solve (n-1) help from to) </code></pre> <p>However my iterative version looks terrible with a lot of code repetition:</p> <pre><code>hanoi n = map rep $ solve [1..n] [] [] where rep (x,y) | odd n = ([1,3,2] !! (x-1), [1,3,2] !! (y-1)) | otherwise = (x,y) solve from help to = head $ mapMaybe ready $ iterate step (from,help,to,[]) where step (1:xs,ys,zs,sol) = let (xs',zs',sol') = try xs zs 1 3 ((1,2):sol) in (xs',1:ys,zs',sol') step (xs,1:ys,zs,sol) = let (xs',ys',sol') = try xs ys 1 2 ((2,3):sol) in (xs',ys',1:zs,sol') step (xs,ys,1:zs,sol) = let (ys',zs',sol') = try ys zs 2 3 ((3,1):sol) in (1:xs,ys',zs',sol') try [] [] _ _ sol = ([],[], sol) try (x:xs) [] a b sol = (xs,[x], (a,b):sol) try [] (y:ys) a b sol = ([y],ys, (b,a):sol) try (x:xs) (y:ys) a b sol | x &lt; y = (xs,x:y:ys, (a,b):sol) | y &lt; x = (y:x:xs,ys, (b,a):sol) ready ([],[],_,sol) = Just $ reverse sol ready ([],_,[],sol) = Just $ reverse sol ready _ = Nothing </code></pre> <p>Any ideas? More general, how to deal with situations like this where you have a lot of different cases and args?</p> <p><strong>[Clarification]</strong></p> <p>With "iterative solution" I mean the algorithm described here: <a href="http://en.wikipedia.org/wiki/Tower_of_Hanoi#Iterative_solution">http://en.wikipedia.org/wiki/Tower_of_Hanoi#Iterative_solution</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T09:54:47.347", "Id": "60462", "Score": "0", "body": "Iterative solutions: http://rosettacode.org/wiki/Towers_of_Hanoi#Iterative http://cboard.cprogramming.com/cplusplus-programming/26380-iterative-towers-hanoi.html http://hanoitower.mkolar.org/algo.html http://dekudekuplex.wordpress.com/2009/04/13/climbing-the-towers-of-hanoi-with-haskell-style-curry-from-a-monadic-container-while-sparing-the-sugar/ http://blogs.msdn.com/b/ericlippert/archive/2004/05/19/135392.aspx?PageIndex=2" } ]
[ { "body": "<p>Umm. What about</p>\n\n<pre><code>import Data.Bits\nhanoi :: Int -&gt; [(Int, Int)]\nhanoi n = map (\\x -&gt; ((x .&amp;. (x-1)) `mod` 3, ((x .|. (x-1)) + 1) `mod` 3)) [1..shift 1 n]\nmain = print $ hanoi 5\n</code></pre>\n\n<p>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T15:41:11.547", "Id": "4968", "Score": "0", "body": "It almost works, but calling \"hanoi 3\" gives you an extra move at the end: [(0,2),(0,1),(2,1),(0,2),(1,0),(1,2),(0,2),(0,1)]. Same with \"hanoi 4\". Still, this is pretty ingenious, and easily fixed by adding \"init $\" in front of your map." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-15T19:03:59.057", "Id": "1913", "ParentId": "1684", "Score": "4" } } ]
{ "AcceptedAnswerId": "1913", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-06T18:48:23.743", "Id": "1684", "Score": "8", "Tags": [ "haskell", "tower-of-hanoi" ], "Title": "Towers of Hanoi in Haskell" }
1684
<p>An anagram is like a mix-up of the letters in a string: </p> <blockquote> <p><strong>pots</strong> is an anagram of <strong>stop</strong> </p> <p><strong>Wilma</strong> is an anagram of <strong>ilWma</strong></p> </blockquote> <p>I am going through the book <a href="http://rads.stackoverflow.com/amzn/click/145157827X" rel="noreferrer"><em>Cracking the Coding Interview</em></a> and in the basic string manipulation there's the problem:</p> <blockquote> <p><em>write a method to check if two strings are anagrams of each other.</em></p> </blockquote> <p>My method uses <code>StringBuffer</code> instead of String because you can <code>.deleteCharAt(index)</code> with <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuffer.html" rel="noreferrer">StringBuffer</a>/<a href="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html" rel="noreferrer">StringBuilder</a>.</p> <pre><code>public boolean areAnagrams(StringBuffer s1b, StringBuffer s2b) { for (int i=0; i&lt;s1b.length(); ++i) { for (int j=0; j&lt;s2b.length(); ++j) { if (s1b.charAt(i) == s2b.charAt(j)) { s1b.deleteCharAt(i); s2b.deleteCharAt(j); i=0; j=0; } } } if (s1b.equals(s2b)) { return true; } else return false; } </code></pre> <p>I iterate over every character in s1b and if I find a matching char in s2b I delete them both from each string and restart the loop (set <code>i</code> and <code>j</code> to zero) because the length of the <code>StringBuffer</code> objects changes when you <code>.deleteCharAt(index)</code>.</p> <p>I have two questions:</p> <ul> <li>Should I use <code>StringBuilder</code> over <code>StringBuffer</code> (in Java)?</li> <li>How can I make this faster?</li> </ul> <p>In regards to fasterness:</p> <p>This method is good in that it doesn't require any additional space, but it sorta destroys the data as you're working on it. Are there any alternatives that I have overlooked that could potentially preserve the strings but still see if they are anagrams without using too much external storage (i.e. copies of the strings are not allowed -- as a challenge)?</p> <p>And, if you can use any sort of storage space in addition to this, can one lower the time complexity to \$O(n)\$ (technically \$O(2n)\$) instead of \$O(n^2)\$?</p> <p>Also, the above code might not compile because I just wrote it from scratch in here; sorry if it's bugg'd.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T04:23:57.783", "Id": "2957", "Score": "1", "body": "Scott's answer is great, so to your other question you should use `StringBuilder` because it doesn't use synchronization here. It will be faster and you aren't using multiple threads to access the same buffer, making `StringBuffer` slower with no payoff. As for your code, no need to reset `i` since you don't want to start over, and if `i` gets to the end of the first string they aren't anagrams." } ]
[ { "body": "<p>This is essentially asking you to compare if two sets are equivalent, thinking of the strings as a set of characters where the order doesn't matter.</p>\n\n<p>For an O(n) runtime algorithm, you could iterate through the first string, and count the number of instances of each letter. Then iterate over the second string and do the same. Afterwards, make sure the counts match.</p>\n\n<p>To save a little bit of storage, use the same array for both counts; while iterating the first string, increment the count once for each letter. When iterating the second, decrement. Afterwards, make sure each letter count is zero.</p>\n\n<p>When running this algorithm over generic sets of objects, one might store the counts in a dictionary keyed off the object's hashcode. However, because we're using a relatively small alphabet, a simple array would do. Either way, storage cost is O(1).</p>\n\n<p>Cosider the following pseudo-code:</p>\n\n<pre><code>function are_anagrams(string1, string2)\n\n let counts = new int[26];\n\n for each char c in lower_case(string1)\n counts[(int)c]++\n\n for each char c in lower_case(string2)\n counts[(int)c]--\n\n for each int count in counts\n if count != 0\n return false\n\n return true\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T02:58:26.340", "Id": "1693", "ParentId": "1690", "Score": "15" } }, { "body": "<p><code>deleteCharAt(index)</code> needs to shuffle the characters after index across, so you might be better off iterating over the text starting from the end.</p>\n\n<p>If you are comparing many strings against each other, I would probably start by creating (and caching) copies of the strings but with their characters sorted. This would allow you to identify anagrams with a standard string comparison. As an added benefit, you can use the string with sorted characters as a hash table key making it quick and easy to find anagrams in a long list.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T02:59:58.937", "Id": "1694", "ParentId": "1690", "Score": "1" } }, { "body": "<p>Start with a simple, easy to understand version. Try to reuse API functions.</p>\n\n<pre><code>import java.util.Arrays;\n... \n\npublic boolean areAnagrams(String s1, String s2) {\n char[] ch1 = s1.toCharArray();\n char[] ch2 = s2.toCharArray();\n Arrays.sort(ch1);\n Arrays.sort(ch2);\n return Arrays.equals(ch1,ch2);\n}\n</code></pre>\n\n<p>Of course this is not the fastest way, but in 99% it is \"good enough\", and you can <strong>see</strong> what's going on. I would not even <em>consider</em> to juggle with things like deleted chars in StringBuilder if there were no serious performance problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T10:48:10.807", "Id": "2967", "Score": "1", "body": "In particular since this version is asymptotically *faster* than the original version." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T12:45:24.677", "Id": "2973", "Score": "0", "body": "Thank you for the awesome answer. On the vein of reusing API functions, do you know of any good resources for an overview of the Java library methods? Maybe just like a list of ones that are most commonly used would be cool." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T12:57:43.943", "Id": "2975", "Score": "0", "body": "It's hard to give a good advise here, as Java's libs are so huge. Generally it's a good idea to look at least through the APIs ( http://download.oracle.com/javase/6/docs/api/ ) of `java.lang`,`java.util` and `java.math`. For Swing there are Oracle's \"How to...\" tutorials." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-13T04:35:14.413", "Id": "337332", "Score": "0", "body": "There is a problem with the answer. It is possible for the strings to not be of equal lengths but can still be considered as anagrams e.g. An anagram for \"anagram\" is \"nag a ram\". Thus, it would be wise to replace all special characters, spaces, and whatnot in each string before turning them into char Arrays." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-02-13T12:27:48.140", "Id": "357742", "Score": "1", "body": "@Rocket Pingu It depends on how you define your requirements. Nothing stops you from using my code and preprocess the input strings. On the other hand, if I include your suggestions, the code wouldn't be usable for stricter definitions of anagrams." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T06:48:42.533", "Id": "1704", "ParentId": "1690", "Score": "28" } }, { "body": "<blockquote>\n <p>how can I make this faster?</p>\n</blockquote>\n\n<p>Perform a preliminary check if both strings have equal lengths. But that doesn't change the Big-O complexity of the algorithm though.</p>\n\n<p>Your algorithm is <code>O(a * b) * (a+b)</code>, where <code>a</code> and <code>b</code> are the lengths of your input strings. The last <code>(a+b)</code> are the two <code>deleteCharAt(...)</code> operations, making it in all a O(n^3) algorithm. You could bring that down to <code>O(n)</code> (linear) by creating a frequency map of your strings, and comparing those maps.</p>\n\n<p>A demo:</p>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Map;\n\npublic class Main {\n\n public static boolean anagram(String s, String t) {\n // Strings of unequal lengths can't be anagrams\n if(s.length() != t.length()) {\n return false;\n }\n\n // They're anagrams if both produce the same 'frequency map'\n return frequencyMap(s).equals(frequencyMap(t));\n }\n\n // For example, returns `{b=3, c=1, a=2}` for the string \"aabcbb\"\n private static Map&lt;Character, Integer&gt; frequencyMap(String str) {\n Map&lt;Character, Integer&gt; map = new HashMap&lt;Character, Integer&gt;();\n for(char c : str.toLowerCase().toCharArray()) {\n Integer frequency = map.get(c);\n map.put(c, frequency == null ? 1 : frequency+1);\n }\n return map;\n }\n\n public static void main(String[] args) {\n String s = \"Mary\";\n String t = \"Army\";\n System.out.println(anagram(s, t));\n System.out.println(anagram(\"Aarmy\", t));\n }\n}\n</code></pre>\n\n<p>which prints:</p>\n\n<pre><code>true\nfalse\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T07:47:32.053", "Id": "2960", "Score": "0", "body": "PS. silly me, I didn't notice Scott already suggested the exact same thing... I'll leave my answer though, since it contains some code that can be tested without making any modifications." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T10:50:17.653", "Id": "2969", "Score": "1", "body": "`deleteCharAt` is O(n) … I believe the worst-case runtime of OP’s algorithm is O(n^3), not O(n^2)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T11:01:17.827", "Id": "2970", "Score": "0", "body": "Konrad, didn't even notice the `deleteCharAt(...)`! :) You're right: `deleteCharAt(...)` is another n-operations in the 2nd for-statement, making it `O(n^3)`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T12:53:00.347", "Id": "2974", "Score": "0", "body": "The frequency map is a cool idea! I wasn't sure how to increment the values in the hashmap but it's clear now, thanks =)!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-13T04:27:56.103", "Id": "337331", "Score": "0", "body": "\"Strings of unequal lengths can't be anagrams\"\n\nThey can be anagrams! Definition of anagrams [here](https://www.vocabulary.com/dictionary/anagram).\n\nThe check for lengths is unnecessary. @BartKiers" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T07:45:49.793", "Id": "1707", "ParentId": "1690", "Score": "6" } }, { "body": "<p>I'm going to answer this a bit more meta:</p>\n\n<p>Seeing this question I ask myself: What does the interviewer want to know from me? </p>\n\n<p>Does he expect </p>\n\n<ul>\n<li>a low-level, highly optimized algorithm (as you are attempting) </li>\n<li>or does he want to see, that I can apply the standard Java API to the problem (as Landei suggests)</li>\n<li>or maybe something in between, like the optimized implementation and use of a multi-set/counted set/bag (as Bart and Scott do) </li>\n</ul>\n\n<p>Possibly the interviewer just expects you to discuss exactly that with him, so that he sees that you know that these alternatives exist and which advantages and disadvantages they have.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T08:12:39.823", "Id": "1708", "ParentId": "1690", "Score": "2" } }, { "body": "<pre><code>// in Java this would be an unusual signature\npublic boolean areAnagrams(StringBuffer s1b, StringBuffer s2b) {\n\nfor (int i=0; i&lt;s1b.length(); ++i) {\n for (int j=0; j&lt;s2b.length(); ++j) {\n // what could you do if the condition evaluates fo false here?\n if (s1b.charAt(i) == s2b.charAt(j)) {\n // ouch. ask yourself what might be happening inside this JDK method\n // best case it bumps an offset, worst case it reallocs the backing array?\n s1b.deleteCharAt(i);\n s2b.deleteCharAt(j);\n\n // double ouch. one failure mode for fiddling with the loop var would be infinite loop\n // avoid this\n i=0;\n j=0;\n }\n }\n}\n\n// if you have reached this line of code, what else do you know about s1b and s2b?\nif (s1b.equals(s2b)) {\n return true;\n} else\n return false;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T13:58:11.290", "Id": "3174", "Score": "0", "body": "what would you write as the signature instead? It's not obvious to me that it's a weird Java signature" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T14:11:02.467", "Id": "3176", "Score": "0", "body": "It would be better to accept two Strings or CharSequences. My main beef with StringBuffer/StringBuilder here is they are mutable and this function should not alter the inputs" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T15:53:42.687", "Id": "3177", "Score": "0", "body": "That's a reasonable guideline. By mutable do you mean that if I edit s1b or s2b in this method body then the original values (passed to this function) are changed?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T04:53:37.663", "Id": "1726", "ParentId": "1690", "Score": "1" } }, { "body": "<p>Assume that we want to check Str1 and Str2 if they are anagrams or not </p>\n\n<pre><code>public boolean checkAnagram(String s1 , String s2 ) {\n int i=0;\n int j=0;\n\n // no need to check if that j &lt; s2.length() \n // because the two strings must be that the same length.\n\n while(i &lt; s1.length()) { \n\n if(s1.indexOf(s2.charAt(j) &lt; 0 || s2.indexOf(s1.charAt(i)) &lt; 0 ) \n return false;\n\n i++;\n j++;\n } // end of While\n\n return true;\n}// end of Check Anagram Method. the Big-Oh is O(n log n)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T06:17:37.233", "Id": "13322", "Score": "2", "body": "Something looks wrong here. Checking only if characters are contained in the other string will make \"aab\" anagram of \"abb\". Also i and j will always be equals with this code so maybe something is missing." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T15:12:47.560", "Id": "8500", "ParentId": "1690", "Score": "0" } }, { "body": "<p>Using <a href=\"http://code.google.com/p/guava-libraries/\" rel=\"nofollow\">Guava's</a> <a href=\"http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset\" rel=\"nofollow\">MultiSet</a>, you can get some very readable and concise code:</p>\n\n<pre><code>public static boolean areAnagrams(String s1, String s2) {\n Multiset&lt;Character&gt; word1 = HashMultiset.create(Lists.charactersOf(s1));\n Multiset&lt;Character&gt; word2 = HashMultiset.create(Lists.charactersOf(s2)); \n return word1.equals(word2);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T06:47:20.417", "Id": "8533", "ParentId": "1690", "Score": "2" } }, { "body": "<p>I like the guava based response but here is a histogram based answer for completion sake. It builds a single histogram to capture differences in two words for the given character set (in this case, assumes 8-bit) and uses the histogram later to identify whether two words are Anagrams.</p>\n\n<pre><code>public boolean areAnagrams(String word1, String word2) {\n int[] counts = new int[256]; /*assuming 8-bit character set */\n\n if(word1.length() != word2.length())\n return false;\n\n int inputLength = word1.length();\n\n for(int index=0; (int)word1.charAt(index) &gt; 0 &amp;&amp; (int)word2.charAt(index) &gt; 0; index++ ) {\n counts[(int)word1.charAt(index)] ++;\n counts[(int)word2.charAt(index)] --;\n }\n\n for(int index=0; index &lt; inputLength; index++ )\n if(counts[index] &gt; 0)\n return false;\n return true;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-03T14:56:49.237", "Id": "52357", "ParentId": "1690", "Score": "1" } }, { "body": "<p>I think this works with a complexity O(2n). \nThis can be done with an array level operations.<br>\nThe solution uses a buffer array of size 256 (assuming string contains chars with ASCII value less than 256), ASCII value of each char is used as array index.</p>\n\n<p>First loop: increments the array position of each characters.</p>\n\n<p>Second loop: Check any of the positions are zero, that means the character is not present in the first string or it presents more number of times than the first one. </p>\n\n<pre><code>public static boolean isAnagram(String str1, String str2){\n if(str1.length() != str2.length()){ return false;}\n int[] buffer = new int[256]; \n for(char ch : str1.toCharArray()){\n buffer[ch]++;\n }\n for(char ch : str2.toCharArray()){\n if(buffer[ch]==0) return false;\n buffer[ch] = (buffer[ch] &gt; 0)?(buffer[ch] - 1 ): -1 ; \n }\n return true;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-22T09:49:01.967", "Id": "218754", "Score": "0", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and how it improves upon the original) so that the author can learn from your thought process." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-22T10:06:59.497", "Id": "218755", "Score": "0", "body": "Added a description, please see" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-22T09:43:05.803", "Id": "117576", "ParentId": "1690", "Score": "0" } } ]
{ "AcceptedAnswerId": "1704", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-06T22:29:28.977", "Id": "1690", "Score": "11", "Tags": [ "java", "strings", "interview-questions" ], "Title": "Optimizing Java Anagram checker (compare 2 strings)" }
1690
<p>Motivating SO question: <a href="https://stackoverflow.com/questions/5454195/is-there-a-c-cli-smart-pointer-project-e-g-scoped-ptr">Is there a C++/CLI smart pointer project (e.g. scoped_ptr)?</a></p> <p>I'm interested in any reviewer comments, and especially identified bugs or inconsistencies with the native scoped_ptr template after which this code is patterned.</p> <pre><code>#pragma once /** @file clr_scoped_ptr.h ** @author R Benjamin Voigt ([email protected]) ** ** Rights reserved. This code is not public domain. ** ** Licensed under CC BY-SA 3.0 http://creativecommons.org/licenses/by-sa/3.0/ ** or Lesser GPL 3 or later http://www.gnu.org/copyleft/lesser.html ** with the following restrictions (per GPL section 7): ** - all warranties are disclaimed, and if this is prohibited by law, your sole remedy shall be recovery of the price you paid to receive the code ** - derived works must not remove this license notice or author attribution ** - modifications must not be represented as the work of the original author ** - attribution is required in the "about" or "--version" display of any work linked hereto, or wherever copyright notices are displayed by the composite work **/ struct safe_bool { private: safe_bool(); }; /** \brief C++/CLI analogue to boost::scoped_ptr, also similar to std::unique_ptr, for management of the lifetime of an unmanaged class instance by a managed object **/ template&lt;typename T&gt; public ref class clr_scoped_ptr { T* m_native_ptr; // declare copy-constructors and assignment operators to prevent double-free clr_scoped_ptr( clr_scoped_ptr&lt;T&gt;% ) /* = delete */ { throw gcnew System::InvalidOperationException("clr_scoped_ptr is non-copyable"); } template&lt;typename U&gt; clr_scoped_ptr( clr_scoped_ptr&lt;U&gt;% ) { throw gcnew System::InvalidOperationException("clr_scoped_ptr is non-copyable"); } clr_scoped_ptr% operator=( clr_scoped_ptr&lt;T&gt;% ) /* = delete */ { throw gcnew System::InvalidOperationException("clr_scoped_ptr is non-copyable"); } template&lt;typename U&gt; clr_scoped_ptr% operator=( clr_scoped_ptr&lt;U&gt;% ) { throw gcnew System::InvalidOperationException("clr_scoped_ptr is non-copyable"); } public: clr_scoped_ptr( void ) : m_native_ptr(nullptr) {} explicit clr_scoped_ptr( T* ptr ) : m_native_ptr(ptr) {} !clr_scoped_ptr( void ) { reset(); } ~clr_scoped_ptr( void ) { clr_scoped_ptr::!clr_scoped_ptr(); } template&lt;typename U&gt; clr_scoped_ptr( U ptr ) : m_native_ptr(ptr) {} void reset( T* ptr ) { delete m_native_ptr; m_native_ptr = ptr; } void reset( void ) { reset(nullptr); } clr_scoped_ptr% operator=( T* ptr ) { reset(ptr); } template&lt;typename U&gt; clr_scoped_ptr% operator=( U ptr ) { reset(ptr); } operator struct safe_bool*() { return reinterpret_cast&lt;struct safe_bool*&gt;(m_native_ptr); } void swap( clr_scoped_ptr&lt;T&gt;% other ) { using std::swap; swap(m_native_ptr, other.m_native_ptr); } T* release( void ) { T* retval = m_native_ptr; m_native_ptr = nullptr; return retval; } T* get( void ) { return m_native_ptr; } static T* operator-&gt;( clr_scoped_ptr&lt;T&gt;% sptr ) { return sptr.get(); } static T&amp; operator*( clr_scoped_ptr&lt;T&gt;% sptr ) { return *sptr.get(); } }; template&lt;typename T&gt; inline void swap( clr_scoped_ptr&lt;T&gt;% left, clr_scoped_ptr&lt;T&gt;% right ) { left.swap(right); } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T09:37:13.847", "Id": "2963", "Score": "0", "body": "Well the code seems to fine. But on [this page](http://www.functionx.com/cppcli/classes/Lesson13b.htm) this syntax is used for copy ctor : `ClassName(const ClassName^ & Name);` What is the difference?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T14:08:22.920", "Id": "2977", "Score": "0", "body": "@sad_man: That page is wrong in two ways. First, however useful passing in a `ClassName^` to a constructor might be, it's not a *copy constructor*. And secondly, since a `ClassName^` can live on the gc heap, the tracking reference `%` must be used instead of `&`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T15:00:21.790", "Id": "2980", "Score": "0", "body": "I see. So what does `ClassName^ & Name` mean? A native reference to a managed reference? What is the use of it? I thought it was a special syntax for copy constructor." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T18:51:16.977", "Id": "2992", "Score": "0", "body": "@sad_man: Yes, it would be a native reference to a managed handle. Theoretically, since you can have a managed handle on the stack, you could have a native reference to it. But I don't think the compiler allows that. `%` is definitely better, since it works with both variables on the stack and in the heap." } ]
[ { "body": "<p>I have only superficially tested the code so far, but it seems to make sense. However, there are some details where I'm either missing something (which wouldn't surprise me, I'm more at home with C#) or the code is more complex than it needs to be. Any comments are appreciated!</p>\n\n<ul>\n<li>The private copy constructors and assignment operators throw exceptions although they can never be called. Wouldn't it suffice to leave them empty?</li>\n<li>The constructor and assignment operator both accept not only arguments of type <code>T*</code>, but also exist in a templated version taking <code>U*</code>. I can't quite figure out why. My first thought was that this allows pointers to derived types to be passed; but then again, this is also possible using just the first form.</li>\n<li>Similarly, I don't understand the role of the template versions of the private constructor and assignment operator. From my understanding, neither of these will be auto-generated if you don't provide private versions.</li>\n<li>The safe bool pattern sound like a great idea (I first had to research it). However, VS2010 shows a compile error saying \"cannot convert from '<code>clr_scoped_ptr&lt;T&gt;::operator safe_bool *::safe_bool *</code>' to '<code>safe_bool *</code>'\". Apparently, it treats the two occurrences of <code>struct safe_bool</code> as two different types. Am I missing something here?</li>\n<li>You end the private methods and operators with a semicolon and you write empty argument lists as <code>(void)</code> rather than <code>()</code>. Are these just stylistic choices, or are there advantages in doing this?</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T00:28:39.450", "Id": "3050", "Score": "0", "body": "In standard C++, the \"deleted\" special functions would have no definition at all, resulting in a linker error if they were used. I think the semicolon got added then and simply stuck around. Throwing the exception is protection against accidentally calling those from inside the class, because `private` doesn't prevent that. The constructor taking `U*` is supposed to take simply `U`, accepting any smart pointer with an implicit conversion to `T*`, thanks for catching that. And the private template constructor is to exclude `clr_scoped_ptr` objects from using the public template." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T00:33:47.387", "Id": "3051", "Score": "0", "body": "Also, not all C-like languages interpret an empty parameter list the same way, but `void` in the parameter list has the same meaning in every language, so that's what I use. The safe_bool idiom usually involves a private nested type, but a native type can't be nested inside a managed type (and a nested managed type would cause accessibility complaints from the compiler) so to make this work, it needs a struct defined in the same namespace, which I've just added." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T10:07:18.513", "Id": "3059", "Score": "1", "body": "Ben, thanks for your explanations. They make perfect sense." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T16:39:37.250", "Id": "1746", "ParentId": "1695", "Score": "7" } }, { "body": "<p>You declare the <code>operator=</code> as returning a <code>clr_scoped_ptr%</code>, but there's no return statement in their body. This gives me compilation errors. I suppose the implementation should be:</p>\n\n<pre><code>clr_scoped_ptr% operator=( T* ptr ) { reset(ptr); return (clr_scoped_ptr%)this; } \n\ntemplate&lt;typename U&gt;\nclr_scoped_ptr% operator=( U ptr ) { reset(ptr); return (clr_scoped_ptr%)this; }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-04T22:41:27.023", "Id": "98797", "Score": "0", "body": "Good catch, although the correct code is simply `return *this;`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-04T21:02:55.737", "Id": "56137", "ParentId": "1695", "Score": "3" } }, { "body": "<p>I would also add that the copy constructors and assignments operators should throw <code>NotSupportedException</code> rather than <code>InvalidOperationException</code>. The latter is supposed to be dependent on object state.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-07T14:21:25.050", "Id": "56342", "ParentId": "1695", "Score": "3" } } ]
{ "AcceptedAnswerId": "1746", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-07T03:27:29.087", "Id": "1695", "Score": "19", "Tags": [ ".net", "pointers", "c++-cli" ], "Title": "scoped_ptr for C++/CLI (ensure managed object properly frees owned native object)" }
1695
<p>With just a brief look over I can think of a large amount of changes that would improve the clarity but I would love to see how someone else would refactor this mess. </p> <p><strong>Spec</strong></p> <p><img src="https://i.stack.imgur.com/ebKzE.png" alt="Spec"></p> <p><strong>Code</strong></p> <pre><code>static Func&lt;string, RegExpParser.MatchState, string&gt; MakeReplacer(string format) { var tokens = new Regex(@"[^\$]*(\$[\$&amp;`']|\$\d{1,2})") .Matches(format) .Cast&lt;Match&gt;() .Select(m =&gt; (Capture)m.Groups[1]) .ToList(); if (tokens.Count == 0) { return (value, state) =&gt; format; } var appendMethod = typeof(StringBuilder).GetMethod("Append", new[] { typeof(string) }); var toStringMethod = typeof(StringBuilder).GetMethod("ToString", new Type[0]); var substringMethod = typeof(string).GetMethod("Substring", new[] { typeof(int) }); var substringWithLengthMethod = typeof(string).GetMethod("Substring", new[] { typeof(int), typeof(int) }); var zero = Expression.Constant(0); var one = Expression.Constant(1); var dollarSign = Expression.Constant("$"); var valueVariable = Expression.Parameter(typeof(string), "value"); var stateVariable = Expression.Parameter(typeof(RegExpParser.MatchState), "state"); var sbVariable = Expression.Variable(typeof(StringBuilder), "sb"); var capturesProp = Expression.Property(stateVariable, "captures"); var capturesLengthProp = Expression.Property(capturesProp, "Length"); var endIndexProp = Expression.Property(stateVariable, "endIndex"); var inputProp = Expression.Property(stateVariable, "input"); var appendDollarSign = Expression.Call(sbVariable, appendMethod, Expression.Constant("$")); var getMatchedSubstring = Expression.ArrayIndex(capturesProp, zero); var appendMatchedSubstring = Expression.Call(sbVariable, appendMethod, getMatchedSubstring); var getBeforeSubstring = Expression.Call(inputProp, substringWithLengthMethod, zero, Expression.Subtract(endIndexProp, one)); var appendBeforeSubstring = Expression.Call(sbVariable, appendMethod, getBeforeSubstring); var getAfterSubstring = Expression.Call(inputProp, substringMethod, endIndexProp); var appendAfterSubstring = Expression.Call(sbVariable, appendMethod, getAfterSubstring); var e = (Expression)Expression.New(typeof(StringBuilder)); var index = 0; foreach (var token in tokens) { if (token.Index &gt; 0) { e = Expression.Call(e, appendMethod, Expression.Constant(format.Substring(index, token.Index - index))); } index = token.Index + token.Length; if (token.Value == "$$") { e = Expression.Call(e, appendMethod, dollarSign); } else if (token.Value == "$&amp;") { e = Expression.Call(e, appendMethod, valueVariable); } else if (token.Value == "$`") { e = Expression.Call(e, appendMethod, getBeforeSubstring); } else if (token.Value == "$'") { e = Expression.Call(e, appendMethod, getAfterSubstring); } else { var n = token.Value.Substring(1); if (n.Length == 2 &amp;&amp; n[0] == '0') { n = n.Substring(1); } var i = int.Parse(n) - 1; var nConst = Expression.Constant(i); var t = Expression.Constant(token.Value); if (i &lt; 0) { e = Expression.Call(e, appendMethod, t); } else { var cond = Expression.Condition( Expression.GreaterThan( capturesLengthProp, nConst ), Expression.ArrayIndex(capturesProp, nConst), t ); e = Expression.Call(e, appendMethod, cond); } } } e = Expression.Call(e, toStringMethod); var lambda = Expression.Lambda&lt;Func&lt;string, RegExpParser.MatchState, string&gt;&gt;(e, valueVariable, stateVariable); return lambda.Compile(); } IDynamic Replace(IEnvironment environment, IArgs args) { var o = environment.Context.ThisBinding; var so = o.ConvertToString(); var s = so.BaseValue; var matches = new List&lt;Tuple&lt;int, int, Func&lt;string, string&gt;&gt;&gt;(); var searchValueArg = args[0]; var replaceValueArg = args[1]; var replaceValueFunc = replaceValueArg as ICallable; var replaceValueString = replaceValueArg.ConvertToString(); if (searchValueArg is NRegExp) { var regExpObj = (NRegExp)searchValueArg; var matcher = regExpObj.RegExpMatcher; Func&lt;int, RegExpParser.MatchState, Func&lt;string, string&gt;&gt; makeReplacer = null; if (replaceValueFunc != null) { makeReplacer = (startIndex, state) =&gt; _ =&gt; { var nullArg = (IDynamic)environment.Null; var cArgs = new List&lt;IDynamic&gt;(); foreach (var c in state.captures) { if (c == null) { cArgs.Add(environment.Null); continue; } cArgs.Add(c == null ? nullArg : environment.CreateString(c)); } cArgs.Add(environment.CreateNumber(startIndex)); cArgs.Add(so); var result = replaceValueFunc.Call( environment, environment.Undefined, environment.CreateArgs(cArgs) ); return result.ConvertToString().BaseValue; }; } else { var replacer = MakeReplacer(replaceValueString.BaseValue); makeReplacer = (_, state) =&gt; v =&gt; replacer(v, state); } if (!regExpObj.Flags.Contains("g")) { var index = 0; do { var r = matcher(s, index); if (!r.success) { index++; continue; } matches.Add( Tuple.Create( index, r.matchState.endIndex - index, makeReplacer(index, r.matchState) ) ); break; } while (index &lt; s.Length); } else { var index = (int)regExpObj.Get("lastIndex").ConvertToNumber().BaseValue; do { var r = matcher(s, index); if (!r.success) { index++; continue; } matches.Add( Tuple.Create( index, r.matchState.endIndex - index, makeReplacer(index, r.matchState) ) ); index = r.matchState.endIndex; regExpObj.Put("lastIndex", environment.CreateNumber(index), false); } while (index &lt; s.Length); } } else { Func&lt;string, string&gt; replace = null; if (replaceValueFunc == null) { replace = _ =&gt; replaceValueString.BaseValue; } else { replace = v =&gt; { var arg = environment.CreateString(v); var result = replaceValueFunc.Call( environment, environment.Undefined, environment.CreateArgs(new[] { arg }) ); return result.ConvertToString().BaseValue; }; } var searchValue = args[0].ConvertToString().BaseValue; var index = 0; do { var resultIndex = s.IndexOf(searchValue, index); if (resultIndex &lt; 0) { index++; continue; } matches.Add( Tuple.Create&lt;int, int, Func&lt;string, string&gt;&gt;( resultIndex, searchValue.Length, replace ) ); index = resultIndex + 1; } while (index &lt; s.Length); } if (matches.Count == 0) return so; var sb = new StringBuilder(); var i = 0; foreach (var match in matches) { if (match.Item1 &gt; 0) sb.Append(s.Substring(i, match.Item1 - i)); sb.Append(match.Item3(s.Substring(match.Item1, match.Item2))); i = match.Item1 + match.Item2; } if (i &lt; s.Length) sb.Append(s.Substring(i)); return environment.CreateString(sb.ToString()); } </code></pre>
[]
[ { "body": "<p>My first instinct was “why do you construct all these expressions, only to compile it and return just the function — why not just use lambdas directly”... but after a second thought it seems that this wouldn’t be any clearer at all, so I think using expressions here is actually really nice :)</p>\n\n<p>Things I notice that could be improved:</p>\n\n<p>Instead of</p>\n\n<pre><code>var tokens =\n new Regex(@\"[^\\$]*(\\$[\\$&amp;`']|\\$\\d{1,2})\")\n .Matches(format)\n .Cast&lt;Match&gt;()\n .Select(m =&gt; (Capture)m.Groups[1])\n .ToList();\n</code></pre>\n\n<p>I think you could write</p>\n\n<pre><code>var items =\n Regex.Matches(format, @\"([^\\$]*)(\\$[\\$&amp;`']|\\$\\d{1,2})\")\n .Cast&lt;Match&gt;()\n .Select(m =&gt; new { TextBefore = m.Groups[1].Value,\n Token = m.Groups[2].Value });\n</code></pre>\n\n<p>Notice that I’ve changed the <code>Regex</code> object instantiation to a static method call; it makes little difference, I just think it’s more readable. I’ve also removed the call to <code>ToList()</code> because it seems you are only iterating over it, you are not manipulating the list, so there is no need for this extra list instantiation.</p>\n\n<p>Now you don’t need to care about the index anymore and can get rid of that variable:</p>\n\n<pre><code>foreach (var item in items)\n{\n if (item.TextBefore.Length &gt; 0)\n {\n e = Expression.Call(e, appendMethod, Expression.Constant(item.TextBefore));\n }\n\n // ... etc.\n</code></pre>\n\n<p>The next thing I notice is:</p>\n\n<pre><code>var n = token.Value.Substring(1);\nif (n.Length == 2 &amp;&amp; n[0] == '0')\n{\n n = n.Substring(1);\n}\nvar i = int.Parse(n) - 1;\n</code></pre>\n\n<p>You don’t need to remove the leading zero. It’s not going to throw <code>int.Parse</code> off (it doesn’t make it mean octal if that’s what you thought). So you can just write:</p>\n\n<pre><code>var i = int.Parse(item.Token.Substring(1)) - 1;\n</code></pre>\n\n<p>That’s all I notice in the first method. I cannot claim to fully understand the code that makes use of <code>RegExpParser.MatchState</code>, but it looks clean, if that means anything :)</p>\n\n<p>As for the second method...</p>\n\n<pre><code>var nullArg = (IDynamic)environment.Null;\nvar cArgs = new List&lt;IDynamic&gt;();\nforeach (var c in state.captures)\n{\n if (c == null)\n {\n cArgs.Add(environment.Null);\n continue;\n }\n cArgs.Add(c == null ? nullArg : environment.CreateString(c));\n}\n</code></pre>\n\n<p>Is it just me, or is all of that just a roundabout way of saying</p>\n\n<pre><code>var cArgs = state.captures\n .Select(c =&gt; c == null ? (IDynamic)environment.Null\n : environment.CreateString(c))\n .ToList();\n</code></pre>\n\n<p>Having too many local variables that are used only once does not always improve readability. The reader cannot tell instantly that the variable is used only once, so it is not obvious which variables they need to keep in their head while reading. This is why I inlined <code>nullArg</code>. If you disagree, of course you can change it back to a local variable.</p>\n\n<p>In the <code>if (!regExpObj.Flags.Contains(\"g\"))</code> block you seem to have a bit of duplicated code. It seems to me that it can easily be refactored:</p>\n\n<pre><code>var globalFlag = regExpObj.Flags.Contains(\"g\");\nvar index = globalFlag ? (int)regExpObj.Get(\"lastIndex\").ConvertToNumber().BaseValue : 0;\ndo\n{\n var r = matcher(s, index);\n if (!r.success)\n {\n index++;\n continue;\n }\n matches.Add(\n Tuple.Create(\n index,\n r.matchState.endIndex - index,\n makeReplacer(index, r.matchState)\n )\n );\n\n if (!globalFlag)\n break;\n\n index = r.matchState.endIndex;\n regExpObj.Put(\"lastIndex\", environment.CreateNumber(index), false);\n}\nwhile (index &lt; s.Length);\n</code></pre>\n\n<p>Looking at it again, however, I’m beginning to wonder why you are populating this <code>matches</code> list; you are not returning it or otherwise passing it anywhere. It seems that you actually only need the resulting string, not the list of matches, right? If that is the case, then personally I would probably just generate the string and not bother with the list of matches. That also gets rid of the problem I see of using tuples: the names <code>Item1</code>, <code>Item2</code>, <code>Item3</code> are really not very readable.</p>\n\n<p>Also, this is a significant performance problem:</p>\n\n<pre><code>var resultIndex = s.IndexOf(searchValue, index);\nif (resultIndex &lt; 0)\n{\n index++;\n continue;\n}\n</code></pre>\n\n<p>You are searching the same string for the same substring many times even when you know it’s not there. If <code>resultIndex &lt; 0</code> you can stop:</p>\n\n<pre><code>var resultIndex = s.IndexOf(searchValue, index);\nif (resultIndex &lt; 0)\n break;\n</code></pre>\n\n<p>The same may apply to the regex-matching part of the block depending on what <code>matcher</code> does. If it only matches a regular expression anchored to the beginning of the string, then of course your existing code is correct. If it matches anywhere in the string, the same optimisation should be made there.</p>\n\n<p>I believe this is a serious bug:</p>\n\n<pre><code>index = resultIndex + 1;\n</code></pre>\n\n<p>I think you want this to say</p>\n\n<pre><code>index = resultIndex + searchValue.Length;\n</code></pre>\n\n<p>Imagine the client wants to replace all instances of <code>aa</code> with <code>x</code> and the input string contains <code>aaaa</code>. If I read the code at the end correctly (the code that uses <code>Item1</code>/<code>Item2</code>/<code>Item3</code> a lot), it would throw because you would be passing a negative value into <code>Substring</code>.</p>\n\n<p>That’s all I could find that I would change if I had to maintain the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T15:35:27.323", "Id": "3016", "Score": "0", "body": "Talk about a thorough code review. To be honest I was not expecting anything this good. Thanks. Just in case you were curious *(Shameless plug for my project: https://github.com/ChaosPandion/Machete)*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T20:19:10.403", "Id": "3022", "Score": "0", "body": "I just posted my latest version of the code with your suggestions and it is really turning out well. Thanks again." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T01:40:45.173", "Id": "1723", "ParentId": "1699", "Score": "2" } } ]
{ "AcceptedAnswerId": "1723", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-07T04:15:33.230", "Id": "1699", "Score": "5", "Tags": [ "c#" ], "Title": "Implementation of String.prototype.replace" }
1699
<blockquote> <p><strong>Exercise 2.27</strong></p> <p>Modify your reverse procedure of exercise 2.18 to produce a deep-reverse procedure that takes a list as argument and returns as its value the list with its elements reversed and with all sublists deep-reversed as well. For example,</p> <pre><code>(define x (list (list 1 2) (list 3 4))) x ((1 2) (3 4)) (reverse x) ((3 4) (1 2)) (deep-reverse x) ((4 3) (2 1)) </code></pre> </blockquote> <p>I wrote the following:</p> <pre><code>(define (deep-reverse lis) (define (snoc elem lis) (if (null? lis) (cons elem lis) (cons (car lis) (snoc elem (cdr lis))))) (cond ((null? lis) lis) ((pair? (car lis)) (snoc (deep-reverse (car lis)) (deep-reverse (cdr lis)))) (else (snoc (car lis) (deep-reverse (cdr lis)))))) (define a (list 1 2 3 4 5 (list 1 2 3 4) (list 5 6 7 8))) </code></pre> <p>What do you think?</p>
[]
[ { "body": "<p>The main problem with using <code>snoc</code> (or <code>append</code>, which your <code>snoc</code> effectively does) is that <em>each</em> call is O(n). This makes your function O(n²), which is (pun intended) deeply problematic.</p>\n\n<p>Here's my O(n) implementation, which is tail-recursive along the <code>cdr</code>s:</p>\n\n<pre><code>(define (deep-reverse l)\n (let loop ((x l)\n (r '()))\n (cond ((null? x) r) \n ((pair? x) (loop (cdr x) (cons (deep-reverse (car x)) r)))\n (else x))))\n</code></pre>\n\n<p>Here's an even shorter version, using <code>fold</code> (also tail-recursive along the <code>cdr</code>s):</p>\n\n<pre><code>(define (deep-reverse l)\n (define (iter x y)\n (cons (if (pair? x) (deep-reverse x) x) y))\n (fold iter '() l))\n</code></pre>\n\n<p>For even more fun, an <code>unfold-right</code> version (also tail-recursive along the <code>cdr</code>s); requires <code>compose</code> as well:</p>\n\n<pre><code>(define (deep-reverse l)\n (define (iter x)\n (if (pair? x) (deep-reverse x) x))\n (unfold-right null? (compose iter car) cdr l))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T05:01:07.473", "Id": "1701", "ParentId": "1700", "Score": "2" } } ]
{ "AcceptedAnswerId": "1701", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-07T04:33:34.980", "Id": "1700", "Score": "0", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Producing a deep-reverse procedure" }
1700
<p>I want to get <code>distinct</code> of two columns from an SQL table. Can I optimize this query?</p> <pre><code>create TABLE #Temporary_tbl ( ProductColour VARCHAR(50), ProductSize VARCHAR(20), ) insert into #Temporary_tbl (ProductColour) select distinct productcolour from shoptransfer insert into #Temporary_tbl (ProductSize) select distinct ProductSize from shoptransfer select * from #Temporary_tbl </code></pre>
[]
[ { "body": "<p>This will give you the same result as your sql.</p>\n\n<pre><code>select distinct ProductColour, null as ProductSize\nfrom shoptransfer\n\nunion all\n\nselect distinct null as ProductColor, ProductSize\nfrom shoptransfer\n</code></pre>\n\n<p>You don't actually need the \"as\" clause on the second select, but I find it good for readability.</p>\n\n<p>Ultimatly, sql server will mostly be doing the same thing, but by removing the explicit temporary table and putting it all into one command, you give sql server a better chance of doing the two selects in parallel.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T09:31:06.933", "Id": "2962", "Score": "1", "body": "Can i union them without null values." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T09:39:21.443", "Id": "2964", "Score": "0", "body": "The number of columns needs to line up, if the nulls were removed then all the values would be placed in a single column, which would be a change in behavior from what you provided as your starting point." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T10:11:55.563", "Id": "2966", "Score": "0", "body": "But i want them in two column with out null is this possible." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T10:49:26.437", "Id": "2968", "Score": "0", "body": "If both columns from the source table have the same number of distinct values (or if it's distinct *pairs* you want) then I'm sure you can. The details of which depend largely on exactly what it is you want." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T05:57:54.310", "Id": "3609", "Score": "0", "body": "Shouldn't the first NULL be converted explicitly to `varchar(20)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T09:22:14.967", "Id": "3612", "Score": "0", "body": "@Andriy, sql server seems to do a good job of inferring this based on the other selects in the union (or at least sql server 2008 does). Personally I wouldn't add it unless sql server ran into difficulties, as it adds another location that needs to be updated if the field length increases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T12:06:14.107", "Id": "3613", "Score": "0", "body": "I should have checked the result of `SQL_VARIANT_PROPERTY(NULL, 'BaseType')` before asking that foolish question. Thanks for the explanation!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T08:38:08.187", "Id": "1709", "ParentId": "1703", "Score": "5" } }, { "body": "<pre><code>SELECT DISTINCT\n CASE x.f WHEN 1 THEN s.ProductColour END AS ProductColour\n CASE x.f WHEN 2 THEN s.ProductSize END AS ProductSize\nFROM shoptransfer s\n CROSS JOIN (SELECT 1 UNION ALL SELECT 2) x (f)\n</code></pre>\n\n<p>This produces the same output as Brian's solution. The idea is to make every row of <code>shoptransfer</code> output twice without scanning the table twice. That is achieved by cross-joining the table to a tiny tally table created 'on the fly'. When the tally table's first row is current, the query produces a row with a ProductColour value and NULL as ProductSize, and the second time it's the other way round, i.e. ProductColour is NULL and ProductSize contains a value from the <code>shoptransfer</code> table.</p>\n\n<p>The syntax used for defining the tally table may seem a bit unusual. For those of you not acquainted with that way of aliasing, <code>x</code> is the subselect's alias, the <code>f</code> in brackets is the alias for the subselect's single column. In short, the following two definitions are absolutely equivalent to each other:</p>\n\n<ol>\n<li><p><code>(SELECT 1 UNION ALL SELECT 2) x (f)</code></p></li>\n<li><p><code>(SELECT 1 AS f UNION ALL SELECT 2) x</code></p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-07T08:57:31.247", "Id": "4379", "Score": "1", "body": "Good idea. A quick test shows your approach runs in about half the time of mine, though it took me a moment to see what you were doing (I have never seen that `x (f)` notation before). You might want to add a short comment to your answer explaining the logic behind it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-01T14:28:18.593", "Id": "2761", "ParentId": "1703", "Score": "4" } }, { "body": "<p>No temporary table should be necessary.</p>\n\n<pre><code>SELECT DISTINCT productcolour FROM shoptransfer\n UNION ALL\nSELECT DISTINCT ProductSize FROM shoptransfer;\n</code></pre>\n\n<p>Furthermore, it would be a good idea to be more consistent with capitalization, even though SQL Server is not case sensitive.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-19T00:14:09.677", "Id": "74121", "ParentId": "1703", "Score": "0" } } ]
{ "AcceptedAnswerId": "1709", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-07T05:59:16.643", "Id": "1703", "Score": "5", "Tags": [ "sql", "sql-server" ], "Title": "Get distinct of two columns" }
1703
<p>Because I don't like using <code>\</code> to break long lines (to comply with PEP8), I tend to do something like this:</p> <pre><code>message = "There are {} seconds in {} hours." message = message.format(nhours*3600, nhours) print(message) </code></pre> <p>It also makes code cleaner. Is this an okay way of doing things?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T18:33:42.040", "Id": "2989", "Score": "1", "body": "Not really a Code Review, I feel this is more appropriate at [Programmers.SE](http://programmers.stackexchange.com/)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T02:35:35.867", "Id": "3000", "Score": "4", "body": "I think this is perfectly *on-topic* here." } ]
[ { "body": "<p>Nothing necessarily wrong with doing that - I use that for situations that the message would be used more than once. However, for one-shot, multiline messages I'd do:</p>\n\n<pre><code>message = \"There are %d seconds \" % nhours*3600\nmessage += \"in %d hours.\" % nhours\nprint message\n</code></pre>\n\n<p>Honestly, the only difference is stylistic. I prefer this method because it places the variables directly within the string, which I feel is more readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T17:33:41.293", "Id": "2985", "Score": "0", "body": "What does `it places the variables directly within the string` mean?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T17:40:35.867", "Id": "2986", "Score": "0", "body": "Maybe a bad wording there. I mean that since the variable is assigned in the same line as the string, it's a bit clearer what goes where. In fact, I'd prefer `msg = \"There are \" + nhours*3600 + \" seconds in \" + nhours + \" hours.\"` but I'm not certain whether you can do that in Python." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T17:43:34.833", "Id": "2987", "Score": "0", "body": "That's a lot uglier I think, but yeah you can do that. You just need to convert your integers to string: `msg = \"There are \" + str(nhours*3600) + \" seconds in \" + str(nhours) + \" hours.\"`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T18:01:43.387", "Id": "2988", "Score": "0", "body": "Like I said, matter of personal style :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T18:40:35.857", "Id": "2990", "Score": "0", "body": "You do lose reuseability which is important to note (without putting this code in a function). Ofcourse this isn't relevant if you only format once." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T18:52:14.340", "Id": "2993", "Score": "0", "body": "@StevenJeuris: What reusability do you lose?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T18:55:55.517", "Id": "2994", "Score": "0", "body": "@Tshepang: Both of our formats only allow for one use: Yours because the format overwrites the template, and mine because the message is constructed in situ." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T19:04:45.223", "Id": "2995", "Score": "0", "body": "@Michael: I'm referring to the possible reuse if you wouldn't overwrite. :)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T16:50:36.230", "Id": "1717", "ParentId": "1716", "Score": "-2" } }, { "body": "<p>It's more than okay, it is nicely readable, has no problems and involves no abuse whatsoever. I sometimes do the same. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T19:22:24.887", "Id": "1719", "ParentId": "1716", "Score": "2" } } ]
{ "AcceptedAnswerId": "1719", "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T16:20:41.737", "Id": "1716", "Score": "6", "Tags": [ "python" ], "Title": "Is it okay to 'abuse' re-assignment?" }
1716
<p>I wrote <a href="https://github.com/jacktrades/Lispy/tree/master/liSpy" rel="nofollow">this interpreter</a> a little while ago and was hoping I could get some comments/criticisms. It it somewhat similar to the "languages as libraries" concept of Racket, though obviously with less features.</p> <p>Another goal was to see how little I could implement and still have a usable language. I chose to implement a Scheme FFI (scheme-syntax ...) that allows defining of primitive syntax forms in the "language layer".</p> <p>Is this a good/bad approach? Are there any problems with the implementation in general? I've never had a code review before and, save for one commenter on Reddit yesterday, I've never had someone read/comment on my code before.</p> <p>This particular interpreter was written for a <a href="http://pointlessprogramming.wordpress.com/lispy-in-scheme/" rel="nofollow">series of blog posts</a> in the style of "An Incremental Approach to Compiler Construction". It is meant to be as simplistic as possible. If you want to review that as well I would appreciate it (though don't expect it at all).</p> <pre><code>(use srfi-69) (use srfi-1) (define global-syntax-definitions (make-hash-table)) (define-record primitive function) (define-record proc parameters body environment) (define (current-environment env) (car env)) (define (enclosing-environment env) (cdr env)) (define (extend-environment bindings base-environment) (cons (alist-&gt;hash-table bindings) base-environment)) (define the-global-environment (extend-environment '() '())) (define (set-symbol! symbol value env) (hash-table-set! (current-environment env) symbol value)) (define (lookup-symbol-value symbol environment) (if (null? environment) (conc "Error: Unbound symbol: " symbol) (if (hash-table-exists? (current-environment environment) symbol) (hash-table-ref (current-environment environment) symbol) (lookup-symbol-value symbol (enclosing-environment environment))))) (define (self-evaluating? expr) (or (number? expr) (string? expr) (char? expr) (boolean? expr) (proc? expr))) (define (lispy-eval expr env) (cond ((self-evaluating? expr) expr) ((symbol? expr) (lookup-symbol-value expr env)) (else (if (hash-table-exists? global-syntax-definitions (car expr)) ((hash-table-ref global-syntax-definitions (car expr)) (cdr expr) env) (lispy-apply (lispy-eval (car expr) env) (eval-arguments (cdr expr) env)))))) (define (eval-arguments args env) (map (lambda (x) (lispy-eval x env)) args)) (define (eval-body args env) (last (eval-arguments args env))) (define (assign-values procedure args) (map cons (proc-parameters procedure) args)) (define (lispy-apply procedure arguments) (cond ((primitive? procedure) (apply (primitive-function procedure) arguments)) ((proc? procedure) (eval-body (proc-body procedure) (extend-environment (assign-values procedure arguments) (proc-environment procedure)))) (else (conc "Error: Undefined procedure: " (-&gt;string procedure))))) (hash-table-set! global-syntax-definitions 'scheme-syntax (lambda (expr env) (hash-table-set! global-syntax-definitions (car expr) (eval (cadr expr))))) (hash-table-set! global-syntax-definitions 'load (lambda (expr env) (define f (open-input-file (car expr))) (let loop ((e (read f))) (if (equal? e #!eof) "Successfully Loaded!" (begin (lispy-eval e env) (loop (read f))))))) ((hash-table-ref global-syntax-definitions 'load) '("scheme_in_lispy.chicken") the-global-environment) (define (repl) (define input (read)) (print ";===&gt; " (lispy-eval input the-global-environment)) (repl)) (repl) </code></pre> <p>And here's an example of a very small subset of Scheme implemented in this framework:</p> <pre><code>(scheme-syntax define-primitive (lambda (expr env) (set-symbol! (car expr) (make-primitive (eval (cadr expr))) env))) (scheme-syntax define (lambda (expr env) (if (list? (car expr)) (set-symbol! (caar expr) (make-proc (cdar expr) (cdr expr) env) env) (set-symbol! (car expr) (lispy-eval (cadr expr) env) env)))) (scheme-syntax lambda (lambda (expr env) (make-proc (car expr) (cdr expr) env))) (scheme-syntax if (lambda (expr env) (if (lispy-eval (car expr) env) (lispy-eval (cadr expr) env) (lispy-eval (caddr expr) env)))) (scheme-syntax quote (lambda (expr env) (car expr))) (scheme-syntax set! (lambda (expr env) (set-symbol! (car expr) (lispy-eval (cadr expr) env) env))) (scheme-syntax begin (lambda (expr env) (eval-body expr env))) (scheme-syntax let (lambda (expr env) (eval-body (cdr expr) (extend-environment (car expr) env)))) (scheme-syntax equal? (lambda (expr env) (equal? (lispy-eval (car expr) env) (lispy-eval (cadr expr) env)))) (define-primitive + +) (define-primitive - -) (define-primitive &lt; &lt;) (define-primitive &gt; &gt;) (define-primitive car car) (define-primitive cdr cdr) (define-primitive cons cons) (define-primitive print print) </code></pre>
[]
[ { "body": "<p>There is a hidden bug in the interpreter.</p>\n\n<p>Your <code>eval-body</code> calls <code>eval-arguments</code> to evaluate the body expressions of a compound procedure, but the evaluation order of <code>map</code> it not defined in Scheme. The procedure bodies should be evaluated with <code>for-each</code> as it has well-defined evaluation order from left to right. Both the following are correct implementations of Scheme <code>map</code> (for simplicity, shown with unary function arguments only):</p>\n\n<pre><code> (define (map f ls) ;; evaluates in left-to-right order\n (if (null? ls) '()\n (let ((val (f (car ls))))\n (cons val (map f (cdr ls))))))\n\n (define (map f ls) ;; evaluates in right-to-left order\n (if (null? ls) '()\n (let ((rs (map f (cdr ls))))\n (cons (f (car ls)) rs))))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-16T22:38:06.113", "Id": "3227", "Score": "0", "body": "Thanks for pointing that out. That was the result of oversimplifying this:\n`(define (eval-arguments exps env)\n (if (null? exps)\n '()\n (cons (meta-eval (car exps) env)\n (eval-arguments (cdr exps) env))))`\nI'll look into using for-each. I've never used it before and this seems as good an excuse as any." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-17T23:41:29.833", "Id": "3247", "Score": "0", "body": "Yes, `for-each` is like `map` but used when you evaluate the expression for their side-effects instead of their values; because of this emphasis, `for-each` has a well-defined execution order." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-15T21:50:26.090", "Id": "1917", "ParentId": "1718", "Score": "2" } } ]
{ "AcceptedAnswerId": "1917", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-07T16:58:02.537", "Id": "1718", "Score": "3", "Tags": [ "scheme", "interpreter" ], "Title": "Interpreter framework for writing Scheme-like interpreters in < 60 loc" }
1718
<p>I'm only asking because almost the entire code base I've inherited here, in C# and PHP, looks like this:</p> <pre><code>if (varOne == flag) { run_some_sql(); set_some_flag = true; } if (varTwo == flag) { run_some_sql(); set_some_flag = true; } if (varThree == flag) { run_some_sql(); set_some_flag = true; } if (varFour == flag) { run_some_sql(); set_some_flag = true; } if (varFive == flag) { run_some_sql(); set_some_flag = true; } if (varSix == flag) { run_some_sql(); set_some_flag = true; } if (varSeven == flag) { run_some_sql(); set_some_flag = true; } if (varEight == flag) { run_some_sql(); set_some_flag = true; } </code></pre> <p>For about ten thousand lines.</p> <p>I haven't lost my mind, right? Is this bad? There's only about five loops in the entire code base of about 50,000 lines. </p> <p>I would normally go about this sort of thing by storing the data into an associated array, and loop over that, rather than adding a new <code>if</code> statement for every variable.</p> <p>Have I totally lost my mind? Eight people worked on this before me, and I'm seriously worried here. Is there ever a good reason to do this sort of thing?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T22:42:41.170", "Id": "2998", "Score": "3", "body": "Well, at least you are sure you will do better than the previous employees. ;p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T03:29:06.230", "Id": "3002", "Score": "0", "body": "wtf!? oh my god... o.O" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T09:20:29.370", "Id": "3006", "Score": "1", "body": "Reminds me of the SO question [get rid of ugly if statements](http://stackoverflow.com/q/3786358/342852)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T07:19:37.550", "Id": "3035", "Score": "2", "body": "you're not crazy... although, i wonder if SLOC stats are management's measure for employees' productivity/contribution within the project ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T08:41:45.417", "Id": "7230", "Score": "0", "body": "You don't know http://thedailywtf.com/ , right?" } ]
[ { "body": "<p>No, you haven't lost your mind. It should more like...</p>\n\n<pre><code>// declared and set somewhere\nflags = new int[x];\n\n//...\n\nfor (int value: flags) {\n if (value == flag) {\n run_some_sql();\n set_some_flag = true;\n }\n}\n</code></pre>\n\n<p>...assuming that the flags are the same type and they really do do the exact same thing. Are you sure that there are no god objects somewhere that the other methods are basing their responses of off?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T19:51:01.830", "Id": "1721", "ParentId": "1720", "Score": "9" } }, { "body": "<p>This is bad. Very bad.</p>\n\n<p>It appears the original implementer doesn't quite understand arrays. You should definitely refactor this. <a href=\"https://codereview.stackexchange.com/questions/1720/im-not-crazy-right-endless-if-statements-this-is-a-bad-pattern-yes/1721#1721\">Michael K's answer</a> has the right approach. In C# syntax:</p>\n\n<pre><code>// Hopefully these variables are already in an array or list already, otherwise:\nMyType[] myVariables = new MyType[] { varOne, varTwo, /* ... */ varEight };\n\nforeach (MyType variable in myVariables)\n{\n if (variable == flag)\n {\n run_some_sql();\n set_some_flag = true;\n }\n}\n</code></pre>\n\n<p>Note that if <code>run_some_sql()</code> only needs to be executed once, you can break out early and save some computation time:</p>\n\n<pre><code>foreach (MyType variable in myVariables)\n{\n if (variable == flag)\n {\n run_some_sql();\n set_some_flag = true;\n\n break;\n }\n}\n</code></pre>\n\n<p>If it is the case that you only need to execute <code>run_some_sql()</code> once, you can make the code even simpler using new LINQ syntax:</p>\n\n<pre><code>if (myVariables.Any(v =&gt; v == flag))\n{\n run_some_sql();\n set_some_flag = true;\n}\n</code></pre>\n\n<p>While refactoring, I'd also recommend choosing some better variable names than <code>varOne</code>, <code>varTwo</code>, <code>flag</code>, etc. Though I assume these are just your examples. :) </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T02:57:06.050", "Id": "3001", "Score": "0", "body": "Well, what I'm dealing with is a group of variables that are clearly all related, but not stored as an array. varOne, varTwo is an accurate generic representation of this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T15:50:40.477", "Id": "3017", "Score": "0", "body": "@user2905 Is there a logical place where you can put them into an array or List, such as during initialization? If they are all related, I imagine this won't be the only function you'll find that has copy-paste code like this." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T20:35:39.383", "Id": "1722", "ParentId": "1720", "Score": "12" } }, { "body": "<p>Another possible approach is to store the SQL statements in a dictionary and to use the flag as key</p>\n\n<pre><code>Dictionary&lt;TypeOfFlag, string&gt; dict = new Dictionary&lt;TypeOfFlag, string&gt;();\ndict.Add(valueOne, \"SELECT x FROM y\");\ndict.Add(valueTwo, \"SELECT z FROM t\");\n...\n\nstring sql;\nif (dict.TryGetValue(flag, out sql)) {\n RunSQL(sql);\n set_some_flag();\n}\n</code></pre>\n\n<p>If you need more information in order to run a query, you could create a class containing this information, the SQL statement, and possibly even an <code>Execute</code> method and store that one in the dictionary. See: <a href=\"http://en.wikipedia.org/wiki/Command_pattern\" rel=\"nofollow\">Command pattern</a> (Wikipedia).</p>\n\n<p>Dictionaries have a constant access time <code>O(1)</code> and require no loops in order to access an item and of course require no endless if statements!</p>\n\n<hr>\n\n<p>Endless <code>if</code>-chains and <code>switch</code>-statements (Case-statements in other languages) are often a strong hint that a poor procedural approach has been used. Applying the <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a> principle can even improve such procedural approaches. <a href=\"http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29\" rel=\"nofollow\">Polymorphism</a> (<a href=\"http://en.wikipedia.org/wiki/Subtyping\" rel=\"nofollow\">Subtyping</a>) is an object-oriented approach that can often eliminate these unpleasant structures as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T22:39:54.737", "Id": "44535", "ParentId": "1720", "Score": "5" } } ]
{ "AcceptedAnswerId": "1722", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-04-07T19:44:34.373", "Id": "1720", "Score": "9", "Tags": [ "c#", "design-patterns" ], "Title": "Executing functions and declaring flags with a long battery of if conditions" }
1720
<p>I am looking for a suggestion or advises about some code I have written. I build an online application about 3 month ago the app registers new buildings including description names and so on. The app works perfectly and does what it suppose to. While working on it I was constantly learning and improving my skills. I did include the internal CSS as it was designed specifically for this page but I also used external one as well. I used a lot of ajax, php, and js. I looked at many tutorial and articles while working on this. My main question is<br> 1) some suggestion toward improving the structure</p> <p>2) is the code similar to something that in a real world in real companies programmer write. 3) Is it good for someone who just started it career and the first major web app he is written. Here is a sample file again it all working I do not want you to go thru every line just suggestions. </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;style type="text/css"&gt; /* demo styles */ fieldset { border:0; } select { width: 400px; } a.ggg{ color: #003366; font-size: x-large; font-family: Monotype Corsiva; } a.gg{ color: #003366; font-size: medium; font-family: Monotype Corsiva; } .darkbg{ background:#ddd !important; } #status{ font-family:Arial; padding:5px; } ul#files{ list-style:none; padding:0; margin:0; } ul#files li{ margin-bottom:2px; width:200px; float:left; } ul#files li img{ max-width:180px; max-height:150px; } .success{ background:#FFCC99; border:1px solid #FF9933; } .error{ background:#f0c6c3; border:1px solid #cc6622; } #button { padding: .5em 1em; text-decoration: none; } #effect { width: 700px; height: 200px; padding: 0.4em; position: relative; } #effect h3 { margin: 0; padding: 0.4em; text-align: center; } &lt;/style&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="content-type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;&lt;/title&gt; &lt;link href="styles.css" rel="stylesheet" type="text/css" media="screen" /&gt; &lt;link type="text/css" href="css/custom-theme/jquery-ui-1.8.5.custom.css" rel="stylesheet" /&gt; &lt;script type="text/javascript" src="js/ajaxupload.3.5.js" &gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/jquery-1.4.2.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/jquery-ui-1.8.5.custom.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="tags.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="ui/jquery.ui.core.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="ui/jquery.ui.widget.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="ui/jquery.ui.position.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="ui/jquery.ui.selectmenu.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(function(){ // gui function for builodin select box gui $('select#Building').selectmenu({ style:'popup', maxHeight: 150 }); $('select#Building4').selectmenu({ style:'popup', maxHeight: 150 }); $('select#Building24').selectmenu({ style:'popup', maxHeight: 150 }); }); //a custom format option callback // builds gui for tabs $(function() { $( "#tabs" ).tabs(); }); // gui function for buttons $(function() { $( "#search" ).button(); $( "#delete" ).button(); $( "#view" ).button(); $( "#insert" ).button(); $( "#upload" ).button(); $( "#finish" ).button(); $( "#thub" ).button(); $( "#insroom" ).button(); $( "#clearfields" ).button(); $("#date").datepicker(); }); // ajax Function used to retrive all question runs getallquestions.php function allQuestions(){ $.ajax({ type: "POST", url: "getallquestions.php", success: function(html){ $("#allquestions").html(html); } }); } // ajax function send date to the getquestionsbydate.php and brings questions function Questionsbydate(){ $.ajax({ type: "POST", url: "getquestionsbydate.php", data: "date=" + document.getElementById('date').value, success: function(html){ $("#allquestions").html(html); } }); } function deletebuilding(){ // gets building information var x=document.getElementById("Building"); var building=x.options[x.selectedIndex].text; // runs ajax function to delete the building $.ajax({ type: "POST", url: "deletebuilding.php", data: "building=" + building, success: function(html){ $("#deletebuilding").html(html); } }); } // gets the building information function update(){ var x=document.getElementById("Building4"); var building4=x.options[x.selectedIndex].text; // ajax function to run the updatebuilding.php $.ajax({ type: "POST", url: "updatebuilding.php", data: "building4=" + building4, success: function(html){ $("#updateinfo").html(html); } }); } function insert(){ // ajax function to run insertbuilding.php $.ajax({ type: "POST", url: "insertbuilding.php", data: "building2=" + document.getElementById('building2').value + "&amp;list2=" + document.getElementById('list2').value+ "&amp;NoonMap2=" + document.getElementById('NoonMap2').value+ "&amp;Description2=" + document.getElementById('Description2').value+ "&amp;bldg2=" + document.getElementById('bldg2').value, success: function(html){ $("#buli").html(html); } }); } function EMPTY(){ // retrives the building information document.getElementById('building2').value ="" ; document.getElementById('list2').value="" ; document.getElementById('NoonMap2').value="" ; document.getElementById('Description2').value="" ; document.getElementById('bldg2').value="" ; document.getElementById('buli').innerHTML=""; } // runs funvtion to inset the thumbnail to the database function thub(){ $.ajax({ type: "POST", url: "blobpart11.php", data: "building2=" + document.getElementById('building2').value, success: function(html){ $("#thumres").html(html); } }); } // function to run the insert question runs addquestion.php function addquestion(){ $.ajax({ type: "POST", url: "addquestion.php", data: "quest=" + document.getElementById('quest').value + "&amp;ans="+document.getElementById('ans').value, success: function(html){ $("#allquestions").html(html); } }); } // function for creating button gui and dialog effect $(function() { $( "#submit" ).button(); function runEffect() { var selectedEffect = $( "#effectTypes" ).val(); var options = {}; $( "#effect" ).show( selectedEffect, options, 500, callback ); }; function callback() { }; // set effect from select menu value $( "#button" ).click(function() { runEffect(); return false; }); $( "#effect" ).hide(); }); function callback45() { $( "#effect:visible" ).removeAttr( "style" ).fadeOut(); }; function insertroom(){ // retrives building information var x=document.getElementById("Building24"); var building24=x.options[x.selectedIndex].text; $.ajax({ // ajax function used to run the addroom specification.php type: "POST", url: "addroomspecification.php", data: "building24=" + $( "#Building24" ).val() + "&amp;Rm_Nm=" + document.getElementById('rm').value+ "&amp;Filled=" + document.getElementById('fill').value+ "&amp;Gender=" + document.getElementById('gen').value+ "&amp;Dimensions=" + document.getElementById('dim').value+ "&amp;Comments=" + document.getElementById('com').value+ "&amp;prcd=" + document.getElementById('prcd').value+ "&amp;bl=" + document.getElementById('bl').value+ "&amp;rest=" + document.getElementById('rest').value+ "&amp;Capacity=" + document.getElementById('cap').value, success: function(html){ $("#room").html(html); } }); } function clearfilds(){ // function for clearing fields document.getElementById('rm').value= "" ; document.getElementById('fill').value="" ; document.getElementById('gen').value= "" ; document.getElementById('dim').value= "" ; document.getElementById('com').value= "" ; document.getElementById('prcd').value= "" ; document.getElementById('bl').value= "" ; document.getElementById('rest').value= "" ; document.getElementById('cap').value= "" ; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="content"&gt; &lt;!-- header begins --&gt; &lt;div id="menu"&gt; &lt;ul&gt; &lt;li id="button1"&gt;&lt;a href="#" title="" &gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li id="button2"&gt;&lt;a href="#" title=""&gt;Blog&lt;/a&gt;&lt;/li&gt; &lt;li id="button3"&gt;&lt;a href="#" title=""&gt;Gallery&lt;/a&gt;&lt;/li&gt; &lt;li id="button4"&gt;&lt;a href="#" title=""&gt;About&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id="logo"&gt; &lt;img src="images/logo.jpg" width="300" height="180" alt="" /&gt; &lt;/div&gt; &lt;br /&gt;&lt;br /&gt; &lt;div id="tabs" style="height: 700px; overflow: scroll"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#tabs-1"&gt;Search By Key word&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tabs-2"&gt;Search By Specification&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tabs-3"&gt;Modify Building Information&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tabs-4"&gt;Modify Building Information&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tabs-5"&gt;Modifyn&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div id="tabs-1" &gt; &lt;br /&gt;&lt;br /&gt; &lt;input id="search" type="button" name="Search by date" value="Search by Date" onclick="Questionsbydate()"/&gt;&amp;nbsp;&amp;nbsp; &lt;input id="date" name="date" /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input id="view" type="button" name="View All QUESTIONS" value="View All QUESTIONS" onclick="allQuestions()" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;div id="allquestions"&gt;&lt;/div&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt; &lt;div class="demo"&gt; &lt;div align="center" class="toggler"&gt; &lt;div style="width: 700px; height: 200px" id="effect" class="ui-widget-content ui-corner-all"&gt; &lt;h3 class="ui-widget-header ui-corner-all"&gt;Add QUESTION&lt;/h3&gt; &lt;p&gt; &lt;a class='gg' &gt;Please Enter The Question&lt;/a&gt;&amp;nbsp;&amp;nbsp;&lt;input id="quest" style="width: 300px" name="quest" /&gt;&lt;br /&gt;&lt;br /&gt; &lt;a class='gg' &gt;Please Enter The Answer&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;input id="ans" style="width: 300px" name="ans" /&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;select style="visibility: hidden" name="effects" id="effectTypes"&gt; &lt;option value="blind"&gt;Blind&lt;/option&gt; &lt;/select&gt; &lt;center&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; &lt;a href="#" id="button" class="ui-state-default ui-corner-all"&gt;Add Question&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input id="submit" type="button" name="Submit" value="Submit" onclick=" addquestion(), callback45() " /&gt;&lt;/center&gt; &lt;/div&gt; &lt;div style="display: none" id="dialog" title="Basic dialog"&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;&lt;a&gt;E-Mail&lt;/a&gt;&lt;/td&gt; &lt;td&gt;&lt;input id="email" name="email" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;a&gt;Question Asked&lt;/a&gt;&lt;/td&gt; &lt;td&gt;&lt;textarea id="qu" name="quest" rows="3"&gt;&lt;/textarea&gt;&lt;br /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;a&gt;Question Answer&lt;/a&gt;&lt;/td&gt; &lt;td&gt;&lt;textarea id="answ" name="quest" rows="3"&gt;&lt;/textarea&gt;&lt;br /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;input id="op" type="button" name="reply" value="Reply" onclick="se()" /&gt; &lt;/div&gt; &lt;div id="response"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- /#tabs-1 --&gt; &lt;div id="tabs-2"&gt; &lt;?php $con = mysql_connect("localhost", "root"); if (!$con) { die('Could not connect: ' . mysql_error()); } // retrives the list of buildings mysql_select_db("buildings", $con); $result6 = mysql_query("SELECT `Building Name` FROM `buildingsinfo` WHERE `Building Name` &lt;&gt; '' GROUP BY `Building Name` "); echo "&lt;center&gt;&lt;a class='ggg' &gt;Please select House&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;select name=Building id='Building' value=''&gt;Building Name&lt;/option&gt;"; // printing the list box select command while($nt6=mysql_fetch_array($result6)) { //Array or records stored in $nt $hello=$nt6['Building Name']; echo "&lt;option value=$hello&gt;$hello&lt;/option&gt;"; /* Option values are added by looping through the array */ } echo "&lt;/select&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;";// Closing of list box ?&gt; &lt;center&gt; &lt;input type="button" id="delete" style="width: 200px; height: 100px; font-size: large" value="DELETE BUILDING" onclick="deletebuilding()"&gt; &lt;/center&gt;&lt;br /&gt;&lt;br /&gt; &lt;div id="deletebuilding"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- /#tabs-2 --&gt; &lt;div id="tabs-3"&gt; &lt;?php $con = mysql_connect("localhost", "root"); if (!$con){ die('Could not connect: ' . mysql_error()); } // retrives the list of buildings and builds dropdown box mysql_select_db("buildings", $con); $result6 = mysql_query("SELECT `Building Name` FROM `buildingsinfo` WHERE `Building Name` &lt;&gt; '' GROUP BY `Building Name` "); echo "&lt;a class='ggg' &gt;Please select House&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;select name=Building id='Building4' value='' onchange='update()' &gt;Building Name&lt;/option&gt;"; // printing the list box select command echo "&lt;option value=ANY&gt;ANY&lt;/option&gt;"; while($nt6=mysql_fetch_array($result6)) { //Array or records stored in $nt $hello=$nt6['Building Name']; echo "&lt;option value=$hello&gt;$hello&lt;/option&gt;"; /* Option values are added by looping through the array */ } echo "&lt;/select&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;"; // Closing of list box ?&gt; &lt;div id="updateinfo"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- /#tabs-3 --&gt; &lt;div id="tabs-4"&gt; &lt;h2&gt;Step 1 Insert The Building Info&lt;/h2&gt; &lt;a class='gg' &gt;Building Name&lt;/a&gt;&amp;nbsp;&amp;nbsp;&lt;input id="building2" name="building" value="" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;a class='gg' &gt; List No. &lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input id="list2" name="list" value="" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;a class='gg' &gt; No. on Map.&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input id="NoonMap2" name="NoonMap2" value="" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;a class='gg' &gt;Description&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;textarea rows="7" style="width: 200px" id="Description2" name="Description" &gt; &lt;/textarea&gt; &lt;br /&gt; &lt;br /&gt; &lt;a class='gg' &gt;Building Initials&lt;/a&gt;&amp;nbsp;&amp;nbsp; &lt;input id="bldg2" name="Bldg" value="" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;input id="insert" type="button" name="INSERT" value="insert" onclick=" insert()" /&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt; &lt;h2&gt;Step 2 Insert Insert Thubnail&lt;/h2&gt; &lt;input id="thub" type="button" name="thub" value="THUBNAIL" onclick="thub()" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;div id="thumres"&gt;&lt;/div&gt; &lt;br /&gt;&lt;br /&gt; &lt;h2&gt;Step 3 Insert Pictures&lt;/h2&gt; &lt;div id="buli"&gt;&lt;/div&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; &lt;input id="finish" type="button" name="FINISH" value="FINISH" onclick=" EMPTY()" /&gt; &lt;/div&gt; &lt;!-- /#tabs-4 --&gt; &lt;div id="tabs-5"&gt; &lt;?php $con = mysql_connect("localhost", "root"); if (!$con) { die('Could not connect: ' . mysql_error()); } // Retrives a list of buildings and builds dropdown box mysql_select_db("buildings", $con); $result6 = mysql_query("SELECT `Building Name` , `Bldg` FROM `buildingsinfo` WHERE `Bldg` &lt;&gt; ''"); echo "&lt;a class='ggg' &gt;Please select House&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;select name=Building24 id='Building24' value='' &gt;Building Name&lt;/option&gt;"; // printing the list box select command while($nt6=mysql_fetch_array($result6)) { //Array or records stored in $nt $hello=$nt6['Building Name']; echo "&lt;option value=$hello&gt;$hello&lt;/option&gt;"; /* Option values are added by looping through the array */ } echo "&lt;/select&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;";// Closing of list box ?&gt; &lt;a class='gg' &gt;Please Enter Room Number&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input id="rm" name="rm" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;a class='gg' &gt;Please Enter Building Letter&lt;/a&gt; &lt;input id="bl" name="bl" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;a class='gg' &gt;Filled&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input id="fill" name="fill" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;a class='gg' &gt;Please Enter Pricing Code&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input id="prcd" name="prcd" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;a class='gg' &gt;Please Enter Capacity&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input id="cap" name="cap" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;a class='gg' &gt;Please Enter Gender&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input id="gen" name="gen" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;a class='gg' &gt;Please Enter Dimension&lt;/a&gt;&amp;nbsp;&amp;nbsp; &lt;input id="dim" name="dim" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;a class='gg' &gt;Please Enter Restriction Name&lt;/a&gt; &lt;input id="rest" name="rest" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;a class='gg' &gt;Please Enter Comments&lt;/a&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input id="com" name="com" /&gt; &lt;br /&gt;&lt;br /&gt; &lt;input id="insroom" type="button" name="insroom" value="Insert Room" onclick="insertroom()" /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input id="clearfields" type="button" name="clearfilds" value="Clear Fields/Insert Another Room" onclick="clearfilds()"/&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt; &lt;div id="room"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- /#tabs-5 --&gt; &lt;/div&gt; &lt;!-- /#tabs --&gt; &lt;/div&gt; &lt;!-- /#content --&gt; &lt;!-- End demo --&gt; &lt;div&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt; &lt;img src="images/logo_lsu_dsa.JPG" width="231" height="83" alt="" /&gt; &lt;/div&gt; &lt;!--footer begins --&gt; &lt;div id="footer"&gt; &lt;p&gt;Copyright 2009. &lt;a href="#"&gt;Privacy Policy&lt;/a&gt; | &lt;a href="#"&gt;Terms of Use&lt;/a&gt; | &lt;a href="http://validator.w3.org/check/referer" title="This page validates as XHTML 1.0 Transitional"&gt;&lt;abbr title="eXtensible HyperText Markup Language"&gt;XHTML&lt;/abbr&gt;&lt;/a&gt; | &lt;a href="http://jigsaw.w3.org/css-validator/check/referer" title="This page validates as CSS"&gt;&lt;abbr title="Cascading Style Sheets"&gt;CSS&lt;/abbr&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Design by &lt;a href="http://www.metamorphozis.com/" title="Flash Website Templates"&gt;Flash Website Templates&lt;/a&gt;&lt;/p&gt; &lt;/div&gt;&lt;!-- footer ends--&gt; &lt;div style="text-align: center; font-size: 0.75em;"&gt; Design downloaded from &lt;a href="http://www.freewebtemplates.com/"&gt;free website templates&lt;/a&gt;. &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T11:49:19.680", "Id": "3009", "Score": "2", "body": "Welcome to CodeReview.SE. Please post your code in the post and remove the link to the pastebin. All of this is mentioned in the FAQ: http://codereview.stackexchange.com/faq. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T19:35:24.963", "Id": "3023", "Score": "0", "body": "Thank you all!! \r\n\r\n\r\nI was trying to post the code but i guess it to long and not getting displayed properly." } ]
[ { "body": "<p>When it comes down to improving the structure there's reallly 2 ways to go about it when it comes to the client side.</p>\n\n<p>I can see that your loading your CSS Directly within the page, this can be a pro when it comes to loading speeds, but with today's internet speeds that's practically nothing.</p>\n\n<p>I would separate each entity of the site, entities being:</p>\n\n<ul>\n<li>CSS</li>\n<li>Javascript</li>\n</ul>\n\n<p>And i would use link / script tag's to include this to your page, the reason for this is that if you have multiple pages you would have to copy and paste each block of a css and javascript to that page, and then when you make a small change you would have edit lots of files.</p>\n\n<p>When it comes to PHP, you seem to be doing the same thing, directly typing the code into the main page, as stated before this would cause issues with updates, so place it within a template and include it:</p>\n\n<p>You can make your templates a lot more flexible this way, here's how i think your layout should look:</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n &lt;?php require('templates/head.php'); ?&gt;\n &lt;body&gt;\n &lt;div class=\"wrapper\"&gt;\n &lt;?php require('templates/header.php'); ?&gt;\n &lt;?php require('templates/menu.php'); ?&gt;\n &lt;div id=\"container\"&gt;\n &lt;div id=\"main\"&gt;\n &lt;?php require('templates/content/main.php'); ?&gt;\n &lt;/div&gt;\n &lt;div id=\"main\"&gt;\n &lt;?php require('templates/content/sidebar.php'); ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php require('templates/content/footer'); ?&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Also another major issue that I see is that your code is extremely invalid, you should google <strong>W3C Validator</strong> and validate your html</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T07:42:23.133", "Id": "3153", "Score": "0", "body": "id=\"main\" twice?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T09:04:55.500", "Id": "1728", "ParentId": "1724", "Score": "2" } }, { "body": "<p>Your code shows real promise!</p>\n\n<p>Web based systems are complex and you have been able to utilise different elements to achieve your goals: CSS, javascript, PHP, SQL. You are seeking advice, which means you will learn more quickly than most programmers. You have correctly comprehended the basic tools for organising your code, and have also begun good habits like using comments to make your code more readable. All really great to see in a new programmer!</p>\n\n<p>The previous response was excellent on the point of organising your code.</p>\n\n<p>Because you show promise and are asking questions, I will also take the time to comment on some other areas you may improve:</p>\n\n<ul>\n<li>Inconsistent indentation</li>\n<li>Comments could be improved (always the case, even for the most experienced of us!)</li>\n<li>Inconsistent capitalisation in variable, function and SQL column names (<code>lowercase_with_underscores()</code> is my preference as it saves typing and <code>isMoreReadableThanThisCrapWhichIsCalledCamelCase()</code>, however many OOP-focused coders use the second style. That doesn't make them right, though!)</li>\n<li>Inconsistent naming of SQL column names. There are various approaches to this, personally I almost always have a primary key column called <code>id</code>, name my tables with a plural (eg: <code>buildings</code>) and so wind up with very readable queries like <code>select id from buildings</code>. It is almost always a bad idea to use <code>CamelCase</code> or <code>Multi Word</code> column names, since they mean that you have to write escaping backquotes around them all the time.</li>\n<li>Strange SQL queries. Your query <code>SELECT ``Building Name`` , ``Bldg`` FROM ``buildingsinfo`` WHERE ``Bldg`` &lt;&gt; ''</code> blah is asking for apparently every row in the database table. The easier way to do this is simply <code>SELECT column,list,here FROM buildingsinfo</code>. There is no need for the <code>WHERE</code> clause.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T02:06:06.863", "Id": "1795", "ParentId": "1724", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T03:11:42.363", "Id": "1724", "Score": "3", "Tags": [ "php", "javascript" ], "Title": "The first major app CMS writen" }
1724
<p>I have written some survey functionality for a project. Basically, a generic survey form that can be composed of sections and questions.</p> <p>I have a <code>Survey</code> class, <code>Questions</code> and <code>Sections</code>. The <code>Survey</code> is basically a tree, where each node can be a <code>Question</code> or a <code>Section</code>. Nodes have children -- so essentially <code>Question</code> can have a collection of subsections and subquestions, and a <code>Section</code> can have a collection of subsections and subquestions.</p> <p>The nodes in my <code>Survey</code> have derive from the abstract class <code>SurveyPart</code>.</p> <pre><code>namespace Surveys { public abstract class SurveyPart { public abstract List&lt;SurveyPart&gt; Children { get; set; } } public class Survey { public List&lt;SurveyPart&gt; Children { get; set; } public Survey() { Children = new List&lt;SurveyPart&gt;(); } } public class Question : SurveyPart { public override List&lt;SurveyPart&gt; Children { get; set; } public string QuestionText { get; set; } public Question() { Children = new List&lt;SurveyPart&gt;(); } } public class Section : SurveyPart { public override List&lt;SurveyPart&gt; Children { get; set; } public string Header { get; set; } public Section() { Children = new List&lt;SurveyPart&gt;(); } } } </code></pre> <p>As far as I understand this is the Composite pattern? Not sure I've got it entirely right.</p> <p>So with that I can build a survey (at present with the sections and questions coming from a DB.) Next thing is to render it. For that I'm attempting to use the Visitor pattern implemented with extension methods.</p> <pre><code>namespace ExtensionMethods { using Surveys; public static class SurveyTextRenderer { public static int Depth; public static void Write(this Survey survey) { Depth = 0; Console.WriteLine("Survey"); Console.WriteLine(new string('-', "Survey".Length)); foreach (SurveyPart child in survey.Children) { Depth++; child.Write(); Depth--; } } public static void Write(this SurveyPart part) { if (part is Section) (part as Section).Write(); if (part is Question) (part as Question).Write(); } public static void Write(this Section section) { Console.Write(new String('\t', Depth)); Console.WriteLine("S:" + section.Header); foreach (SurveyPart child in section.Children) { Depth++; child.Write(); Depth--; } } public static void Write(this Question question) { Console.Write(new String('\t', Depth)); Console.WriteLine("Q: " + question.QuestionText); foreach (SurveyPart child in question.Children) { Depth++; child.Write(); Depth--; } } } } </code></pre> <p>It all works OK -- if I set up the following mock survey:</p> <pre><code>Survey survey = new Survey { Children = new List&lt;SurveyPart&gt; { new Section { Header = "Section 1", Children = new List&lt;SurveyPart&gt; { new Question { QuestionText = "Foo?" }, new Question { QuestionText = "Bar?" }, new Question { QuestionText = "Barry?" } } }, new Section { Header = "Section 2", Children = new List&lt;SurveyPart&gt; { new Question { QuestionText = "Did you like it?", Children = new List&lt;SurveyPart&gt; { new Section { Header = "If you answered yes, please answer the following", Children = new List&lt;SurveyPart&gt; { new Question { QuestionText = "How come?" }, new Question { QuestionText = "How much did you like it?" } } } } }, new Question { QuestionText = "Please leave a comment" }, } } } }; </code></pre> <p>and call</p> <pre><code>survey.Write(); </code></pre> <p>I get:</p> <pre><code>Survey ------ S:Section 1 Q: Foo? Q: Bar? Q: Barry? S:Section 2 Q: Did you like it? S:If you answered yes, please answer the following Q: How come? Q: How much did you like it? Q: Please leave a comment </code></pre> <p>So basically to sum up, I'm trying to use the <strong>Composite</strong> pattern to allow for a tree of sections and questions. Then to navigate and render this tree I'm trying to use the <strong>Visitor</strong> pattern.</p> <p>A few questions occurring to me:</p> <ul> <li>I'm using the static member <code>Depth</code> to keep track of how deep the visitor has gone. Could it be problematic having state on my extension methods static class?</li> <li>Would the SurveyPart abstract class make more sense as an interface?</li> <li>Am I using Visitor and Composite in the right way, or am I borking them up? </li> </ul> <p>(Note I've left a lot a parts out... e.g. different types of questions, scores/responses to questions, etc... just focused on the tree/Composite/Visitor parts of the code for now.)</p>
[]
[ { "body": "<blockquote>\n <p>I'm using the static member Depth to\n keep track of how deep the visitor has\n gone. Could it be problematic having\n state on my extension methods static\n class?</p>\n</blockquote>\n\n<p>Absolutely. The reason for this is simply that <code>static</code> methods should always be thread-safe, they are expected to be self-contained units-of-work, so to speak - currently your variable is not exclusively accessible to the current calling thread. This means that your method/s could have side-effects on execution, dependant on things once-removed from such. Stress testing might make issues become apparent, but without that it is simply a matter of usage and time before things get eerie.</p>\n\n<blockquote>\n <p>Would the SurveyPart abstract class\n make more sense as an interface?</p>\n</blockquote>\n\n<p>That depends, do you intend to add any base functionality to this type? Expose any helpful reusable elements that could be contained there and utilised in the same fashion by all inheritors? If so, then yes, otherwise, if the only reason for this type is to constrain other types to a certain model (or adhere to patterns), then no. </p>\n\n<blockquote>\n <p>Am I using Visitor and Composite in\n the right way, or am I borking them\n up?</p>\n</blockquote>\n\n<p>To be honest, I'm at work and don't really have time to analyse your patterns right now. Though, the composite pattern might dictate the use of interfaces to de-mark your known types, with levels of abstraction starting form this level.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T14:02:05.323", "Id": "3012", "Score": "0", "body": "Oh right, so... say I use the static member Depth. Say my survey was rendering to two different users at the same time in two different threads. Would they both alter the value of Depth, and have side effects on each other?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T04:52:01.890", "Id": "3026", "Score": "0", "body": "While I agree that depth should not be static, I think the use of Console would preclude using it on more than one thread anyway." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T13:52:20.800", "Id": "1731", "ParentId": "1729", "Score": "4" } }, { "body": "<p>That design will work well for multiple renderers - when you stated in the comment that you would it made much more sense. You should remove the static <code>Depth</code> variable though - it makes your code not thread-safe. Also, you can reduce the number of overloads. Here's a way to refactor your renderer:</p>\n\n<pre><code>public class SurveyTextRenderer\n{\n public Write(Survey survey)\n {\n Console.WriteLine(survey.Name);\n Console.WriteLine(new string('-', survey.Name.Length);\n\n for (SurveyPart part in survey.Children)\n {\n processNode(part, 0);\n }\n }\n\n protected void ProcessNode(SurveyPart part, int depth)\n {\n if (part is Section)\n WriteSection(part as Section, depth);\n else if (part is Question)\n WriteQuestion(part as Question, depth);\n else\n // Error handling or default case\n\n for (SurveyPart part in survey.Children)\n {\n ProcessNode(part, depth + 1);\n }\n }\n}\n</code></pre>\n\n<p>Note the error handling - what happens if you add a new SurveyPart and don't update the renderer? Also, I changed the name to use a Survey name, which you should see how to implement easily.</p>\n\n<p>I did not implement <code>WriteSection</code> and <code>WriteQuestion</code>; they'll be pretty close to what you have already except that the recursion is removed. I don't think you really need <code>static</code>s in this case, but you can make them static if you want. However, you could make, say, </p>\n\n<pre><code>public abstract class Renderer\n{\n public abstract void Write(Survey survey);\n}\n</code></pre>\n\n<p>and extend that. It may or may not be useful to you. It depends on your calling code whether it would be worth adding that abstraction. If you have a method that is called like <code>PrintSurvey(new TextRenderer(), datasource)</code> where <code>datasource</code> is one of multiple places the survey could be stored (XML, database, file, etc.) it might be useful. You don't want to repeat yourself. In fact, you could have Survey extend SurveyPart (maybe rename it SurveyElement?) and remove the sort-of-redundant Write()->ProcessNode() calls.</p>\n\n<p>Hopefully at least this gives you a few ideas!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T18:31:57.160", "Id": "3019", "Score": "0", "body": "Thanks for the comments Michael -- I guess I was thinking with the Visitor pattern, to keep any rendering code out of the various Survey classes. Let them represent the tree, but not do anything else. I realise I didn't mention it in the question, but say for example I might have a SurveyHtmlRenderer, a SurveyJsonRenderer, etc. I guess by keeping these responsibilities in the Visitors I'm trying to avoid giving each class WriteAsText, WriteAsHtml, WriteAsJson, etc. I'm not sure these could go simply in the abstract SurveyPart, as a Section would render different to a Question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T19:24:10.027", "Id": "3020", "Score": "0", "body": "You're right - my code really didn't allow for that. I've rewritten my answer since it was inflexible. Please let me know what you think!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T17:15:12.327", "Id": "1736", "ParentId": "1729", "Score": "5" } }, { "body": "<p>I think trying to implement a visitor pattern with static members is the wrong way to go, you should use an actual instance of the visitor and pass it around the data structure.</p>\n\n<p>Also, I generally don't like the idea of one class making decisions based on the type of another, just feels wrong to me.</p>\n\n<p>In all the descriptions of the visitor pattern I have seen, it was the responsibility of the objects in the hierarchy to pass the visitor object to their children, though I have always found it more convenient for the visitor to do its own propagation (different visitors may want different traversals - prefix, postfix, infix, etc).</p>\n\n<pre><code>public interface IVisitor\n{\n void Visit(Survey survey);\n void Visit(Section section);\n void Visit(Question question);\n}\n\npublic abstract class SurveyPart\n{\n // ...\n\n public abstract void Apply(IVisitor visitor);\n}\n\npublic class Survey\n{\n // ...\n\n public abstract void Apply(IVisitor visitor);\n}\n\npublic class Question : SurveyPart\n{\n // ...\n\n public override void Apply(IVisitor visitor)\n {\n visitor.Visit(this);\n }\n}\n\npublic class Section : SurveyPart\n{\n // ...\n\n public override void Apply(IVisitor visitor)\n {\n visitor.Visit(this);\n }\n}\n</code></pre>\n\n<p>The render visitor can then be implemented as follows.</p>\n\n<pre><code>public class RenderVisitor : IVisitor\n{\n public RenderVisitor(TextWriter writer)\n {\n this.writer = writer;\n }\n\n void Visit(Survey survey)\n {\n writer.Write(...);\n VisitChildren(servey.Children);\n }\n\n void Visit(Section section);\n {\n writer.Write(...);\n VisitChildren(servey.Children);\n }\n\n void Visit(Question question);\n {\n writer.Write(...);\n VisitChildren(servey.Children);\n }\n\n void VisitChildren(List&lt;SurveyPart&gt; children)\n {\n depth++;\n\n foreach(SurveyPart child in children)\n {\n child.Apply(this);\n }\n\n depth--;\n }\n\n int depth;\n readonly TextWriter writer;\n}\n</code></pre>\n\n<p>And used as:</p>\n\n<pre><code>servey.Apply(new RenderVisitor(Console.Out));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-25T15:16:15.120", "Id": "427104", "Score": "0", "body": "It might be more convenient to let the visitor handle the scope of classes to visit, but that means that your visitor decides both the behavior and scope. This is not a good seperation of control. You would have to make another visitor with the same behavior for classes where you want a different scope to work on. In your model, I would remove the Accept method altogether. It is a useless wrapper for calling the visitor." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T02:58:36.840", "Id": "1740", "ParentId": "1729", "Score": "5" } }, { "body": "<h2>Prelude</h2>\n\n<blockquote>\n <p>I'm using the static member Depth to keep track of how deep the\n visitor has gone. Could it be problematic having state on my extension\n methods static class?</p>\n</blockquote>\n\n<p>It would be uncommon. In fact, I wouldn't use extension methods to begin with. Tree walking should be performed by a dedicated tree walker.</p>\n\n<blockquote>\n <p>Would the SurveyPart abstract class make more sense as an interface?</p>\n</blockquote>\n\n<p>I would definately keep the abstract class, but perhaps it could implement an interface. I don't think it would hurt the design to have an interface as well.</p>\n\n<blockquote>\n <p>Am I using Visitor and Composite in the right way, or am I borking\n them up?</p>\n</blockquote>\n\n<ul>\n<li>You have implemented the <a href=\"https://www.infoworld.com/article/3173065/implementing-the-composite-design-pattern-in-c.html\" rel=\"nofollow noreferrer\">Composite</a> pattern correctly.</li>\n<li>This is a good example of the <a href=\"https://exceptionnotfound.net/visitor-the-daily-design-pattern/\" rel=\"nofollow noreferrer\">Visitor</a> pattern. I don't think you have implemented this pattern correctly. What you did do is implement in the spirit of the pattern: \"<em>Visitor lets you define a new operation without changing the classes of the elements on which it operates.</em>\"</li>\n</ul>\n\n<p><strong>Tree Walking</strong></p>\n\n<p>Your survey project is a perfect example of how to walk a tree of objects. There are two common patterns for walking a tree. They are both used heavely in compiler generators. A good source for understanding the difference is given <a href=\"https://saumitra.me/blog/antlr4-visitor-vs-listener-pattern/\" rel=\"nofollow noreferrer\">here</a> .</p>\n\n<ol>\n<li>Visitor Pattern</li>\n<li>Listener Pattern</li>\n</ol>\n\n<p>The main difference is that a visitor acts upon the caller whenever it gets accepted by that caller, while a listener gets notified about the steps in a tree walk over the caller. The listener requires a tree walker to get called. All will become clear in my proposed solution further in the review.</p>\n\n<blockquote>\n <p><strong>The text rendering of your survey fits better as a listener pattern.</strong></p>\n</blockquote>\n\n<p>pseudo-code:</p>\n\n<pre><code>- tree walker: walks survey\n- listener: writes 'hello survey'\n- tree walker: walks section\n- listener: pushes indent\n- listener: writes 'hello section'\n- ..\n- tree walker: exits section\n- listener: pops indent\n- tree walker: exits survey\n- listener: pops indent\n</code></pre>\n\n<hr>\n\n<h2>Model Design</h2>\n\n<p>I would keep the abstract class, accomodate it with an interface, and see no reason why <code>Children</code> have to be abstract. Since the class is abstract, it could do with a protected constructor.</p>\n\n<blockquote>\n<pre><code> public abstract class SurveyPart\n {\n public abstract List&lt;SurveyPart&gt; Children { get; set; }\n }\n</code></pre>\n</blockquote>\n\n<pre><code>public interface ISurveyPart\n{\n IList&lt;ISurveyPart&gt; Children { get; set; }\n}\n\npublic abstract class SurveyPart : ISurveyPart\n{\n public IList&lt;ISurveyPart&gt; Children { get; set; }\n\n protected SurveyPart() {\n Children = new List&lt;ISurveyPart&gt;();\n }\n}\n</code></pre>\n\n<p>The derived classes can then be simplified. You no longer have to create <code>Children</code> for each of them. I have also made a design decision to include <code>Survey</code> as derived type of <code>SurveyPart</code>. <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.xml.xmldocument?view=netframework-4.8\" rel=\"nofollow noreferrer\">Many tree API's</a> allow for the container to be part of the nodes.</p>\n\n<pre><code>public class Survey : SurveyPart\n{\n public Survey() { }\n}\n\npublic class Question : SurveyPart\n{\n public string QuestionText { get; set; }\n public Question() {}\n}\n\npublic class Section : SurveyPart\n{\n public string Header { get; set; }\n public Section() { }\n}\n</code></pre>\n\n<hr>\n\n<h2>Pattern Design</h2>\n\n<p>As suggested in the foreword, I would opt for a listener pattern. However, you could combine it neatly with the visitor pattern. So let's do that :-)</p>\n\n<p>First, we'll have to create some interfaces. </p>\n\n<pre><code>public interface ISurveyListener\n{\n void Enter();\n void Enter(ISurveyPart surveyPart);\n void Exit(ISurveyPart surveyPart);\n void Exit();\n}\n\npublic interface ISurveyVisitor\n{\n void Visit(ISurveyPart surveyPart);\n}\n</code></pre>\n\n<p>It is very important to see how the listener and visitor each have their own way of dealing with <code>ISurveyPart</code>. <code>ISurveyListener</code> gets called by <code>SurveyTreeWalker</code> and <code>ISurveyVisitor</code> gets called by <code>SurveyPart</code>.</p>\n\n<pre><code>public interface ISurveyPart\n{\n IList&lt;ISurveyPart&gt; Children { get; set; }\n void Accept(ISurveyVisitor visitor);\n}\n\npublic abstract class SurveyPart : ISurveyPart\n{\n public IList&lt;ISurveyPart&gt; Children { get; set; }\n\n protected SurveyPart() {\n Children = new List&lt;ISurveyPart&gt;();\n }\n\n public virtual void Accept(ISurveyVisitor visitor) {\n if (visitor == null) return;\n visitor.Visit(this);\n if (Children == null) return;\n foreach (var child in Children) {\n child.Accept(visitor);\n }\n }\n}\n\npublic class SurveyTreeWalker\n{\n public static void Walk(ISurveyPart surveyPart, ISurveyListener listener) {\n listener.Enter();\n WalkNode(surveyPart, listener);\n listener.Exit();\n }\n\n public static void WalkNode(ISurveyPart surveyPart, ISurveyListener listener) {\n if (surveyPart == null) return;\n listener.Enter(surveyPart);\n if (surveyPart.Children != null) {\n foreach (var child in surveyPart.Children) {\n WalkNode(child, listener);\n }\n }\n listener.Exit(surveyPart);\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>Text Rendering</h2>\n\n<p>Now that we have our model and patterns ready, we can implement <code>SurveyTextRenderer</code>. It is both a <code>ISurveyVisitor</code> and <code>ISurveyListener</code>. For rendering the entire tree, we will use it as listener.</p>\n\n<p>We first make a base class that adheres to our patterns. 3 abstract <code>Render</code> methods are available for derived classes to render the survey parts to text. There is functionality for writing with indentations: <code>PushIndent</code>, <code>PopIndent</code>, <code>Write</code>, <code>WriteLine</code>. The visitor pattern is implemented as to render the accepting survey part. The listener pattern is implemented as to visit the survey parts and deal with indentations.</p>\n\n<pre><code>public abstract class SurveyTextRendererBase : ISurveyVisitor, ISurveyListener\n{\n public const string DefaultIndentToken = \"\\t\";\n public TextWriter Writer { get; set; }\n public string IndentToken { get; set; }\n protected string IndentText { get { return string.Join(string.Empty, indent); } }\n\n private Stack&lt;string&gt; indent;\n private ISurveyPart rootPart;\n\n protected SurveyTextRendererBase(TextWriter writer) {\n Writer = writer;\n IndentToken = DefaultIndentToken;\n }\n\n protected abstract void Render(Survey survey);\n protected abstract void Render(Question question);\n protected abstract void Render(Section section);\n\n protected virtual void Render(ISurveyPart surveyPart) {\n if (surveyPart == null) return;\n if (surveyPart is Survey) Render(surveyPart as Survey);\n if (surveyPart is Question) Render(surveyPart as Question);\n if (surveyPart is Section) Render(surveyPart as Section);\n }\n\n public void Visit(ISurveyPart surveyPart) {\n Render(surveyPart);\n }\n\n public void Enter() {\n indent = new Stack&lt;string&gt;();\n }\n\n public void Enter(ISurveyPart surveyPart) {\n if (rootPart == null) {\n rootPart = surveyPart;\n } else {\n PushIndent();\n }\n Visit(surveyPart);\n }\n\n public void Exit(ISurveyPart surveyPart) {\n if (surveyPart != rootPart) {\n PopIndent();\n }\n }\n\n public void Exit() {\n indent = null;\n rootPart = null;\n }\n\n protected void Write(string text) {\n Writer.Write(string.Format(\"{0}{1}\", IndentText, text));\n }\n\n protected void WriteLine(string text) {\n Writer.WriteLine(string.Format(\"{0}{1}\", IndentText, text));\n }\n\n protected void PushIndent() {\n indent.Push(IndentToken);\n }\n\n protected bool PopIndent() {\n if (indent.Any()) {\n indent.Pop();\n return true;\n }\n return false;\n }\n}\n</code></pre>\n\n<p>The specific class <code>SurveyTextRenderer</code> performs the rendering as specifed in the OP's situation.</p>\n\n<pre><code>public class SurveyTextRenderer : SurveyTextRendererBase\n{\n public SurveyTextRenderer(TextWriter writer) \n : base (writer) {\n }\n\n protected override void Render(Survey survey) {\n WriteLine(\"Survey\");\n WriteLine(new string('-', \"Survey\".Length));\n }\n\n protected override void Render(Question question) {\n WriteLine(\"Q: \" + question.QuestionText);\n }\n\n protected override void Render(Section section) {\n WriteLine(\"S:\" + section.Header);\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>Usage Scenario</h2>\n\n<p>Let's put the example data in a method <code>CreateTestSurvey</code>. Now we can perform the following test and get the output the OP requested.</p>\n\n<pre><code>public static void Main()\n{\n var survey = CreateTestSurvey();\n var canvas = new StringBuilder();\n\n using (var writer = new StringWriter(canvas)) \n {\n SurveyTreeWalker.Walk(survey, new SurveyTextRenderer(writer));\n }\n\n Console.Write(canvas.ToString());\n Console.ReadKey();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-25T17:43:04.600", "Id": "427132", "Score": "1", "body": "This review is amazing with very interesting links! btw these `if (surveyPart is Survey) Render(surveyPart as Survey);` could be replaced by the new `switch` with pattern matching. You're gonna get a bonus ;-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-25T17:45:30.290", "Id": "427133", "Score": "0", "body": "@t3chb0t thanks man, it took me a while to make this one. I'm now working on your tree. Unfortunately, I am using v4.5. That's why my semantics are so 'classic'. :-p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-25T18:03:17.533", "Id": "427136", "Score": "0", "body": "My curiosity wants me to ask you whether there is a reason for _avoiding_ (?) the latest language enhancements?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-25T18:07:40.623", "Id": "427138", "Score": "0", "body": "@t3chb0t I see no reason why not to update. I've only been active since a week on this community. I normally don't program that much in my free time. It's just a time in my life I feel like doing this :-) I shall update! :p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-25T18:18:31.437", "Id": "427142", "Score": "1", "body": "I like this time in your life ;-] I've been missing someone with your knowledge here for quite a some time. Your reviews are super educational and they greatly enrich the `C#` _room_. I'm studying them thoroughly. The language version doesn't matter, I was just curious... it's the _real_ stuff that matters. I hope you're having good time here and we can keep you here for longer ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-25T18:23:15.073", "Id": "427143", "Score": "1", "body": "@t3chb0t Thanks again. I'm also intrigued with both your questions and answers. Let's keep learning, educating and have some fun :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-26T17:46:59.873", "Id": "427323", "Score": "1", "body": "@t3chb0t Cheers man, I appreciate your support!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-25T17:11:30.073", "Id": "221006", "ParentId": "1729", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T13:23:53.487", "Id": "1729", "Score": "11", "Tags": [ "c#", "design-patterns", "tree" ], "Title": "Composite and Visitor patterns for tree-based survey functionality in C#" }
1729
<blockquote> <p>Define a procedure square-tree analogous to the square-list procedure of exercise 2.21. That is, square-list should behave as follows:</p> <pre><code>(square-tree (list 1 (list 2 (list 3 4) 5) (list 6 7))) (1 (4 (9 16) 25) (36 49)) </code></pre> <p>Define square-tree both directly (i.e., without using any higher-order procedures) and also by using map and recursion.</p> </blockquote> <p>I wrote this solution. What do you think?</p> <pre><code>(define (square x) (* x x)) (define (square-tree tree) (cond ((null? tree) null) ((pair? tree) (cons (square-tree (car tree)) (square-tree (cdr tree)))) (else (square tree)))) (define (map-square-tree tree) (map (lambda (subtree) (if (pair? subtree) (cons (square-tree (car subtree)) (square-tree (cdr subtree))) (square subtree))) tree)) (define a (list 1 1 (list (list 2 3) 1 2))) </code></pre> <p><strong>EDIT:</strong> This is a much better solution for map-square-tree.</p> <pre><code>(define (square x) (* x x)) (define (square-tree tree) (cond ((null? tree) null) ((pair? tree) (cons (square-tree (car tree)) (square-tree (cdr tree)))) (else (square tree)))) (define (map-square-tree tree) (map (lambda (subtree) ((if (pair? subtree) map-square-tree square) subtree)) tree)) (define a (list 1 1 (list (list 2 3) 1 2))) </code></pre>
[]
[ { "body": "<p>Your direct definition of <code>square-tree</code> is correct.</p>\n\n<p>Your definition using <code>map</code> calls <code>square-tree</code>; to make it properly recursive, call <code>map-square-tree</code> instead. Further, you may recurse on the <code>subtree</code> itself. This will make your code succinct.</p>\n\n<pre><code>(define (map-square-tree tree)\n (map (lambda (subtree)\n ((if (pair? subtree) map-square-tree square) subtree))\n tree))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T20:16:03.023", "Id": "1749", "ParentId": "1732", "Score": "1" } } ]
{ "AcceptedAnswerId": "1749", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T14:14:50.070", "Id": "1732", "Score": "1", "Tags": [ "recursion", "lisp", "scheme", "sicp" ], "Title": "Square-tree using maps and recursion" }
1732
<blockquote> <p>Exercise 2.31. Abstract your answer to exercise 2.30 to produce a procedure tree-map with the property that square-tree could be defined as</p> <pre><code>(define (square-tree tree) (tree-map square tree)) </code></pre> </blockquote> <p>I wrote the following solution:</p> <pre><code>(define (square x) (* x x)) (define (tree-map f tree) (cond ((null? tree) null) ((pair? tree) (cons (tree-map f (car tree)) (tree-map f (cdr tree)))) (else (f tree)))) (define (map-tree-map f tree) (map (lambda (subtree) (if (pair? subtree) (cons (map-tree-map f (car subtree)) (map-tree-map f (cdr subtree))) (f subtree))) tree)) (define (square-tree tree) (tree-map square tree)) (define (map-square-tree tree) (map-tree-map square tree)) (define a (list 1 1 (list (list 2 3) 1 2))) </code></pre> <p>Can this be improved in any way?</p>
[]
[ { "body": "<p>Your direct definition of <code>tree-map</code> looks good.</p>\n\n<p>The version using <code>map</code> may be written more succinctly (with the recursive portion factored out) as follows:</p>\n\n<pre><code>(define (tree-map f tree)\n (define (rec tree)\n (map (lambda (subtree)\n ((if (pair? subtree) rec f) subtree))\n tree))\n (rec tree))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T03:37:34.017", "Id": "1837", "ParentId": "1733", "Score": "2" } } ]
{ "AcceptedAnswerId": "1837", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T14:23:47.483", "Id": "1733", "Score": "4", "Tags": [ "lisp", "tree", "scheme", "sicp" ], "Title": "Abstract tree-map function" }
1733
<p><strong>EDIT: My code DOES not work, see <a href="https://gis.stackexchange.com/questions/294380/if-rectangle-corner-points-have-same-nearest-neighbor-does-whole-interior">https://gis.stackexchange.com/questions/294380/if-rectangle-corner-points-have-same-nearest-neighbor-does-whole-interior</a></strong></p> <p>Given 5 (currently hardcoded) cities, this code uses Google Maps to split the world into 5 regions, each region being the points closer to a given city than to the other 4.</p> <p><a href="http://test.barrycarter.info/gmap8.php" rel="nofollow noreferrer">It works</a>, but is slow in two senses:</p> <ul> <li><p>The program takes a long time to run, especially when <code>$minarea</code> is small.</p></li> <li><p>The program generates <em>many</em> polygons, slowing down the Google Map above. With smaller '$minarea', I've even run out of JavaScript stack space.</p></li> </ul> <p>Thought: Would something w/ qhull be faster?</p> <p>The <code>bvoronoi</code> subroutine does most of the work:</p> <pre><code>#!/bin/perl # Unusual approach to Voronoi diagram of Earth sphere: cut into 4 # pieces and compare closest point for 4 vertices # TODO: this program is long and clumsy and can doubtless be improved use POSIX; # defining constants here is probably bad $PI = 4.*atan(1); $EARTH_RADIUS = 6371/1.609344; # miles open(A,"&gt;/home/barrycarter/BCINFO/sites/TEST/gvorbin.txt"); # latitude and longitude of points %points = ( "Albuquerque" =&gt; "35.08 -106.66", "Paris" =&gt; "48.87 2.33", "Barrow" =&gt; "71.26826 -156.80627", "Wellington" =&gt; "-41.2833 174.783333", "Rio" =&gt; "-22.88 -43.28" ); # primartish colors %colors = ( "Albuquerque" =&gt; "#ff0000", "Paris" =&gt; "#00ff00", "Barrow" =&gt; "#0000ff", "Wellington" =&gt; "#ffff00", "Rio" =&gt; "#ff00ff", "BORDER" =&gt; "#000000" ); # stop at what gridsize $minarea = .5; # the four psuedo-corners of the globe $nw = bvoronoi(0,90,-180,0); $ne = bvoronoi(0,90,0,180); $sw = bvoronoi(-90,0,-180,0); $se = bvoronoi(-90,0,0,180); for $i (split("\n","$nw\n$ne\n$sw\n$se")) { # create google filled box my($latmin, $latmax, $lonmin, $lonmax, $closest) = split(/\s+/, $i); # build up the coords print A &lt;&lt; "MARK"; var myCoords = [ new google.maps.LatLng($latmin, $lonmin), new google.maps.LatLng($latmin, $lonmax), new google.maps.LatLng($latmax, $lonmax), new google.maps.LatLng($latmax, $lonmin), new google.maps.LatLng($latmin, $lonmin) ]; myPoly = new google.maps.Polygon({ paths: myCoords, strokeColor: "$colors{$closest}", strokeOpacity: 1, strokeWeight: 0, fillColor: "$colors{$closest}", fillOpacity: 0.5 }); myPoly.setMap(map); MARK ; } # workhorse function: given a "square" (on an equiangular map), # determine the closest point of 4 vertices; if same, return square # and point; otherwise, break square into 4 squares and recurse sub bvoronoi { # Using %points as global is ugly my($latmin, $latmax, $lonmin, $lonmax) = @_; my($mindist, $dist, %closest); # compute distance to each %points for each corner # TODO: this is wildly inefficient, since I just need relative # distance, not exact! for $lat ($latmin,$latmax) { for $lon ($lonmin,$lonmax) { # TODO: has to be easier way to do this? $mindist = 0; $dist= 0; for $point (keys %points) { my($plat,$plon) = split(/\s+/, $points{$point}); $dist = gcdist($lat, $lon, $plat, $plon); if ($dist &lt; $mindist || !$mindist) { $mindist = $dist; $minpoint = $point; } } # this point is closest to one vertex of the square # TODO: should abort loop if we already have two different closest points $closest{$minpoint} = 1; } } # if there's just one point closest to all four corners, return it my(@keys) = keys %closest; # if @keys has length 1, return it unless ($#keys) { return "$latmin $latmax $lonmin $lonmax $keys[0]"; } # if we've hit a border point, return it (area too small) my($area) = ($latmax-$latmin)*($lonmax-$lonmin); if ($area &lt;= $minarea) { return "$latmin $latmax $lonmin $lonmax BORDER"; } # split square and recurse my($latmid) = ($latmax+$latmin)/2.; my($lonmid) = ($lonmax+$lonmin)/2.; my(@sub) = (); push(@sub, bvoronoi($latmin, $latmid, $lonmin, $lonmid)); push(@sub, bvoronoi($latmid, $latmax, $lonmin, $lonmid)); push(@sub, bvoronoi($latmin, $latmid, $lonmid, $lonmax)); push(@sub, bvoronoi($latmid, $latmax, $lonmid, $lonmax)); return join("\n", @sub); } =item gcdist($x,$y,$u,$v) Great circle distance between latitude/longitude x,y and latitude/longitude u,v in miles Source: http://williams.best.vwh.net/avform.htm =cut sub gcdist { my(@x)=@_; my($x,$y,$u,$v)=map {$_*=$PI/180} @x; my($c1) = cos($x)*cos($y)*cos($u)*cos($v); my($c2) = cos($x)*sin($y)*cos($u)*sin($v); my($c3) = sin($x)*sin($u); return ($EARTH_RADIUS*acos($c1+$c2+$c3)); } </code></pre> <p><a href="https://github.com/barrycarter/bcapps/blob/master/bc-closest-gmap.pl" rel="nofollow noreferrer">Another failed approach</a></p> <p>EDIT: Thanks to whoever upvoted this. I've now fixed the <a href="http://test.barrycarter.info/gmap8.php" rel="nofollow noreferrer">http://test.barrycarter.info/gmap8.php</a> link and am including a screenshot below:</p> <p><a href="https://i.stack.imgur.com/8XyEe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8XyEe.png" alt="enter image description here"></a></p>
[]
[ { "body": "<p>In short, try <a href=\"http://ngwww.ucar.edu/ngmath/cssgrid/csshome.html\" rel=\"nofollow noreferrer\">cssgrid</a> from <a href=\"http://ngwww.ucar.edu/\" rel=\"nofollow noreferrer\">NCAR Graphics</a>.</p>\n\n<p>At length:</p>\n\n<p>There's <a href=\"https://stackoverflow.com/questions/545870/algorithm-to-compute-a-voronoi-diagram-on-a-sphere\">a similar question on StackOverflow</a>, but it has no accepted answer.</p>\n\n<p>So here's an answer, if you'll permit two apologies. 1. I'll leave the Google Maps work to you. 2. I didn't read your code thoroughly.</p>\n\n<p>The algorithm's running time should be no higher in order than sorting, O(n log n). At least, \"<a href=\"http://dx.doi.org/10.1016/S0925-7721(02)00077-9\" rel=\"nofollow noreferrer\">Voronoi diagrams on the sphere</a>\", openly available as a <a href=\"http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.6737\" rel=\"nofollow noreferrer\">Utrecht University report</a>, claims that that result is in <a href=\"http://wwwlib.umi.com/dissertations/fullcit/8012772\" rel=\"nofollow noreferrer\">Kevin Quintin Brown's dissertation</a>. Furthermore \"<a href=\"http://dx.doi.org/10.1016/0021-9991(85)90140-8\" rel=\"nofollow noreferrer\">On the construction of the Voronoi mesh on a sphere</a>\" claims in its abstract to construct the mesh in O(n).</p>\n\n<p>It looks like qhull doesn't do all that you need, but I found something else. <a href=\"http://ngwww.ucar.edu/whatsnew.html#WhatsNew4_2_0\" rel=\"nofollow noreferrer\">The cssgrid package is found in the GPL-licensed NCAR Graphics software</a> and does what you need, with C, Fortran, and NCAR-specific bindings. You can download all of <a href=\"http://ngwww.ucar.edu/\" rel=\"nofollow noreferrer\">NCAR Graphics</a> from its page at the (United States) National Center for Atmospheric Research. If you wish, you can use SWIG to make the relevant C binding available to Perl.</p>\n\n<p>The <a href=\"http://ngwww.ucar.edu/ngmath/cssgrid/csshome.html\" rel=\"nofollow noreferrer\">cssgrid</a> package has its own documentation page online. The functions *csvoro* (Voronoi) and *css2c* (spherical to cartesian, that is, latitude-longitude to X-Y-Z coordinates) are the most relevant ones.</p>\n\n<p>The cssgrid package is based on STRIPACK by permission of STRIPACK's author. STRIPACK comes up higher in web searches and is cost-free for noncommercial use. However, STRIPACK itself as an ACM TOMS algorithm is <a href=\"http://www.gnu.org/software/gsl/design/gsl-design.html\" rel=\"nofollow noreferrer\">neither public domain nor GPL-compatible</a>. Also it is Fortran 90 code without a provided C binding, although that difficulty might be surmountable using FortWrap.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T04:15:01.793", "Id": "10142", "ParentId": "1739", "Score": "4" } } ]
{ "AcceptedAnswerId": "10142", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-04-09T02:41:05.910", "Id": "1739", "Score": "7", "Tags": [ "performance", "perl", "geospatial", "google-maps" ], "Title": "Spherical Voronoi diagram, binary splitting approach" }
1739
<p>I need to figure out the best way to deal with memory pre-allocation</p> <p>Below is pseudo-code for what I am doing now, and it seems to be working fine.</p> <p>I am sure there is a better way to do this, I would like to see if anyone has any good idea.</p> <p>In Thread A I need to allocate 300 MB of memory and zero it out:</p> <p>Thread A:</p> <pre><code>char* myMemory = new char[10*30*1024*1024]; </code></pre> <p>In Thread B I incrementally get 10 sets of data 30 MB each. As I get this data it must be written to memory</p> <p>Thread B:</p> <pre><code>int index1 = 0; char* newData = getData(...); // get a pointer to 30 MB of data memcpy(&amp;myMemory[index1*30*1024*1024], &amp;newData[0], 30*1024*1024]; SetEvent(...) // tell Thread C that I have written new data // use index i as circular Buffer if (index1 &lt; 10) index1++; else index1 = 0; </code></pre> <p>In Thread C, when new data is written, I need to get it and process it</p> <p>Thread C:</p> <pre><code>int index2 = 0; char* dataToProcess[] = new char[30*1024*1024]; if (event Fires) // if event in Thread B is set memcpy(&amp;dataToProcess[0], &amp;myMemory[index2*30*1024*1024], 30*1024*1024]; processData(dataToProcess) // use index i as circular Buffer if (index2 &lt; 10) index2++; else index2 = 0; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T01:06:41.130", "Id": "3027", "Score": "1", "body": "Wait, if it seems to be working fine, then what exactly are you looking for? I'm confused..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T01:09:13.743", "Id": "3028", "Score": "0", "body": "I think it is bad design and it will be hard for others to edit. I can't think of any other way to do it though. My main concern is the indexing independent in the two threads." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T01:18:45.217", "Id": "3029", "Score": "0", "body": "perhaps, I was not aware of this website." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T01:22:09.603", "Id": "3030", "Score": "0", "body": "@rossb83: Yeah no worries, it's relatively new. If you need advice on writing a particular piece of code (like here), that's where you should probably post it. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T01:24:28.613", "Id": "3031", "Score": "0", "body": "I don't see the point to Thread A. You could just as easily allocate the 300MB in B, fill in the data, zeroing out any padding, and pass it on to C. You can't do anything in B & C until A is done anyway." } ]
[ { "body": "<p>Another approach I can think of could be this. Get rid of <code>myMemory</code> altogether. Once you receive data in thread B, allocate memory and copy that data (as you're doing now). Send thread C a message that data is received. Once thread C copies the data into its internal buffer, thread C can send message back to thread B that the data has been copied. Thread B then deallocate the buffer.</p>\n\n<p>Your design seems fine to me. Yet another approach could be avoiding the data copy in thread C.</p>\n\n<pre><code>int index2 = 0;\nchar* dataToProcess;\nif (event Fires) // if event in Thread B is set\n dataToProcess = &amp;myMemory[index2*30*1024*1024];\n processData(dataToProcess)\n// Rest of the code\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T05:56:22.037", "Id": "3032", "Score": "0", "body": "Suggestion: if Thread B has receieved a vacated memory buffer from Thread C, and if Thread B still has work to do (loop count hasn't reached the limit), Thread B can reuse the memory buffer for new data. This is the idea in multithreaded resource pooling." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T01:27:10.843", "Id": "1742", "ParentId": "1741", "Score": "2" } }, { "body": "<p>I'm not sure how your threads work, but it looks like you need some more synchronization.</p>\n\n<p>If B and C are a pair, I don't see indexing getting out of control, but have you thought about out-of-order execution and reordering of memory writes? B's CPU might execute code firing the event before completing the write to <code>myMemory</code>, resulting in C reading partial data. Granted, it may be highly unlikely or downright impossible in your case, but it's something to think about. You may need a <a href=\"http://en.wikipedia.org/wiki/Memory_barrier\" rel=\"nofollow\">memory barrier</a> or a higher-level synchronization concept.</p>\n\n<p>In fact, why aren't you using a <a href=\"http://en.wikipedia.org/wiki/Message_queue\" rel=\"nofollow\">message queue</a>? Or something simpler, like a circular buffer? (Incidentally, boost::circular_buffer's thread-safe <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/circular_buffer/doc/circular_buffer.html#boundedbuffer\" rel=\"nofollow\">bounded buffer example</a> looks very similar to your question.)</p>\n\n<p>Or if you could attach the 30 MB data to the events, it would be a very simple solution.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T01:52:30.577", "Id": "3033", "Score": "0", "body": "The problem with boost circular buffers is that the memory has to be preallocated in Thread A. I wanted to use boost circular buffers. Is there a way to preallocate the memory as well as use a circular buffer?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T03:13:51.007", "Id": "3034", "Score": "0", "body": "Can't thread A simply create the object?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T01:38:19.023", "Id": "1743", "ParentId": "1741", "Score": "1" } }, { "body": "<p>you could use an approach like this (pseudocode);</p>\n\n<pre><code>template &lt; typename T, size_t BlockSize_ &gt;\nclass t_lockable_array {\npublic:\n static const size_t BlockSize = BlockSize_;\n typedef T t_object;\n\n/* ...stuff... */\n\n void copyElements(std::vector&amp; dest, const t_range&amp; range) {\n t_lock_scope lock(this-&gt;mutex());\n /* copy @a range to @a dest here... */\n }\n\n/* ...stuff... */\n\nprivate:\n t_mutex d_mutex; /* assumption in this example: lock/unlock is a mutation */\n t_object d_object[BlockSize];\n};\n\ntemplate &lt; typename T, size_t BlockSize_, size_t BlockCount_ &gt;\nclass t_partitioned_array {\n\npublic:\n static const size_t BlockSize = BlockSize_;\n static const size_t BlockCount = BlockCount_;\n static const size_t ObjectCount = BlockCount * BlockSize;\n typedef T t_object;\n\n/* ...stuff... */\n\n t_lockable_array&lt;t_object, BlockSize&gt;&amp; at(const size_t&amp; idx) {\n /*\n direct access: each partition handles its locking/interface.\n alternatively, you could rewrap the lockable array's\n interface if you prefer encapsulation here.\n */\n return this-&gt;d_array[idx];\n }\n\n/* ...stuff... */\n\nprivate:\n t_lockable_array&lt;t_object, BlockSize&gt; d_array[BlockCount];\n};\n</code></pre>\n\n<p>then just create a <code>t_partitioned_array&lt;char,10,ThirtyMB&gt;</code> on thread A</p>\n\n<p>on thread B:</p>\n\n<pre><code>t_partitioned_array&lt;char,10,ThirtyMB&gt;&amp; array(this-&gt;getSharedArray());\nstd::vector&lt;char&gt;&amp; localBuffer(this-&gt;getLocalBuffer());\n\n// the accessed partition will lock itself during read/write\narray.at(this-&gt;partitionToRead()).copyElements(localBuffer, this-&gt;rangeOfMemoryToRead());\n\nthis-&gt;processData(localBuffer);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T21:09:12.123", "Id": "3072", "Score": "0", "body": "This is not what I would call pseudocode" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T06:19:58.463", "Id": "1744", "ParentId": "1741", "Score": "1" } } ]
{ "AcceptedAnswerId": "1742", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T01:00:13.053", "Id": "1741", "Score": "2", "Tags": [ "c++", "multithreading" ], "Title": "Multi-Threaded Memory Preallocation" }
1741
<blockquote> <p>Given a Binary Search Tree, determine its k-th element in inorder traversal.</p> </blockquote> <p>Here's my node structure:</p> <pre><code>struct node { int elem; node *left, *right; static node* create(int elem) { node *newnode = new node; newnode-&gt;elem = elem; newnode-&gt;left = newnode-&gt;right = NULL; return newnode; } // Forget freeing up memory }; </code></pre> <p>Here's my BST:</p> <pre><code>class tree { private: node *root; public: tree(int elem) { root = node::create(elem); } bool insert(int elem) { node *newnode = node::create(elem); node *travnode = root; while(1) { if(elem &amp;lt travnode-&gt;elem) { if(travnode-&gt; left == NULL) { travnode-&gt;left = node::create(elem); return true; } else travnode = travnode-&gt;left; } // elem &lt; travnode-&gt;elem else if(elem &gt; travnode-&gt;elem) { if(travnode-&gt;right == NULL) { travnode-&gt;right = node::create(elem); return true; } else travnode = travnode-&gt;right; } else return false; } /* findKthInorder @param mynode [in] -- the root of tree whose kth largest is to be found @param k [in] -- value k @param count [in] -- a counter to keep track of which node we're in @param result [in,out] -- returns mynode-&gt;elem once we're in kth node */ void findKthInorder(const node *mynode, const int k, int &amp;count, int &amp;result) const { if(mynode != NULL) { findKthInorder(mynode-&gt;left,k,count,result); if(!--count) { result = mynode-&gt;elem; return; } // if (!--count) findKthInorder(mynode-&gt;right,k,count,result); } // if (mynode != NULL) } // findKthInorder /* findKthInorder abstracts away previous function and is exposed to outside world */ int findKthInorder(const int k) const { int count = k,result = 0; findKthInorder(root,k,count,result); return result; } }; // class tree </code></pre> <p>Here's some test code that I wrote:</p> <pre><code>int main() { tree T = tree(5); T.insert(1); T.insert(7); T.insert(-1);T.insert(6); for(int i = 1;i != 5; ++i) printf("%d, " T.findKthInorder(i)); // -1, 1,5,6,7 return 0; } </code></pre> <p>I'll be happy to listen to any suggestions for a more elegant <code>findKthInorder()</code> function.</p>
[]
[ { "body": "<p>If you add a total count field to each node, you can find the k-th element efficiently (in logarithmic time) by writing a method like this (untested):</p>\n\n<pre><code>node *kth(int k)\n{\n assert(k &gt;= 0 &amp;&amp; k &lt; total);\n\n if (left != NULL) {\n if (k &lt; left-&gt;total)\n return left-&gt;kth(k);\n k -= left-&gt;total;\n }\n\n if (k == 0)\n return this;\n\n assert(right != NULL);\n return right-&gt;kth(k - 1);\n}\n</code></pre>\n\n<p>Otherwise, the recursive algorithm you used for <code>findKthInorder</code> is the most elegant way I can think of to do this. I would clean it up a bit, though:</p>\n\n<pre><code>static const Node *kth_(const Node *node, int &amp;k)\n{\n if (node == NULL)\n return NULL;\n\n const Node *tmp = kth_(node-&gt;left, k);\n if (tmp != NULL)\n return tmp;\n\n if (k-- == 0)\n return node;\n\n return kth_(node-&gt;right, k);\n}\n\nint kth(int k) const\n{\n assert(k &gt;= 0);\n\n const Node *node = kth_(this, k);\n if (node == NULL) {\n std::cerr &lt;&lt; \"kth: k is too large\\n\";\n exit(1);\n }\n\n return node-&gt;elem;\n}\n</code></pre>\n\n<p>Returning a node pointer instead of an element from the helper function has two advantages:</p>\n\n<ul>\n<li>We can use <code>NULL</code> to indicate failure.</li>\n<li>We get to drop an argument from the helper function.</li>\n<li>In the future, it will be easier to write a function to update the kth element.</li>\n</ul>\n\n<p>In your <code>findKthInOrder</code> helper function, the <code>k</code> argument is never actually used, and can be dropped as well.</p>\n\n<p>A couple cleanups on the side:</p>\n\n<ul>\n<li>I renamed the class <code>node</code> to <code>Node</code> to avoid having to say <code>mynode</code> all over the place. I suppose this is just a matter of taste, seeing how the STL uses lowercase type names.</li>\n<li>I switched to zero-based indexing. Again, this is a matter of taste, but zero-based indexing is far more common in C++, and is easier to work with in many cases.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T04:37:24.620", "Id": "1777", "ParentId": "1750", "Score": "5" } } ]
{ "AcceptedAnswerId": "1777", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T20:26:52.123", "Id": "1750", "Score": "4", "Tags": [ "c++", "tree" ], "Title": "Finding the k-th element in a BST" }
1750
<p>I have written the following tiny extension method to help me when I'm working with sequences in which I have to find a pattern.</p> <pre><code>public static IEnumerable&lt;T[]&gt; SearchPattern&lt;T&gt;(this IEnumerable&lt;T&gt; seq, params Func&lt;T[], T, bool&gt;[] matches) { Contract.Requires(seq != null); Contract.Requires(matches != null); Contract.Requires(matches.Length &gt; 0); var matchedItems = new List&lt;T&gt;(matches.Length); int itemIndex = 0; foreach (T item in seq) { if (matches[matchedItems.Count](matchedItems.ToArray(), item)) { matchedItems.Add(item); if (matchedItems.Count == matches.Length) { yield return matchedItems.ToArray(); matchedItems.Clear(); } } else { if (matchedItems.Any()) { foreach (T[] results in seq.Skip(itemIndex - matchedItems.Count + 1).SearchPattern(matches)) // is this a tail call? can it be optimized? { yield return results; } break; } } itemIndex++; } } </code></pre> <p>It appears to be working fine, but I'm wondering if there's a better way to do it. Primarily I'm concerned with the recursive call (at the nested foreach), which makes the method very inefficient, not to mention potential stack-overflows when working with very large collections.</p> <p>I know about tail-calls, and that they can be optimized into a loop (like in F#). I also recall having seen something about tail-calls on an IL level. What confuses me is that I'm already using the iterator pattern (yield return) - so is it a tail call at all? If it is, is it one I can eliminate?</p> <p>Any input would be much appreciated!</p> <p><strong>Edit</strong>: usage sample:</p> <pre><code>var results = (new int[] { 0, 1, 2, 3, 3, 4, 4, 5, 7, 9 }).SearchPattern( (prevs, curr) =&gt; true, (prevs, curr) =&gt; prevs[0] == curr, (prevs, curr) =&gt; curr % 2 != 0 ); // =&gt; { [ 4, 4, 5 ] } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T22:47:55.747", "Id": "3048", "Score": "0", "body": "I haven't looked at the details of your code, but just keep in mind that LINQ itself -- as well as the `yield` statements -- are *very* inefficient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T22:51:00.843", "Id": "3049", "Score": "0", "body": "@Mehrdad: I understand that, and a certain level of inefficiency is an acceptable trade for ease-of-use. What I'm trying to determine is whether it's possible to optimize the above recursive code, mainly by eliminating the recursive call." } ]
[ { "body": "<p>The way a tail call works at the IL level, is that the current stack frame is discarded before calling the method*. So whatever the called method returns is effectively by the calling method. I read somewhere that Microsoft's x64 JIT will optimise this into a loop while their x86 JIT will leave it as a standard function call.</p>\n\n<p>In your particular instance, the tail call cannot be used since the calling method uses the result of the inner call to generate its own result rater than simply returning it.</p>\n\n<p>You can drop the recursion by copying the enumerable into a list and indexing into it. You will need to iterate over all the elements anyway, and by doing it this way you do not need to restart the enumeration every time you recurse.</p>\n\n<pre><code>public static IEnumerable&lt;T[]&gt; SearchPattern&lt;T&gt;(this IEnumerable&lt;T&gt; seq, params Func&lt;T[], T, bool&gt;[] matches)\n{\n Contract.Requires(seq != null);\n Contract.Requires(matches != null);\n Contract.Requires(matches.Length &gt; 0);\n\n var matchedItems = new List&lt;T&gt;(matches.Length);\n var seqList = new List&lt;T&gt;(seq);\n int start = 0;\n\n while (start + matches.Length &lt; seqList.Count)\n {\n bool fail = false;\n\n for (int i = 0; i &lt; matches.Length; i++)\n {\n T[] itemsArray = matchedItems.ToArray();\n\n if (!matches[i](itemsArray, seqList[i + start]))\n {\n fail = true;\n break;\n }\n\n matchedItems.Add(seqList[i + start]);\n }\n\n if (!fail)\n {\n yield return matchedItems.ToArray();\n start = start + matches.Length;\n }\n else\n {\n start++;\n }\n\n matchedItems.Clear()\n }\n}\n</code></pre>\n\n<hr>\n\n<p>[*] The stack will not always be discarded, particularly if it's required for security checks (see <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.tailcall.aspx\" rel=\"nofollow\">OpCodes.TailCall</a>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T00:50:12.777", "Id": "3052", "Score": "0", "body": "I suspect that instead of `start = start + matches.Length;` you actually want `start++;` as otherwise you will be skipping items that could potentially match. As far as I can tell the original implementation in the question *does* look at all sequences starting at every item." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T00:52:34.023", "Id": "3053", "Score": "1", "body": "Furthermore, I believe you will need to move the `matchedItems.Clear();` and the `start++;` to after the `if`. You want to clear it and move to the next item whether the match failed or not; otherwise the next iteration will have junk in it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T01:17:09.087", "Id": "3054", "Score": "0", "body": "@Timwi: On your first point, I thought about that, but the original increments by matches.Length upon recursing without continuing upon return. So I figured the OP did not want overlapping matches. Good point on the second one though, I'll fix." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T16:11:25.823", "Id": "3063", "Score": "0", "body": "Very nice answer, thank you! I have not tried your implementation yet, but I understand what you're doing - and that's the real point. To be entirely honest, I haven't given overlapping matches a thought, but this is something easy to change, and e.g. bind to a bool allowOverlapping parameter." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T00:00:47.190", "Id": "1755", "ParentId": "1753", "Score": "3" } }, { "body": "<p>Personally, here is how I would do it. I think this is pretty straight-forward. I think it is also no less efficient than the other (longer, more complex) answer. The method <code>Subarray</code> is something I wrote before, I didn’t write it just for this.</p>\n\n<pre><code>/// &lt;summary&gt;Similar to &lt;see cref=\"string.Substring(int,int)\"/&gt;, only for arrays. Returns a new\n/// array containing &lt;paramref name=\"length\"/&gt; items from the specified\n/// &lt;paramref name=\"startIndex\"/&gt; onwards.&lt;/summary&gt;\npublic static T[] Subarray&lt;T&gt;(this T[] array, int startIndex, int length)\n{\n if (array == null)\n throw new ArgumentNullException(\"array\");\n if (startIndex &lt; 0)\n throw new ArgumentOutOfRangeException(\"startIndex\", \"startIndex cannot be negative.\");\n if (length &lt; 0 || startIndex + length &gt; array.Length)\n throw new ArgumentOutOfRangeException(\"length\", \"length cannot be negative or extend beyond the end of the array.\");\n T[] result = new T[length];\n Array.Copy(array, startIndex, result, 0, length);\n return result;\n}\n\npublic static IEnumerable&lt;T[]&gt; SearchPattern&lt;T&gt;(this IEnumerable&lt;T&gt; seq, params Func&lt;T[], T, bool&gt;[] matches)\n{\n Contract.Requires(seq != null);\n Contract.Requires(matches != null);\n Contract.Requires(matches.Length &gt; 0);\n\n // No need to create a new array if seq is already one\n var seqArray = seq as T[] ?? seq.ToArray();\n\n // Check every applicable position for the matching pattern\n for (int j = 0; j &lt;= seqArray.Length - matches.Length; j++)\n {\n // If this position matches...\n if (Enumerable.Range(0, matches.Length).All(i =&gt;\n matches[i](seqArray.Subarray(j, i), seqArray[i + j])))\n {\n // ... yield it\n yield return seqArray.Subarray(j, matches.Length);\n\n // and jump to the item after the match so we don’t get overlapping matches\n j += matches.Length - 1;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T16:20:49.057", "Id": "3064", "Score": "0", "body": "A most elegant solution, thank you very much! I'm going to wait a few more hours to see if anybody can offer an even better answer (which I doubt), but so far I like your solution the most." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T01:21:28.020", "Id": "1756", "ParentId": "1753", "Score": "4" } }, { "body": "<p>You might consider the <a href=\"http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm\" rel=\"nofollow\">Knuth-Morris-Pratt</a> algorithm. It was designed for finding a sequence of characters within a string but might be adapted to your needs.</p>\n\n<p>The main thing is in KMP you build a table of offsets of duplicated starting sequences for the pattern you want to find. This lets you efficiently fall back to an earlier position in the pattern and continue your comparisons against the main sequence - no recursion needed.</p>\n\n<p>Edit:</p>\n\n<p>KMP requires the specific pattern in order to build its fall back table. Your sample usage implies a pattern that is more like characteristics (e.g. any number of repeated items that are not odd) which would require customization of the KMP algorithm to work with characteristics, probably by way of a Func as you are doing now.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T13:50:53.260", "Id": "3096", "Score": "0", "body": "That looks fairly interesting, although I believe what the others have suggested are better in my case. Thanks anyway, +1." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T16:36:09.500", "Id": "1761", "ParentId": "1753", "Score": "2" } } ]
{ "AcceptedAnswerId": "1756", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T22:17:20.433", "Id": "1753", "Score": "11", "Tags": [ "c#", ".net" ], "Title": "Searching a sequence for a pattern" }
1753
<p>Lately I seem to run into a situation very frequently where I want to write something like the following:</p> <pre><code>var x = condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : condition4 ? value4 : throw new InvalidOperationException(); </code></pre> <p>Suppose the conditions are not simply constants so I can’t use <code>switch</code>, but they are not complex enough expressions to warrant saying that <code>?:</code> is too unreadable.</p> <p>Of course the above construct doesn’t compile because <code>throw</code> is a statement, not an expression. Therefore, I considered writing a method that does exactly that:</p> <pre><code>/// &lt;summary&gt;Throws the specified exception.&lt;/summary&gt; /// &lt;typeparam name="TResult"&gt;The type to return.&lt;/typeparam&gt; /// &lt;param name="exception"&gt;The exception to throw.&lt;/param&gt; /// &lt;returns&gt;This method never returns a value. It always throws.&lt;/returns&gt; public static TResult Throw&lt;TResult&gt;(Exception exception) { throw exception; } [...] var x = condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : condition4 ? value4 : Ut.Throw&lt;MyType&gt;(new InvalidOperationException()); </code></pre> <p>Are there any problems with this approach that I’m not seeing?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T23:18:25.757", "Id": "3075", "Score": "1", "body": "How odd. `throw` expressions are legal in `?:` expressions in C++." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-16T21:52:28.607", "Id": "3222", "Score": "1", "body": "Originality? This kind of code appears all over the place and has for years." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-18T18:32:38.133", "Id": "3267", "Score": "1", "body": "@OJ.: Including the generic return type?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-18T22:42:03.720", "Id": "3272", "Score": "0", "body": "@Supercat: yes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T14:03:21.133", "Id": "7638", "Score": "0", "body": "Trackback: this inspired me to http://codereview.stackexchange.com/questions/5115/using-a-function-to-emulate-f-match-in-c\nI don't think it answers your question though" } ]
[ { "body": "<p>I would avoid using such statement. It doesn't seem to be a right place for this construction inside <code>?:</code> operators and I do not see major benefits in using it. I would consider using following options: </p>\n\n<p>1) </p>\n\n<pre><code>Type variable;\nif (condition1) variable = value1;\nelse if (condition2) variable = value2;\n...\nelse throw new InvalidOperationException();\n</code></pre>\n\n<p>This has a disadvantage that in each line you have <code>variable =</code> but anyway compiler will let you know if you haven't initialized <code>variable</code> value before using it so it won't bother me much.</p>\n\n<p>2) Also if your <code>value1</code>, <code>value2</code>, etc cannot be null then I would consider using this: </p>\n\n<pre><code>var variable = \n condition1 ? value1 :\n condition2 ? value2 :\n condition3 ? value3 :\n condition4 ? value4 :\n null;\nif (variable == null) throw new InvalidOperationException();\n</code></pre>\n\n<p>P.S.: Of course I cannot be sure without knowing the context but if you have to write such statements frequently then it already seems to be wrong for me, maybe something may be changed on higher level?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T16:48:48.427", "Id": "1762", "ParentId": "1760", "Score": "18" } }, { "body": "<p>One problem with this approach is stack trace population.</p>\n\n<p>The stack trace (generally) gives most immediate access to information relating to <em>where</em> whatever it was that went wrong actually went wrong. In this case it is populated with information spelling out extra method calls that are once removed from the actual location of the issue and may require (in absence of useful error messages, or their brain) developers (or, eeek! users) to <em>think</em>.</p>\n\n<p>The fact that the method is generic aids in saturating the stack trace with irrelevant information.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T16:58:12.297", "Id": "3067", "Score": "3", "body": "A full stack trace would not contain any less information. One would only have to ignore the first line of the stack trace — which you often have to do anyway, e.g. when a method’s precondition failed (`ArgumentOutOfRangeException` etc.)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T17:01:43.340", "Id": "3068", "Score": "0", "body": "I understand; and it's not unheard of, yet certainly isn't preferential or common (from my experience). I'm just bringing one view to the table - if you can dismiss this point easily then so be it. I wouldn't use such a construct indiscriminately." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T16:51:32.213", "Id": "1763", "ParentId": "1760", "Score": "8" } }, { "body": "<p>I think the only thing that's really wrong with this is that it's a bit unusual. That's not very wrong IMO, but may be hard to get past conservative reviewers. It's easier to accept this construct in the context of large expressions that aren't trivially expandable into multiple statements.</p>\n\n<p>The only reason I can think of against such a feature in the core language is that it may be considered as not making the cost/benefit bar, along with lots of other small syntactic sugar ideas which look nice one by one, but together could make a language too complicated if not carefully considered and balanced.</p>\n\n<p>Here's an example of something that becomes less elegant without Throw:</p>\n\n<pre><code>mylist.Add(new Item\n{\n Prop1 = int.Parse(input1),\n Prop2 = input2 == \"stuff\" ? true : input2 == \"notstuff\" ? false : Ut.Throw(),\n});\n</code></pre>\n\n<p>Just imagine this with a few more properties with more meaningful names.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T17:13:13.373", "Id": "1765", "ParentId": "1760", "Score": "4" } }, { "body": "<p>If it makes you feel any better, <code>mscorlib</code> and <code>System</code> assemblies both have internal <code>ThrowHelper</code> classes full of nothing but methods whose only statement is <code>throw</code>, like this:</p>\n\n<pre><code>internal static void ThrowKeyNotFoundException()\n{\n throw new KeyNotFoundException();\n}\n</code></pre>\n\n<p>Now I'm not going to say it's a good idea, but surely MS has a good reason for this, right?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T16:37:55.330", "Id": "3104", "Score": "2", "body": "I believe Microsoft’s reason for this is to minimise code size. A single call to a static method is smaller than a constructor call followed by a throw, especially if the constructor call takes arguments. But this doesn’t really relate to my question: these methods are still void and thus cannot be used in expressions..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T17:02:41.670", "Id": "3105", "Score": "1", "body": "@Timwi: I'm not suggesting that you would use *these* methods, so it doesn't matter that these are void. You can put any type on your \"Throw\" methods, obviously. My point, though, is that if it's OK for MS to do it, it should be OK for you to do it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-16T21:54:36.107", "Id": "3223", "Score": "0", "body": "@Timwi I doubt code size is the issue, especially when the compiler will optimise out the call and essentially inline the `throw`. I'd say it's more about consistency; making sure that exception messages/contents are consistent across uses." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-17T14:08:56.373", "Id": "3236", "Score": "0", "body": "@OJ: I was refering to IL code size, not jitted code size. But I take your point, consistency may play a role in it too." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T05:19:22.857", "Id": "1779", "ParentId": "1760", "Score": "8" } }, { "body": "<p>Although you do solve a bit of the code clutter by using ternary operators instead of a bunch of if else statements, I believe you didn't solve the original problem.</p>\n\n<p>Usually a long list of if else statements indicate the need to refactor. Usually this is possible by applying the <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">Strategy pattern</a>, where an 'algorithm' is selected at runtime. Whether or not this is a viable approach for your code is dependant on the specific situations where you use it.</p>\n\n<p>If the conditions you are checking on can easily be attributed to different states or concrete implementations, I advise a redesign.</p>\n\n<p>If there is no 'logical' way to separate the different assignments, I'd prefer <a href=\"https://codereview.stackexchange.com/questions/1760/whats-your-opinion-on-a-throw-method/1762#1762\">Snowbear's solution with the null check</a>. I do see the benefit of your solution however, and find it clear enough.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T15:24:07.940", "Id": "1783", "ParentId": "1760", "Score": "7" } } ]
{ "AcceptedAnswerId": "1779", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T16:00:00.217", "Id": "1760", "Score": "14", "Tags": [ "c#", "exception" ], "Title": "What’s your opinion on a Throw() method?" }
1760
<p>I don't want anything to execute if any preceding step fails:</p> <pre><code>#!/bin/sh file="v0.9" renamed=$file".tar.gz" dir="utils/external/firepython/" location="https://github.com/darwin/firepython/tarball/$file" wget --no-check-certificate $location --output-document=$renamed &amp;&amp; \ mkdir -p $dir &amp;&amp; \ gunzip $renamed &amp;&amp; \ echo "extracting to $dir" &amp;&amp; \ tar xf $file".tar" --directory $dir --strip-components 1 &amp;&amp; \ echo "Cleaning up..." &amp;&amp; \ rm -r $file".tar" &amp;&amp; \ echo "Done" </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T14:35:54.057", "Id": "3097", "Score": "1", "body": "If you use tar -zxf it will gunzip the file for you." } ]
[ { "body": "<p>You're looking for <code>set -e</code>. From <a href=\"http://pubs.opengroup.org/onlinepubs/009695399/utilities/set.html\">POSIX</a>:</p>\n\n<blockquote>\n <p><code>-e</code>\n When this option is on, if a simple command fails for any of the reasons listed in <a href=\"http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_08_01\">Consequences of Shell Errors</a> or returns an exit status value >0, and is not part of the compound list following a while, until, or if keyword, and is not a part of an AND or OR list, and is not a pipeline preceded by the ! reserved word, then the shell shall immediately exit.</p>\n</blockquote>\n\n<p>In other words, plain commands cause the shell to exit if they fail. (You can use something like <code>command || true</code> to allow <code>command</code> to return nonzero.) If you need to perform some cleanup, you can set a trap for the <code>EXIT</code> pseudo-signal.</p>\n\n<p>And better double-quote all your variable expansions. That way your script won't fail horribly if you ever point it at a directory or an URL containing <code>?</code> or <code>*</code> or a space.</p>\n\n<pre><code>dry -r\nwget --no-check-certificate \"$location\" --output-document=\"$renamed\"\nmkdir -p \"$dir\"\ngunzip \"$renamed\"\necho \"extracting to $dir\"\ntar xf \"$file.tar\" --directory \"$dir\" --strip-components 1\necho \"Cleaning up...\"\nrm -r \"$file.tar\"\necho \"Done\"\n</code></pre>\n\n<hr>\n\n<p>Another useful shell idiom to pass optional arguments to a shell script without hassle is to set variables only if they're unset. That way you can pass arguments through the environment, e.g. <code>file=v0.9.1 myscript</code>.</p>\n\n<pre><code>: \"${file=v0.9}\"\n: \"${renamed=$file.tar.gz}\"\n: \"${dir=utils/external/firepython/}\"\n: \"${location=https://github.com/darwin/firepython/tarball/$file}\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T18:07:46.460", "Id": "1768", "ParentId": "1766", "Score": "15" } }, { "body": "<p>@Gilles answer about <code>set -e</code> is right on target. An alternative way if only one or two commands in a script are must-haves, you can use <code>important-command || exit</code> as a way to drop out of the script if any one command fails.</p>\n\n<p>I often include an auxilary function in my scripts called 'flunk' that handles any cleanup that needs to be done if something fails. It might look something like this:</p>\n\n<pre><code>function flunk () {\n echo \"SCRIPT FAILED: $1\"\n rm $TMPFILES\n exit 1\n}\n\ncommand\nimportant-command || flunk \"Could not do X\"\ncommand\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T07:36:00.850", "Id": "3124", "Score": "0", "body": "I was actually wondering about failure scenarios like that, but held back since that was outside the scope of the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T17:56:44.167", "Id": "3135", "Score": "1", "body": "@Tshepang: For most tasks, I prefer to program defensively: return an error code if there's anything suspicious. So failing commands abort the script, and only specifically-vetted commands are allowed to fail. Caleb's approach is right in cases where there's a very important command you want to execute, and its preparatory steps are optional; that's not the case here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T19:31:25.890", "Id": "3146", "Score": "2", "body": "The other thing that I don't think you can do with just having `set -e` is handling cleanup if there are things you need to do if a command fails. For example in my backup scripts I often have mounts. If something goes wrong with the backup process, I still want the end of the script to run that cleanly unmounts the drives. Putting each of those aspects in functions, then using a flunk function like above allows you to do any cleanup you want before the script closes even when your important-command bombed for some reason." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T12:38:04.880", "Id": "1782", "ParentId": "1766", "Score": "8" } }, { "body": "<p>You are probably may use pipe instead of creating and deleting downloaded file:</p>\n\n<pre><code>mkdir -p \"$dir\"\necho \"extracting to $dir\"\nwget --no-check-certificate \"$location\" --output-document=- |\n tar zxvf - --strip-components 1 --directory=\"$dir\"\necho \"Done\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T16:40:35.510", "Id": "1816", "ParentId": "1766", "Score": "6" } }, { "body": "<p>Sometimes using &amp;&amp; or || can induce a race condition, so it may be better to rewrite this with if statements instead, as I do not see at a glance why exit status with the one-liner/\"pipeline\" approach is not doing it for you... And you can always test if the extracted files are present with like <code>test -f \"dir/whatever.file\" || exit 1</code> or something.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-06T06:34:06.250", "Id": "318925", "Score": "0", "body": "Could you provide justification or a citation to back up your remark about possible race conditions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-07T17:36:49.733", "Id": "319282", "Score": "0", "body": "TBH I am not entirely sure. This is just some advice that an old posix savy friend gave me. I was hoping someone might ask this because I am not entirely sure and would like to know more myself. However, I do think it's better to use `if ; then; else` in general. Some pitfalls can be avoided. Please see : http://mywiki.wooledge.org/BashPitfalls#cmd1_.26.26_cmd2_.7C.7C_cmd3" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-06T04:44:29.640", "Id": "167444", "ParentId": "1766", "Score": "0" } }, { "body": "<p>Just a reminder, these kind of scripts sometimes tend to fail if wget or gunzip is not installed. This might happen in some minimal installations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-06T08:30:44.043", "Id": "318948", "Score": "1", "body": "If `wget` or `gunzip` are not installed, it will not *tend to fail*, but certainly fail ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-07T17:43:55.047", "Id": "319283", "Score": "0", "body": "Agreed, it's a good idea to check the existence of whatever your script depends on. `if ! gunzip -V >/dev/null 2>&1 ; then { echo gunzip not found;exit 1 ;} ;else { do_whatever ;} ; fi`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-06T07:56:25.417", "Id": "167459", "ParentId": "1766", "Score": "0" } } ]
{ "AcceptedAnswerId": "1768", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-10T17:34:16.707", "Id": "1766", "Score": "7", "Tags": [ "shell", "sh" ], "Title": "Shell script to download and extract a tarball from GitHub" }
1766
<p>I have been trying to wrap my head around MVVM for the last week or more and still struggling a bit. I have watched <a href="http://www.lab49.com/files/videos/Jason%20Dolinger%20MVVM.wmv" rel="nofollow">Jason Dolingers MVVM video</a> and gone through <a href="http://reedcopsey.com/series/windows-forms-to-mvvm/" rel="nofollow">Reed Copsey lessons</a> and still find myself wondering if i am doing this right... I found both sources very interesting yet a bit different on the approach. If anyone has any other links, I would be interested as I would really like to learn this. </p> <p>What is the best practice for the model to alert the viewmodel the something has happened? As you will see in the code below, I created a very simple clock application. I am using an event in my model but am not sure if this is the best way to handle this. The output of the program is as expected, however I'm more interested in if I'm actually using the pattern correctly. Any thoughts comments etc would be appreciated.</p> <p><strong>My model</strong></p> <pre><code>using System; using System.Threading; namespace Clock { public class ClockModel { private const int TIMER_INTERVAL = 50; private DateTime _time; public event Action&lt;DateTime&gt; TimeArrived; public ClockModel() { Thread thread = new Thread(new ThreadStart(GenerateTimes)); thread.IsBackground = true; thread.Priority = ThreadPriority.Normal; thread.Start(); } public DateTime DateTime { get { return _time; } set { this._time = value; if (TimeArrived != null) { TimeArrived(DateTime); } } } private void GenerateTimes() { while (true) { DateTime = DateTime.Now; Thread.Sleep(TIMER_INTERVAL); } } } } </code></pre> <p><strong>My View</strong></p> <pre><code>&lt;Window x:Class="Clock.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ViewModels="clr-namespace:Clock" Title="MainWindow" Height="75" Width="375"&gt; &lt;Window.DataContext&gt; &lt;ViewModels:ClockViewModel /&gt; &lt;/Window.DataContext&gt; &lt;StackPanel Background="Black"&gt; &lt;TextBlock Text="{Binding Path=DateTime}" Foreground="White" Background="Black" FontSize="30" TextAlignment="Center" /&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p><strong>My View Model</strong></p> <pre><code>using System; using System.ComponentModel; namespace Clock { public class ClockViewModel : INotifyPropertyChanged { private DateTime _time; private ClockModel clock; public ClockViewModel() { clock = new ClockModel(); clock.TimeArrived += new Action&lt;DateTime&gt;(clock_TimeArrived); } private void clock_TimeArrived(DateTime time) { DateTime = time; } public DateTime DateTime { get { return _time; } set { _time = value; this.RaisePropertyChanged("DateTime"); } } /// &lt;summary&gt; /// Occurs when a property value changes. /// &lt;/summary&gt; public event PropertyChangedEventHandler PropertyChanged; /// &lt;summary&gt; /// Raises the property changed event. /// &lt;/summary&gt; /// &lt;param name="propertyName"&gt;Name of the property.&lt;/param&gt; private void RaisePropertyChanged(string property) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } } } </code></pre>
[]
[ { "body": "<p>It seems your implementation is correct. You also touch a common discussion of MVVM.</p>\n\n<p><a href=\"https://stackoverflow.com/q/772214/590790\">In MVVM should the ViewModel or Model implement INotifyPropertyChanged?</a></p>\n\n<p>One could argue you could let the model implement INotifyPropertyChanged. I'm not experienced enough with MVVM to answer this with a pro/contra argumentation.</p>\n\n<p>The main intent however is implemented and the separation is there either way.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T19:29:44.867", "Id": "1789", "ParentId": "1771", "Score": "5" } }, { "body": "<p>Found this link which proved usefull to me:</p>\n\n<p><a href=\"http://karlshifflett.wordpress.com/2010/11/07/in-the-box-ndash-mvvm-training/\" rel=\"nofollow\">http://karlshifflett.wordpress.com/2010/11/07/in-the-box-ndash-mvvm-training/</a></p>\n\n<p>It explains MVVM and what each part of it is. I as well have been (and still am) searching for the correct ways to implement MVVM, but, as said, there are many different ways to go about. One of them is e.g. M-MV-V-VM; Model ModelView - View ViewModel, which I use @work. This is because the Model is actually an entity class (coming straight from the db, can't do anything about it), and so I opted to make a ViewModel for the model (wrapper class) and then implement INotifyPropertyChanged there.</p>\n\n<p>Actually, come to think of it, my preference is to leave the model alone, entity or not. So as to have a clean as possible model.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-19T19:25:36.070", "Id": "3302", "Score": "0", "body": "I actually found this link yesterday, think it was mentioned in a video series i have been watching from NYC DevReady. I highly recommend watching this 5 part session. You can find the videos and code here \n\nhttp://blogs.msdn.com/b/peterlau/archive/2011/04/07/nyc-devready-mvvm-content-and-links.aspx" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-19T18:43:08.290", "Id": "1990", "ParentId": "1771", "Score": "3" } } ]
{ "AcceptedAnswerId": "1789", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T01:13:24.003", "Id": "1771", "Score": "6", "Tags": [ "c#", "datetime", "wpf", "mvvm" ], "Title": "Simple clock view model" }
1771
<p>I'm trying to figure out how to do this more dynamically. Right now I save each and every form field individually/manually. I would love to maybe have some kind of master form list that I could loop through. I'm fairly new to C#, so I don't know many tricks yet. Please let me know what you think.</p> <p>Here is my simplified version of my code:</p> <p>Note: None of the variable names are numbered in my real code. I changed them for simplicity in my example. So I can't loop through form names by iterating.</p> <pre><code>//BINDED FORM COLLECTION public class FormLink { private string _fObj1; private string _fObj2; private string _fObj3; private string _fObj4; private bool _fObj5; private bool _fObj6; private bool _fObj7; public string fObj1 { get { return this._fObj1; } set { this._fObj1 = value; } } public string fObj2 { /*...*/ } public string fObj3 { /*...*/ } public string fObj4 { /*...*/ } public bool fObj5 { /*...*/ } public bool fObj6 { /*...*/ } public bool fObj7 { /*...*/ } } //SETTINGS HANDLE public class Settings { private string SettingsFile = "settings.xml"; FormLink form; public Settings(FormLink form) { this.form = form; } public void iStart() { if (!File.Exists(this.SettingsFile)) { this.createDefaultsFile(); } this.iLoad(); } public void iEnd() { this.alterNodeValue(this.SettingsFile, "Settings", "fObj1", this.form.fObj1.ToString()); this.alterNodeValue(this.SettingsFile, "Settings", "fObj2", this.form.fObj2.ToString()); this.alterNodeValue(this.SettingsFile, "Settings", "fObj3", this.form.fObj3.ToString()); this.alterNodeValue(this.SettingsFile, "Settings", "fObj4", this.form.fObj4.ToString()); this.alterNodeValue(this.SettingsFile, "Settings", "fObj5", this.form.fObj5.ToString()); this.alterNodeValue(this.SettingsFile, "Settings", "fObj6", this.form.fObj6.ToString()); this.alterNodeValue(this.SettingsFile, "Settings", "fObj7", this.form.fObj7.ToString()); } private void createDefaultsFile() { XDocument xml = new XDocument( new XElement("Settings", new XElement("fObj1", "string"), new XElement("fObj2", "string"), new XElement("fObj3", "string"), new XElement("fObj4", "string"), new XElement("fObj5", false), new XElement("fObj6", false), new XElement("fObj7", false), )); xml.Save(this.SettingsFile, SaveOptions.None); } private void iLoad() { var settings = this.getNodes(XDocument.Load(this.SettingsFile, "Settings"); this.form.fObj1 = Help.getDictVal(settings, "fObj1"); this.form.fObj1 = Help.getDictVal(settings, "fObj2"); this.form.fObj1 = Help.getDictVal(settings, "fObj3"); this.form.fObj1 = Help.getDictVal(settings, "fObj4"); this.form.fObj1 = Help.getDictVal(settings, Help.stringToBool("fObj5")); this.form.fObj1 = Help.getDictVal(settings, Help.stringToBool("fObj6")); this.form.fObj1 = Help.getDictVal(settings, Help.stringToBool("fObj7")); } private void alterNodeValue(string xmlFile, string parent, string node, string newVal) { /* Alters a single XML Node and saves XML File */ } private Dictionary&lt;string, string&gt; getNodes(XDocument xml, string parent) { /* Retrieves all Child Nodes of specified Parent and returns them in a Dictionary */ } } //Basic Utilies class public static class Help { public static bool stringToBool(string BoolMe) { /* Safely converts String to Bool */ } public static string getDictVal(Dictionary&lt;string, string&gt; dict, string key) { /* Safely gets value from Dictionay based on Key*/ } } </code></pre>
[]
[ { "body": "<p>It looks like what you're trying to do here is possible by using .NET's built-in support for application settings. Check out <a href=\"http://msdn.microsoft.com/en-us/library/k4s6c3a0.aspx\" rel=\"nofollow\">this link</a> for details on how to use it. Essentially, you can define your settings within a <code>App.config</code> XML file in a standard format, and then retrieve them with the built-in <code>ConfigurationManager</code> class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T03:48:30.263", "Id": "3079", "Score": "0", "body": "Unfortunately that's not gonna work for what I'm doing. App.config and Settings.config are nice but have too many limitations for what I'm doing. The above code is just a simplified version of what I'm using just to make my question clear." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T03:12:58.067", "Id": "1774", "ParentId": "1772", "Score": "4" } }, { "body": "<p>you can just use an XML serializer? </p>\n\n<pre><code>var s = new XmlSerializer(typeof(FormLink));\nTextWriter w = new StreamWriter(\"settings.xml\");\ns.Serialize(w, form);\nw.Close();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T15:32:06.533", "Id": "3102", "Score": "0", "body": "Hmmm... that's a very very interesting idea... And I like it. Especially the part where I can customize how each property is saved(element, attribute, etc..). In order to make that work though, I would need to break `FormLink` into sections that would be serialized separately. Due to the nature of my application, I have to be able to save sections of settings in separate xml files. I can't have them all in 1 file. Do you have any idea how I could do that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T18:19:13.813", "Id": "3140", "Score": "0", "body": "+1 for using XmlSerializer. you can add ignore attribute to fields and add logic to setters and getters of properties using those fields" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T04:45:43.753", "Id": "1778", "ParentId": "1772", "Score": "7" } } ]
{ "AcceptedAnswerId": "1778", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T01:43:24.100", "Id": "1772", "Score": "7", "Tags": [ "c#", "xml" ], "Title": "XML settings implementation" }
1772
<p>At work I am developing an application using hand-coded Swing, and I've found that I have an easier time reading, writing, and maintaining hierarchical component creation using code blocks like:</p> <pre><code> JPanel mainPanel = new JPanel(new BorderLayout()); { JLabel centerLabel = new JLabel(); centerLabel.setText("Hello World"); mainPanel.add(centerLabel, BorderLayout.CENTER); } { JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0,0)); { JLabel label1 = new JLabel(); label1.setText("Hello"); southPanel.add(label1); } { JLabel label2 = new JLabel(); label2.setText("World"); southPanel.add(label2); } mainPanel.add(southPanel, BorderLayout.SOUTH); } </code></pre> <p>So I wondered what that would look like using F# and WinForms, and I translated <a href="http://code.msdn.microsoft.com/F-WinForms-43d78356">this</a> code example (go to "Browse Code" tab, then click on F# -> editor.fsx in tree view) in two ways and I'd like feedback on which of the following two ways seems better. The first uses code blocks like the approach shown in Swing, and I think it is nice but a bit cluttered with <code>begin ... end</code> everywhere:</p> <pre><code>open System open System.Windows.Forms let form = new Form() form.Width &lt;- 400 form.Height &lt;- 300 form.Visible &lt;- true form.Text &lt;- "Hello World Form" begin // Menu bar, menus let mMain = new MainMenu() begin let mFile = new MenuItem("&amp;File") begin let miQuit = new MenuItem("&amp;Quit") miQuit.Click.Add(fun _ -&gt; form.Close()) mFile.MenuItems.Add(miQuit) |&gt; ignore end mMain.MenuItems.Add(mFile) |&gt; ignore end form.Menu &lt;- mMain end begin // RichTextView let textB = new RichTextBox() textB.Dock &lt;- DockStyle.Fill textB.Text &lt;- "Hello World\n\nOK." form.Controls.Add(textB) end </code></pre> <p>The second approach is interesting because it takes advantage of the fact that in F# everything is an expression, but it seems a little harder for me to follow and I'm not sure if that's just because I'm used to the code block approach:</p> <pre><code>open System open System.Windows.Forms let form = new Form() form.Width &lt;- 400 form.Height &lt;- 300 form.Visible &lt;- true form.Text &lt;- "Hello World Form" form.Menu &lt;- // Menu bar, menus let mMain = new MainMenu() mMain.MenuItems.Add( let mFile = new MenuItem("&amp;File") mFile.MenuItems.Add( let miQuit = new MenuItem("&amp;Quit") miQuit.Click.Add(fun _ -&gt; form.Close()) miQuit ) |&gt; ignore mFile ) |&gt; ignore mMain form.Controls.Add( // RichTextView let textB = new RichTextBox() textB.Dock &lt;- DockStyle.Fill textB.Text &lt;- "Hello World\n\nOK." textB ) </code></pre> <p>Or maybe someone can suggest some other approach for structuring F# + WinForms code which is in this same spirit (i.e. emphasizing the component hierarchy both visually and in limiting scope).</p> <p><strong>Update</strong></p> <p>I recently learned that in F#, <code>begin ... end</code> and <code>( ... )</code> are interchangeable. Which means that my concern with the first example is eliminated since I can write:</p> <pre><code>open System open System.Windows.Forms let form = new Form() form.Width &lt;- 400 form.Height &lt;- 300 form.Visible &lt;- true form.Text &lt;- "Hello World Form" ( // Menu bar, menus let mMain = new MainMenu() ( let mFile = new MenuItem("&amp;File") ( let miQuit = new MenuItem("&amp;Quit") miQuit.Click.Add(fun _ -&gt; form.Close()) mFile.MenuItems.Add(miQuit) |&gt; ignore ) mMain.MenuItems.Add(mFile) |&gt; ignore ) form.Menu &lt;- mMain ) ( // RichTextView let textB = new RichTextBox() textB.Dock &lt;- DockStyle.Fill textB.Text &lt;- "Hello World\n\nOK." form.Controls.Add(textB) ) </code></pre> <p>And indeed, the second example could be written as</p> <pre><code>open System open System.Windows.Forms let form = new Form() form.Width &lt;- 400 form.Height &lt;- 300 form.Visible &lt;- true form.Text &lt;- "Hello World Form" form.Menu &lt;- // Menu bar, menus let mMain = new MainMenu() mMain.MenuItems.Add begin let mFile = new MenuItem("&amp;File") mFile.MenuItems.Add begin let miQuit = new MenuItem("&amp;Quit") miQuit.Click.Add(fun _ -&gt; form.Close()) miQuit end |&gt; ignore mFile end |&gt; ignore mMain form.Controls.Add begin // RichTextView let textB = new RichTextBox() textB.Dock &lt;- DockStyle.Fill textB.Text &lt;- "Hello World\n\nOK." textB end </code></pre> <p>So syntax isn't an issue anymore, but there still is a difference in style.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T10:37:52.503", "Id": "3091", "Score": "0", "body": "I'd argue it looks difficult to follow because of the way you're using F# - WinForms certainly isn't its choice arena, and while there may be coincidental conveniences, it is inherently less concise for this purpose than the variety of .NET languages available that had UI in mind but mostly providing a generally explanatory syntax, a little like English." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T08:00:52.440", "Id": "4410", "Score": "1", "body": "@Mr. Disappointment: I respectfully disagree. It may not be obvious how to do it at first, but declaring hierarchies of objects in F# benefits from nested declarations. C-like languages like C# allow it only through blocks, resulting in a verbose use of braces." } ]
[ { "body": "<p>Here is my take on your code:</p>\n\n<pre><code>open System\nopen System.Windows.Forms\n\nlet form =\n new Form(\n Width = 400,\n Height = 300,\n Visible = true,\n Text = \"Hello World Form\")\n\n// Menu bar, menus \nlet mMain = \n let miQuit = new MenuItem(\"&amp;Quit\")\n miQuit.Click.Add(fun _ -&gt; form.Close())\n\n let mFile = new MenuItem(\"&amp;File\")\n mFile.MenuItems.Add(miQuit) |&gt; ignore\n\n let mMain = new MainMenu()\n mMain.MenuItems.Add(mFile) |&gt; ignore\n\n mMain\n\nform.Menu &lt;- mMain\n\n// RichTextView \nlet textB = new RichTextBox(Dock = DockStyle.Fill, Text = \"Hello World\\n\\nOK.\")\n\nform.Controls.Add(textB)\n</code></pre>\n\n<p>I tried to improve by assigning properties directly in the constructor call. I also used nested let declarations to reflect the hierarchy. Finally, I used indentation instead of explicit begin/end or parens to delimit blocks.</p>\n\n<p>Note also how I used mMain within the declaration of the top-level mMain. Others might have used tmp, I think using the same name makes the intent clear. It might be a bit confusing for new-comers, though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-08T07:57:34.067", "Id": "2869", "ParentId": "1773", "Score": "4" } } ]
{ "AcceptedAnswerId": "2869", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T02:29:25.513", "Id": "1773", "Score": "11", "Tags": [ "winforms", "f#", "swing" ], "Title": "Approach to programmatically building hierarchical GUI components" }
1773
<blockquote> <p>Exercise 2.35. Redefine count-leaves from section <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-15.html" rel="nofollow">2.2.2</a> as an accumulation:</p> <pre><code>(define (count-leaves t) (accumulate &lt;??&gt; &lt;??&gt; (map &lt;??&gt; &lt;??&gt;))) </code></pre> </blockquote> <p>I wrote the following:</p> <pre><code>(define (accumulate op initial sequence) (if (null? sequence) initial (op (car sequence) (accumulate op initial (cdr sequence))))) (define (count-leaves t) (accumulate + 0 (map (lambda (subtree) (if (pair? subtree) (count-leaves subtree) 1)) t))) (define a (list 1 2 (list 1) (list 1 2 (list 2 (list 1 2))))) </code></pre> <p>What do you think?</p>
[]
[ { "body": "<p>The code doesn't handle the case of only a single leaf, i.e.</p>\n\n<pre><code> (count-leaves 'leaf)\n</code></pre>\n\n<p>but I guess that's a side-effect of the original problem formulation. A cleaner solution would be</p>\n\n<pre><code>(define (count-leaves t)\n (if (pair? t)\n (accumulate + 0 (map count-leaves t))\n 1)))\n</code></pre>\n\n<p>also because it's shorter but this doesn't fit the pattern of the original exercise.</p>\n\n<p>Incidentally, in this case the standard Scheme procedure apply would be enough because the Scheme + routine takes in an arbitrary number of arguments, and you could write just:</p>\n\n<pre><code>(define (count-leaves t)\n (if (pair? t)\n (apply + (map count-leaves t))\n 1)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-15T01:41:02.070", "Id": "1892", "ParentId": "1775", "Score": "2" } } ]
{ "AcceptedAnswerId": "1892", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T03:46:19.563", "Id": "1775", "Score": "6", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Redefine count-leaves as an accumulation" }
1775
<p>An algorithm is a set of ordered instructions based on a formal language with the following conditions:</p> <ul> <li><strong>Finite</strong>. The number of instructions must be finite.</li> <li><strong>Executable</strong>. All instructions must be executable in some language-dependent way, in a finite amount of time.</li> <li><strong>Deterministic</strong>. The algorithm must be predictable.</li> </ul> <p>An algorithm can be expressed in many ways:</p> <ul> <li>As a sequence of instructions</li> <li>As a block-scheme</li> <li>As a code in an existing or new programming language</li> <li>As a piece of text in a human language</li> <li>In other similar ways.</li> </ul> <p>An algorithm can solve a class of problems. For example, both "sum 1 and 3" and "sum 4 and 5" are problems in the same class: "sum two integer numbers." Furthermore, a given class of problems can generally be solved by a variety of algorithms.</p> <p>One important aspect of algorithm design is performance. For large datasets, a good algorithm may outperform a poor algorithm by several orders of magnitude. Algorithm performance is often rated with <a href="http://en.wikipedia.org/wiki/Big_O_notation" rel="nofollow">Big O or Θ notation</a>, but one should be cautious with asymptotic notation, since big constants may be involved.</p> <p>A key algorithm classification is known as <a href="http://en.wikipedia.org/wiki/Computational_complexity_theory" rel="nofollow">Algorithm Complexity</a>.</p> <h1>Related Links</h1> <p>Additional resources on algorithms include:</p> <ul> <li><a href="http://en.wikipedia.org/wiki/Algorithm" rel="nofollow">Algorithm on Wikipedia</a></li> <li><a href="http://computer.howstuffworks.com/question717.htm" rel="nofollow">Algorithm on Howstuffworks</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T05:57:01.993", "Id": "1780", "Score": "0", "Tags": null, "Title": null }
1780
An algorithm is a sequence of well-defined steps that define an abstract solution to a problem. Use this tag when your issue is related to algorithm design.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T05:57:01.993", "Id": "1781", "Score": "0", "Tags": null, "Title": null }
1781
<p>I have written a cart Class, it use session to store data. Is the code well implemented or could been better? You can rewrite my code if you can.</p> <p>Each item have a number of options with price</p> <p>Each Option can have many extras or without extras</p> <p><strong>For example:</strong> </p> <p>Item 1 -> (Option ID 1)</p> <p>Item 2 -> (Option ID 3, Option ID 4)</p> <p>Option ID 4 => (Extras ID: 1,5,7,8)</p> <pre><code>&lt;?php session_start(); class Cart { private $cartName; public function __construct($cartName) { $this-&gt;cartName = $cartName; if (!isset($_SESSION[$this-&gt;cartName])) { $_SESSION[$this-&gt;cartName] = array(); } } public function addItem($itemid, $optionid) { if (array_key_exists($optionid, $_SESSION[$this-&gt;cartName])) { $_SESSION[$this-&gt;cartName][$optionid]['quantity']++; $_SESSION[$this-&gt;cartName]['LastUpdated'] = $optionid; } else { $_SESSION[$this-&gt;cartName]['LastUpdated'] = $optionid; $_SESSION[$this-&gt;cartName][$optionid] = array(); $_SESSION[$this-&gt;cartName][$optionid]['quantity'] = 1; $_SESSION[$this-&gt;cartName][$optionid]['item_id'] = $itemid; $_SESSION[$this-&gt;cartName][$optionid]['extras_id'] = array(); } } public function addExtra($optionid,$extraid) { if (array_key_exists($optionid, $_SESSION[$this-&gt;cartName])) { if (!in_array($extraid, $_SESSION[$this-&gt;cartName][$optionid]['extras_id'])) { $_SESSION[$this-&gt;cartName][$optionid]['extras_id'][] = $extraid; } } } } $test = new Cart("shopCart"); $test-&gt;addItem(5,2); $test-&gt;addExtra(2,10); $test-&gt;addExtra(2,20); $test-&gt;addExtra(2,30); $test-&gt;addItem(5,4); echo "&lt;pre&gt;"; print_r($_SESSION); echo "&lt;/pre&gt;"; </code></pre>
[]
[ { "body": "<p>OK, bear with me here, but the formatting stinks.</p>\n\n<p>I won't rewrite the code for you, but I will continue to provide the information that I can to enable you to do so, should you (based on existing knowledge, or in any of my opinions being finely refuted by others) choose to disagree, then don't implement any of it.</p>\n\n<p>I was about to refuse even to read the code until the formatting (proper indentation) was applied. Formatting is one of the fundamental aspects of our job, yet (seeing as it isn't mentioned as a target of the desired review) is something you are oblivious to, can't be bothered to correct the copy+paste anomalies of, or otherwise have reasoning betwixt these matters that inhibits any action on your part to correct it.</p>\n\n<p>I won't judge harshly, however, so let us imagine you do need advice on this before even thinking about moving on. It is not only necessary to format code in a easily readable fashion, consistency of formatting is expected too; in fact, in this role, consistency to the highest degree possible is of the utmost importance in both <strong>what</strong> is to be done and <strong>how</strong> it is done. What indentation gives us is a clear view of the scope of the code we're currently looking at - without it, or when it is malformed, such can be either laborious to determine, misleading, or irritating <em>(or any combination thereof!)</em></p>\n\n<p>This is why (where curly braces are available for this purpose) I think it is a friendly approach to <a href=\"http://en.wikipedia.org/wiki/Indent_style#Allman_style_.28bsd_in_Emacs.29\" rel=\"nofollow\">start and end execution scopes on dedicated lines</a>; meaning, nothing before (other than the proper number of indentation spaces) or after the brace. And it's not just indentation, either: spacing, naming conventions, structure et cetera, all need attention. </p>\n\n<p>On the note of naming convention: Is it a <a href=\"http://upload.wikimedia.org/wikipedia/commons/f/ff/Dockworkers_in_Cap-Haitien.jpg\" rel=\"nofollow\">cart</a>? Is it a <a href=\"http://en.wikipedia.org/wiki/CART_%28disambiguation%29\" rel=\"nofollow\">CART</a>? Oh, it's a <a href=\"http://upload.wikimedia.org/wikipedia/commons/7/75/Colourful_shopping_carts.jpg\" rel=\"nofollow\">cart...</a>? Reductio ad absurdum aside, I would suggest you name this type (and its corresponding file) explicitly as <code>ShoppingCart</code> in order to make clear as to what it actually is. File size is of smaller concern these days meaning even web-code can speak for itself most times - if size is a concern, then I'm sure you could find a tool for PHP that 'minifies' your release source, still enabling you (and others) to work on self-explanatory code.</p>\n\n<p>PHP <a href=\"http://giorgiosironi.blogspot.com/2010/01/practical-php-patterns-composite.html\" rel=\"nofollow\">supports composite types</a> and, by its nature and the nature of the task at hand, you start off using it but fail to extend it to be of any further use (even, if for nothing else, code-readability as mention above.) For instance, a <code>ShoppingCartItem</code> could expose the fields that are currently stored in a standard array (which is an error-prone method of doing so too, where maintenance and extensibility are concerned) relating the to actual item. A <code>ShoppingCartItemExtra</code> class could do the same for its properties. I'll let you chew further on that.</p>\n\n<p>I'll just assume you were in too much of a hurry to add the ending php tag (<code>?&gt;</code>).</p>\n\n<p>I'll leave it there, with scope-formatted version of your code. :)</p>\n\n<pre><code>class Cart\n{\n public function __construct($cartName)\n {\n if (!isset($_SESSION[$this-&gt;cartName]))\n {\n }\n }\n\n public function addItem($itemid, $optionid)\n {\n if (array_key_exists($optionid, $_SESSION[$this-&gt;cartName]))\n {\n }\n else\n {\n }\n }\n\n public function addExtra($optionid, $extraid)\n {\n if (array_key_exists($optionid, $_SESSION[$this-&gt;cartName]))\n {\n if (!in_array($extraid, $_SESSION[$this-&gt;cartName][$optionid]['extras_id']))\n {\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T20:55:54.963", "Id": "3114", "Score": "0", "body": "`I'll just assume you were in too much of a hurry to add the ending php tag` -- leaving off the ending tag is pretty standard practice in a lot of places. Unless you're outputting HTML in your file there's no reason for it and it can lead to accidental blank lines AFTER the closing PHP tag which may cause problems. At my company we usually end our non-view PHP files with `# EOF complete/path/and/file.name`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T20:58:53.353", "Id": "3115", "Score": "0", "body": "For the love of *insert deity*, why can't I find more PHP code that looks like this! Excellent reply!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T21:12:22.477", "Id": "3117", "Score": "0", "body": "@Erik: Good point, though, since you at least mention a practice of doing so - I tried to skirt around any language specifics and probably shouldn't really have concerned myself with this particular element. @JohnKraft: Thanks." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T19:32:05.160", "Id": "1790", "ParentId": "1784", "Score": "4" } }, { "body": "<p>I have been programming PHP since the 1990s and am more than happy to help others to think more about their code and grow as programmers. I love the idea of this site: I would have killed for it when I started! This is my first post here, here goes.</p>\n<h2>array_key_exists() vs. is_array()</h2>\n<p>Totally optionally, you might consider avoiding <code>array_key_exists()</code> in this case and using a shorter hand form of test, like <code>is_array()</code>. This saves typing and should be just as clear, though perhaps very slightly slower. Due to the way the English language works, the negative notion <code>!is_array()</code> is arguably more readable than <code>!array_key_exists()</code> at some subconscious level... but this is hair-splitting. As a dubiously useful fringe benefit, switching to <code>is_array()</code> will also make your code self-healing in the event that the structure ever corrupted and a nonsensical non-array value is assigned to a position you wish to access, since the code will then clobber any such non-array value with a new array just as if the array key hadn't existed. (Though, the idea of coding this defensively is pretty useless in most cases and should not really be a huge consideration.)</p>\n<h2>Repetition</h2>\n<p>Your assignment statements are pointlessly repetitive. This is a rookie mistake, and one that is very common to see in PHP codebases.</p>\n<pre><code> $_SESSION[$this-&gt;cartName][$optionid] = array();\n $_SESSION[$this-&gt;cartName][$optionid]['quantity'] = 1;\n $_SESSION[$this-&gt;cartName][$optionid]['item_id'] = $itemid;\n $_SESSION[$this-&gt;cartName][$optionid]['extras_id'] = array();\n</code></pre>\n<p>This could all be replaced easily with...</p>\n<pre><code># 1. Create\n$cart = array(\n 'quantity' =&gt; 1,\n 'item_id' =&gt; $itemid,\n 'extras_id' =&gt; array()\n );\n\n# 2. Assign\n$_SESSION[$this-&gt;cartName][$optionid] = $cart;\n</code></pre>\n<p>Which option seems more readable to you? Which would you prefer to type? Readability kills bugs, it's a good thing™</p>\n<h2>Performance Considerations</h2>\n<p>Although performance and memory use are of dubious concern to most web applications, it is good to be aware that the second solution actually creates a second instance of <code>$cart</code> in memory (one for <code>$cart</code>, and one for the part of the <code>$_SESSION</code> structure that it is eventually assigned to.)</p>\n<p>If performance were actually a concern (hint: it isn't, such tweaks are a waste of programmer time, which is more valuable than CPU time and memory in almost every case) then you could use PHP's 'references' (kind of like 'pointers' in other languages) to maintain the concise syntax but save on the dual memory utilisation. I'm actually rusty on this side of PHP and haven't tested this example, but assuming <code>=&amp;</code> is correct then we might create a solution more like this...</p>\n<pre><code># 1. Obtain reference\n$cart =&amp; $_SESSION[$this-&gt;cartName][$optionid];\n\n# 2. Assign concisely\n$cart = array(\n 'quantity' =&gt; 1,\n 'item_id' =&gt; $itemid,\n 'extras_id' =&gt; array()\n ); \n</code></pre>\n<p>This solution preserves increased legibility and the code remains concise, whilst avoiding the duplication of our new <code>$cart</code> structure in memory.</p>\n<h2>Lack of documentation</h2>\n<p>There are no comments at all. Code without comments is bad code, and in many companies you would not get away with this. I would recommend at least adding the following at a bare minimum:</p>\n<ul>\n<li>A short description of what the entire block of code does (ie: the cart Class). The notion of 'items' and 'options' should definitely be explored.</li>\n<li>A short description of each function's input (arguments), processing and output (result)\nWhilst some people go overboard writing loads of documentation, a few well-placed and well-written snippets are vastly superior to none at all.</li>\n</ul>\n<h2>Architectural Concern: Why OO?</h2>\n<p>Object oriented methodology is a tool for approaching certain kinds of problems. However, it is not always the appropriate tool! In this case, what do you think would happen if we left it out? Certainly, the code would be more concise without it.</p>\n<p>I notice that another response already suggested including the verb Shopping before Cart to impart further information about the structure. This reminds me of both some personal experiences working with people trying to manage scope change on OO code, and comments I read in Peter Seibel's book <a href=\"http://codersatwork.com/\" rel=\"nofollow noreferrer\">Coders at Work</a> where we see quite some number of experienced programmers discussing OO with various perspectives.</p>\n<p>At its core, the OO notion is one of abstraction that takes you further from the way code executes on the underlying system, but while this can be powerful many of those experienced persons discuss the problems that maintaining large abstract object systems can have, the notion of a jungle of Class nomenclature and the difficulties reusing such code when large implicit semantic relationships have been created.</p>\n<p>In short, have a broad think about whether you want to use OO or not, what it may give you and at what cost.</p>\n<h2>Comments regarding previous responses</h2>\n<ul>\n<li>I would argue against including a path and file name within your code, since this creates a synchronisation problem when moving files around the filesystem, and really adds no clear value. Any decent editor will give you that information when editing a file, and any good revision or version control systems (RCS/VCS) will also expand short-hand macros to relative path and filename for free.</li>\n<li>Adding a closing tag is probably a good habit as being lazy about such things means, for example, that you can't concatenate two source files without first hacking in the extra tag... a fact that you may forget at a later point.</li>\n</ul>\n<h2>Use of magic numbers</h2>\n<p>You should never use fixed values in your code without explaining their purpose. Although we see this only in the example code, I don't think it's a good thing™</p>\n<pre><code>$test-&gt;addItem(5,2);\n$test-&gt;addExtra(2,10);\n$test-&gt;addExtra(2,20);\n$test-&gt;addExtra(2,30);\n\n$test-&gt;addItem(5,4);\n</code></pre>\n<h2>24 Hour Challenge</h2>\n<ul>\n<li>Re-write the code twice, once with OO as an improved <code>Cart</code> class, and once without. Include comments that you consider the minimum necessary for another programmer to understand the code clearly. Once you're done, post your improved code.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T01:27:53.137", "Id": "1792", "ParentId": "1784", "Score": "4" } } ]
{ "AcceptedAnswerId": "1792", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T16:21:19.690", "Id": "1784", "Score": "6", "Tags": [ "php", "php5" ], "Title": "Cart Class feedback" }
1784
<p>I am trying to use <code>HibernateCompositeUser</code> type to handle i18n specific data in my application. I am trying to use the below approach.</p> <p>I have a table named <code>master table</code> which contains all locale independent data, while I have created another table <code>master_translation</code> which contains all locale sensitive information. <code>Master table</code> contains a reference to the <code>master_translation</code>. </p> <p>Here is the detailed table structure:</p> <pre><code>master ---ID ---master_translation ---Other locale independent fields. master_translation ---ID ---language_id ---Other locale sensitive fields </code></pre> <p>Now I am using <code>HibernateCompositeUser</code> type to handle this internal process. Here is the mapping for master class:</p> <pre><code>&lt;hibernate-mapping&gt; &lt;class name="Master" table="MASTER"&gt; &lt;id name="uuid" type="java.lang.String"&gt; &lt;column name="UUID" /&gt; &lt;generator class="uuid" /&gt; &lt;/id&gt; &lt;property name="master_i18n" type="masteri18n"&gt; &lt;column name="NAME"/&gt; &lt;column name="SHORTDESCRIPTION"/&gt; &lt;column name="LONGDESCRIPTION"/&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre> <p>where <code>type="masteri18n"</code> is hibernate <code>CompositeUserType.now</code>.</p> <p>When I am fetching the master content, it is correctly fetching the data based on the language and my Master class contains a reference to the <code>Master_translation</code> which holds locale specific data.</p> <p>I am handling this case:</p> <pre><code>public Object nullSafeGet(ResultSet rs, String[] arg1, SessionImplementor arg2, Object arg3) throws HibernateException, SQLException { Master_i18n master_i18n=Master_i18n.getInstance(); master_i18n=dao.getMaster_i18n(rs.getString(arg1[0]), "nl_NL");; //return Master_i18n.getName(); return Master_i18n; } @Override public void nullSafeSet(PreparedStatement ps, Object arg1, int index, SessionImplementor arg3) throws HibernateException, SQLException { if(arg1==null){ ps.setNull(index, Hibernate.STRING.sqlType()); //ps.setNull(index+1, Hibernate.STRING.sqlType()); //ps.setNull(index+2, Hibernate.STRING.sqlType());set } else{ Master_i18n des=(Master_i18n)arg1; des=dao.saveMaster_i18n(des); ps.setString(index, des.getUuid()); ps.setString(index+1, des.getUuid()); ps.setString(index+2, des.getUuid()); ps.setString(index+3, des.getUuid()); } } </code></pre> <p>Somehow I am not feeling confident about my approach. Am I implementing it correctly or not?</p>
[]
[ { "body": "<p>I'm not too familiar with Hibernate, so just some generic notes:</p>\n\n<ol>\n<li><p>DBMSs usually have case-insensitive attribute names, so a lot of people use underscore to separate words in attribute and table names.</p>\n\n<blockquote>\n<pre><code>&lt;column name=\"SHORTDESCRIPTION\"/&gt;\n&lt;column name=\"LONGDESCRIPTION\"/&gt;\n</code></pre>\n</blockquote>\n\n<p>In the case above <code>SHORT_DESCRIPTION</code> and <code>LONG_DESCRIPTION</code> would be easier to read.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/153944/843804\">Is SQL syntax case sensitive?</a></li>\n</ul></li>\n<li><blockquote>\n<pre><code> Master_i18n master_i18n=Master_i18n.getInstance();\n master_i18n=dao.getMaster_i18n(rs.getString(arg1[0]), \"nl_NL\");;\n</code></pre>\n</blockquote>\n\n<p><code>Master_i18n.getInstance()</code> call seems unnecessary, since on the next line the local variable is overwritten. The following is the same (and the first line might not be required at all):</p>\n\n<pre><code>Master_i18n.getInstance();\nMaster_i18n master_i18n=dao.getMaster_i18n(rs.getString(arg1[0]), \"nl_NL\");;\n</code></pre></li>\n<li><blockquote>\n<pre><code>&lt;id name=\"uuid\" type=\"java.lang.String\"&gt;\n</code></pre>\n</blockquote>\n\n<p><code>java.lang.String</code> could be simply <code>string</code> here.</p></li>\n<li><blockquote>\n<pre><code>public Object nullSafeGet(ResultSet rs, String[] arg1,\n SessionImplementor arg2, Object arg3) throws HibernateException,\n SQLException {\n\n Master_i18n master_i18n=Master_i18n.getInstance();\n master_i18n=dao.getMaster_i18n(rs.getString(arg1[0]), \"nl_NL\");;\n\n //return Master_i18n.getName();\n return Master_i18n;\n}\n</code></pre>\n</blockquote>\n\n<p>I think currently it does not compile, since <code>return Master_i18n</code> is uppercased <code>Master_i18n</code> which seems a class, not a local variable.</p></li>\n<li><blockquote>\n<pre><code>master_i18n=dao.getMaster_i18n(rs.getString(arg1[0]), \"nl_NL\");;\n</code></pre>\n</blockquote>\n\n<p><code>nl_NL</code> could be a parameter/constant. (Does every caller want to use this locale?) (One of the semicolons is unnecessary at the end of the line.)</p></li>\n<li><p>I'd use longer and more descriptive variable names than <code>ps</code>, <code>rs</code>, <code>arg1</code>, <code>arg3</code>. Longer names would make the code more readable since readers don't have to decode the abbreviations every time when they read the code and don't have to guess which abbreviation the author uses.</p>\n\n<p>(Clean Code by Robert C. Martin, Avoid Mental Mapping, p25)</p></li>\n<li><p><code>Master_i18n</code> is rather an ugly class name. It does not follow the usual <code>CamelCase</code> naming convention.</p></li>\n<li><p>It also looks like a singleton which is rather an antipattern nowadays. They make testing harder and often hide dependencies which leads to spaghetti code which is really hard to work with. </p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/138012/843804\">What is so bad about singletons?</a></li>\n<li><a href=\"http://googletesting.blogspot.co.uk/2008/05/tott-using-dependancy-injection-to.html\" rel=\"nofollow noreferrer\">TotT: Using Dependency Injection to Avoid Singletons</a></li>\n<li><a href=\"http://blogs.msdn.com/b/nickmalik/archive/2005/09/07/462054.aspx\" rel=\"nofollow noreferrer\">Eliminating static helper classes</a></li>\n<li><a href=\"https://softwareengineering.stackexchange.com/questions/37249/the-singleton-pattern\">The Singleton Pattern</a></li>\n</ul></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T15:29:17.780", "Id": "77842", "Score": "1", "body": "I don't think that `java.lang.String` could be `String`. In all xml configurations I've seen, you need to specify the complete \"path\" to the class. I can't find a clear reference but I'll keep searching." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T19:21:26.813", "Id": "77911", "Score": "1", "body": "@Marc-Andre: Thanks for the correction, you're probably right and I'Ve mixed it up with `<property id=\"string=`. I'll try to check it tomorrow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T09:12:55.017", "Id": "78038", "Score": "2", "body": "@Marc-Andre: I've tried it, it works with lowercase `string` (Hibernate 3.5.5). (`String` throws an exception.)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T10:44:58.070", "Id": "44740", "ParentId": "1786", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T17:23:28.037", "Id": "1786", "Score": "11", "Tags": [ "java", "hibernate" ], "Title": "Is this the way to use HibernateCompositeUser type for handling localized contents?" }
1786
<p>UPDATE: I didn't write the library pasted below I just make use of it. I'm unable to paste the <a href="https://github.com/ocanbascil/Performance-AppEngine/blob/master/PerformanceEngine/__init__.py" rel="nofollow">part I wrote</a> here because the message exceeds 30k characters when I try to do so. </p> <p>I have been working on my <a href="http://tweethit.com" rel="nofollow">webapp</a> and this a simple came into life as I needed to scratch my own itch. It basically enables you to store models and query results into datastore, memcache or local instance storage using a basic API. </p> <p>I haven't published any open source work before, but as this thing helped me keep the lines of code and CPU usage low, I thought it would help others too. </p> <p>How can I make it any better? I'm planning to write unit tests, but I'm not experienced with it, so any suggestions on which libraries to use etc. is welcome.</p> <pre><code>""" Author: Juan Pablo Guereca Module which implements a per GAE instance data cache, similar to what you can achieve with APC in PHP instances. Each GAE instance caches the global scope, keeping the state of every variable on the global scope. You can go farther and cache other things, creating a caching layer for each GAE instance, and it's really fast because there is no network transfer like in memcache. Moreover GAE doesn't charge for using it and it can save you many memcache and db requests. Not everything are upsides. You can not use it on every case because: - There's no way to know if you have set or deleted a key in all the GAE instances that your app is using. Everything you do with Cachepy happens in the instance of the current request and you have N instances, be aware of that. - The only way to be sure you have flushed all the GAE instances caches is doing a code upload, no code change required. - The memory available depends on each GAE instance and your app. I've been able to set a 60 millions characters string which is like 57 MB at least. You can cache somethings but not everything. """ import time import logging import os CACHE = {} STATS_HITS = 0 STATS_MISSES = 0 STATS_KEYS_COUNT = 0 """ Flag to deactivate it on local environment. """ ACTIVE = True#False if os.environ.get('SERVER_SOFTWARE').startswith('Devel') else True """ None means forever. Value in seconds. """ DEFAULT_CACHING_TIME = None URL_KEY = 'URL_%s' """ Curious thing: A dictionary in the global scope can be referenced and changed inside a function without using the global statement, but it can not be redefined. """ def get( key ): """ Gets the data associated to the key or a None """ if ACTIVE is False: return None global CACHE, STATS_MISSES, STATS_HITS """ Return a key stored in the python instance cache or a None if it has expired or it doesn't exist """ if key not in CACHE: STATS_MISSES += 1 return None value, expiry = CACHE[key] current_timestamp = time.time() if expiry == None or current_timestamp &lt; expiry: STATS_HITS += 1 return value else: STATS_MISSES += 1 delete( key ) return None def set( key, value, expiry = DEFAULT_CACHING_TIME ): """ Sets a key in the current instance key, value, expiry seconds till it expires """ if ACTIVE is False: return None global CACHE, STATS_KEYS_COUNT if key not in CACHE: STATS_KEYS_COUNT += 1 if expiry != None: expiry = time.time() + int( expiry ) try: CACHE[key] = ( value, expiry ) except MemoryError: """ It doesn't seems to catch the exception, something in the GAE's python runtime probably """ logging.info( "%s memory error setting key '%s'" % ( __name__, key ) ) def delete( key ): """ Deletes the key stored in the cache of the current instance, not all the instances. There's no reason to use it except for debugging when developing, use expiry when setting a value instead. """ global CACHE, STATS_KEYS_COUNT if key in CACHE: STATS_KEYS_COUNT -= 1 del CACHE[key] def dump(): """ Returns the cache dictionary with all the data of the current instance, not all the instances. There's no reason to use it except for debugging when developing. """ global CACHE return CACHE def flush(): """ Resets the cache of the current instance, not all the instances. There's no reason to use it except for debugging when developing. """ global CACHE, STATS_KEYS_COUNT CACHE = {} STATS_KEYS_COUNT = 0 def stats(): """ Return the hits and misses stats, the number of keys and the cache memory address of the current instance, not all the instances.""" global CACHE, STATS_MISSES, STATS_HITS, STATS_KEYS_COUNT memory_address = "0x" + str("%X" % id( CACHE )).zfill(16) return {'cache_memory_address': memory_address, 'hits': STATS_HITS, 'misses': STATS_MISSES , 'keys_count': STATS_KEYS_COUNT, } def cacheit( keyformat, expiry=DEFAULT_CACHING_TIME ): """ Decorator to memoize functions in the current instance cache, not all the instances. """ def decorator( fxn ): def wrapper( *args, **kwargs ): key = keyformat % args[:keyformat.count('%')] data = get( key ) if data is None: data = fxn( *args, **kwargs ) set( key, data, expiry ) return data return wrapper return decorator </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T21:57:20.317", "Id": "3118", "Score": "5", "body": "Welcome to code review! If you read the FAQ you'll learn that any code that you want reviewed should really be pasted into your question. Its also geared towards smaller pieces of code (classes/functions) rather then even a small library like yours. You'll probably have better success if you show specific pieces of code you want feedback on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T13:10:57.533", "Id": "3130", "Score": "0", "body": "On a side note, I like the app --- I got distracted from looking at its technical merits by my interest in the content!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T12:35:34.007", "Id": "3157", "Score": "0", "body": "Thanks for your interest, I'm not the author of cachepy but I guess I may have to rewrite it based on your suggestions. Also I refrained from pasting the whole library code here as it is about 1000 loc (400 loc comments), to keep the question less intimidating." } ]
[ { "body": "<pre><code>\"\"\"\nCurious thing: A dictionary in the global scope can be referenced and changed inside a function without using the global statement, but it can not be redefined.\n\"\"\"\n</code></pre>\n\n<p>It's default behavior for global variable. When you try to redefine global variable inside some function without <code>global</code> keyword then python interpreter creates local variable with the same name. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T16:35:28.420", "Id": "1815", "ParentId": "1791", "Score": "0" } }, { "body": "<p>You are using a collection of global variables. I think the code would be cleaner if you moved all of those variables into a class. That would eliminate all of the global statements, and it would increase the flexibility of how you can use such the code.</p>\n\n<pre><code>if ACTIVE is False:\n</code></pre>\n\n<p>There are many false objects besides False in python. You shouldn't assume that a given value is exactly False. Just use <code>if not ACTIVE:</code></p>\n\n<pre><code> if key not in CACHE:\n STATS_MISSES += 1\n return None\n\n value, expiry = CACHE[key]\n</code></pre>\n\n<p>This code looks up key in CACHE twice. Its better to try to access the object and catch an exception or use .get and pass a default value.</p>\n\n<pre><code>if expiry != None:\n</code></pre>\n\n<p>Using <code>is None</code> is better, IMO. Its a little bit faster and None is a singleton.</p>\n\n<pre><code>try:\n CACHE[key] = ( value, expiry )\nexcept MemoryError:\n \"\"\" It doesn't seems to catch the exception, something in the GAE's python runtime probably \"\"\"\n logging.info( \"%s memory error setting key '%s'\" % ( __name__, key ) )\n</code></pre>\n\n<p>I don't know GAE, but if you are getting MemoryErrors it probably means you have more serious problems.</p>\n\n<pre><code>key = keyformat % args[:keyformat.count('%')]\n</code></pre>\n\n<p>Converting you arguments into a string seems inefficient. Why not use a tuple of the arguments?</p>\n\n<p>I try to avoid global variables, so I'd probably have cacheit create a Cache object for every function and attach it to the function as .cache attribute. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T12:46:36.707", "Id": "3158", "Score": "0", "body": "Regarding MemoryError, I haven't really come upon that while looking at the application logs and I probably store about 800K model entities in local cache (per day). If a local instance of application engine exceeds 187 MB, then it is shut down and new ones are restarted. A restart due to bloated local instances occurs about 3 or 4 times a day." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T23:25:42.870", "Id": "1835", "ParentId": "1791", "Score": "1" } } ]
{ "AcceptedAnswerId": "1835", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T21:48:59.503", "Id": "1791", "Score": "4", "Tags": [ "python" ], "Title": "Review request: My App Engine library (python)" }
1791
<p><a href="http://php.net/" rel="nofollow">PHP</a> (stands for: PHP: Hypertext Preprocessor) is a widely-used general-purpose scripting language that is especially suited for web development.</p> <p>For this purpose, PHP code can be embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document. It also has evolved to include a command-line interface capability and can be used in standalone graphical applications. PHP can be deployed on most web servers and as a standalone interpreter, on almost every operating system and platform free of charge. PHP is installed on more than 20 million websites and 1 million web servers.</p> <p>Frameworks such as <a href="/questions/tagged/laravel" class="post-tag" title="show questions tagged &#39;laravel&#39;" rel="tag">laravel</a>, <a href="/questions/tagged/symfony2" class="post-tag" title="show questions tagged &#39;symfony2&#39;" rel="tag">symfony2</a>, and <a href="/questions/tagged/zend-framework" class="post-tag" title="show questions tagged &#39;zend-framework&#39;" rel="tag">zend-framework</a> are written in PHP.</p> <hr> <p><strong>Online documentation</strong></p> <p>The <a href="http://www.php.net/manual" rel="nofollow">PHP manual</a> is the official documentation for the <a href="http://www.php.net/langref" rel="nofollow">language syntax</a>, featuring function search and URL shortcuts (for example <a href="http://php.net/explode" rel="nofollow">http://php.net/explode</a>). <a href="http://www.php.net/funcref" rel="nofollow">The API is well documented</a> for native and additional extensions.</p> <p>Most additional extensions can be found in <a href="http://pecl.php.net/packages.php" rel="nofollow">PECL</a>. The <a href="http://pear.php.net/" rel="nofollow">PEAR</a> repository contains a plethora of community supplied classes.</p> <hr> <p><strong>Free PHP Programming Books</strong></p> <ul> <li><a href="http://www.techotopia.com/index.php/PHP_Essentials" rel="nofollow">PHP Essentials</a></li> <li><a href="http://www.tuxradar.com/practicalphp" rel="nofollow">Practical PHP Programming</a> (wiki containing O'Reilly's PHP In a Nutshell)</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T02:40:42.030", "Id": "1800", "Score": "0", "Tags": null, "Title": null }
1800
PHP is a widely-used, general-purpose scripting language that is especially suited for web development.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T02:40:42.030", "Id": "1801", "Score": "0", "Tags": null, "Title": null }
1801
<blockquote> <p>Exercise 2.37. Suppose we represent vectors v = (vi) as sequences of numbers, and matrices m = (mij) as sequences of vectors (the rows of the matrix). For example, the matrix <img src="https://i.stack.imgur.com/1HQmE.gif" alt="matrix m"></p> <p>is represented as the sequence ((1 2 3 4) (4 5 6 6) (6 7 8 9)). With this representation, we can use sequence operations to concisely express the basic matrix and vector operations. These operations (which are described in any book on matrix algebra) are the following:</p> </blockquote> <p><img src="https://i.stack.imgur.com/0y5K5.gif" alt="matrix multiplication equations"></p> <blockquote> <p>We can define the dot product as17</p> <pre><code>(define (dot-product v w) (accumulate + 0 (map * v w))) </code></pre> <p>Fill in the missing expressions in the following procedures for computing the other matrix operations. (The procedure accumulate-n is defined in exercise 2.36.)</p> <pre><code>(define (matrix-*-vector m v) (map &lt;??&gt; m)) (define (transpose mat) (accumulate-n &lt;??&gt; &lt;??&gt; mat)) (define (matrix-*-matrix m n) (let ((cols (transpose n))) (map &lt;??&gt; m))) </code></pre> </blockquote> <p>I wrote the following solutions:</p> <pre><code>(define (accumulate op initial items) (if (null? items) initial (op (car items) (accumulate op initial (cdr items))))) (define (accumulate-n op init seqs) (if (null? (car seqs)) null (cons (accumulate op init (map (lambda (x) (car x)) seqs)) (accumulate-n op init (map (lambda (x) (cdr x)) seqs))))) (define (dot-product v w) (accumulate + 0 (map * v w))) (define (matrix-*-vector m v) (accumulate-n + 0 (map (lambda (row) (map (lambda (i j) (* i j)) row v)) m))) (define (transpose mat) (accumulate-n (lambda (x y) (cons x y)) null mat)) (define (matrix-*-matrix m n) (let ((cols (transpose n))) (map (lambda (m-row) (accumulate-n + 0 (map (lambda (col) (map * m-row col)) cols))) m))) (define m1 (list (list 1 2 3 4) (list 4 5 6 6) (list 6 7 8 9))) (define m2 (list (list 10 20 30) (list 40 50 60) (list 70 80 90) (list 100 110 120))) (define v1 (list 10 20 30 40)) </code></pre> <p>What do you think?</p>
[]
[ { "body": "<p>Your definition of <code>transpose</code> is correct, although it can be written succinctly as:</p>\n\n<pre><code>(define (transpose mat)\n (accumulate-n cons null mat))\n</code></pre>\n\n<p>The remaining two definitions may be written more succinctly by using functions defined earlier. Notice that multiplying a matrix to a vector is conceptually the same as obtaining the dot-product of the vector and each row of the matrix. Thus, one may define <code>matrix-*-vector</code> as:</p>\n\n<pre><code>(define (matrix-*-vector m v)\n (map (lambda (row) (dot-product v row)) m))\n</code></pre>\n\n<p>The above definition satisfies the requirement of the exercise.</p>\n\n<p>Similarly, matrix multiplication of A to B is the same as transposing B and performing a matrix-vector multiplication with each row of A. Thus, one may define <code>matrix-*-matrix</code> as:</p>\n\n<pre><code>(define (matrix-*-matrix m n)\n (let\n ((cols (transpose n)))\n (map (lambda (row) (matrix-*-vector cols row)) m)))\n</code></pre>\n\n<p>If you wish to go farther than the exercise requires, you may consider using function currying. Currying allows one to apply a function to arguments incrementally. If your implementation of Scheme provides the <code>curry</code> function, you may write:</p>\n\n<pre><code>(define (matrix-*-vector m v)\n (map (curry dot-product v) m))\n\n(define (matrix-*-matrix m n)\n (map (curry matrix-*-vector (transpose n)) m))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-15T19:47:52.173", "Id": "1914", "ParentId": "1802", "Score": "2" } } ]
{ "AcceptedAnswerId": "1914", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T02:48:06.000", "Id": "1802", "Score": "5", "Tags": [ "lisp", "scheme", "matrix", "sicp" ], "Title": "Matrix multiplication and dot-product" }
1802
<blockquote> <p><strong>Exercise 2.39</strong></p> <p>Complete the following definitions of reverse (exercise 2.18) in terms of fold-right and fold-left from exercise 2.38:</p> <pre><code>(define (reverse sequence) (fold-right (lambda (x y) &lt;??&gt;) nil sequence)) (define (reverse sequence) (fold-left (lambda (x y) &lt;??&gt;) nil sequence)) </code></pre> </blockquote> <p>I wrote this answer:</p> <pre><code>(define (fold-right op initial seq) (define (rec rest) (if (null? rest) initial (op (car rest) (rec (cdr rest))))) (rec seq)) (define (fold-left op initial seq) (define (iter result rest) (if (null? rest) result (iter (op result (car rest)) (cdr rest)))) (iter initial seq)) (define (reverse sequence) (fold-right (lambda (x y) (append y (list x))) null sequence)) (define (reverse-l sequence) (fold-left (lambda (x y) (cons y x)) null sequence)) (define a (list 1 2 3 4 5)) </code></pre>
[]
[ { "body": "<p>Yep, youve got it. I don't think there are any reasonable alternatives.</p>\n\n<p>It's umderstandable if you were hoping to avoid <code>append</code> with some clever combo of <code>cons</code>/<code>car</code>/<code>cdr</code> but i dont believe there is such a way.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T05:57:16.423", "Id": "1805", "ParentId": "1803", "Score": "1" } }, { "body": "<p>Your implementation of <code>reverse</code> using <code>fold-left</code> is correct.</p>\n\n<p>In the case of <code>reverse</code> using <code>fold-right</code>, you may use <code>snoc</code> (described below) in place of <code>append</code>. It looks better and its complexity is no worse than that of <code>append</code>, so there is no loss in efficiency:</p>\n\n<pre><code>(define (snoc e lis)\n (if (null? lis)\n (cons e lis)\n (cons (car lis) (snoc e (cdr lis)))))\n\n(define (reverse sequence)\n (fold-right (lambda (x y)\n (snoc x y)) null sequence))\n</code></pre>\n\n<p>... or even more succinct:</p>\n\n<pre><code>(define (reverse sequence)\n (fold-right snoc null sequence))\n</code></pre>\n\n<p>It is curious that SICP's definition of <code>fold-left</code> swaps arguments to <code>op</code> (but retains the correct ordering of arguments to <code>op</code> in <code>fold-right</code>), resulting in the use of a rather tedious <code>(lambda (x y) (cons y x))</code> instead of a simple <code>cons</code>. <a href=\"http://srfi.schemers.org/srfi-1/srfi-1.html\" rel=\"nofollow\">SRFI-1</a> gets the definitions of <code>fold</code> and <code>fold-right</code> correct, of course.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T06:13:53.493", "Id": "3152", "Score": "0", "body": "Thanks! I was surprised that you didn't have to snoc in reverse order for fold-right, but I tested it and it works. Interesting." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T04:18:29.770", "Id": "1838", "ParentId": "1803", "Score": "2" } } ]
{ "AcceptedAnswerId": "1838", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T03:51:22.880", "Id": "1803", "Score": "5", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Reverse in terms of fold-right and fold-left" }
1803
<p>I'm new to rails and have built a multi-model form. It's working, but some of the code doesn't feel right.</p> <p>The model code is below. I'm using <a href="https://github.com/plataformatec/devise" rel="nofollow">Devise</a> for my user authentication:</p> <pre><code># models/signup.rb class Signup &lt; ActiveRecord::Base has_one :company accepts_nested_attributes_for :company end # models/company.rb class Company &lt; ActiveRecord::Base belongs_to :signup has_many :users accepts_nested_attributes_for :users end # models/user.rb class User &lt; ActiveRecord::Base devise :database_authenticatable, :confirmable, :recoverable, :rememberable, :trackable, :validatable, :registerable attr_accessible :email, :password, :password_confirmation belongs_to :company end </code></pre> <p>My view is fairly standard and follows the typical pattern for multiple models. The most important code is the initial <code>Signup</code> creation which is done via the following helper:</p> <pre><code># signup is created via signups#new def setup_signup(signup) signup.company ||= Company.new if signup.company.users[0] == nil 1.times { signup.company.users.build } end signup end </code></pre> <p>I had to add a condition to not create additional users, because if the form validation failed it would create another user.</p> <p>Finally my controller code looks like this:</p> <pre><code># controllers/signups_controller.rb class SignupsController &lt; ApplicationController respond_to :html def new @signup = Signup.new end def create @signup = Signup.new(params[:signup]) # The first user to signup for a company should be an admin user # But this feels really awkward @signup.company.users.first.admin = true # Skip confirmation for the first user to signup @signup.company.users.first.skip_confirmation! if @signup.save sign_in_and_redirect(@signup.company.users.first) else render :action =&gt; "new" end end end </code></pre> <p>This is what feels wrong to me:</p> <ul> <li>When signing up to my website, there will only ever be a single <code>User</code> created. However, because a user is associated via a <code>Company</code>, and a Company has_many users I have to access this user in an awkward manner: <code>signup.company.users.first</code>. Obviously I could create an instance variable <code>user = signup.company.users.first</code>, and if that's the best solution, I'll take it, but it feels like there should be a better solution.</li> <li>The <code>setup_signup</code> helper method requires checking if a user has already been created so a second user isn't created: <code>if signup.company.users[0] == nil</code>. To me if feels like Rails ought to have a cleaner way of handling this.</li> <li>It feels like my <code>create</code> action is too <em>fat</em> for a controller, and that there ought to be a better way to set the admin boolean.</li> </ul> <p>Am I right? Are there cleaner ways to accomplish these tasks?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T17:59:22.700", "Id": "3136", "Score": "2", "body": "Any reason you're using a Signup model and controller, instead of doing it directly from Company?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T18:01:13.773", "Id": "3137", "Score": "0", "body": "@Dogbert - yes. I haven't gotten there yet, but I will be adding an additional model under the signup model." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T18:18:38.610", "Id": "3139", "Score": "0", "body": "I was going to suggest a solution that would do away with the signup model completely. Could you explain a bit more about what kind of things you would be adding to the signup model, that can't be added to Company or Users?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T18:22:57.750", "Id": "3141", "Score": "0", "body": "@Dogbert - I'll be adding an ActiveMerchant model when I get around to the credit card processing part of the application. So a Signup will have a Company and a CreditCard model." } ]
[ { "body": "<p>Firstly (and yes I did read the comments) the signup model seems unessential.</p>\n\n<p>So firstly we should do away with that, if you need to associate payment details then that could easily be done directly on the company model.</p>\n\n<p>Secondly you controller is getting a bit cuddly. In favour of having \"fat model, skinny controller\" let's move all that signup logic into the company model in the form of a <code>Company::register</code> method.</p>\n\n<p>So far we have changes like this:</p>\n\n<pre><code># app/models/company.rb\nclass Company &lt; ActiveRecord::Base\n has_many :users\n accepts_nested_attributes_for :users\n\n def self.register(params)\n company = self.new(params)\n\n company.users.first.admin = true\n company.users.first.skip_confirmation!\n\n if company.save\n company\n else\n false\n end\n end\nend\n</code></pre>\n\n<p>Now your controller can look like this:</p>\n\n<pre><code># app/controllers/companies_controller.rb\nclass CompaniesController &lt; ApplicationController\n\n def new\n @company = Company.new\n end\n\n def create\n if @company = Company.register(params[:company])\n sign_in_and_redirect(@company.users.first)\n else\n render :new\n end\n end\nend\n</code></pre>\n\n<p>I'm also pretty sure that it's unessential to use that helper you have above. The form builder should be able to work it out from the model accepting nested attributes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-29T06:06:07.567", "Id": "6376", "ParentId": "1804", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T03:54:00.290", "Id": "1804", "Score": "4", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Cleaning up a multi-model view in Rails3" }
1804
<p>C# is a multiparadigm, managed, garbage-collected, object-oriented programming language created by Microsoft in conjunction with the .NET platform. C# is also used with non-Microsoft implementations (most notably, <a href="http://www.mono-project.com/" rel="nofollow noreferrer">Mono</a>).</p> <h2>C# Background</h2> <p>Versions 1.0/1.2 and 2.0 of C# were submitted and approved as both <a href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf" rel="nofollow noreferrer">ECMA</a> and <a href="http://standards.iso.org/ittf/PubliclyAvailableStandards/c042926_ISO_IEC_23270_2006(E).zip" rel="nofollow noreferrer">ISO/IEC</a> standards. As of December 2010, there are no ECMA or ISO/IEC specifications for C# 3.0 through 5.0; however, language specifications are available from Microsoft (<a href="http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc" rel="nofollow noreferrer">3.0</a> and <a href="http://www.microsoft.com/downloads/details.aspx?displaylang=en&amp;FamilyID=dfbf523c-f98c-4804-afbd-459e846b268e" rel="nofollow noreferrer">5.0</a>).</p> <p>The language's type-system was originally static, with only explicit variable declarations allowed. However, the introduction of <code>var</code> (C# 3.0) and <code>dynamic</code> (C# 4.0) allow it to use type-inference for implicit variable typing, and to consume dynamic type-systems, respectively. Delegates (especially with lexical-closure support for anonymous-methods (C# 2.0) and lambda-expressions (C# 3.0)) allow the language to be used for functional programming.</p> <p>Compilation is usually to the Common Intermediate Language (CIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR); however, options like <a href="http://msdn.microsoft.com/en-us/library/6t9t5wcf.aspx" rel="nofollow noreferrer">Ngen</a> (.NET) and <a href="http://www.mono-project.com/AOT" rel="nofollow noreferrer">AOT</a> (Mono) mean this isn't the only option. Additionally, some frameworks (e.g. the Micro Framework) act as CIL interpreters, with no JIT.</p> <p>Perhaps unusually, generics in C# are provided (in part) by the runtime, unlike (for comparison) C++ templates, or Java's generics (which use type-erasure).</p> <p>With the combination of Microsoft .NET for Windows (desktop/server), Mono (desktop/server/mobile), Silverlight / Moonlight (browser/mobile), Compact Framework (mobile), and Micro Framework (embedded devices), C# is available for a wide range of platforms.</p> <h2>Current Version</h2> <ul> <li>Stable: <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-3" rel="nofollow noreferrer">C# 7.3</a></li> <li>Preview: <a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8" rel="nofollow noreferrer">C# 8.0 - Preview 5</a></li> </ul> <h2>Hello World</h2> <pre><code>using System; class Hello { static void Main() { Console.WriteLine(&quot;Hello, World&quot;); } } </code></pre> <p>##Resources</p> <ul> <li><a href="http://go.microsoft.com/fwlink/?LinkId=188622" rel="nofollow noreferrer">Specification</a></li> <li><a href="http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29" rel="nofollow noreferrer">Wikipedia Article</a></li> <li><a href="https://docs.microsoft.com/en-us/archive/blogs/ericlippert/" rel="nofollow noreferrer">Eric Lippert's blog</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/67ef8sbd.aspx" rel="nofollow noreferrer">Programming Guide</a></li> <li>MSDN <ul> <li><a href="https://msdn.microsoft.com/en-us/library/ms229002.aspx" rel="nofollow noreferrer">Naming Guidelines</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/ms229042.aspx" rel="nofollow noreferrer">Framework Design Guidelines</a></li> </ul> </li> <li>Books <ul> <li><a href="http://www.microsoft.com/learning/en/us/books.aspx?id=13874&amp;locale=en-us" rel="nofollow noreferrer">CLR via C#</a></li> <li><a href="http://www.albahari.com/nutshell/" rel="nofollow noreferrer">C# in a Nutshell</a></li> <li><a href="http://www.manning.com/skeet3/" rel="nofollow noreferrer">C# in Depth</a></li> <li><a href="http://apress.com/book/view/9781430225379" rel="nofollow noreferrer">Accelerated C#</a></li> <li><a href="https://rads.stackoverflow.com/amzn/click/com/1449380344" rel="nofollow noreferrer" rel="nofollow noreferrer">Head First C#</a></li> <li>The C# Programming Language (<a href="http://www.informit.com/store/product.aspx?isbn=0321562992" rel="nofollow noreferrer">3rd Edition</a>, <a href="http://www.informit.com/store/product.aspx?isbn=0321741765" rel="nofollow noreferrer">4th Edition</a>)</li> <li><a href="https://rads.stackoverflow.com/amzn/click/com/0321545613" rel="nofollow noreferrer" rel="nofollow noreferrer">Framework Design Guidelines</a></li> <li>[Essential C# (<a href="https://rads.stackoverflow.com/amzn/click/com/0321694694" rel="nofollow noreferrer" rel="nofollow noreferrer">4.0 (3rd Edition)</a>)</li> <li><a href="https://rads.stackoverflow.com/amzn/click/com/B0040ZN34G" rel="nofollow noreferrer" rel="nofollow noreferrer">Pro C# 2010 and the .Net 4 Platform</a></li> </ul> </li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-04-12T13:00:51.323", "Id": "1808", "Score": "0", "Tags": null, "Title": null }
1808
C# is a multi-paradigm, managed, garbage-collected, object-oriented programming language created by Microsoft in conjunction with the .NET platform. Use this tag for questions related to C#. In case a specific version of the framework is used, you could also include that tag; for instance .net-2.0.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-04-12T13:00:51.323", "Id": "1809", "Score": "0", "Tags": null, "Title": null }
1809
<p>This is an intersection-detection algorithm I developed as an alternative method to the one developed for my coursework. I won't post some of the other functions as they are used in the coursework too, feel free to ask if their names aren't self explanatory. This function simply returns whether 2 <code>bcw</code> objects are intersecting. <code>bcw</code> objects are either boxes or circles. What I'd like is any comments on my algorithm/coding style to help make me a better programmer.</p> <pre><code>def bcw_do_collide_i(obj_A,obj_B,tracer=None, accuracy = 30): """ Check whether Box-Circle World objects obj_A and obj_B collode. If so, return True, otherwise return False. """ # items to be checked comp1 = [obj_A] comp2 = [obj_B] # does a component circumcircle collide, True = collides truth1 = [False] truth2 = [False] # Depth used to limit iterations to accuracy depth = 0 while len(comp1)!=0 and depth&lt;accuracy: # Find any non colliding components for c1,t1 in zip(comp1,range(len(truth1))): circum_1 = bcw_circumcircle(c1) for c2,t2 in zip(comp2,range(len(truth2))): circum_2 = bcw_circumcircle(c2) if tracer &lt;&gt; None: tracer([c1,c2,circum_1,circum_2], ["k--","b--","r--","r--"]) if bcw_do_circles_overlap(circum_1,circum_2) == True: truth1[t1] = True truth2[t2] = True # Check for colliding components in_1 = bcw_incircle(c1) in_2 = bcw_incircle(c2) if tracer &lt;&gt; None: tracer([c1,c2,in_1,in_2], ["g--","b--","r--","r--"]) if bcw_do_circles_overlap(in_1,in_2): return True # Subdivide all components whose outers collide sub = [] for c1,t1 in zip(comp1,truth1): if t1: sub+=bcw_components(c1) comp1 = sub[::] truth1 = [False for i in comp1] sub =[] for c2,t2 in zip(comp2,truth2): if t2: sub+=bcw_components(c2) comp2 = sub[::] truth2 = [False for i in comp1] depth+=1 return False </code></pre> <p>I was tempted by using the <code>bcw</code> objects as dictionary keys but they had to be mutable.</p>
[]
[ { "body": "<p>A few quick stylistic things:</p>\n\n<ol>\n<li>Don't use &lt;>, its considered an older style use != instead</li>\n<li>When comparing against None, use \"x is None\" not \"x &lt;> None\" or \"x != None\" This is because there is only one None object so its more correct to compare object identity</li>\n<li>Don't use == True or == False. There are some corner cases that won't do what you expect. They clutter your code and make it look like you don't know what you are doing.</li>\n<li>Your variables do not provide much hints about what they are doing. For example you have variables named truth. Given that we already knew there were holding booleans thats not very useful.</li>\n</ol>\n\n<p>To actually rework your code:</p>\n\n<ol>\n<li><p>You set values in a truth list, then use those values to decide whether or not to take an action. Flags clutter code. Rather then setting those flags, why don't we maintain a list. By adding a remaining_Comp1 and remaining_comp2 list I push elements in there instead of setting Truth values in my list. This completely eliminates the neccesity of keeping the truth lists and eliminates a lot of the code.</p></li>\n<li><p>You have two for loops which iterate over all possible combinations of elements from your two lists. By using itertools.product, we can make this simpler</p></li>\n<li><p>You check that comp1 is not empty, but not comp2. This looks like an oversight. </p></li>\n<li><p>You are keeping track of depth to make sure you don't go into too much detail. But you've basically reimplemented a for loop. I'd move depth into a for loop and simply bail out with a break statement if comp1 or comp2 is empty.</p></li>\n<li><p>Rather then checking whether trace is None, I recommend using a NullTracer which simply does nothing when it is called. </p></li>\n</ol>\n\n<p>Your code reworked:</p>\n\n<pre><code>def bcw_do_collide_i(obj_A,obj_B,tracer=None, accuracy = 30):\n \"\"\" Check whether Box-Circle World objects obj_A\n and obj_B collode. If so, return True,\n otherwise return False.\n \"\"\"\n if tracer is None:\n tracer = NullTracer()\n\n # items to be checked\n comp1 = [obj_A]\n comp2 = [obj_B]\n\n for depth in range(accuracy):\n if not comp1 or not comp2:\n return False\n\n remaining_comp1 = []\n remaining_comp2 = []\n # Find any non colliding components\n for c1, c2 in itertools.product(comp1, comp2):\n circum_1 = bcw_circumcircle(c1)\n circum_2 = bcw_circumcircle(c2)\n tracer([c1,c2,circum_1,circum_2], [\"k--\",\"b--\",\"r--\",\"r--\"])\n if bcw_do_circles_overlap(circum_1,circum_2):\n remaining_comp1.append(c1)\n remaining_comp2.append(c2)\n # Check for colliding components\n in_1 = bcw_incircle(c1)\n in_2 = bcw_incircle(c2)\n tracer([c1,c2,in_1,in_2],\n [\"g--\",\"b--\",\"r--\",\"r--\"])\n if bcw_do_circles_overlap(in_1,in_2): return True\n\n # Subdivide all components whose outers collide\n def expand_components(components):\n result = []\n for c1 in remaining_comp1:\n result += bcw_components(components)\n return result\n\n comp1 = expand_components(remaining_comp1)\n comp2 = expand_components(remaining_comp2)\n\n\n return False\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T21:13:31.863", "Id": "3150", "Score": "0", "body": "Neat :) exactly the kind of advice I was looking for. I'd never even come across itertools before. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T22:16:37.053", "Id": "71189", "Score": "0", "body": "I usually do the `x is None` and `x is not None` (this prevents nasty bugs when `bool(x)` is `False`). Actually you could do that for numbers as well (e.g. `x is 1`). The semantics is the same. Would you do such a thing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T23:33:43.477", "Id": "71197", "Score": "0", "body": "@Dacav, actually it is not guaranteed to work for numbers. In current implementations of Python it'll work for small numbers, but not big ones. See for example: `123456789 + 1 is 123456789 + 1` It's False." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T20:12:51.353", "Id": "1828", "ParentId": "1810", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T14:02:37.787", "Id": "1810", "Score": "3", "Tags": [ "python", "algorithm", "collections", "collision" ], "Title": "Intersection-detection algorithm" }
1810
<p>This is a small extension based on a <code>boost::property_tree</code>, which supports arbitrary values for the properties and appropriate serialization. It can be used as an alternative to QSettings in Qt and provides very convenient way to pass properties inside your applications.</p> <p>I would like to have a code review from somebody, just to point out what I might be doing wrong, because I'm not that good at C++ coding.</p> <pre><code>#include &lt;boost/any.hpp&gt; #include &lt;boost/variant.hpp&gt; #include &lt;boost/algorithm/string.hpp&gt; #include &lt;boost/property_tree/ptree.hpp&gt; #include &lt;boost/property_tree/ptree_serialization.hpp&gt; #include &lt;boost/property_tree/xml_parser.hpp&gt; #include &lt;boost/property_tree/json_parser.hpp&gt; #include &lt;boost/property_tree/ini_parser.hpp&gt; #include &lt;boost/property_tree/info_parser.hpp&gt; #include "core_defines.h" #include "core_extensions_lexical_cast.h" namespace boost { namespace property_tree { // Generic value holder, which will attempt to cast objects rather than // indicate error if wrong type was supplied. This behavior is likely to // be more error-prone, but is more 'user-friendly'. See 'strict_value_holder' // class if you need strict type support. // Supports trivial integral, floating point and string types in 'strict' // mode and also allows the storage to hold arbitrary values using // 'boost::any' storage. Note that due to implementation details, // values of specific (non-default) types can't be serialized // (we skip them / replace with dummy objects). class value_holder { // Main value holder type, which has support for common types // and can use the internal visitor for casting. typedef boost::variant&lt;bool, int, unsigned, float, double, std::string, std::wstring&gt; Holder; public: // Models 'DefaultConstructible', default constructor // leaves the storage uninitialized. value_holder() : using_any_holder_(false) { } template &lt;typename T&gt; value_holder(const T&amp; value, typename boost::enable_if&lt; typename boost::mpl::contains&lt;Holder::types, T&gt; &gt;::type* = 0) : holder_(value), using_any_holder_(false) { } // Custom constructing routine for string-like types. explicit value_holder(const char* value) : holder_(std::string(value)), using_any_holder_(false) { } // Custom constructing routine for string-like types. explicit value_holder(const wchar_t* value) : holder_(std::wstring(value)), using_any_holder_(false) { } // Custom constructing routine for non-standard types. template &lt;typename T&gt; value_holder(const T&amp; value, typename boost::disable_if&lt; typename boost::mpl::contains&lt;Holder::types, T&gt; &gt;::type* = 0) : any_holder_(value), using_any_holder_(true) { } // Retrieves held value with possible additional type casts. // Note that this method won't even compile for unsupported // types. template &lt;typename T&gt; typename boost::enable_if&lt;typename boost::mpl::contains&lt;Holder::types, T&gt;, T&gt;::type as() const { // Apply internal casting visitor. return boost::apply_visitor(type_casting_visitor&lt;T&gt;(), holder_); } // Attempts to retrieve non-standard type from internal 'boost::any'-based // storage. Throws 'boost::bad_any_cast' on errors. template &lt;typename T&gt; typename boost::disable_if&lt;typename boost::mpl::contains&lt;Holder::types, T&gt;, T&gt;::type as() const { // Apply internal 'boost::any_cast' routine. return boost::any_cast&lt;T&gt;(any_holder_); } // Generic holder swapping (required by 'boost::property_tree' // specification). void swap(value_holder&amp; value) { holder_.swap(value.holder_); any_holder_.swap(value.any_holder_); std::swap(using_any_holder_, value.using_any_holder_); } // Check if current holder is empty (required by // 'boost::property_tree' specification). bool empty() const { // Dispatch emptiness check based on currently // used value holder. if (using_any_holder_) return any_holder_.empty(); return holder_.empty(); } private: // Internal functional object used to retrieve common types and perform // appropriate casting. template &lt;typename T&gt; struct type_casting_visitor : boost::static_visitor&lt;T&gt; { // Handles every possible arithmetic type with // 'boost::numeric_cast'. template &lt;typename Y&gt; T operator()(const Y&amp; value) const { return boost::numeric_cast&lt;T&gt;(value); } // Template specialization for 'std::string' -&gt; type casting template &lt;&gt; inline T operator()&lt;std::string&gt;(const std::string&amp; value) const { return boost::lexical_cast&lt;T&gt;(value); } // Template specialization for 'std::wstring' -&gt; type casting template &lt;&gt; inline T operator()&lt;std::wstring&gt;(const std::wstring&amp; value) const { return boost::lexical_cast&lt;T&gt;(value); } }; // Template specialization for type -&gt; 'std::string' casting. template &lt;&gt; struct type_casting_visitor&lt;std::string&gt; : boost::static_visitor&lt;std::string&gt; { template &lt;typename Y&gt; std::string operator()(const Y&amp; value) const { return boost::lexical_cast&lt;std::string&gt;(value); } }; // Template specialization for type -&gt; 'std::wstring' casting. template &lt;&gt; struct type_casting_visitor&lt;std::wstring&gt; : boost::static_visitor&lt;std::wstring&gt; { template &lt;typename Y&gt; std::wstring operator()(const Y&amp; value) const { return boost::lexical_cast&lt;std::wstring&gt;(value); } }; public: // Custom serialization implementation. template &lt;typename Archive&gt; void serialize(Archive&amp; ar, const unsigned int) { using namespace ::boost; ar &amp; serialization::make_nvp("using_any_holder", using_any_holder_); // Serialize only what we can - if the value shares one // of the predefined types, use the default 'boost::variant' // serialization routine. if (!using_any_holder_) ar &amp; serialization::make_nvp("holder", holder_); } private: // Main value holder instance. Holder holder_; // Alternative value holder, which is used to store // objects and data that differ from supported by main holder. // These can actually be treated as temporary objects, because // due to language / implementation limitations, they aren't // serialized / deserialized (it's impossible to combine benefits // from 'generics' while still having the strict typing - which // is a requirement for our serialization routines). boost::any any_holder_; // Indicates if the current value is actually using a 'boost::any'- // based value holder (non-common value). bool using_any_holder_; }; // Strict variation of generic value holder, which // does not support arbitrary types and will // throw if types do not match exactly. class strict_value_holder : public value_holder { // Main value holder type, which has support for common types. typedef boost::variant&lt;bool, int, unsigned, float, double, std::string, std::wstring&gt; Holder; public: // Models 'DefaultConstructible'. strict_value_holder() { } // Custom constructors for any of the available basic cases (which are // supported by initial 'boost::variant' placeholder). template &lt;typename T&gt; strict_value_holder(const T&amp; value, typename boost::enable_if&lt; typename boost::mpl::contains&lt;Holder::types, T&gt; &gt;::type* = 0) : holder_(value) { } // Custom constructing routine for string-like types. explicit strict_value_holder(const char* value) : holder_(std::string(value)) { } // Custom constructing routine for string-like types. explicit strict_value_holder(const wchar_t* value) : holder_(std::wstring(value)) { } // Retrieves held value without any type casts. Throws 'boost::bad_get' if // casting was unsuccessful. template &lt;typename T&gt; typename boost::enable_if&lt;typename boost::mpl::contains&lt;Holder::types, T&gt;, T&gt;::type as() const { return boost::get&lt;T&gt;(holder_); } // Generic holder swapping (required by 'boost::property_tree' // specification). void swap(strict_value_holder&amp; value) { holder_.swap(value.holder_); } // Check if current holder is empty (required by // 'boost::property_tree' specification). bool empty() const { return holder_.empty(); } public: // Custom serialization implementation. template &lt;typename Archive&gt; void serialize(Archive&amp; ar, const unsigned int) { using namespace ::boost; // Serialize the value holder. ar &amp; serialization::make_nvp("holder", holder_); } private: // Main value holder instance. Holder holder_; }; // Custom holder-based translator implementation. template &lt;typename T, typename Y&gt; struct value_holder_translator { // Type definitions required by the // 'Translator' concept. typedef T internal_type; typedef Y external_type; boost::optional&lt;Y&gt; get_value(const T&amp; value_holder) const { // Attempt to use casting routine // specific for template type. return value_holder.as&lt;Y&gt;(); } boost::optional&lt;T&gt; put_value(const Y&amp; value) const { // Construct appropriate value holder for specified // value (doesn't throw). return T(value); } }; // Set custom translator for internal 'value_holder' type. template &lt;typename Y&gt; struct translator_between&lt;value_holder, Y&gt; { typedef value_holder_translator&lt;value_holder, Y&gt; type; }; // Set custom translator for internal 'strict_value_holder' type. template &lt;typename Y&gt; struct translator_between&lt;strict_value_holder, Y&gt; { typedef value_holder_translator&lt;strict_value_holder, Y&gt; type; }; } // namespace property_tree // Type definition for custom holder-based properties collection. Note that // for convenience, properties collection is brought to '::boost' namespace. // This kind of properties allows arbitrary parameter types and, therefore, // will substitute unsupported parameter types with dummies when writing. Also // note, that if the parameter structure is filled from some xml-like file, // you will lose the performance of custom value holder, because in this // case parameters are stored as strings (that obviously brings a huge // casting overhead to 'get&lt;non-string-type&gt;' operations). // If you want to save the benefits of type checking and remove type casting // overhead, use serialization instead of raw xml writing / reading. typedef property_tree::basic_ptree&lt; std::string, property_tree::value_holder&gt; properties; // This variation of properties structure supports // wide character keys. typedef property_tree::basic_ptree&lt; std::wstring, property_tree::value_holder&gt; wproperties; // Bring property-specific path declaration into the '::boost' // namespace. using property_tree::path; using property_tree::wpath; // Enable custom tree-like format parsers. using property_tree::xml_parser::write_xml; using property_tree::xml_parser::read_xml; using property_tree::json_parser::write_json; using property_tree::json_parser::read_json; using property_tree::ini_parser::write_ini; using property_tree::ini_parser::read_ini; using property_tree::info_parser::write_info; using property_tree::info_parser::read_info; } // namespace boost </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-26T21:43:16.913", "Id": "3445", "Score": "0", "body": "Looks interesting. Maybe add some comments or test case to illustrate how it is used and what it bring over boost (if it is pertinent) would be great. Your coding style looks pretty nice though (I didn't have time to check in details)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-12T06:44:26.163", "Id": "13418", "Score": "0", "body": "To be honestly - I would like to use your extension, but I can't because of missing files\ncore_defines.h and core_extensions_lexical_cast.h. Could you share a minimum required for compilation? Thanks in advance!" } ]
[ { "body": "<p>I think use boost::serialize is not are good idea. I read about this library (not all Boost) and they have problem compatibility with previous versions.</p>\n\n<p>I wrote other property container and property manager some times ago. And we use template class, without Boost, like this:</p>\n\n<pre><code>//Contains one property any complexity you want\ntemplate &lt;typename Type&gt;\nclass Property : public PropertyBase\n{\nprotected:\n Type m_property;\npublic:\n /**\n for deep copy you must define copy c-tor\n @param Type const&amp; prop - any property\n **/\n Property(Type const&amp; prop)\n :m_property(prop)\n {\n }\n virtual ~Property() { }\npublic:\n // @return Type const&amp; - contained property\n Type const&amp; GetProperty() const { return m_property; }\n\n /**\n for deep copy you must define operator=\n @param Type const&amp; prop - any property\n **/\n void SetProperty(Type const&amp; prop)\n {\n m_property = prop;\n }\n};\n\ntypedef PointerContainer&lt;int, PropertyBase&gt; TProperties; //list of properties for group\ntypedef PointerContainer&lt;int, TProperties&gt; TPropertyGroupList; //list of properties groups\n\n//Class for manipulation with properies\nclass BasePropertyProvider\n{\nprotected:\n TPropertyGroupList m_propertyGroupList; // container of all properties\n.................\npublic:\n /**\n @param int propertyGroup - group of properties for which we search \n @param int propertyType - type of property which we search\n @return Type const* - pointer on value or 0 if searching failed\n **/\n template &lt;typename Type&gt;\n Type const* GetProperty(int propertyGroup, int propertyType) const;\n\n /**\n Add property in inner storage\n @param int propertyGroup - group of properties for add\n @param int propertyType - type of property for add\n @param Type const &amp; - reference on value for add\n **/\n template &lt;typename Type&gt;\n void AddProperty(int propertyGroup, int propertyType, Type const &amp;prop);\n};\n</code></pre>\n\n<p>It's not full realization, but I think you understand the direction.</p>\n\n<p>Also I know Qt solution property. You can find it <a href=\"http://qt.gitorious.org/qt-solutions/qt-solutions/trees/master/qtpropertybrowser\" rel=\"nofollow\">here</a>.</p>\n\n<p>But they're really heavy tools, and if you want to add some original property you must write 3 or 4 classes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-25T10:33:02.303", "Id": "2081", "ParentId": "1818", "Score": "4" } } ]
{ "AcceptedAnswerId": "2081", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T17:34:40.537", "Id": "1818", "Score": "10", "Tags": [ "c++", "tree", "extension-methods", "boost" ], "Title": "Small C++ Boost extension based on boost::property_tree" }
1818
<pre><code>function reformat($data, $registration = false) { // Initializing aircompanies codes $iata = new iata; for ($i = 0; $i &lt; count($data); $i = $i + 6) { if ($registration) { $r = str_replace('&lt;nobr&gt;', '', $this-&gt;prep_value($data[$i])); $block[$i]['reis'] = str_replace('&lt;/nobr&gt;', '', $r); $a = explode(' ', $block[$i]['reis']); $block[$i]['company'] = $a[0]; } else { $r = explode('&amp;nbsp;', $this-&gt;prep_value($data[$i])); $block[$i]['reis'] = (strlen($r[0]) &gt; 2) ? strrev(substr(strrev($r[0]), 15, 2)) . ' ' . $r[1] : $r[0] . ' ' . $r[1]; $block[$i]['company'] = (strlen($r[0]) &gt; 2) ? strrev(substr(strrev($r[0]), 15, 2)) : $r[0]; } $block[$i]['companyname'] = $iata-&gt;aircompanies[strtoupper($block[$i]['company'])]; if (file_exists(ROOT_HTML_PATH . '/content/aircompanies/' . $block[$i]['company'] . '.png')) { $block[$i]['company'] = $block[$i]['company'] . '.png'; } else { /** * @todo Write e-mail notifications, but only once; */ } $block[$i]['airport'] = $this-&gt;prep_value($data[$i + 1]); $block[$i]['terminal'] = substr(strrev($this-&gt;prep_value($data[$i + 2])), 2, 1); $block[$i]['shedtime'] = $this-&gt;prep_value($data[$i + 3]); $block[$i]['facttime'] = str_replace('&amp;nbsp;', '', $this-&gt;prep_value($data[$i + 4])); $block[$i]['status'] = str_replace('&amp;nbsp', '&lt;br /&gt;', trim(strip_tags($this-&gt;prep_value($data[$i + 5]), '&lt;img /&gt;'), '&amp;nbsp;/r/n')); $block[$i]['status'] = str_replace(';', '', $block[$i]['status']); } return $block; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-09T14:35:41.320", "Id": "245328", "Score": "0", "body": "This question could use some explanation of what the code is supposed to do and how it works." } ]
[ { "body": "<pre><code>function reformat($data, $registration = false) {\n // Initializing aircompanies codes\n $iata = new iata;\n $block = array();\n for ($i = 0; $i &lt; count($data); $i += 6) {\n $block[$i] = array(\n 'airport' =&gt; $this-&gt;prep_value($data[$i + 1]),\n 'terminal' =&gt; substr(strrev($this-&gt;prep_value($data[$i + 2])), 2, 1),\n 'shedtime' =&gt; $this-&gt;prep_value($data[$i + 3]),\n 'facttime' =&gt; str_replace('&amp;nbsp;', '', $this-&gt;prep_value($data[$i + 4])),\n 'status' =&gt; str_replace(';', '', \n str_replace('&amp;nbsp', '&lt;br /&gt;', \n trim(\n strip_tags($this-&gt;prep_value($data[$i + 5]), '&lt;img /&gt;'), \n '&amp;nbsp;/r/n'\n )\n )\n ),\n );\n\n if ($registration) {\n $r = str_replace('&lt;nobr&gt;', '', $this-&gt;prep_value($data[$i]));\n $block[$i]['reis'] = str_replace('&lt;/nobr&gt;', '', $r);\n $a = explode(' ', trim($block[$i]['reis']));\n $block[$i]['company'] = $a[0];\n } else {\n $r = explode('&amp;nbsp;', $this-&gt;prep_value($data[$i]));\n $block[$i]['company'] = (strlen($r[0]) &gt; 2) ? substr($r[0], -17, 2) : $r[0];\n $block[$i]['reis'] = $block[$i]['company'] . ' ' . $r[1];\n }\n $block[$i]['companyname'] = $iata-&gt;aircompanies[strtoupper($block[$i]['company'])];\n if (file_exists(ROOT_HTML_PATH . '/content/aircompanies/' . $block[$i]['company'] . '.png')) {\n $block[$i]['company'] = $block[$i]['company'] . '.png';\n } else {\n /**\n * @todo Write e-mail notifications, but only once;\n */\n }\n }\n return $block;\n}\n</code></pre>\n\n<p>But it is many questions here: </p>\n\n<pre><code>$this-&gt;prep_value($data[$i + 2])\n</code></pre>\n\n<p>It is really bad idea. May be you need a little another cycle, like</p>\n\n<pre><code>for ($i = 0; $i &lt; count($data) - 6; $i ++) { // or something for preventing array index overloading\n</code></pre>\n\n<p>It would be much better.\nBut I cannot know it for sure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T13:35:25.650", "Id": "3161", "Score": "0", "body": "`$this->prep_value($data[$i + 2])`\nThat's cause of parsing data. Sorry, could do nothing with this. Maybe =)\n`for ($i = 0; $i < count($data) - 6; $i ++) `\nThat's cause i use for block[0] - first six items, for block[1] - next six items.\nReally, don't know what to do with this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-03T16:14:20.120", "Id": "168128", "Score": "0", "body": "It appears that your data comes in as an array `$data`. What you could consider based on what is in that data array, is to perform all `str_replace` operations in one go at the top (if feasible). You could flatten the array initially with `json_encode` then do `str_replace` on all the `<br/>`, `/r/n`, `$nbsp` etc. and then recreate it with `json_decode`. That could speed the process up. Again it depends on your data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-07T21:01:37.303", "Id": "215608", "Score": "1", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and how it improves upon the original) so that the author can learn from your thought process." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T20:13:26.657", "Id": "1829", "ParentId": "1819", "Score": "-1" } } ]
{ "AcceptedAnswerId": "1829", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T18:12:29.260", "Id": "1819", "Score": "0", "Tags": [ "php", "formatting" ], "Title": "Formatting some data about some airlines" }
1819
<p>So, here's my code:</p> <pre><code>public class NList : SExp, IEnumerable&lt;Object&gt; { private Object _car; private NList _cdr; IEnumerator&lt;Object&gt; IEnumerable&lt;Object&gt;.GetEnumerator() { return new NListEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new NListEnumerator(this); } public object car () { return _car; } public NList cdr () { return _cdr; } public NList cons (object o) { return new NList(o, this); } public NList() // empty list { } public NList(List&lt;Object&gt; lst) { if (lst.Count == 1) { this._car = lst[0]; this._cdr = null; } else { this._car = lst[0]; this._cdr = new NList(lst.GetRange(1, lst.Count - 1)); } } public NList (Object fst) { this._car = fst; this._cdr = null; } public NList (Object fst, NList rst) { this._car = fst; this._cdr = rst; } public object Last() { NList list = this; while(list.cdr() != null) { list = list.cdr(); } return list.car(); } public int Count { get { return this.length(); } } public int length() { if (this._car == null &amp;&amp; this._cdr == null) return 0; NList list = this; int len = 1; while(list.cdr() != null) { list = list.cdr(); len++; } return len; } public NList cddr() { return this.cdr().cdr(); } public object cadr() { return this.cdr().car(); } public object elm(int k) { if(k == 0) return car(); NList list = cdr(); for(int i = 1; i &lt; k; i++, list = list.cdr()) ; return list.car(); } public NList append(NList lst) { NList lst1 = this; NList lst2 = lst; if (this._car == null &amp;&amp; this._cdr == null) return lst2; foreach(var e in Reverse(lst1)) { lst2 = lst2.cons(e); } return lst2; //return lst1.Aggregate(lst2, (NList acc, object b) =&gt; acc); } public static NList Reverse(NList lst) { NList l = lst; NList res = null; while(l != null) { res = new NList(l.car(), res); l = l.cdr(); } return res; } public override string ToString () { if (this._car == null &amp;&amp; this._cdr == null) return "()"; string s = "("; for(int i = 0; i&lt;this.Count-1; i++) { s+=this.elm(i).ToString() + " "; } s+=this.Last().ToString() + ")"; return s; } public NObj[] ToNObjArray() { NObj[] a = new NObj[this.Count]; int k = 0; foreach (var e in this) { a[k] = (e as NObj); k++; } return a; } public object[] ToArray() { object[] a = new object[this.Count]; int k = 0; foreach(var e in this) { a[k] = e; k++; } return a; } } public class NListEnumerator : IEnumerator&lt;Object&gt;, IEnumerator { NList list; NList tmp; public void Dispose() { } public NListEnumerator(NList list) { this.list = list; this.tmp = list.cons(null); } public object Current { get { return tmp.car(); } } public bool MoveNext() { tmp = tmp.cdr(); return (tmp != null); } public void Reset() { tmp = list.cons(null); } } </code></pre> <p>I am kinda worried that I have no separate class for simple pairs (eg: non-properly terminated lists like (1 . 2), (a . b)). Should I create a separate class (and an interface for both classes), or should I try to expand this one?</p> <p>TIA.</p>
[]
[ { "body": "<p>There is a serious flaw in your handling of the empty list. A user would expect that these definitions are equivalent, but they ain't:</p>\n\n<pre><code>Nlist n1 = new NList(\"x\");\nNlist n2 = new NList(\"x\", new NList());\n</code></pre>\n\n<p>I strongly recommend to have an explicit subclass for the empty list (possibly a singleton) and to prohibit null for _cdr.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T06:20:33.003", "Id": "1842", "ParentId": "1830", "Score": "2" } }, { "body": "<blockquote>\n <p>Should I create a separate class (and an interface for both classes), or should I try to expand this one?</p>\n</blockquote>\n\n<p>In real LISP there is no separate representation for lists. List is just a chain of dotted pairs actually. So, I think, it's better to modify the original class and allow assigning list's cdr to anything other than NList.</p>\n\n<p>By the way, why not just use properties for this:</p>\n\n<pre><code>public object car ()\n{\n return _car;\n}\n\npublic NList cdr ()\n{\n return _cdr;\n}\n</code></pre>\n\n<p>Also, if you already have class SExp, it may be a good idea to return SExp instead of object here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T10:39:26.520", "Id": "3172", "Score": "0", "body": "I tried doing that, but it resulted in a pretty big mess, for example: (cdr '(1 . 2)) returns 2, while (cdr '(1 2)) returns (2). So I would have to convert Object to NList every time I call cdr and expect a list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-11T12:41:53.547", "Id": "320890", "Score": "0", "body": "@Daniil: I hope you found out that what you describe above in your comment is actually correct when done in any Lisp?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T08:44:17.047", "Id": "1852", "ParentId": "1830", "Score": "1" } }, { "body": "<h2>Review</h2>\n\n<p><sup>Note that I'm using arrow notation which was not available back then. But that does not impact the issues addresses in this review.</sup></p>\n\n<p>Method overload resolution allows an explicitly implemented interface method to call the implicitly one:</p>\n\n<blockquote>\n<pre><code>IEnumerator IEnumerable.GetEnumerator()\n{\n return new NListEnumerator(this);\n}\n</code></pre>\n</blockquote>\n\n<pre><code>IEnumerator IEnumerable.GetEnumerator() =&gt; GetEnumerator();\n</code></pre>\n\n<p>Use properties for getters, and pascal-case naming convention.</p>\n\n<blockquote>\n<pre><code>public object car ()\n{\n return _car;\n}\n\npublic NList cdr ()\n{\n return _cdr;\n}\n</code></pre>\n</blockquote>\n\n<pre><code>public object Car =&gt; _car;\n\npublic NList Cdr =&gt;_cdr; // TODO and favour using a fully qualified name over an abbreviation\n</code></pre>\n\n<p>The factory method should be made static and use naming conventions.</p>\n\n<blockquote>\n<pre><code>public NList cons (object o)\n{\n return new NList(o, this);\n}\n</code></pre>\n</blockquote>\n\n<pre><code>public static NList Construct(object o) =&gt; new NList(o, this);\n</code></pre>\n\n<p>Extract all common steps out the branches to have more DRY code.</p>\n\n<blockquote>\n<pre><code>public NList(List&lt;Object&gt; lst)\n{\n if (lst.Count == 1)\n {\n this._car = lst[0];\n this._cdr = null;\n }\n else\n {\n this._car = lst[0];\n this._cdr = new NList(lst.GetRange(1, lst.Count - 1));\n }\n}\n</code></pre>\n</blockquote>\n\n<pre><code>public NList(List&lt;Object&gt; lst)\n{\n _car = lst.FirstOrDefault();\n if (lst.Count &gt; 1)\n {\n _cdr = new NList(lst.GetRange(1, lst.Count - 1));\n }\n}\n</code></pre>\n\n<p>Use constructor overloads.</p>\n\n<blockquote>\n<pre><code>public NList (Object fst)\n{\n this._car = fst;\n this._cdr = null;\n}\n</code></pre>\n</blockquote>\n\n<pre><code>public NList (Object fst) : this (fst, null)\n{\n}\n</code></pre>\n\n<p>There is no need for the function <code>length</code>. Put the logic behind property <code>Count</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T10:42:25.357", "Id": "226412", "ParentId": "1830", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-04-12T20:13:41.563", "Id": "1830", "Score": "4", "Tags": [ "c#", "iterator", "lisp" ], "Title": "LISP-like list class" }
1830
<p>I'm trying to speed up the following code for summing doubles with full precision, based on a <a href="http://code.activestate.com/recipes/393090/" rel="nofollow">Python recipe</a> from Raymond Hettinger. Any thoughts on how to make this go faster?</p> <pre><code>-- Full precision summation based on http://code.activestate.com/recipes/393090/ msum :: [Double] -&gt; Double msum [] = 0 msum (x:xs) = sum $ foldl' (\ps x' -&gt; reverse (partials x' ps)) [x] xs partials :: Double -&gt; [Double] -&gt; [Double] partials x = foldl' (\acc p -&gt; case hilo x p of (hi, 0) -&gt; hi:acc (hi, lo) -&gt; hi:lo:acc) [] hilo :: Double -&gt; Double -&gt; (Double, Double) hilo x y | abs x &lt; abs y = hilo y x | otherwise = (hi, lo) where hi = x + y lo = y - (hi - x) </code></pre> <p>This is already a second draft; you can see a previous version of the code in <a href="https://gist.github.com/912588" rel="nofollow">this gist</a>.</p>
[]
[ { "body": "<p>You could write <code>hilo</code> as <code>hilo :: Double -&gt; Double -&gt; [Double]</code>, which returns <code>[hi,lo]</code> for <code>lo /= 0</code> and <code>[hi]</code> for <code>lo = 0</code>. Then you can write <code>partials</code> as</p>\n\n<pre><code>partials x = foldl' (\\acc p -&gt; (hilo x p) ++ acc) -&gt; hi:acc []\n</code></pre>\n\n<p>BTW: How could <code>lo</code> ever become non-zero considering</p>\n\n<pre><code>lo = y - (hi - x) = y - (x + y - x) = y - y = 0\n</code></pre>\n\n<p>Rounding?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T16:30:49.473", "Id": "3179", "Score": "0", "body": "Did you benchmark that approach? For me it's ending up slightly slower. And, yes, lo only ends up nonzero as an artifact of IEEE754; the lack of precision in floating point is what this function is intended to address. The original Python recipe I linked to explains more and links to the paper that proves it works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T16:38:32.650", "Id": "3180", "Score": "0", "body": "Also, I've got a version that passes the acc through to hilo and lets hilo do the appending itself. I'm really surprised to see that that version is also slightly slower than this in wall time on my benchmark, and ends up not doing the math right when run under the profiler (and before ghc 7.0.3, it didn't do the math right at all - I need to file a bug)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T20:29:50.157", "Id": "3182", "Score": "0", "body": "It was just an educated guess, no benchmarking. I don't see much other things you could try. Maybe you could get rid of the reverse in msum by building the result list in partials somehow backwards?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T14:55:31.323", "Id": "1882", "ParentId": "1834", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T23:00:44.157", "Id": "1834", "Score": "6", "Tags": [ "performance", "haskell" ], "Title": "Full-precision summation in Haskell" }
1834
<p><strong>NOTE: My implementation is based on codeproject <a href="http://www.codeproject.com/KB/threads/CritSectEx.aspx">article</a> by Vladislav Gelfer.</strong></p> <p>Based on <a href="http://www.codeproject.com/script/Membership/View.aspx?mid=541463">valdok</a>'s codes, I rewrote the critical section class. The difference is that my implementation integrated recursive(reentrantable) locking feature into a single critical section class. (FYI, valdok provides 2 classes: one without recursion and the other with recursion.)</p> <p>I just want to verify that my implementation is still correct and intact.</p> <p><strong>Please, do not try to argue that the implementation is meaningless against using the WIN32 critical section object. I think this implementation has many advantages for many reasons. And, one reason is I needed to provide <code>try_enter()</code> feature for all versions of Windows.</strong></p> <pre><code>#pragma once #include &lt;windows.h&gt; #include &lt;intrin.h&gt; #pragma intrinsic(_WriteBarrier) #pragma intrinsic(_ReadWriteBarrier) class critical_section { private: struct cpu_type { enum type { unknown, single, multiple }; }; public: critical_section(u32 spin_count=0) : m_semaphore(null) , m_thread_id(0) , m_wait_count(0) , m_spin_count(0) , m_recur_count(0) { // determine the cpu type if( m_cpu_type == cpu_type::unknown ) { SYSTEM_INFO sys_info; ::GetSystemInfo(&amp;sys_info); m_cpu_type = (sys_info.dwNumberOfProcessors &gt; 1)?cpu_type::multiple:cpu_type::single; } // set the spin count. set_spin_count(spin_count); } ~critical_section() { if(m_semaphore != null) { CloseHandle(m_semaphore); m_semaphore = null; } ::memset(this, 0, sizeof(*this)); } void set_spin_count(u32 count) { // on single core, there should be no spinning at all. if(m_cpu_type == cpu_type::multiple) { m_spin_count = count; } } public: bool enter(u32 timeout=INFINITE) { u32 cur_thread_id = ::GetCurrentThreadId(); if(cur_thread_id == m_thread_id) { // already owned by the current thread. m_recur_count++; } else { if((!m_thread_id &amp;&amp; lock_immediate(cur_thread_id)) || (timeout &amp;&amp; lock_internal(cur_thread_id, timeout))) { // successfully locked! m_recur_count = 1; } else { // failed to lock! return false; } } return true; } bool try_enter() { return enter(0); } void leave() { assert(m_recur_count &gt; 0); if(--m_recur_count == 0) { unlock_internal(); } } inline bool is_acquired() const { return (::GetCurrentThreadId() == m_thread_id); } private: inline bool lock_immediate(u32 thread_id) { // return true only if m_thread_id was 0 (and, at the same time, replaced by thread_id). return (_InterlockedCompareExchange(reinterpret_cast&lt;long volatile*&gt;(&amp;m_thread_id), thread_id, 0) == 0); } bool lock_kernel(u32 thread_id, u32 timeout) { bool waiter = false; for(u32 ticks=GetTickCount();;) { if(!waiter) _InterlockedIncrement(reinterpret_cast&lt;long volatile*&gt;(&amp;m_wait_count)); // try locking once again before going to kernel-mode. if(lock_immediate(thread_id)) return true; u32 wait; if(timeout==INFINITE) { wait = INFINITE; } else { // update the remaining time-out. wait = GetTickCount()-ticks; if(timeout&lt;=wait) return false; // timed-out wait = timeout-wait; } // go kernel assert(m_semaphore!=null); switch(WaitForSingleObject(m_semaphore, wait)) { case WAIT_OBJECT_0: // got a change! waiter = false; break; case WAIT_TIMEOUT: // timed-out. // but, there's one more change in the upper section of the loop. waiter = true; break; default: assert(false); } } } bool lock_internal(u32 thread_id, u32 timeout) { // try spinning and locking for(u32 spin=0; spin&lt;m_spin_count; spin++) { if(lock_immediate(thread_id)) return true; // give chance to other waiting threads. // on single-core, it does nothing. YieldProcessor(); } // prepare semaphore object for kernel-mode waiting. allocate_semaphore(); bool locked = lock_kernel(thread_id, timeout); _InterlockedDecrement(reinterpret_cast&lt;long volatile*&gt;(&amp;m_wait_count)); return locked; } void unlock_internal() { // changes done to the shared resource are committed. _WriteBarrier(); // reset owner thread id. m_thread_id = 0; // critical section is now released. _ReadWriteBarrier(); // if there are waiting threads: if(m_wait_count &gt; 0) { _InterlockedDecrement(reinterpret_cast&lt;long volatile*&gt;(&amp;m_wait_count)); // wake up one of them by incrementing semaphore count by 1. assert(m_semaphore); ReleaseSemaphore(m_semaphore, 1, null); } } void allocate_semaphore() { if(m_semaphore==null) { // create a semaphore object. HANDLE semaphore = CreateSemaphore(null, 0, 0x7FFFFFFF, null); assert(semaphore!=null); // try assign it to m_semaphore. if(InterlockedCompareExchangePointer(&amp;m_semaphore, semaphore, null)!=null) { // other thread already created and assigned the semaphore. CloseHandle(semaphore); } } } private: // prevent copying critical_section(const critical_section&amp;); void operator=(const critical_section&amp;); private: // type of cpu: single-core or multiple-core static cpu_type::type m_cpu_type; // owner thread's id volatile u32 m_thread_id; // number of waiting threads volatile u32 m_wait_count; // spinning count volatile u32 m_spin_count; // recursion(reentrance) count s32 m_recur_count; // semaphore for kernel-mode wait volatile HANDLE m_semaphore; }; </code></pre> <p>Don't worry about a static member. <code>critical_section::m_cpu_type</code> is defined and initialized to <code>unknown</code> in other .cpp file. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T12:08:26.630", "Id": "3155", "Score": "1", "body": "It would be nice if you provided unit tests for this piece of code, because it's hard to test it's correctness based on only it's implementation. *Also, why not stick to something like `boost::threads` and don't spend your time reinventing the wheel?*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-15T13:15:41.903", "Id": "3196", "Score": "2", "body": "Even if he is reinventing the wheel, it could be because the existing wheel isn't round enough. I grow tired of that stupid argument. Let people write their code for pity's sake. Who knows, maybe we'll learn something from a radical new idea rather than stagnating with what we already have." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-17T08:41:17.763", "Id": "3229", "Score": "0", "body": "Thanks guys. As I stated, I just wanted to verify that my implementation is still intact. Actually, I'm using boost. Don't worry about it :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T12:12:27.510", "Id": "21334", "Score": "0", "body": "What is the purpose of the `memset` in your code? Also, you are modifying `m_recur_count` concurrently without locking. **This is not an atomic variable**. The code *will* provoke a race condition. Also note that the `CRITICAL_SECTION` struct doesn’t even bother declaring its members as `volatile` since `volatile` does nothing here. In conclusion, no this implementation isn’t correct. I can’t verify whether valdok’s original code is since I have to register to CP to download the source code." } ]
[ { "body": "<p>To be honest it is quite difficult to verify this sort of thing works by dry running code.</p>\n\n<p>I would take the original code and design some test cases which show it working.\nRun them with and without the code.</p>\n\n<p>Then design some test cases which fail due to the problem you have spotted, or perhaps do not work well enough without your enhancement.</p>\n\n<p>Run those test cases over your new code (all of them not just the newest ones) and hey presto you know if your code works.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T12:19:21.680", "Id": "21335", "Score": "1", "body": "Writing unit tests which reliably show faults in parallel code is *hard*, almost as hard as writing those implementations in the first place. That’s not to say that you shouldn’t write tests, they are still great for showing failure. But you mustn’t rely on them. So I agree with this answer, except the last sentence." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-30T10:51:35.737", "Id": "12160", "ParentId": "1836", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T02:48:50.420", "Id": "1836", "Score": "8", "Tags": [ "c++", "multithreading", "locking" ], "Title": "C++ critical section with timeout" }
1836
<p>Does this code look OK?</p> <pre><code>public Map&lt;String, String&gt; getById(long id) { String sql = "select * from " + this._TABLE_NAME + " where id = ?"; PreparedStatement p; Map&lt;String, String&gt; result = new HashMap&lt;String, String&gt;(); try { p = conn.prepareStatement(sql); p.setLong(1, id); ResultSet rs = p.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int fieldsCount = rsmd.getColumnCount(); // is this ok? rs.next(); for (int i=1;i&lt;fieldsCount+1;i++) { String cName = rsmd.getColumnName(i); result.put(cName, rs.getString(cName)); } } catch (SQLException e) { e.printStackTrace(); } return result; } </code></pre>
[]
[ { "body": "<p>Why not just do it like:</p>\n\n<pre><code>while(rs.next()) {\n result.put(....);\n return result;\n}\n</code></pre>\n\n<p>You can also wrap it in a <code>try</code>-<code>catch</code>-<code>finally</code>.</p>\n\n<p>Also, the use of prepared statement may not be justified in this example, since you use it only once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T15:02:13.170", "Id": "62285", "Score": "0", "body": "please give more explanation. it makes for a better review" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T15:15:19.793", "Id": "62289", "Score": "0", "body": "No need to call `while(rs.next())` when it would only happen once." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T15:16:14.440", "Id": "62291", "Score": "2", "body": "Using a prepared statement is perfectly OK, no matter if it's used only once or 100 times. It removes any possible vulnerabilities of SQL injection." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T06:02:30.843", "Id": "1840", "ParentId": "1839", "Score": "-2" } }, { "body": "<p>Here is a bit reworked version of you code. Some explanation:</p>\n\n<ul>\n<li>Assume <code>_TABLE_NAME</code> is a constant, so there is no need to build query in every method call. </li>\n<li>Force getting connection and close resources to avoid side effects.</li>\n<li>Propagate <code>SQLException</code> to caller (caller should decide what to do with thrown exception).</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>private final static String GET_DATA_BY_ID = \"select * from \" + _TABLE_NAME + \" where id = ?\";\n\npublic Map&lt;String, String&gt; getById(long id) throws SQLException {\n\n Connection conn = null;\n Map&lt;String, String&gt; result = new HashMap&lt;String, String&gt;();\n\n try {\n conn = getConnection();\n\n PreparedStatement preparedStatement = null;\n\n ResultSet rs = null;\n try {\n preparedStatement = conn.prepareStatement(GET_DATA_BY_ID);\n preparedStatement.setLong(1, id);\n try {\n rs = preparedStatement.executeQuery();\n\n if (rs.next()) {\n ResultSetMetaData rsmd = rs.getMetaData();\n int fieldsCount = rsmd.getColumnCount();\n\n for (int i = 1; i &lt; fieldsCount + 1; i++) {\n String cName = rsmd.getColumnName(i);\n result.put(cName, rs.getString(cName));\n }\n }\n } finally {\n if (rs != null)\n rs.close();\n }\n } finally {\n if (preparedStatement != null)\n preparedStatement.close();\n }\n } finally {\n if (conn != null)\n conn.close();\n }\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-05T14:33:54.223", "Id": "3639", "Score": "1", "body": "I'd define the `Connection`, `PreparedStatement`, and `ResultSet` all in the same scope before the first `try` so that they can be closed in the same `finally` block, avoiding all of that nesting and having only one `finally`. You already have null checks prior to calling `close()` so it would work fine." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T06:25:49.470", "Id": "1843", "ParentId": "1839", "Score": "7" } }, { "body": "<p>You don't need check <code>if (rs != null)</code> and <code>if (preparedStatement != null)</code>, because <code>prepareStatement()</code> and <code>executeQuery()</code> always return non-null or fails. Just declare these objects without initialization and close them after. Same for connection probably.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T08:16:19.687", "Id": "1850", "ParentId": "1839", "Score": "5" } }, { "body": "<p>Sergey's answer highlights the importance of closing the resources - if you omit that, you'll have a connection leak, which means that the database will run out of connections. In a long-running application this is a critical bug, so the ugly try-finally-approach is fully justified. (You could actually hide it by wrapping it in an utility class.)</p>\n\n<p>Checking the ResultSet and PreparedStatement obtained from the JDBC implementation for null is not necessary, since if e.g. obtaining the result set by <code>rs = preparedStatement.executeQuery()</code> did fail already, that means it cannot be closed anyway.</p>\n\n<p>However, I would not throw the raw SQLException to the client, but wrap them in an application specific exception. This allows you to treat different error conditions differently, and decouples your calling code from the SQL layer, which is useful should you want to switch to another persistence mechanism later. (Also, it is very simple.)</p>\n\n<pre><code>private final static String GET_DATA_BY_ID = \n \"select * from \" + _TABLE_NAME + \" where id = ?\";\n\npublic Map&lt;String, String&gt; getById(long id) throws YourSpecificPersistenceException {\n\n final Map&lt;String, String&gt; result;\n try {\n Connection conn = getConnection();\n try {\n\n PreparedStatement preparedStatement = \n conn.prepareStatement(GET_DATA_BY_ID);\n\n try {\n preparedStatement.setLong(1, id);\n ResultSet rs = preparedStatement.executeQuery();\n\n try {\n if (rs.next()) {\n ResultSetMetaData rsmd = rs.getMetaData();\n int fieldsCount = rsmd.getColumnCount();\n result = new HashMap&lt;String, String&gt;(fieldsCount);\n\n for (int i = 1; i &lt; fieldsCount + 1; i++) {\n String cName = rsmd.getColumnName(i);\n result.put(cName, rs.getString(cName));\n }\n } else {\n result = Collections.emptyMap();\n }\n } finally {\n rs.close();\n }\n } finally {\n preparedStatement.close();\n }\n } finally {\n conn.close();\n }\n } catch (SQLException e) {\n throw new YourSpecificPersistenceException(\"Unable to execute statement: '\"\n + GET_DATA_BY_ID + \"' with parameter [\" + id + \"]\", e);\n }\n return result;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T08:51:07.377", "Id": "1853", "ParentId": "1839", "Score": "5" } }, { "body": "<p>Besides the things that others have already mentioned, I have a couple of things to say:</p>\n\n<ul>\n<li>Variable naming: <code>p</code> is way too short for a variable name. Consider <code>preStmt</code>, <code>stmt</code> or <code>statement</code> instead. (I commonly use <code>stmt</code> myself) Also, the name <code>_TABLE_NAME</code> does not adhere to the Java naming conventions. If it is a field in the class, then use lower case naming without an underscore at the beginning, like <code>tableName</code>.</li>\n<li>To make it more clear what you are doing (that you are not iterating over the ResultSet but only returning the first and only row), call <code>rs.first()</code> instead of <code>rs.next()</code>.</li>\n<li>Instead of first getting the column name from the meta data and then using <code>getString(columnName)</code>, there is a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getString%28int%29\" rel=\"nofollow noreferrer\">getString(int)</a> method that takes the column <strong>index</strong> as an argument. No need to get the column name when you know the column index.</li>\n<li>Your <code>PreparedStatement</code> variable should be declared inside the <code>try</code>, since it is not needed outside it. This also applies to your <code>String sql</code> variable.</li>\n</ul>\n\n<p>Other than these things, I agree with <a href=\"https://codereview.stackexchange.com/questions/1839/accessing-the-only-element-of-java-resultset/1853#1853\">StitzL's answer</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T17:26:18.897", "Id": "37606", "ParentId": "1839", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T04:32:55.177", "Id": "1839", "Score": "7", "Tags": [ "java", "sql", "jdbc" ], "Title": "Accessing the only element of Java ResultSet" }
1839
<p>From the section called <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-4.html" rel="nofollow">Nested Mappings</a></p> <blockquote> <p><strong>Exercise 2.40</strong></p> <p>Define a procedure unique-pairs that, given an integer <code>n</code>, generates the sequence of pairs (<code>i</code>,<code>j</code>) with <code>1 &lt; j &lt; i &lt; n</code>. Use unique-pairs to simplify the definition of prime-sum-pairs given above.</p> </blockquote> <p>I wrote the following:</p> <pre><code>(define (prime-sum-pairs n) (filter (lambda (seq) (prime? (+ (car seq) (cadr seq)))) (unique-pairs n))) (define (enumerate-integers start end) (if (&gt;= start end) (list end) (cons start (enumerate-integers (+ 1 start) end)))) (define (unique-pairs n) (flat-map (lambda (i) (map (lambda (j) (list i j)) (enumerate-integers 1 (- i 1)))) (enumerate-integers 2 n))) (define (filter test-fn seq) (if (null? seq) null (if (test-fn (car seq)) (cons (car seq) (filter test-fn (cdr seq))) (filter test-fn (cdr seq))))) (define (accumulate op initial seq) (if (null? seq) initial (op (car seq) (accumulate op initial (cdr seq))))) (define (flat-map f seq) (accumulate append null (map (lambda (x) (f x)) seq))) (define (prime? n) (= (smallest-divisor n) n)) (define (divisible? n i) (= 0 (remainder n i))) (define (square x) (* x x)) (define (smallest-divisor n) (define (rec i) (cond ((&gt; n (square i)) n) ((divisible? n i) i) (else (rec (+ 1 i))))) (rec 2)) </code></pre> <p>Can this be improved in any way?</p>
[]
[ { "body": "<p>Your code</p>\n\n<pre><code>(define (enumerate-integers start end)\n (if (&gt;= start end)\n (list end)\n (cons start (enumerate-integers (+ 1 start) end))))\n\n(define (unique-pairs n)\n (flat-map (lambda (i) \n (map (lambda (j) (list i j)) \n (enumerate-integers 1 (- i 1))))\n (enumerate-integers 2 n)))\n</code></pre>\n\n<p>looks fine to me. If you want to massage some details, you could rewrite enumerate-integers e.g. to:</p>\n\n<pre><code>(define (enumerate-integers start end)\n (if (&gt; start end) '()\n (cons start (enumerate-integers (+ 1 start) end))))\n</code></pre>\n\n<p>which is cleaner because you don't have (list end) as a special case, and you can correctly produce an empty list of integers if start > end.</p>\n\n<p>If you want to be even cleaner, you can do:</p>\n\n<pre><code>(define (enumerate-integers start end)\n (define (iter n)\n (if (&gt; n end) '()\n (cons n (iter (+ n 1)))))\n (iter start))\n</code></pre>\n\n<p>This is a good pattern in case of more complex procedures.</p>\n\n<p>Your flat-map is more complex than needed, your code:</p>\n\n<pre><code>(define (flat-map f seq)\n (accumulate append\n null\n (map (lambda (x) (f x)) seq)))\n</code></pre>\n\n<p>can be replaced with:</p>\n\n<pre><code>(define (flat-map f seq)\n (accumulate append\n null\n (map f seq)))\n</code></pre>\n\n<p>because (lambda (x) (f x)) is equal to f.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-15T01:35:05.850", "Id": "1891", "ParentId": "1841", "Score": "3" } } ]
{ "AcceptedAnswerId": "1891", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T06:06:33.690", "Id": "1841", "Score": "1", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Defining a unique-pairs procedure" }
1841
<p>How can I write this code better?</p> <pre><code>$cookieUrl = 'https://-------------/ps/scc/login.php'; $sessionUrl = 'https://-------------/ps/scc/php/check.php'; $balanceUrl = 'https://-------------/SCWWW/ACCOUNT_INFO'; $vars = "LOGIN={$this-&gt;login}&amp;PASSWORD={$this-&gt;password}"; $response = $this-&gt;_sendPostRequest($cookieUrl, '', null, 1); preg_match_all("/PHPSESSID.*;/isU", $response, $matches, PREG_PATTERN_ORDER); $phpsessid = $matches[0][0]; $response = $this-&gt;_sendPostRequest($sessionUrl, $vars, $phpsessid); preg_match_all("/&lt;SESSION_ID&gt;.*&lt;\/SESSION_ID&gt;/isU", $response, $matches, PREG_PATTERN_ORDER); $sessionId = strip_tags($matches[0][0]); $vars = "SESSION_ID={$sessionId}"; $response = $this-&gt;_sendPostRequest($balanceUrl, $vars); preg_match_all("/&lt;div class=\"balance_good td_def\"&gt;.*&lt;\/div&gt;/isU", $response, $matches, PREG_PATTERN_ORDER); if (count($matches[0]) == 0) { preg_match_all("/&lt;div class=\"balance_not_good td_def\"&gt;.*&lt;\/div&gt;/isU", $response, $matches, PREG_PATTERN_ORDER); } $this-&gt;balance = strip_tags($matches[0][0]); $this-&gt;updated = date(Settings_Constants::DATETIME_DATABASE_FORMAT); $this-&gt;save(); $this-&gt;balance; </code></pre>
[]
[ { "body": "<p>It is not perfect example, but your code might be like this:</p>\n\n<pre><code>function __construct()\n{\n//...\n $this-&gt;cookieUrl = 'https://-------------/ps/scc/login.php';\n $this-&gt;sessionUrl = 'https://-------------/ps/scc/php/check.php';\n $this-&gt;balanceUrl = 'https://-------------/SCWWW/ACCOUNT_INFO';\n//...\n}\n\nfunction loginToService()\n{\n $response = $this-&gt;_sendPostRequest($this-&gt;cookieUrl, '', null, 1);\n preg_match_all(\"/PHPSESSID.*;/isU\",\n $response, $matches, PREG_PATTERN_ORDER);\n $this-&gt;phpsessid = $matches[0][0];\n if (!this-&gt;phpsessid) {\n throw new Exception ('Could not retrieve PHP session id');\n }\n}\n\nfunction getServiceSessionId()\n{\n $vars = array(\n 'LOGIN' =&gt; $this-&gt;login, \n 'PASSWORD' =&gt; $this-&gt;password,\n );\n $response = $this-&gt;_sendPostRequest($this-&gt;sessionUrl, implode('&amp;', $vars), $this-&gt;phpsessid);\n preg_match_all(\"/&lt;SESSION_ID&gt;.*&lt;\\/SESSION_ID&gt;/isU\",\n $response, $matches, PREG_PATTERN_ORDER);\n $this-&gt;sessionId = strip_tags($matches[0][0]);\n if (!$this-&gt;sessionId) {\n throw new Exception ('Could not retrieve Service session id');\n }\n}\n\nfunction getBalanceMessage()\n{\n $vars = \"SESSION_ID={$sessionId}\";\n $response = $this-&gt;_sendPostRequest($balanceUrl, $vars);\n preg_match_all(\"/&lt;div class=\\\"balance_good td_def\\\"&gt;.*&lt;\\/div&gt;/isU\",\n $response, $matches, PREG_PATTERN_ORDER);\n if (count($matches[0]) == 0) {\n preg_match_all(\"/&lt;div class=\\\"balance_not_good td_def\\\"&gt;.*&lt;\\/div&gt;/isU\",\n $response, $matches, PREG_PATTERN_ORDER);\n }\n retrun strip_tags($matches[0][0]);\n}\n\n/* begin */\ntry {\n $this-&gt;loginToService();\n $this-&gt;getServiceSessionId();\n} catch Exception $e {\n return $e-&gt;getMessage();\n}\n$this-&gt;balance = $this-&gt;getBalanceMessage();;\n$this-&gt;updated = date(Settings_Constants::DATETIME_DATABASE_FORMAT);\n$this-&gt;save();\n$this-&gt;balance; //What the hell is this?\n/* end */\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T10:22:58.507", "Id": "1856", "ParentId": "1844", "Score": "3" } } ]
{ "AcceptedAnswerId": "1856", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T06:44:30.163", "Id": "1844", "Score": "4", "Tags": [ "php", "parsing" ], "Title": "Parse the phone balance from the operator site" }
1844
<blockquote> <p>Exercise 2.41. Write a procedure to find all ordered triples of distinct positive integers i, j, and k less than or equal to a given integer n that sum to a given integer s.</p> </blockquote> <pre><code>(define (enumerate-integers i j) (if (= i j) (list j) (cons i (enumerate-integers (+ i 1) j)))) (define (filter f seq) (if (null? seq) null (if (f (car seq)) (cons (car seq) (filter f (cdr seq))) (filter f (cdr seq))))) (define (remove x seq) (filter (if (pair? x) (lambda (y) (not (member y x))) (lambda (y) (not (= x y)))) seq)) (define (unique-triples-less-than n) (let ((the-number-list (enumerate-integers 1 (- n 1)))) (flatmap (lambda (i) (flatmap (lambda (j) (map (lambda (k) (list i j k)) (remove (list i j) the-number-list))) (remove i the-number-list))) (enumerate-integers 1 (- n 1))))) (define (flatmap f seq) (accumulate append null (map f seq))) (define (accumulate op initial seq) (if (null? seq) initial (op (car seq) (accumulate op initial (cdr seq))))) (define (s-sum-triples-below-n n s) (filter (lambda (y) (= (accumulate + 0 y) s)) (unique-triples-less-than n))) </code></pre> <p>Can this code be improved in any way?</p>
[]
[ { "body": "<p>Does this variant fit?</p>\n\n<pre><code>#lang racket\n(define (filtered-by-sum-triples s n)\n (filter (sum-equal? s)\n (unique-triples n)))\n\n(define (unique-triples n)\n (unique-sequences n 3))\n\n(define (unique-sequences n arity)\n (define (rec num arity tail)\n (if (= arity 1)\n (map (lambda (x) (cons x tail))\n (enumerate-interval 1 num))\n (flatmap (lambda (x) (rec (sub1 x) (sub1 arity) (cons x tail)))\n (enumerate-interval 1 num))))\n (rec n arity null))\n\n(define (sum-equal? s)\n (lambda (sequence)\n (= (foldr + 0 sequence) s)))\n\n(define (flatmap proc sequence) (foldr append null (map proc sequence)))\n\n(define (enumerate-interval low high)\n (if (&gt; low high)\n null\n (cons low (enumerate-interval (add1 low) high))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T08:09:24.590", "Id": "1849", "ParentId": "1845", "Score": "2" } }, { "body": "<p>Your unique-triples-less-than-n is unnecessarily complex because you can state it recursively. S. Kucherenko's answer tries to achieve this but is also unnecessarily complex. \nA simple recursive formulation is here, but this assumes that enumerate-integers returns an empty list if called with values from > to.</p>\n\n<pre><code> (define (unique-tuples m from to)\n (if (= n 0) '(())) ; one empty tuple\n (flatmap (lambda (n)\n (map (lambda (t) (cons n t))\n (unique-tuples (- m 1) (+ n 1) to)))\n (enumerate-integers from to))))\n</code></pre>\n\n<p>This unfolds as recursive calls e.g. like this:</p>\n\n<pre><code> (u-t 3 1 4) = (flatmap ... '(1 2 3 4))\n = (flatten '(,(map (lambda (t) (cons 1 t))\n (u-t 2 2 4))\n ,(map (lambda (t) (cons 2 t)) ;; X\n (u-t 2 3 4))\n ,(map (lambda (t) (cons 2 t))\n (u-t 2 4 4))\n ,(map (lambda (t) (cons 2 t))\n (u-t 2 5 4))))\n</code></pre>\n\n<p>and e.g. if you look at line marked with X, this takes recursively (unique-tuples 2 3 4), i.e. 2-tuples whose first integer is between 3 and 4, so the list is '((3 4)), and then for every element of that list, we add 2 at the beginning, so map returns '((2 3 4)).</p>\n\n<p>Then just</p>\n\n<pre><code>(define (unique-triples n) (unique-tuples 3 1 n))\n</code></pre>\n\n<p>The results need to be filtered afterwards for the sum.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-15T02:04:48.180", "Id": "1894", "ParentId": "1845", "Score": "3" } }, { "body": "<p>The way I understand it, the exercise asked for <strong>ordered</strong> triples, that meant:</p>\n\n<pre><code>(i, j, k) foreach 0 &lt; i &lt;= j &lt;= k &lt;= n\n</code></pre>\n\n<p>Therefore, you could use the <code>unique-pairs</code> procedure,<a href=\"https://codereview.stackexchange.com/questions/1841/scheme-sicp-ex-2-40-unique-pairs\">defined in the previous exercise</a>, to come up with something simple like this:</p>\n\n<pre><code>(flatmap\n (lambda (a)\n (map (lambda (b) (cons a b))\n (unique-pairs (- a 1))))\n(enumerate-interval 1 n))\n</code></pre>\n\n<p>If you don't want to modify your code, you could always filter away the results who aren't ordered, but that's just a waste of CPU cycles.</p>\n\n<p>Other than that, procedures like <code>filter</code> or <code>remove</code> are builtin procedures in the Scheme interpreter I'm using (MIT/GNU Scheme). I don't know if they're part of the standard, but in any case I don't feel you should have to redefine them every time you post an exercise solution :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-12T22:00:42.220", "Id": "11723", "ParentId": "1845", "Score": "1" } } ]
{ "AcceptedAnswerId": "1894", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T07:09:07.590", "Id": "1845", "Score": "8", "Tags": [ "lisp", "scheme", "sicp" ], "Title": "Find all distinct triples less than N that sum to S" }
1845
<p>I use VS 2008 and .NET 3.5</p> <p>I have this code using CustomChannelFactory and Proxy ServiceReference. I would like refactor using lambdas, Action, ...</p> <p>any suggestions ?</p> <pre><code>ServiceDependencias.IDependencias svcDependencias = null; public void Dependencias(List&lt;MfaFicheroForm&gt; listaFicherosFormXML, string entorno) { CustomChannelFactory&lt;ServiceDependencias.IDependencias&gt; customChannelFactory = null; if (!string.IsNullOrEmpty(FicheroConfiguracionWCFService) &amp;&amp; !string.IsNullOrEmpty(EndpointNameWCFService)) { if (!File.Exists(FicheroConfiguracionWCFService)) throw new FileNotFoundException("Fichero de configuración WCF no encontrado", FicheroConfiguracionWCFService); customChannelFactory = new CustomChannelFactory&lt;ServiceDependencias.IDependencias&gt;(EndpointNameWCFService, FicheroConfiguracionWCFService); var iDependencias = customChannelFactory.CreateChannel(); svcDependencias = iDependencias; } if (svcDependencias == null) { var depClient = new DependenciasClient(); svcDependencias = depClient; } GenerarDependenciasDeFormulariosFmb(listaFicherosFormXML, entorno); if (svcDependencias is DependenciasClient) { ((DependenciasClient)svcDependencias).Close(); return; } customChannelFactory.Close(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T20:30:39.857", "Id": "3166", "Score": "3", "body": "One of the reasons people normally program in english, is so more people can easily understand it ... e.g. like when doing a code review. ;p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-05T13:33:24.387", "Id": "195372", "Score": "0", "body": "As we all want to make our code more efficient or improve it in one way or another, try to write a title that summarizes what your code does, not what you want to get out of a review. For examples of good titles, check out [Best of Code Review 2014 - Best Question Title Category](http://meta.codereview.stackexchange.com/q/3883/23788) You may also want to read [How to get the best value out of Code Review - Asking Questions](http://meta.codereview.stackexchange.com/a/2438/41243)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-06T07:05:30.130", "Id": "195552", "Score": "0", "body": "I have rolled back the last edit. Please see *[what you may and may not do after receiving answers](http://meta.codereview.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>I don't know any Spanish so it was a bit difficult to understand exactly what was going on (I recommend you provide English translations/descriptions of non-English class names and string literals as comments next time).</p>\n\n<ul>\n<li><p>Why do you create a temporary variable that is only use to set another variable on the very next line instead of just setting it directly? (iDependencias &amp; depClient).</p></li>\n<li><p>You close the channel if it's a DependenciasClient but don't clear the reference to it. svcDependencias is visible outside this method and having it hold a reference to a closed connection may be a problem.</p></li>\n<li><p>You don't check to see if svcDependencias is already set before setting it to a new connection. I don't know if you can re-use the connection, but you should at least close the existing connection before you loose the reference to it.</p></li>\n<li><p>I noticed that you only close the channel factory if the channel is not a DependanciasClient. While this will probably work ok if the channel factory never returns a DependanciasClient, I think a null check would be a clearer solution.</p>\n\n<pre><code>if(customChanelFactory != null)\n{\n customChanelFactory.Close();\n}\n</code></pre></li>\n<li><p>Instead of using the 'is' operator followed by a cast, you should use the 'as' operator and check for null.</p>\n\n<pre><code>DependenciasClient client = svcDependencias as DependenciasClient;\n\nif (client != null)\n{\n client.Close();\n}\n</code></pre></li>\n<li><p>If svcDependencias only exists at the class level for the benefit of GenerarDependenciasDeFormulariosFmb then personally I would prefer to pass it in as an argument rather then use a class field.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-16T06:28:47.623", "Id": "1924", "ParentId": "1854", "Score": "3" } } ]
{ "AcceptedAnswerId": "1924", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T09:22:56.490", "Id": "1854", "Score": "3", "Tags": [ "c#", "proxy" ], "Title": "Refactor for using ChannelFactory" }
1854
<p>This might be a bit silly because there are like a thousand ways to do this, but I'm struggling to come up with one that I like. I feel like this should fit in one line, but I don't like re-using read_attribute(:length) lots and I don't like the below because it's not that clear.</p> <pre><code># returns a human-readable string in the format Xh Ym def length # length stored in seconds len = read_attribute(:length) "#{(len/60/60).floor}h #{len.modulo(60*60)/60}m" unless len.nil? end </code></pre>
[]
[ { "body": "<p>Assuming that len is an integer you won't need to use floor. You can do something like this</p>\n\n<pre><code>\"#{len/3600}h #{(len/60) % 60}m\" unless len.nil?\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T15:19:27.233", "Id": "1862", "ParentId": "1855", "Score": "2" } }, { "body": "<p>In one line</p>\n\n<pre><code>def length\n (len = read_attribute(:length)) &amp;&amp; \"#{(len/60/60).floor}h #{len.modulo(60*60)/60}m\"\nend\n</code></pre>\n\n<p>If <code>len == nil</code> return <code>nil</code>, if not - second operand</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T18:56:23.440", "Id": "1867", "ParentId": "1855", "Score": "6" } }, { "body": "<p>One-liners are nice, but sometimes it's better just to split lines. For example:</p>\n\n<pre><code>def length\n if (len = read_attribute(:length))\n \"#{(len/60/60).floor}h #{len.modulo(60*60)/60}m\" \n end\nend\n</code></pre>\n\n<p>If you really like compact code that deals with nil values, you can work with the idea of <code>maybe</code>'s <a href=\"http://ick.rubyforge.org/\" rel=\"nofollow\">ick</a>:</p>\n\n<pre><code>def length\n read_attribute(:length).maybe { |len| \"#{(len/60/60).floor}h #{len.modulo(60*60)/60}m\" }\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-23T22:13:04.210", "Id": "2055", "ParentId": "1855", "Score": "4" } } ]
{ "AcceptedAnswerId": "1867", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T09:44:37.840", "Id": "1855", "Score": "5", "Tags": [ "ruby", "datetime", "formatting", "null" ], "Title": "Formatting a possibly nil value as hours and minutes" }
1855
<p>I could use the function <code>Intersection</code>, but it returns a <strong>sorted</strong> list. That's why I have to do my own, but it looks too big. I hope it could be done shorter.</p> <pre><code>lists = {{1, 2, 3, 4, 5}, {1, 2, 3, 4}, {2, 3, 4, 5}}; Fold[ Function[ {a, b}, Select[b, MemberQ[a, #] &amp;] ], lists // First, lists // Rest] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-15T09:44:09.233", "Id": "3191", "Score": "0", "body": "what should be result of Intersect[{{1,2},{2,1}}] ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-17T10:55:57.983", "Id": "3233", "Score": "0", "body": "@ralu, in my case such incoming data is impossible. In my case the same pair of elements can't go in reversed order in another list - always in the same order. For example, possible `{5,7,6,3},{5,6,1,3}` but not `{5,7,6,3},{5,6,7,3}`." } ]
[ { "body": "<p>Most efficient and simple way for this is to sort each list before applying such algorithm. \nIn this case you do not need to check if each number is memeber of other list but you just pick first number and compare whit other elements from beginning.</p>\n\n<p>This is reason that Mathematica return sorted list. In case that each list is sorted complexity is O(N) where N is total number of all elements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-15T08:09:50.350", "Id": "3190", "Score": "0", "body": "Sure, but I'm gonna use this code 20-50 times in my life, for 5-10 lists each of 10-30 elements. So here no need of speed, here need of small size of code to read it next time faster." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T06:25:47.640", "Id": "1873", "ParentId": "1858", "Score": "0" } }, { "body": "<p>This function deletes from the first list all the elements not contained in the intersection, thus returning what you want:</p>\n\n<pre><code>f[l_List]:= DeleteCases[First@l, Except[Alternatives @@ (Intersection @@ l)]] \n\nf[{{1, 2, 3, 4, 5}, {1, 2, 3, 4}, {2, 3, 4, 5}}] \n-&gt;{2,3,4}\n\nf[{{5, 7, 6, 3}, {5, 6, 1, 3}}]\n-&gt;{5,6,3}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-28T18:47:34.947", "Id": "2149", "ParentId": "1858", "Score": "3" } }, { "body": "<p>Why use a reverse approach? Just do it directly!</p>\n\n<pre><code>Cases[First[list], Alternatives @@ Intersection @@ list]\n</code></pre>\n\n<p>If speed mattered, one could define a temporary \"tester\" function inside a <code>Module</code> to use in place of <code>MemberQ</code></p>\n\n<pre><code>Module[ {f},\n (f[#] = True)&amp; /@ (Intersection @@ list);\n Select[First[list], f]\n]\n</code></pre>\n\n<p>This is still fairly short.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T23:36:56.053", "Id": "2371", "ParentId": "1858", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T10:58:58.080", "Id": "1858", "Score": "5", "Tags": [ "wolfram-mathematica" ], "Title": "Lists' intersection keeping elements' order" }
1858
<pre><code>public final class Descriptors { public static final EnumValueDescriptor TIME_SETTING = new EnumValueDescriptor( R.string.pref_label_time_setting, Measures.TIME_SETTING_12, R.string.pref_time_setting_12, Measures.TIME_SETTING_24, R.string.pref_time_setting_24); public static final EnumValueDescriptor MEASURE_BG = new EnumValueDescriptor( R.string.pref_label_bg, Measures.BG_MMOL_L, R.string.measure_mmol_l, Measures.BG_MG_DL, R.string.measure_mg_dl); public static final EnumValueDescriptor MEASURE_СH = new EnumValueDescriptor( R.string.pref_label_ch, Measures.CH_G, R.string.measure_g, Measures.CH_EXCH, R.string.measure_exch); // Is there a better way to specify table data? public static final NumericValueDescriptor TBG_MMOL_L = new NumericValueDescriptor( R.string.pref_label_target_blood_glucose, ValueFormat.ONE_SIGNIFICANT_DIGIT, 0.0f, 40.0f, 0.1f, R.string.measure_mmol_l); public static final NumericValueDescriptor TBG_MG_DL = new NumericValueDescriptor( R.string.pref_label_target_blood_glucose, ValueFormat.INT, 0f, 300f, 1f, R.string.measure_mg_dl); public static final NumericValueDescriptor CF_MMOL_L_U = new NumericValueDescriptor( R.string.pref_label_correction_factor, ValueFormat.ONE_SIGNIFICANT_DIGIT, 0.1f, 99.0f, 0.1f, R.string.measure_mmol_l_u); public static final NumericValueDescriptor CF_MG_DL_U = new NumericValueDescriptor( R.string.pref_label_correction_factor, ValueFormat.INT, 1f, 99f, 1f, R.string.measure_mg_dl_u); public static final NumericValueDescriptor MF_G_U = new NumericValueDescriptor( R.string.pref_label_meal_factor, ValueFormat.ONE_SIGNIFICANT_DIGIT, 0.1f, 99.0f, 0.1f, R.string.measure_g_u); public static final NumericValueDescriptor MF_U_EXCH = new NumericValueDescriptor( R.string.pref_label_meal_factor, ValueFormat.INT, 1f, 99f, 1f, R.string.measure_u_exch); public static final int TYPE_TBG_MMOL_L = 0; public static final int TYPE_TBG_MG_DL = 1; public static final int TYPE_CF_MMOL_L_U = 2; public static final int TYPE_CF_MG_DL_U = 3; public static final int TYPE_MF_G_U = 4; public static final int TYPE_MF_U_EXCH = 5; // Actually this is mapping of TYPE_TBG_MMOL_L to an object, how better link constants above with objects? public static final NumericValueDescriptor[] NUMERIC_DESCRIPTORS = { TBG_MMOL_L, TBG_MG_DL, CF_MMOL_L_U, CF_MG_DL_U, MF_G_U, MF_U_EXCH }; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T18:34:43.723", "Id": "3162", "Score": "3", "body": "if would make our lives easier if you tell us what is your actual question" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-28T18:08:27.337", "Id": "58854", "Score": "0", "body": "First, ask yourself: do you really need a table data or can you solve it by applying some OOP principles like polymorphism? I have read the code and couldn't come to another conclusion." } ]
[ { "body": "<p>This class doesn't have any responsibilities, it just holds a group of static variables. It is unclear what the purpose of these variables are. I am sure there is a better way to achieve your goal as I doubt you actually need to be storing these details here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-17T13:06:53.360", "Id": "3235", "Score": "0", "body": "Exactly, it has no responsibilites... I need to specify such static (table) data, what is better approach to do it in Java? (Android application)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-17T19:44:53.600", "Id": "3239", "Score": "0", "body": "@Solvek, if this (whatever it is) really needs to be stored in variable, then put it in the class that uses it instead." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-16T13:00:53.260", "Id": "1925", "ParentId": "1859", "Score": "2" } } ]
{ "AcceptedAnswerId": "1925", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T13:34:23.077", "Id": "1859", "Score": "0", "Tags": [ "java", "android" ], "Title": "Specify table data in code, reference objects" }
1859
<p>In the similar vein as <a href="https://codereview.stackexchange.com/questions/836/is-toienumerablet-good-practice">ToIEnumerable</a> and <a href="https://stackoverflow.com/questions/1577822/passing-a-single-item-as-ienumerablet">FromSingleItem</a></p> <p>Is this a good improvement for making lists on the fly?</p> <pre><code>SyntaxSugar.ToIEnumerable("test1","test2","test3"); </code></pre> <p>vs.</p> <pre><code>new []{"test1","test2","test3"}; </code></pre> <p>Code: </p> <pre><code> public static class SyntaxSugar { public static IEnumerable&lt;T&gt; ToIEnumerable&lt;T&gt;(params T[] items) { return items; } } </code></pre> <p>not technically an extension to prevent T clutter</p> <p>Cons: </p> <ul> <li>longer codefragment</li> </ul> <p>Pros: </p> <ul> <li>more finger friendly- no [] or {}</li> <li>Encapsulates the collection away from being treated as an array.</li> </ul>
[]
[ { "body": "<p>As developers we're pretty used to where the keys for all kinds of brackets, braces and parenthesis are and while I agree you may save (a negligible amount of) twists and turns of the wrist, you're just substituting keystrokes for keystrokes, IMO.</p>\n\n<p>You've already made me (as a colleague) have to remember this exists, as opposed to what I know naturally within the language itself; I've no aversion to such a thing, obviously it is part of our job to build on things with the language, but only in cases where it is a concern - this really isn't a concern. Also, I now have to potentially type even more to get my list.</p>\n\n<p>Or is it a concern?..</p>\n\n<p>With all the other keystrokes required from <s>day-to-day</s> second-to-second that utilise modifier keys I think we can rule out the 'saving' this seems to want to achieve, when you look at it relatively.</p>\n\n<p>On the other hand, for the most part we use a powerful IDE (I pity you if this isn't the case), any modern IDE will give you many shortcuts for productivity (such as Visual Studio's snippet insertion, Intellisense and auto-completion) which means we don't need to create unique constructs for such trivial concerns. Sure, it also means your construct can be utilised just as quickly, but becomes redundant as it isn't necessarily quicker. The argument could then be put forth that using these tools stands to mitigate human error.</p>\n\n<p>And, what's wrong with an array? If you don't want something to be treated as an array, use a collection of different sorts. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T19:09:37.357", "Id": "3164", "Score": "0", "body": "sure knowing where the keys are is not the issue, it's the headache of moving from the homekeys and back (and the related thought process interruption) multiple times, in addition to non-homekey shift modified keystrokes, typing errors while trying to do these maneuvers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T19:29:14.403", "Id": "3165", "Score": "0", "body": "@Maslow I've updated my answer to further address keystrokes and and producivity [second last paragraph]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T21:07:44.970", "Id": "3168", "Score": "0", "body": "Thanks, I feel intellisense/autocomplete is superior to special symbols. I use interfaces (IList, IEnumerable,..) so I don't have to face `[]` often at all, resharper takes most of my `{}` typing out (or more than half with auto `(` and `{` closures. I am doing these building sets from none deals a lot and hating it each time. @use a collection of different sorts.. if this is a collection from individual items, all other solutions/types to get to `IEnumerable<T>` would have the same or uglier construction." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T22:16:01.013", "Id": "3170", "Score": "0", "body": "@Maslow I just think it's unnecessary - and it's only really my opinion. :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T16:39:42.080", "Id": "1864", "ParentId": "1863", "Score": "5" } }, { "body": "<p>I'd kind of put it in the \"marginally cool\" basket. Its cool the language can do this stuff, but there is no real need to do it and won't really make anything clearer (and the typing advantage is incredibly negligible in this case). I would tend not to do this kind of stuff and opt for more vanilla code mainly because anyone who strikes this code the first time will be forced to go look at how ToIEnumerable is implemented to check it doesn't do some weird magic. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T22:05:52.103", "Id": "1868", "ParentId": "1863", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-13T16:06:43.723", "Id": "1863", "Score": "5", "Tags": [ "c#" ], "Title": "Is ToEnumerable<T> for multiple items a good practice?" }
1863