body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have been writing PHP programs in the MVC pattern for quite some time. But I am not sure if I am doing it right.</p> <p>For instance, I have this PHP file that prints results in XML, and I put this file in 'model':</p> <pre><code>header("Content-Type: text/xml"); echo '&lt;?xml version="1.0" encoding="utf-8" standalone="yes" ?&gt; &lt;response&gt; '; # Set object property/ variable. $post = $connection-&gt;arrayToObject($_POST,$property_overloading = true); //print_r($post); # Assuming no error. $error = false; # Get the required field and put them in an array. $array_required = is_array($post-&gt;required)? $post-&gt;required : explode(' ',$post-&gt;required); # Get title if (!$post-&gt;title) { if(in_array('title', $array_required)) { $error = true; echo '&lt;error elementid="title" message="TITLE - Please entitle this album." /&gt;'; } } # Get description if ($post-&gt;description) { if(in_array('description', $array_required)) { $error = true; echo '&lt;error elementid="description" message="DESCRIPTION - Please enter something." /&gt;'; } } else { # Ceck if there is a line break, if the match is found, replace it with an empty space. if (preg_match("/\n/", $post-&gt;description)) { $post-&gt;description = preg_replace("/\n/is", " ", $post-&gt;description); } } # Get hide if(!$post-&gt;hide) $post-&gt;hide = 0; else $post-&gt;hide = 1; # Print general error message. if ($error) echo '&lt;errorgeneral message="Please amend the error above." /&gt;'; # check if no more errors if (!$error) { $sql = " UPDATE album SET title = ?, description = ?, hide = ? WHERE album_id = ? "; # use the instantiated db connection object from the initiator.php, to process the query. $result = $connection-&gt;executeSQL($sql,array( $post-&gt;title, $post-&gt;description, $post-&gt;hide, $post-&gt;album_id )); # Must convert all special characters to XML. # http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references echo '&lt;result message="Updated." itemid="'.$post-&gt;album_id.'" itemtitle="'.htmlspecialchars($post-&gt;title).'" itemdescription="'.htmlspecialchars($post-&gt;description).'" itemcategory="album"/&gt;'; } echo '&lt;/response&gt;'; </code></pre> <p>So, which part of it should be in the controller, and which should be in the model, helper, or view?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T17:13:13.307", "Id": "49454", "Score": "1", "body": "http://php.net/manual/en/book.simplexml.php - Avoid coding your own XML documents by hand: use an API." } ]
[ { "body": "<p>Ok, this might come across as blunt and hurtful, but it's meant to be helpful (code-review IMO should be harsh, <a href=\"https://codereview.meta.stackexchange.com/questions/810/guidelines-for-new-users-proposal-tag\">here's why</a>):</p>\n\n<p><em>\"I have been writing PHP programs in the MVC pattern for quite some time\"</em><br/>\nNo, you haven't. Really. M-V-C stands for, as you well know: Model-View-Controller. The code you pasted just strings all three together in one single script. That's spaghetti-code (at best), not framework-like MVC code. Not even close.</p>\n\n<p><em>\"I have this PHP file that prints a result in XML, and I put this file in 'model'\"</em><br/>\nAgain: any file that generates output belongs in the <em>view</em>. As the name suggests, anything that is sent to the client (ie the client gets to <em>\"see\"</em>), is part of the clients <em>view</em> of your application. You really should read up on MVC, to find out what belongs where. (there's a link at bottom of my answer)</p>\n\n<hr>\n\n<p>At the top, you set your header, then you process the request (without checking if there has been a POST request). Setting the headers as soon as possible (before anything has been sent to the client) is understandable. But in the context of the MVC pattern, it shouldn't really matter. In fact, it's one of the great things about the real MVC pattern: inside your controller and model layer, you're absolutely sure the headers haven't been sent yet, because the view is only generated (and sent to the client) at the very end of the request. <br/>\nSo, as your app sets about processing the request, and you hit a point where the client should be redirected, you can do so, almost blindly. Safe in the knowledge that the headers aren't sent yet. That's why MVC is so successful, and why redirects are mostly found in the controller. To clarify, look at this very simple graph (from cakePHP site, but it applies to MVC in general):</p>\n\n<p><a href=\"https://i.stack.imgur.com/CKvza.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CKvza.png\" alt=\"Simple MVC chart\"></a><br>\n<sub>(source: <a href=\"https://book.cakephp.org/2.0/en/_images/basic_mvc.png\" rel=\"nofollow noreferrer\">cakephp.org</a>)</sub> </p>\n\n<p>Here you see the flow of an MVC webapp:</p>\n\n<ol>\n<li>The client interacts with the view, and a request is sent to the server.</li>\n<li>The dispatcher receives teh request and does some initial processing. Based on this request, the dispatcher deceides which controller needs to be constructed, and which method needs to be called to set things in motion</li>\n<li>The controller can do some more checks, to make sure the request is valid. If this is not the case the Model layer is left alone, and the client is redirected. Back over to the dispatcher, (2). This step should be uncommon (as it only occurs when something isn't quite right.<br/>\nNormally, the inital processing on the request data consists mainly of pouring the data into objects, and deciding what the Model layer needs to do with them.</li>\n<li>The model layer receives data from the controller and takes over. Here's where you'll find the actual logic. DB connections, computation, ... it's all contained here (which is why this is also referred to as the business layer). The data provided by the controller can be broken down more (checked/processed), used in queries etc... The result is returned to the controller. Note that the model layer does not communicate with the view in any way!</li>\n<li>The controller checks what the Model-layer returned. This can either be data, needed to build a new view, or an object/string saying the data turned out to be invalid/insufficient or nothing at all. Whatever it is, the controller can decide to redirect (back to step 1), call the model again (back to 3) or moving on: build the view, passing the data it received from the Model-layer.</li>\n<li>Finally, we can start building the view. The controller passes the data it received from the model layer and the View takes over. It isn't untill we've reached <em>this</em> step that the headers are set. During steps 1 through 4, the headers are nowhere near being set, but at this point, it's too late to go back.\n<br/>That's why the view is a simple script, containing markup and simple PHP (some loops, some <code>if</code>'s and the occasional <code>switch</code>). A view contains <em>no logic at all!</em>.</li>\n<li>Finally, the resulting page (view) is sent to the client. Job done.</li>\n</ol>\n\n<p>I hope this makes a few things clear, but now<Br/>\nMoving on:</p>\n\n<pre><code>$connection-&gt;arrayToObject($_POST,$property_overloading = true);\n</code></pre>\n\n<p><code>$property_overloading = true</code>? why not pass <code>true</code>? now you have a global variable that is just sitting there. <code>$connection</code>, as I gather from the query at the bottom of your code, is a DB class. What is it doing processing your POST parameters? That's not it's job. That's a gross violation of the Single Responsability Principle. Don't. Just Don't!<br/>\n<em>SRP</em> states that an object/class should have one and only one task (reason to change): processing POST params <em>and</em> connecting to the DB are <em>2 distinct tasks.</em></p>\n\n<p>Following that, you check a series of parameters that <em>may or may not</em> be set, and sanitize them one by one. I mean: really! you're using an object, clearly that object should take care of sanitizing the data, and, using getters, you could just do something like this</p>\n\n<pre><code>$post-&gt;get('hide', false);\n//with getter in Post class:\npublic function get($param, $defaultValue = null)\n{\n if (!isset($this-&gt;data[$param]))\n {//not set, return default\n return $defaultValue;\n }\n return $this-&gt;data[$param];\n}\n</code></pre>\n\n<p>The same applies to setters, only the setter <em>sanitizes the data</em>.<br/>\nThough at this point, you have bigger fish to fry: don't do things like</p>\n\n<pre><code>if (preg_match(\"/\\n/\", $post-&gt;description))\n{\n $post-&gt;description = preg_replace(\"/\\n/is\", \" \", $post-&gt;description);\n}\n</code></pre>\n\n<p>In the <code>if</code> experession, you're using a regular expression, only to then use <em>another regex</em> to remove the unwanted chars. Either do:</p>\n\n<pre><code>public function setDescription($desc)\n{//in object, of course\n $this-&gt;description = preg_replace('/\\n/',' ',$desc);\n return $this;\n}\n//or:\n$this-&gt;description = implode(' ', explode(PHP_EOL, $desc));\n</code></pre>\n\n<p>If the string doesn't contain any new-lines, it's not going to be changed! Why bother checking?</p>\n\n<p>Next, you're echo-ing all over the place, to which I can only say: don't. as Dave Jarvis says <a href=\"http://php.net/manual/en/book.simplexml.php\" rel=\"nofollow noreferrer\">use an API like simplexml</a>.</p>\n\n<p>Stringing a query at the end and executing it, depending on what <code>$error</code> hold (is it a global??) is just <em>terrible</em> By the time you're generating output, you should have all your data ready set, good to go. Building the response/view should be a formality. That's why a view should <em>not</em> contain any logic. All data has been fetched and structured accordingly.</p>\n\n<hr>\n\n<p>To answer your question (on which part should go where):</p>\n\n<p>processing the request is usually done in the Routing objects, and the processed request is then used to create/and pass to the (front)controller. The controller passes the bits and pieces of the request to the model-<em>LAYER</em> (services, helpers, data-models), which is where all the logic is kept. The controller then receives the results from the model-layer, and passes it on to the view, which (through a series of loops and if's) generates the output.</p>\n\n<p>If any of this is still a bit merky, <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">refer to the MVC wiki</a> or ask for more details.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T12:44:52.060", "Id": "49513", "Score": "0", "body": "Fair and balanced, +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T12:53:12.463", "Id": "49514", "Score": "0", "body": "@tomdemuyt: I hope I was more fair and balanced than some of the things I've seen on Fox, though :-P, but thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T04:48:36.550", "Id": "49820", "Score": "0", "body": "Thanks Elias for the answer! I have made another post/ question to implement MVC to my existing code, would you like to take a look? http://codereview.stackexchange.com/questions/31301/php-mvc-how-to-do-post-the-right-way" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-09-11T08:57:35.913", "Id": "31085", "ParentId": "31035", "Score": "4" } } ]
{ "AcceptedAnswerId": "31085", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T04:51:21.587", "Id": "31035", "Score": "2", "Tags": [ "php", "object-oriented", "mvc", "xml", "php5" ], "Title": "Printing results in XML" }
31035
<p>I want to optimize the following code:</p> <pre><code>#ifdef USE_SSE #define STRING_PREFETCH_TBL(ptr) \ _mm_prefetch(ptr, _MM_HINT_T0); \ _mm_prefetch(ptr+64, _MM_HINT_T0); \ _mm_prefetch(ptr+128, _MM_HINT_T0); \ _mm_prefetch(ptr+192, _MM_HINT_T0) #else #define STRING_PREFETCH_TBL(ptr) #endif __declspec(align(128)) const char TblToLower[] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34, 35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,97,98, 99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,91, 92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118, 119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169, 170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196, 197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224, 225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, }; void StrToLowerCase( const char* src, char* dst ) { STRING_PREFETCH_TBL(TblToLower); while(*src) { *dst = TblToLower[*src]; dst++; src++; } *dst = '\0'; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T09:59:13.683", "Id": "49408", "Score": "3", "body": "Note that your `StrToLowerCase` function is not Unicode-enabled, and it only handles English letters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T17:24:47.503", "Id": "49457", "Score": "0", "body": "Have you measured this against the standard C provided ::tolower()?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T17:26:39.883", "Id": "49458", "Score": "2", "body": "PS. This is a C question. Nothing about this kind of code is C++ like." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T21:51:43.787", "Id": "49469", "Score": "0", "body": "Does `_mm_prefetch()` stall the processor or does it then allow subsequent instructions to continue in the anticipation that memory subsystem has already started the pre-fetch?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T21:57:49.530", "Id": "49472", "Score": "0", "body": "Why not call prefetch on the source and the destination especially on lines longer than a cache line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T10:39:13.400", "Id": "51984", "Score": "1", "body": "For ASCII you only need 0 .. 127." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T10:48:56.970", "Id": "51985", "Score": "4", "body": "Have you tried profiling it against an implementation like `char c=*src++; *dst++ = (92>c && 64<c)? c|32 :c` which is more complicated, but fits in any cpu-cache and does not need to load an array from the ram or access it there?" } ]
[ { "body": "<p>This is what Visual Studio 2012 with <code>/O2</code> generated for me without SSE support:</p>\n\n<pre><code>_StrToLowerCase:\n 00000000: 8B 54 24 04 mov edx,dword ptr [esp+4]\n 00000004: 8B 44 24 08 mov eax,dword ptr [esp+8]\n 00000008: 8A 0A mov cl,byte ptr [edx]\n 0000000A: 84 C9 test cl,cl\n 0000000C: 74 19 je 00000027\n 0000000E: 2B D0 sub edx,eax\n 00000010: 0F BE C9 movsx ecx,cl\n 00000013: 8D 40 01 lea eax,[eax+1]\n 00000016: 0F B6 89 00 00 00 movzx ecx,byte ptr _TblToLower[ecx]\n 00\n 0000001D: 88 48 FF mov byte ptr [eax-1],cl\n 00000020: 8A 0C 02 mov cl,byte ptr [edx+eax]\n 00000023: 84 C9 test cl,cl\n 00000025: 75 E9 jne 00000010\n 00000027: C6 00 00 mov byte ptr [eax],0\n 0000002A: C3 ret\n</code></pre>\n\n<p>...and this is with SSE:</p>\n\n<pre><code>_StrToLowerCase:\n 00000000: 8B 54 24 04 mov edx,dword ptr [esp+4]\n 00000004: B8 00 00 00 00 mov eax,offset _TblToLower\n 00000009: 8A 0A mov cl,byte ptr [edx]\n 0000000B: 0F 18 08 prefetcht0 [eax]\n 0000000E: B8 40 00 00 00 mov eax,offset _TblToLower+40h\n 00000013: 0F 18 08 prefetcht0 [eax]\n 00000016: B8 80 00 00 00 mov eax,offset _TblToLower+80h\n 0000001B: 0F 18 08 prefetcht0 [eax]\n 0000001E: B8 C0 00 00 00 mov eax,offset _TblToLower+0C0h\n 00000023: 0F 18 08 prefetcht0 [eax]\n 00000026: 8B 44 24 08 mov eax,dword ptr [esp+8]\n 0000002A: 84 C9 test cl,cl\n 0000002C: 74 19 je 00000047\n 0000002E: 2B D0 sub edx,eax\n 00000030: 0F BE C9 movsx ecx,cl\n 00000033: 8D 40 01 lea eax,[eax+1]\n 00000036: 0F B6 89 00 00 00 movzx ecx,byte ptr _TblToLower[ecx]\n 00\n 0000003D: 88 48 FF mov byte ptr [eax-1],cl\n 00000040: 8A 0C 02 mov cl,byte ptr [edx+eax]\n 00000043: 84 C9 test cl,cl\n 00000045: 75 E9 jne 00000030\n 00000047: C6 00 00 mov byte ptr [eax],0\n 0000004A: C3 ret\n</code></pre>\n\n<p>It looks pretty much optimal to me already. So I'd try:</p>\n\n<ol>\n<li>Inlining the function to avoid the overhead of the function call</li>\n<li>Study the input strings given to the function; if you find that you have many reoccurring strings (and long ones), you may want to consider caching the results.</li>\n</ol>\n\n<p>As a bottom note, I'd probably write the main loop of the function as</p>\n\n<pre><code>while ( *src ) *dst++ = TblToLower[*src++];\n</code></pre>\n\n<p>..and declare the <code>TblToLower</code> table as a <code>static</code> inside of the function to improve (read: reduce) the scope of visibility. Maybe this even improves cache locality?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T21:52:55.933", "Id": "49471", "Score": "0", "body": "If you are going to optimize into a single line why not just: `while(*dst++ = TblToLower[*src++]){}`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T07:10:15.590", "Id": "49490", "Score": "0", "body": "@LokiAstari: Because I don't like assignments in conditionals." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T10:04:31.080", "Id": "31042", "ParentId": "31036", "Score": "2" } }, { "body": "<p>As far as optimizing the tolower logic itself for a single ASCII character, your table is about as fast as it gets.</p>\n\n<p>Alternatives would be:<br>\n A) the standard tolower function<br>\n B) this bit trick if you have only ASCII alpha characters </p>\n\n<pre><code>(unsigned char)((c) | (unsigned char)0x20) \n</code></pre>\n\n<p>C) this bit trick for all ASCII characters </p>\n\n<pre><code>// set the most significant bit in value X if greater than or equal to 'A'\n// set the most significant bit in value Y if less than or equal to 'Z'\n// bitwise AND X and Y to determine if both are true and mask out all other bits\n// shift the set bit into the 0x20 place and bitwise OR in the bit\n(unsigned char)(((((unsigned char)0x40 - (c)) &amp; ((c) - (unsigned char)0x5b) &amp; (unsigned char)0x80) &gt;&gt; 2) | (c))\n</code></pre>\n\n<p>I ran 300 iterations on a pre-generated random string of one-billion bytes (including the null terminator) of some x64 code under full optimization and no debugger attached from Visual Studio 2013.</p>\n\n<ul>\n<li>your table lookup took about 22.4 seconds</li>\n<li>alternative A took about 106.0 seconds (the call was not inlined)</li>\n<li>alternative B took about 15.1 seconds (but it only works for strings only containing letters)</li>\n<li>alternative C took about 31.9 seconds (so the table beats the bit tricks)</li>\n</ul>\n\n<p>For whatever it's worth, replacing the tolower logic with a NOP and simply copying the source string took 15.0 seconds, so that's what's being spent in loop overhead.</p>\n\n<p><strong>But no matter, your real opportunity for optimization here is in vectorization and parallelization.</strong></p>\n\n<p>However this cannot happen as the signature and contract to the <code>StrToLowerCase</code> function exists now. This is for two reasons:</p>\n\n<ol>\n<li>Any vectorized instructions will need to access data in larger chunks than one byte, and reading (and writing) past the null is bad if you don't know the arrays are padded out the appropriate amount.</li>\n<li>You don't know the length of the string without doing a byte-by-byte scan for the null terminator. So you can't break the string into chunks easily and spin off threads to process separate chunks, and you're going to have to check for the null terminator in the middle of vectorized code (if you go that route), and you will lose much of if not all of what you gain.</li>\n</ol>\n\n<p>So, for the sake of moving forward. Let's assume our signature now looks like this:<br>\n<code>void StrToLowerCase(const char *src, char *dst, unsigned len)</code><br>\nwhere for the sake simplicity, <code>len</code> is however many chunks of data the function must process whatever its size may be for the given implementation.</p>\n\n<p><strong>Lets explore vectorized approaches:</strong></p>\n\n<p>If you have a processor that supports AVX2 instructions, then you can use the VGATHERDPS instruction which performs 8 vectorized lookups. However I don't have this instruction so I couldn't try it out. In fact few CPUs will since it first showed up in 2013. So moving on...</p>\n\n<p>Almost everyone has SSE2 now days, and luckily the above bit trick can be vectorized with SSE2. Here is an implementation that operates on 128-bit chunks:</p>\n\n<pre><code>__forceinline void StrToLowerCaseSSE2(const char *src, char *dst, unsigned len)\n{\n __m128i const *src128 = (__m128i const*)src;\n __m128i *dst128 = (__m128i*)dst;\n while (len--)\n {\n __m128i const c16 = _mm_load_si128(src128++);\n __m128i const abv = _mm_sub_epi8(_mm_set_epi32(0x40404040, 0x40404040, 0x40404040, 0x40404040), c16);\n __m128i const blw = _mm_sub_epi8(c16, _mm_set_epi32(0x5B5B5B5B, 0x5B5B5B5B, 0x5B5B5B5B, 0x5B5B5B5B));\n __m128i msk = _mm_and_si128(abv, blw);\n msk = _mm_and_si128(msk, _mm_set_epi32(0x80808080, 0x80808080, 0x80808080, 0x80808080));\n msk = _mm_srli_epi16(msk, 2);\n msk = _mm_or_si128(msk, c16);\n _mm_store_si128(dst128++, msk);\n }\n}\n</code></pre>\n\n<p>The above SSE2 implementation finishes the test in just 5.3 seconds, roughly 4.5 times faster than the table lookup code that was previously that fastest. However, keep in mind some of this is in the loop overhead we eliminated by effectively unrolling the loop 16 times (each iteration of the SSE2 loop lower-cases 16 ASCII chars). If we unroll the loop 16 times for the lookup code, it finishes in 15.3 seconds. So loop overhead aside, the SSE2 implementation is about 3 times faster. Furthermore, if we employee the alpha-character only tolower in the unrolled loop it finishes in 8.9 seconds, and the SSE2 code that handles non-alpha ASCII characters as well as extended ASCII (codes greater than 127) is still faster.</p>\n\n<p>The SSE2 implementation will be the fastest presented here, but lets say you don't want to use SSE2, you have 64-bit support, and you only have standard ASCII in the range [0, 127] and not extended ASCII in the range [0, 255] (the most significant bit is always zero). In that case you can use a 64-bit vectorized approach that hijacks the 64-valued bit in the same way the above bit trick operations hijack the 128-valued bit. The subtractions can be done on 8 characters shoved into a 64-bit integer, but the trick will be ensuring carries and borrows don't escape the byte you're working in. This can be done by keeping in mind the 128-valued bit in every byte will be zero. Here is the 64-bit implementation where <code>len</code> is the number of 64-bit chunks:</p>\n\n<pre><code> __forceinline void StrToLowerCase64(const char *src, char *dst, unsigned len)\n{\n unsigned const __int64 *src64 = (unsigned const __int64 *)src;\n unsigned __int64 *dst64 = (unsigned __int64 *)dst;\n while (len--)\n {\n unsigned const __int64 x = *src64++;\n *dst64++ = (((0xC0C0C0C0C0C0C0C0 - x) &amp; (x + 0x2525252525252525) &amp; 0x4040404040404040) &gt;&gt; 1) | x;\n }\n}\n</code></pre>\n\n<p>The above 64-bit implementation finishes the test in 6.3 seconds, and is almost as fast as the 128-bit SSE2 implementation that finished in 5.3 seconds.</p>\n\n<p><strong>Whats next?</strong></p>\n\n<p>From here one can adapt these tricks to higher bit-width vectorization instructions so long as one can be confident the target platform has them available.</p>\n\n<p>There are two other places to go with this that will certainly give even better performance if the strings or number of string to process are large enough. One, is breaking this up into threads either within the function or in the functions that call this function. The other is to resort to offloading the task to the GPU or other more drastic hardware solutions.</p>\n\n<p><strong>EDIT</strong>\nHere is an SSE2 approach adapted to work with the null terminator. The input still needs to be 128-bit aligned, but special logic could easily be added to the function to handle that. It finishes in 5.8 seconds, so it's only marginally slower than the version that does not perform a null check which finished in 5.3 seconds.</p>\n\n<pre><code>__forceinline void StrToLowerCaseSSE(const char* src, char* dst)\n{\n __m128i const *src128 = (__m128i const*)src;\n __m128i *dst128 = (__m128i*)dst;\n for (;;)\n {\n __m128i const c16 = _mm_load_si128(src128);\n __m128i const null = _mm_cmpeq_epi8(c16, _mm_set_epi32(0, 0, 0, 0));\n if (_mm_movemask_epi8(null))\n break;\n ++src128;\n __m128i const abv = _mm_sub_epi8(_mm_set_epi32(0x40404040, 0x40404040, 0x40404040, 0x40404040), c16);\n __m128i const blw = _mm_sub_epi8(c16, _mm_set_epi32(0x5B5B5B5B, 0x5B5B5B5B, 0x5B5B5B5B, 0x5B5B5B5B));\n __m128i msk = _mm_and_si128(abv, blw);\n msk = _mm_and_si128(msk, _mm_set_epi32(0x80808080, 0x80808080, 0x80808080, 0x80808080));\n msk = _mm_srli_epi16(msk, 2);\n msk = _mm_or_si128(msk, c16);\n _mm_store_si128(dst128++, msk);\n }\n src = (const char*)src128;\n dst = (char*)dst128;\n while (*src)\n {\n const unsigned char c = *src++;\n *dst++ = (unsigned char)(((((unsigned char)0x40 - (c)) &amp; ((c)-(unsigned char)0x5b) &amp; (unsigned char)0x80) &gt;&gt; 2) | (c));\n }\n *dst = '\\0';\n}\n</code></pre>\n\n<p>And here is similar null check adaptation of the 64-bit code. It finishes in 6.4 seconds where the original 64-bit version took 6.3.</p>\n\n<pre><code>__forceinline void StrToLowerCase64(const char* src, char* dst)\n{\n unsigned const __int64 *src64 = (unsigned const __int64 *)src;\n unsigned __int64 *dst64 = (unsigned __int64 *)dst;\n for (;;)\n {\n const unsigned __int64 x = *src64;\n if ((x - 0x0101010101010101) &amp; 0x8080808080808080)\n break;\n ++src64;\n *dst64++ = (((0xC0C0C0C0C0C0C0C0 - x) &amp; (x + 0x2525252525252525) &amp; 0x4040404040404040) &gt;&gt; 1) | x;\n }\n src = (const char*)src64;\n dst = (char*)dst64;\n while (*src) {\n const unsigned char x = *src++;\n *dst++ = (unsigned char)(((((unsigned char)0x40 - (x)) &amp; ((x)-(unsigned char)0x5b) &amp; (unsigned char)0x80) &gt;&gt; 2) | (x));\n }\n *dst = '\\0';\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-29T08:10:31.907", "Id": "38263", "ParentId": "31036", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T06:49:16.977", "Id": "31036", "Score": "4", "Tags": [ "optimization", "c", "performance", "strings" ], "Title": "Fastest StringToLowerCase()" }
31036
<p>I need a valid and semantic HTML structure for the user-account (user-panel) section of the overall layout of my web application. </p> <p>What I saw in other web apps include:</p> <ol> <li>User title (or email, or username)</li> <li>A thumbnail (on which you can click to change your picture)</li> <li>A notifications icon (with the number of notifications in red)</li> <li>An arrow besides the whole area (which shows a menu to have further options for your user account settings)</li> </ol> <p>Here is the HTML I've come up with:</p> <pre><code>&lt;section id="user-account"&gt; &lt;span class="title"&gt;Saeed Neamati&lt;/span&gt; &lt;figure&gt; &lt;figcaption&gt;Current User&lt;/figcaption&gt; &lt;a href="#"&gt; &lt;img src="#" /&gt; &lt;/a&gt; &lt;/figure&gt; &lt;div class="notifications"&gt; &lt;span class="number"&gt;2&lt;/span&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;First Notification&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Second Notification&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;ul class="menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Change your password&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Subscription settings&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Payments&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/section&gt; </code></pre>
[]
[ { "body": "<p>\"Saeed Neamati\" should probably be the heading (<code>h1</code>) of the section (instead of <code>span</code>).</p>\n\n<p>Don’t forget the <code>alt</code> attribute for the <code>img</code>.</p>\n\n<p>The <code>.notifications</code> should be a sectioning element, probably <code>section</code>, maybe <code>aside</code>. Then the notification count could be the heading.</p>\n\n<p>The <code>.menu</code> should be enclosed by a <code>nav</code>, as it’s the navigation for that section.</p>\n\n<p>Result:</p>\n\n<pre><code>&lt;section id=\"user-account\"&gt;\n &lt;h1 class=\"title\"&gt;Saeed Neamati&lt;/h1&gt;\n &lt;figure&gt;\n &lt;figcaption&gt;Current User&lt;/figcaption&gt;\n &lt;a href=\"#\"&gt;\n &lt;img src=\"#\" alt=\"\" /&gt;\n &lt;/a&gt;\n &lt;/figure&gt;\n &lt;section class=\"notifications\"&gt;\n &lt;h1 class=\"number\"&gt;2&lt;/h1&gt; &lt;!-- maybe add \" notifications\" --&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;First Notification&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Second Notification&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/section&gt;\n &lt;nav&gt;\n &lt;ul class=\"menu\"&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Change your password&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Subscription settings&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Payments&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;nav&gt;\n&lt;/section&gt;\n</code></pre>\n\n<p>Depending on your implementation, the <code>.menu</code> resp. the <code>.notifications</code> may be the main content for that <code>section</code>. In that case, the corresponding sectioning element should be removed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T07:36:31.533", "Id": "31082", "ParentId": "31038", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T07:23:17.830", "Id": "31038", "Score": "3", "Tags": [ "html", "html5" ], "Title": "Optimizations for this user-account HTML structure?" }
31038
<p>What this should do is wait for <code>dataBlockSize</code> bytes to be ready and then continue, but wait for 10ms if they are not ready yet to not block the CPU, but not the first time as I do not want to wait once even if the bytes are ready.</p> <p>Is there a better way of doing this?</p> <pre><code>while (!cancellationToken.IsCancellationRequested) { var ftdiStatus = ftdiDevice.GetRxBytesWaiting(ref rxBytes); if (ftdiStatus != FTDI.FT_STATUS.FT_OK) return null; if (rxBytes &gt;= dataBlockSize) break; Thread.Sleep(10); } </code></pre>
[]
[ { "body": "<p>I think it is just a matter of taste. Here is one approach:</p>\n\n<pre><code>do\n{\n var ftdiStatus = FtdiDevice.FtdiDevice.Instance.GetRxBytesWaiting(ref rxBytes);\n\n if (ftdiStatus != FTDI.FT_STATUS.FT_OK)\n return null;\n\n if(rxBytes &gt;= dataBlockSize)\n break;\n\n Thread.Sleep(10);\n}\nwhile (true); // Perhaps a check for timeout?\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T13:10:18.493", "Id": "49432", "Score": "0", "body": "This method is very similar to what I use when I get data back from my ftdi devices. I think it looks good and is easy to read." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T10:54:27.533", "Id": "31046", "ParentId": "31040", "Score": "3" } }, { "body": "<p>I think its better to use <code>ManualResetEvent</code>. This way your thread will wake up on cancellation instead of sleeping for 10 ms.</p>\n\n<pre><code>do\n{ \n var ftdiStatus = ftdiDevice.GetRxBytesWaiting(ref rxBytes);\n if (ftdiStatus != FTDI.FT_STATUS.FT_OK)\n return null;\n\n if (rxBytes &gt;= dataBlockSize)\n break;\n}\nwhile (!cancelEvent.WaitOne(10));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T05:42:27.783", "Id": "31079", "ParentId": "31040", "Score": "1" } } ]
{ "AcceptedAnswerId": "31046", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T09:21:14.607", "Id": "31040", "Score": "4", "Tags": [ "c#", "multithreading" ], "Title": "Waiting for bytes to be ready" }
31040
<pre><code>int count; int gcdCount; int testCase = 5; while (testCase &gt; 0) { int n = 5; count = 0; gcdCount = 0; // to get two random numbers a and b a&lt;=n and b&lt;=n //get probablity of gcd(a,b) ==b for (int i = 1; i &lt;= n; i++) { for (int j = 1; j &lt;= n; j++) { count++; // check if gcd(i,j) is equal to second number j if (findgcd(i, j) == j) { gcdCount++; } } } //return probability of gcdcount System.out.println(gcdCount + "/" + count); testCase--; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T11:17:30.517", "Id": "49416", "Score": "1", "body": "Can you fix the formatting of the code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T12:27:11.887", "Id": "49427", "Score": "1", "body": "I'd recommend the [Euclidean algorithm](http://www.math.rutgers.edu/~greenfie/gs2004/euclid.html) for solving this problem as it's more efficient and probably clearer. You're using nested for-loops, giving you an easy O(n^2) (not a good thing)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T12:31:34.583", "Id": "49429", "Score": "0", "body": "Yes i wanted to optimize the inner for loop as it takes O(n^2) time the gcd part is not a problem i have calculated the gcd using Euclidean Algorithm in findgcd method" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T12:34:43.793", "Id": "49430", "Score": "0", "body": "Right, and that algorithm should help. There's some pseudocode on the [Wikipedia page](http://en.wikipedia.org/wiki/Euclidean_algorithm), too." } ]
[ { "body": "<p>You do not need to increment \"count\" variable in every loop. The value of it depends on \"n\".</p>\n\n<p>Here you can find some ways to optimize a loop:\n<a href=\"http://en.wikipedia.org/wiki/Loop_optimization\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Loop_optimization</a></p>\n\n<p>What is the difference between the test cases? For me it seems nothing change; you always run the same double for-loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T11:09:14.260", "Id": "31048", "ParentId": "31044", "Score": "-1" } }, { "body": "<p>Assuming that <code>findgcd</code> is correctly implemented and that <code>i</code> and <code>j</code> are guaranteed to both be non-negative, <code>findgcd(i, j) == j</code> is equivalent to <code>j != 0 &amp;&amp; i % j == 0</code>. That allows a further optimisation to a single loop, because the number of values in <code>1..n</code> which are divisible by <code>j</code> is <code>floor(n/j)</code>:</p>\n\n<pre><code>for (int j = 1; j &lt;= n; j++)\n{\n count += n;\n gcdCount += n / j;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T13:36:23.053", "Id": "49442", "Score": "0", "body": "I did'nt get get it how can you optimize it to one loop" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T12:58:26.050", "Id": "31053", "ParentId": "31044", "Score": "1" } } ]
{ "AcceptedAnswerId": "31053", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T10:48:30.543", "Id": "31044", "Score": "2", "Tags": [ "java", "optimization", "algorithm", "performance" ], "Title": "How can I optimize this code that finds the GCD?" }
31044
<p>Can I create a method to do work with these five sections? I'm doing binding operations so many times. Do you have an idea on how to make this code prettier? </p> <ul> <li><code>ddlModelValue</code> -> ASP.NET <code>DropDownList</code></li> </ul> <p></p> <pre><code>var dtModel = Session[SystemConstant.ModelSessionKey] as DataTable; ddlModelValue.DataSource = dtModel; ddlModelValue.DataTextField = "Name"; ddlModelValue.DataValueField = "Name"; ddlModelValue.DataBind(); var dtGroup = Session[SystemConstant.GroupSessionKey] as DataTable; ddlGroupValue.DataSource = dtGroup; ddlGroupValue.DataTextField = "Name"; ddlGroupValue.DataValueField = "Name"; ddlGroupValue.DataBind(); var dtFit = Session[SystemConstant.FitSessionKey] as DataTable; ddlFitValue.DataSource = dtFit; ddlFitValue.DataTextField = "Name"; ddlFitValue.DataValueField = "Name"; ddlFitValue.DataBind(); var dtShellType = Session[SystemConstant.ShellTypeSessionKey] as DataTable; ddlShellTypeValue.DataSource = dtShellType; ddlShellTypeValue.DataTextField = "Name"; ddlShellTypeValue.DataValueField = "Name"; ddlShellTypeValue.DataBind(); var dtDataTypeCode = Session[SystemConstant.DataTypeCodeSessionKey] as DataTable; ddlDataTypeCodeValue.DataSource = dtDataTypeCode; ddlDataTypeCodeValue.DataTextField = "Name"; ddlDataTypeCodeValue.DataValueField = "Name"; ddlDataTypeCodeValue.DataBind(); </code></pre>
[]
[ { "body": "<p>This would be a start:</p>\n\n<pre><code>Sub bindTableToControl(table as DataTable, _\n control, _\n Optional textField As String = \"Name\", _\n Optional valueField As String = \"Name\")\n\n control.DataSource = table;\n control.DataTextField = textField;\n control.DataValueField = valueField;\n control.DataBind();\n\nEnd Sub\n\nbindTableToControl( ddlModelValue , Session[SystemConstant.ModelSessionKey] );\nbindTableToControl( ddlGroupValue, Session[SystemConstant.GroupSessionKey] );\nbindTableToControl( ddlFitValue, Session[SystemConstant.FitSessionKey] );\nbindTableToControl( ddlShellTypeValue, Session[SystemConstant.ShellTypeSessionKey] );\nbindTableToControl( ddlDataTypeCodeValue, Session[SystemConstant.DataTypeCodeSessionKey] );\n</code></pre>\n\n<p>Basically I removed most of the repetition. I also removed all the Hungarian prefixes in the Sub. </p>\n\n<p>As a side note, I wonder why SystemConstant is part of the Session, that does not seem memory efficient?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T13:09:09.933", "Id": "31099", "ParentId": "31050", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T11:49:10.277", "Id": "31050", "Score": "0", "Tags": [ "c#", "asp.net" ], "Title": "Generalising the data binding operation" }
31050
<p>Can someone give me suggestions on how to improve this program?</p> <p>The <a href="http://projecteuler.net/problem=1" rel="nofollow">objective</a> is to find the sum of all the multiples of 3 or 5 below 1000.</p> <pre><code>#include &lt;stdio.h&gt; main() { int S, s3,s2,S1; int a=333,b=3,c=999, i=5,j=995, k=199, m = 15, n= 66, o= 990; S1= a*(b+c)/2; s2= k*(i+j)/2; s3= n*(m+o)/2; S= S1 + s2 - s3; printf("sum is:%d",S); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T11:56:46.653", "Id": "49420", "Score": "1", "body": "provide a link to the problem, or describe the problem. Some of us don't know what project Euler is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T12:11:06.897", "Id": "49424", "Score": "4", "body": "You may take a look at [this](http://codereview.stackexchange.com/questions/28936/please-review-my-solution-to-project-euler-problem-1/28938) similar post from another user." } ]
[ { "body": "<p>You certainly got the point of the problem. You applied Inclusion-Exclusion principle. Your code works well too. Most of the operations you use are constant time operations and can't be optimized further. The only problem is code formatting. Every coder develops a coding style that suites him or herself, but when you code, always remember that your code can fall into someone else's hand one day and you don't want the person to suffer before understanding your code.</p>\n\n<ul>\n<li>A comment at the beginning of the code will be good. Not just for a third party reader, but you. You may open the code in another decade, you don't wanna have to go to project Euler's site before you understand what your code does.</li>\n<li>Naming variables, your variables name should reflect its meaning. And you initialized way too many variables on the same line. Funny enough those variables are pointless. You can just use their values immediately in S1, S2 and S3.</li>\n<li>Spacing also is important, not for the compiler of course but for you or whoever is reading this code.</li>\n</ul>\n\n<p>This is how I would have done it;</p>\n\n<pre><code>#include&lt;stdio.h&gt;\n\n/* Function to find the sum of the multiples\nof a OR b between 1 and N, excluding N */ \n\nint findSum(int a, int b, int N){\n N--;\n int a_n = (N/a)*a,\n b_n = (N/b)*b,\n ab_n = (N/(a*b))*a*b,\n sum_a = ((N/a) * (a + a_n))/2,\n sum_b = ((N/b) * (b + b_n))/2,\n sum_ab = ((N/(a*b)) * (a*b + ab_n))/2;\n return sum_a + sum_b - sum_ab;\n}\n\nint main(){\n int a = 3, b = 5, N = 1000;\n printf(\"%d\", findSum(a, b, N));\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T13:18:47.680", "Id": "49434", "Score": "0", "body": "[Ideone](http://ideone.com/SoS2f6) reports a runtime error (but still gives the correct output)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T13:25:15.563", "Id": "49435", "Score": "1", "body": "You say that yashika initialised too many variables on one line, but they were simple initialisations. On one line you have `int a_n = (N/a)*a, b_n = (N/b)*b, ab_n = (N/(a*b))*a*b;` which is harder to read/understand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T13:29:26.023", "Id": "49436", "Score": "0", "body": "@JohnMark13 really? well spaced initialization of three variables is hard to read?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T13:29:42.743", "Id": "49437", "Score": "2", "body": "@Jamal I missed return 0" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T13:32:10.770", "Id": "49438", "Score": "0", "body": "@Olayinka: Ah, right. I'm apparently way too used to C++. Also, I agree with JohnMark13. You can still put those initializations on separate lines." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T13:33:47.820", "Id": "49439", "Score": "1", "body": "@Olayinka, well spaced perhaps, but they're 'complex' in the sense that they involve various operators and parentheses. Additional commas are easy enough to miss. Also, it's inconsistent with the two separate lines you use for `sum_a` and `sum_b`. By the same logic they would happen on the same line as all *_n variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T13:35:21.737", "Id": "49441", "Score": "0", "body": "It also defeats another purpose of using separate lines: adding comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T13:38:47.523", "Id": "49443", "Score": "0", "body": "@Elmer Well noted, I changed the style to increase readability" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T12:50:50.750", "Id": "31052", "ParentId": "31051", "Score": "2" } }, { "body": "<p>Your solution is good (and fast) because it uses a mathematical calculation over the more naive looping solutions. However... </p>\n\n<p>I second @Olayinka comments about readability, but I'd go <strong>much</strong> further with <strong>understand-ability</strong>. The variable names and equations don't really express what they are doing. Also, violations of the DRY principle exist because although there are 6 equations, they are really 3 sets of the same two equations. I'd factor them into a function and give the variables names that mean what they are (disclaimer: I don't claim to have gotten the semantics right in <code>sumMultiples</code> below). Then I'd implement the OR concept as another function that clearly expresses what it is doing.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\n///////////////////////////////////////////////////////////\n// Find the sum of the multiples of a divisor 'd' in\n// the range [1, N).\n// TODO: Include a reference as to why this math works. \nint sumMultiples (int N, int d)\n{\n N--;\n int nMultiples = (N / d);\n int maxMultiple = nMultiples * d;\n int sum = nMultiples * (d + maxMultiple) / 2;\n return sum;\n}\n\n\n///////////////////////////////////////////////////////////\n// Find the sum of the multiples of divisors d1 OR d2\n// in the range [1, N). Uses Inclusion-Exclusion\n// principle.\nint sumMultiplesOR (int N, int d1, int d2)\n{\n int sumOR = sumMultiples(N, d1)\n + sumMultiples(N, d2)\n - sumMultiples(N, d1*d2);\n\n return sumOR;\n}\n\n\nint main(){\n int d1 = 3, d2 = 5, N = 1000;\n printf(\"%d\", sumMultiplesOR(N, d1, d2));\n return 0;\n}\n</code></pre>\n\n<p>I can here the performance folks saying \"but the function call overhead!\". Nonsense. <strong>Always</strong> prefer correctness and readability over all else until you really need it. Incidentally, I complied this in Release mode using VC++ 11 (VS2012) and the compiler optimized away <strong>both</strong> functions, and calculated the solution to the problem at compile time! The resulting assembly was essentially:</p>\n\n<pre><code>push 233168\npush &lt;format-string&gt;\ncall printf\nret 0\n</code></pre>\n\n<p>I can also hear the 'minimal typists' saying 'but that's so much more code!'. Also nonsense. Too bad. More people will read the code than will type it. Most good coders I know are also good typists.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-28T02:59:50.423", "Id": "432192", "Score": "0", "body": "I hope any *real* \"performance folks\" know that compilers aggressively inline functions small, and that constant propagation can happen *after* inlining. A compiler that didn't do that wouldn't be worth using! I would suggest making the helper `static inline` though, to make sure the compiler knows it doesn't have to emit a stand-alone definition of the function. Otherwise that's only possible with LTO (which you should use). And (in case you're compiling this into a Unix shared lib) that symbol interposition can't override it, so inlining into a caller in the same file is still allowed." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-18T15:44:07.023", "Id": "32875", "ParentId": "31051", "Score": "2" } }, { "body": "<p>I wouldn't call this a programming solution to the puzzle; it's more of a program that happens to print the correct result. Basically, you've already solved the problem, and are using the computer as a fancy calculator. You might as well do the work on a two-dollar calculator that you can buy at the corner store.</p>\n\n<p>There are, of course, situations where you have to apply a certain amount of ingenuity in order to translate the problem into an algorithm to be implemented. For example, when factoring numbers, it's common to only try odd factors, knowing that 2 is a special case. At some point, though, you have to decide how much work to do in the programmer's brain vs. how much work to give to the CPU. How to make the tradeoff will be guided by your desire for fast runtime performance vs. the elegance of the code.</p>\n\n<p>In this case, a modern computer can solve this problem by \"brute force\" in almost the same amount of time as your \"smart\" summation using the inclusion-exclusion principle. Here's how a brute-force solution would look like:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint main() {\n int sum = 0;\n for (int i = 0; i &lt; 1000; i++) {\n if ((i % 3 == 0) || (i % 5 == 0)) {\n sum += i;\n }\n }\n printf(\"sum is: %d\\n\", sum);\n return 0;\n}\n</code></pre>\n\n<p>It expresses the problem exactly as stated. There is no room for programming error, no mysterious constants, no formulas. If the requirements change (for example, to find the sum of all multiples of 3 or 7 below 10000), it's trivial to adjust the program. The engineering trade-off <em>definitely</em> favours simplicity over runtime performance. (If it takes you more than one second to write the cleverer code, you've already lost!)</p>\n\n<hr>\n\n<p>As I said, though, there are times when human ingenuity has to be built into the program, usually because a brute-force solution cannot yield acceptable performance. In those situations, your job as a programmer is to express the shortcuts while sacrificing as little code maintainability as possible.</p>\n\n<p>One trick is to let the preprocessor and compiler do the work. The proposal below is <em>much</em> more readable and flexible than your original. In fact, if you inspect the assembler output, you'll see that this solution generates <em>identical</em> code to your original solution. Both of them embed the answer right into the executable as a constant!</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\n#define COUNT_MULTIPLES(m, limit) (((limit) - 1) / (m))\n#define MIN_MULTIPLE(m, limit) (m)\n#define MAX_MULTIPLE(m, limit) (COUNT_MULTIPLES(m, limit) * (m))\n#define SUM_MULTIPLES(m, limit) (COUNT_MULTIPLES(m, limit) * \\\n (MIN_MULTIPLE(m, limit) + MAX_MULTIPLE(m, limit)) / 2)\n\nint main() {\n int limit = 1000;\n int sum_mult_3 = SUM_MULTIPLES(3, limit);\n int sum_mult_5 = SUM_MULTIPLES(5, limit);\n int sum_mult_15 = SUM_MULTIPLES(15, limit);\n\n /* Sum using the inclusion-exclusion principle */\n int sum = sum_mult_3 + sum_mult_5 - sum_mult_15;\n printf(\"sum is: %d\\n\", sum);\n return 0;\n}\n</code></pre>\n\n<p>Everything is named to enhance understanding. Repetition of code (the summation formula) is eliminated. Best of all, <strong>no magic numbers</strong>!</p>\n\n<hr>\n\n<p><strong>Update:</strong> Actually, you don't have to use preprocessor macros to get good performance. If you write the macros as functions instead, <code>clang -O2</code> and <code>gcc -O2</code> will both do the entire calculation at compile time, exactly as with preprocessor macros.</p>\n\n<p>Considering the problems with macros (lack of type safety and re-evaluation of arguments), I think that changing them to functions is a better solution.</p>\n\n<pre><code>/* Compilation with optimization level -O2 or better is suggested */\n\n#include &lt;stdio.h&gt;\n\nint count_multiples(m, limit) {\n return (limit - 1) / m;\n}\n\nint min_multiple(m, limit) {\n return m;\n}\n\nint max_multiple(m, limit) {\n return count_multiples(m, limit) * m;\n}\n\nint sum_multiples(m, limit) {\n return count_multiples(m, limit) * (min_multiple(m, limit) + max_multiple(m, limit)) / 2;\n}\n\nint main() {\n int limit = 1000;\n int sum_mult_3 = sum_multiples(3, limit);\n int sum_mult_5 = sum_multiples(5, limit);\n int sum_mult_15 = sum_multiples(15, limit);\n\n /* Sum using the inclusion-exclusion principle */\n int sum = sum_mult_3 + sum_mult_5 - sum_mult_15;\n printf(\"sum is: %d\\n\", sum);\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-28T02:51:38.283", "Id": "432189", "Score": "0", "body": "Indeed, inlining and constant-propagation are *very* powerful optimizations for code that's written generically and then called for specific use-cases with some or all args being constants. Of course for compile-time-constant loop bounds, a compiler will hopefully fully unroll and optimize away even the dumb brute-force loop, but that doesn't always happen if the heuristic thresholds aren't high enough." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-18T19:46:52.067", "Id": "32888", "ParentId": "31051", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T11:52:37.997", "Id": "31051", "Score": "5", "Tags": [ "c", "project-euler" ], "Title": "Please review my solution to Project Euler program 1" }
31051
<p>Please explain the relationship between pointers and arrays. In this <a href="http://www.cprogrammingexpert.com/C/Tutorial/functions/pass_by_reference.aspx" rel="nofollow">tutorial</a>, they change <code>int c</code> by changing <code>*r</code> in the function. How is that possible?</p> <p>Also, please review my code for reversing a string. The string variable belongs to the <code>main()</code> function, and I would like to pass a pointer to let the <code>strreverse()</code> function write to the string. Does my code work?</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;string.h&gt; void strreverse(char *string) { int i, len; char c; len=strlen(string); char string2[len+1]; for(i=0; i&lt;len; i++) { c=string[i]; string2[len-i]=c; } string2[len+1]='\0'; string=string2; //printf("%s\n", string); &lt;-- this would work,but should be in main } int main(int argc, char *argv[]) { char str[256]; printf("Type a String to reverse it.[max. 255 chars]\n"); fgets(str, 255, stdin); strreverse(&amp;str[0]); printf("%s", str); return EXIT_SUCCESS; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T14:38:12.877", "Id": "49447", "Score": "0", "body": "You should be aware that your code requires C99, but that's fine for now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T18:47:13.763", "Id": "49462", "Score": "0", "body": "That was recommended in my books. Thanks for making my request readable!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T22:39:02.593", "Id": "49474", "Score": "0", "body": "I never really understand the point of adding command line arguments when it is not used in the program." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T22:36:17.970", "Id": "49553", "Score": "0", "body": "I don't think this question should have been put on hold. This site is for code reviews, and there are *plenty* of issues in this code for critique. (It fails the \"you must post working code criterion\", but a beginner who has made a good effort doesn't deserve to be turned away, I think.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T13:07:24.963", "Id": "457853", "Score": "0", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<p>No, I've compiled your code with C90 and it doesn't reverse the given string.</p>\n\n<ul>\n<li><code>int main(int argc, char *argv[])</code> If you're not compiling from the command line with arguments to be used by the program, then <code>int main()</code> suffices.</li>\n<li>Passing argument by pointer is used when you want the value of the variable changed. Say I have a variable <code>int var</code> and a function <code>change(.)</code>, I want change to alter the value of <code>var</code>. If I declare change as <code>void change(int n)</code> and I call <code>change(var)</code>, function <code>change</code> will take a copy of <code>var</code> named <code>var</code> but it's only a copy, its address is different from the original <code>var</code>. Any change you make on copy <code>var</code> will not affect the original <code>var</code>. If i declare change as <code>void change(int* n)</code>, then change will only accept <code>int</code> pointers, I have to pass the address, <code>&amp;var</code> into <code>change</code> as <code>change(&amp;var)</code>. Now working on this address is exactly like working on the initial <code>var</code>.</li>\n</ul>\n\n<p>To understand pointer-array relationship read <a href=\"http://en.wikipedia.org/wiki/Pointer_%28computer_programming%29#C_arrays\" rel=\"nofollow noreferrer\">wikipedia</a>.</p>\n\n<pre><code>int array[5]; // Declares 5 contiguous integers \nint *ptr = array; // Arrays can be used as pointers \nptr[0] = 1; // Pointers can be indexed with array syntax \n*(array + 1) = 2; // Arrays can be dereferenced with pointer syntax \n*(1 + array) = 3; // Pointer addition is commutative \n2[array] = 4; // Subscript operator is commutative \n</code></pre>\n\n<p>Array names are not really pointers but can be used as pointers. Instead of <code>strreverse(&amp;str[0])</code>, you can do <code>strreverse(str)</code>. Same result.</p>\n\n<p>You've passed argument as pointer but your code still fails, why?</p>\n\n<ul>\n<li>One thing to know about <code>fgets</code> is that unless there is an <code>[EOF][2]</code> which you can only get from an input file or <kbd>Ctrl</kbd>+<kbd>Z</kbd> if you run from the command line, <code>fgets</code> exits when the length argument is reached or it encounters a newline. In summary, <code>fgets</code> reads the newline as a character when you press enter key, increasing your desired length by 1. So if I had entered <code>\"my string\"</code> + <kbd>Enter</kbd>, your variable <code>str</code> becomes <code>\"my string\\n\"</code>.</li>\n<li>So you got the length of the string into <code>len</code>. The array <code>string</code> is zero-based, calling <code>string[len]</code> return the <code>char</code> after the desired last one. The last char is <code>string[len - 1]</code>. </li>\n</ul>\n\n<p>You should have done this;</p>\n\n<pre><code>char string2[len];\n\nfor(i=0; i&lt;len; i++){\n c=string[i]; //variable c is unimportant\n string2[len-i-1] = string[i]; //observe the -1, when i = 0, string2[len - 1] = string[0]\n}\nstring2[len] ='\\0';\n</code></pre>\n\n<p>Now that you're done reversing, you need to understand the implication of your next move.</p>\n\n<pre><code>string = string2;\n</code></pre>\n\n<p><code>string</code> is a pointer, but that doesn't make it any less of a variable, it's a pointer variable, it also has an address. And if I declare a pointer variable to its address, that pointer will also have an address. Going back to what I said earlier, when you call <code>change(&amp;var)</code>, a copy of the address of <code>var</code> is passed into the function, so when you change the value of this pointer, it no longer holds the address of var. You may think about dereferencing, like this </p>\n\n<pre><code>*string = *string2;\n</code></pre>\n\n<p>but this will only alter the first value of the array since <code>*string</code> is same as <code>string[0]</code>. The solution is to copy element by element.</p>\n\n<pre><code>for(i=0; i&lt;=len; i++)\n string[i] = string2[i];\n</code></pre>\n\n<p>Now your string is reversed.</p>\n\n<p><em>Read this <a href=\"http://en.wikipedia.org/wiki/In-place_algorithm\" rel=\"nofollow noreferrer\">wikipedia article</a> to understand how an array can be reversed faster.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T01:35:37.120", "Id": "49485", "Score": "0", "body": "+1 thank you for this. I'm awful at pointers, even though I don't have to worry too much about the raw ones in C++. It never hurts to learn the fundamentals of C, either. :-) Your changes do work, by the way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T01:46:38.273", "Id": "49486", "Score": "0", "body": "@Jamal I agree, pointers can be a pain in the ass but they force one to code carefully." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T01:50:08.993", "Id": "49487", "Score": "0", "body": "Right. Still, for serious C++ applications, I'll just (learn) and stick with STL pointers. I believe one of my few SO questions shows my earliest attempt at using *double* pointers." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-09-11T01:21:44.553", "Id": "31077", "ParentId": "31056", "Score": "3" } } ]
{ "AcceptedAnswerId": "31077", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T14:29:27.320", "Id": "31056", "Score": "4", "Tags": [ "c", "strings", "beginner", "pointers" ], "Title": "Modifying a string by passing a pointer to a void function" }
31056
<p>I have a situation in which a program, communicating over the network, can timeout or otherwise fail to establish a connection through no fault of my application or its user. If and when this happens, an exception is thrown. The solution is obvious; simply try again a couple more times, and if multiple tries don't work then this is really a problem.</p> <p>I've accomplished this by wrapping the original try-catch in a while loop with a retry counter, producing the following basic pattern:</p> <pre><code>var retryCount = 0; while(true) { try { AttemptToConnect(); break; } catch(TimeoutException tex) { if(++retryCount &lt; 3) continue; throw; //or handle error and break/return } } </code></pre> <p>Do any of you see any problems? The biggest smell, prompting me to ask in the first place, is the conditionless loop, which would be infinite except that the "happy path" breaks out of the loop manually, while the terminating error will throw out. This has been called out before as a potential bug generator, if it's ever modified in the future (for instance to catch a second type of exception, or to do something else that could throw an exception).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T17:19:17.593", "Id": "49456", "Score": "4", "body": "Personally, I don't think that `while (true)` is a code smell." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T23:41:40.960", "Id": "49475", "Score": "0", "body": "I don't know if this is relevant to your situation, but I wrote something along these lines which you can find here: http://codereview.stackexchange.com/questions/19868/please-review-my-unc-path-exists-monitor" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T00:28:20.757", "Id": "49477", "Score": "0", "body": "Might be overkill, but... ever heard of the *circuit breaker* pattern? http://timross.wordpress.com/2008/02/10/implementing-the-circuit-breaker-pattern-in-c/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T07:43:53.480", "Id": "60460", "Score": "0", "body": "Perhaps consider resetting the retry count if you successfully connect, otherwise you may disconnect after separate connect failures followed by successes. Unless of course this is the intended behaviour." } ]
[ { "body": "<p>Yeah, I'd probably redo it with an actual condition. That way, intent looks clear and is not dependent on internal code to <code>break</code>, <code>continue</code>, etc.</p>\n\n<pre><code>const int NumberOfRetries = 3;\nvar retryCount = NumberOfRetries;\nvar success = false;\nwhile(!success &amp;&amp; retryCount &gt; 0)\n{\n try\n {\n AttemptToConnect();\n success = true;\n }\n catch(TimeoutException tex)\n {\n retryCount--;\n\n if (retryCount == 0)\n {\n throw; //or handle error and break/return\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T18:24:06.137", "Id": "49459", "Score": "2", "body": "Change the in-lined `3` to a constant or a configurable parameter and this would be a great solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T10:26:53.403", "Id": "60472", "Score": "0", "body": "This could also be extended by, say that `AttemptToConnect()` returns different `int-success values`, you could handle different cases in your `try` depending on what you want to do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-11T15:23:35.660", "Id": "203523", "Score": "0", "body": "@Max I don't think one should return such values, as failure cases are what exceptions are for. Instead, `AttemptToConnect()` should probably return a `Connection` instance and the `success` flag should be dropped in favor of `connection == null`, which would explain straight away that we keep trying to connect until we get an actual connection or run out of retries. Also that `if (retryCount == 0) ...` thingy could be improved, I believe..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T16:30:40.187", "Id": "31060", "ParentId": "31059", "Score": "12" } }, { "body": "<p>With minor changes I would refactor it as follows:</p>\n\n<pre><code>var retriesLeft = 3;\nvar connectionEstablished=false;\nwhile(retriesLeft&gt;0)\n{\n try\n {\n AttemptToConnect();\n connectionEstablished=true;\n break;\n }\n catch(TimeoutException tex)\n {\n retriesLeft-=1;\n }\n}\nif (connectionEstablished==false) throw new TimeoutException(); // or whatever\n// Do stuff \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T19:12:41.107", "Id": "31067", "ParentId": "31059", "Score": "3" } }, { "body": "<p>I actually like the author's code. It's short and clear.</p>\n\n<p>My only (minor) comment would be the if statement...</p>\n\n<pre><code> if(++retryCount &lt; 3) continue;\n\n throw; //or handle error and break/return\n</code></pre>\n\n<p>I would do;</p>\n\n<pre><code> if(++retryCount &gt; 2)\n throw; //or handle error and break/return\n</code></pre>\n\n<p>But that's only because I think it reads a little better.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T20:45:39.477", "Id": "31385", "ParentId": "31059", "Score": "4" } }, { "body": "<p>I would like to add few changes to the existing. When the attempt to connection fails, it is always better to retry the attempt after some delay.</p>\n\n<ol>\n<li><p>Declare the _retryCounter and _connectionRetryInterval outside scope of the class, and make it configurable. For simplicity I am assigning values directly.</p>\n\n<pre><code>private int _connectionRetryInterval = 3000;\nprivate int _maxRetryCount = 3;\n</code></pre></li>\n<li><p>Modified code is as below</p>\n\n<pre><code>var retryCount = 0;\nvar connectionEstablished = false;\nwhile (retryCount &lt; _maxRetryCount)\n{\n try\n {\n AttemptToConnect();\n connectionEstablished = true;\n break;\n }\n catch (TimeoutException tex)\n {\n // log the exception with retry count.\n System.Threading.Thread.Sleep(_connectionRetryInterval);\n retryCount += 1;\n }\n}\n\nif (connectionEstablished == false)\n{\n throw new TimeoutException(); // or whatever\n}\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-11T17:34:04.317", "Id": "191812", "ParentId": "31059", "Score": "1" } } ]
{ "AcceptedAnswerId": "31060", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T16:05:46.277", "Id": "31059", "Score": "19", "Tags": [ "c#", "error-handling" ], "Title": "Attempt to reconnect, with timeout" }
31059
<p>After learning a lot about programming, I've decided to write some code pertaining to scripting and use of different functions. I've come to a point where I'd like others to verify my code for correctness. Is there anything I can do better, different, or easier, to make my code more efficient?</p> <p>My main goal is to determine whether or not my functions are working correctly. It works perfectly right now, but I'd also like to join new tables to get additional information to the <code>$posts array</code>. I find it very hard to implement this easily. For instance, I'd like to retrieve all <code>likes</code> from table: <code>likes</code> where <code>like_entity</code> = <code>post_id</code>. The code works, but it feels stuck to me.</p> <p>Any ideas / feedback?</p> <pre><code>// Get wall // Returns posts array with comments function GetWall($entity='') { global $tbl_prefix; $sql = " SELECT p.*, c.post_id AS comment_id, c.post_message AS comment_message, c.post_author AS comment_author, c.post_date AS comment_date, c.post_deleted AS comment_deleted, u.name AS post_author_name, u2.name AS comment_author_name, lp.like_entity AS post_like, lc.like_entity AS comment_like FROM " . $tbl_prefix . "posts p LEFT JOIN " . $tbl_prefix . "posts c ON c.post_comment = p.post_id LEFT JOIN " . $tbl_prefix . "users u ON u.user_id = p.post_author LEFT JOIN " . $tbl_prefix . "users u2 ON u2.user_id = c.post_author LEFT JOIN " . $tbl_prefix . "likes lp ON lp.like_entity = p.post_id &amp;&amp; lp.like_author = '" . UserId() . "' LEFT JOIN " . $tbl_prefix . "likes lc ON lc.like_entity = c.post_id &amp;&amp; lc.like_author = '" . UserId() . "' WHERE "; if($entity) { $sql .= "p.post_receiver = '$entity' &amp;&amp; "; } $sql .= "p.post_deleted = '0' &amp;&amp; p.post_comment IS NULL GROUP BY p.post_id, comment_id ORDER BY p.post_date DESC "; $query = doQuery($sql); $posts = array(); $catchedComments = array(); while($row = mysql_fetch_assoc($query)) { // loop query if($row['post_like']) { $user_likes_post = 1; } if($row['comment_like']) { $user_likes_comment = 1; } if(!array_key_exists($row['post_id'], $posts)) { // if wall post is not yet created //////////////// // COMMENTS // //////////////// if($row['comment_id'] &amp;&amp; !$row['comment_deleted']) { // if comment exists on current $comment = array(array( 'id' =&gt; $row['comment_id'], 'message' =&gt; $row['comment_message'], 'author' =&gt; $row['comment_author'], 'author_name' =&gt; $row['comment_author_name'], 'date' =&gt; $row['comment_date'], 'user_likes' =&gt; $row['comment_like'] )); } else { // no comments for current post $comment = array(); } //////////////// // POST ARRAY // //////////////// // Create post ARRAY $posts[$row['post_id']] = array( 'message' =&gt; $row['post_message'], 'author' =&gt; $row['post_author'], 'author_name' =&gt; $row['post_author_name'], 'date' =&gt; $row['post_date'], 'comments' =&gt; $comment, 'user_likes' =&gt; $row['post_like'] ); } else { // if post is created, assume this fetch it is comment/like data foreach($posts[$row['post_id']] as $k =&gt; $v) { // loop post through and scan for arrays if($k == 'comments') { // get comments if(!array_key_exists($row['comment_id'], $v)) { // check if comment is created (with $post array) if(!$comment[$row['comment_id']]) { // check if comment is created (with comment array) if(!$row['comment_deleted']) { // check if comment is deleted // Create array with comment data $comment[$row['comment_id']] = array( 'id' =&gt; $row['comment_id'], 'message' =&gt; $row['comment_message'], 'author' =&gt; $row['comment_author'], 'author_name' =&gt; $row['comment_author_name'], 'date' =&gt; $row['comment_date'], 'deleted' =&gt; $row['comment_deleted'], 'user_likes' =&gt; $row['comment_like'] ); // Push to comment array array_push($posts[$row['post_id']]['comments'], $comment[$row['comment_id']]); } } } } } // end foreach } // end comment/like data section } // end while // Returns array with data return $posts; } // end function </code></pre> <p>I use the function to retrieve wall posts, and all associated comments to them, and then output it to an array. The associated likes, I get externally from a jQuery code (and other MySQL fetch).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T08:30:04.313", "Id": "49496", "Score": "0", "body": "In your `WHERE` clause you're using `&&`, while it _should_ be [`AND`](http://lists.mysql.com/mysql/216549). It may work on `MySQL`, but it's definitly not standard (there is not truth-table, nor is there a char-matrix in the official spec" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T08:59:06.840", "Id": "49499", "Score": "0", "body": "Hi there! Thanks for your answer - but can you tell; is it the right way I'm doing it? I'm about to join another table with even more information (for every like that exists on the current post/comment in the posts table), and that will create probably additionally 500% more rows (depending on the amount of likes), and it feels like that is very unnecessary. Any advice?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T09:03:53.860", "Id": "49500", "Score": "0", "body": "When writing queries, execute your queries, but add `EXPLAIN EXTENDED` before it, so you can see how the tables are actually joined. Another thing: don't use `LIKE` when you don't have to (it's slow). Add your table shema's and storage engines + collation to your question, because looking at the query alone is not going to lead to a definitive answer. And _yes_, 6 joins is a bit much (not uncommon, though), and you're likely to be able to improve on your query" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T09:29:55.980", "Id": "49501", "Score": "0", "body": "I have been advised to convert my database to a relational database, any recommendations on this? I have already build up a lot of tables in my database, but it seems as it is the most recommended. Could I benefit from it, for example on above code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T09:33:06.937", "Id": "49502", "Score": "0", "body": "They already look relational to me (relational tbls are tables that express a relation between the data by storing the id of record X in tbl1 in a field in tbl2 and vice-versa)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T10:12:49.633", "Id": "49504", "Score": "0", "body": "Thanks Elias. I already found out, after spending 30-45 mins of research. I just never knew the technical term for it. What did you mean about that I shouldn't use `LIKE`? I will check up on the explain extended. But lets, say I wish to join the table LIKES as well, then I'll assume I'll just join it in above query, and then sort it out with PHP. It's just such a complicated process, I imagine next time I wish to join another table. Wondered if there was a easier way, to deal with the query than what I do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T10:16:28.370", "Id": "49505", "Score": "0", "body": "For instance; I keep my posts AND comments to these posts in the same table (this is the only place in my database where it isn't relational), only different by a column named \"post_comment\". If the post_comment is NOT NULL, then we know it is a comment, and then the post_comment contains Foreign Key of the post. I was told that this is very wrong. But I can't see why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T10:40:15.997", "Id": "49506", "Score": "0", "body": "Well, I thought you meant `LIKE` as in `tbl.field LIKE '%a%'`, which 9/10 results in a full table scan. that's why `LIKE` should be avoided at all costs. If `likes` is your tbl name, than forget about that. On the `NOT NULL`: if you perform your JOIN's correctly, `NOT NULL` should be redundant (provided your tbl relations are correct). Foreign keys is something I favour. Some can't stand them. It's something like stored procedures: some like them, other don't. FK's _do_ move _some_ logic to the DB, which is considered bad, but it guarantees data integrity, IMO worth the trade-off" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T10:42:54.913", "Id": "49508", "Score": "0", "body": "I can't go into more details, because, like I said: I don't know what your tables look like... I need more info (just the create table stmts for a start). So anything I said here is about as accurate as the average swing, taken at a piñata. I might be spot on, but chances are I'm missing the point completely. PS: don't use `global` in your functions: if you need something in a function, pass it as an arguments. Globals are evil!" } ]
[ { "body": "<p>From a quick glance of your code it looks like you are doing a lot in your PHP that you should be doing on the database with SQL.</p>\n\n<p>I recommend that you look into Stored Procedures for MySQL, I think that a lot of what you are doing can be done using Stored Procedures on your database, then you can call those procedures from the PHP code to display the data that is retrieved. </p>\n\n<p>In my experience it is easier to write SQL in SQL and not SQL in a server side language to run on the database. This would enhance the performance on your web server. </p>\n\n<p>It would also give you the opportunity to view the data before making it visible on your site, this makes your data more secure in the long run and will alleviate stress trying to get your data to look right on the web page. This also compartmentalizes the database stuff from the webpage stuff.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T21:33:47.073", "Id": "35637", "ParentId": "31061", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T17:09:31.340", "Id": "31061", "Score": "2", "Tags": [ "php", "optimization", "performance", "mysql", "sql" ], "Title": "Correct use of my JOIN and arrays to fetch the data?" }
31061
<p>It seems like <a href="https://stackoverflow.com/questions/18685039/how-to-portably-use-system-or-popen-but-with-array-of-arguments">there's no good library function</a> I can use for popen with array of arguments instead of single shell-interpreted shell. So I implemented my own one: <a href="https://github.com/vi/udpserv/blob/master/popen_arr.c" rel="nofollow noreferrer">c</a> <a href="https://github.com/vi/udpserv/blob/master/popen_arr.h" rel="nofollow noreferrer">h</a>.</p> <p><strong>popen_arr.h</strong></p> <pre><code>#pragma once struct FILE; // Implemented by Vitaly _Vi Shukela in 2013, License=MIT /** * Fork and exec the program, enabling stdio access to stdin and stdout of the program * You may close opened streams with fclose. * Note: the procedure does no signal handling except of signal(SIGPIPE, SIG_IGN); * You should waitpid for the returned PID to collect the zombie or use signal(SIGCHLD, SIG_IGN); * * @arg in stdin of the program, to be written to. If NULL then not redirected * @arg out stdout of the program, to be read from. If NULL then not redirected * @arg program full path of the program, without reference to $PATH * @arg argv NULL terminated array of strings, program arguments (includiong program name) * @arg envp NULL terminated array of environment variables, NULL =&gt; preserve environment * @return PID of the program or -1 if failed */ int popen2_arr (FILE** in, FILE** out, const char* program, const char* const argv[], const char* const envp[]); /** like popen2_arr, but uses execvp/execvpe instead of execve/execv, so looks up $PATH */ int popen2_arr_p(FILE** in, FILE** out, const char* program, const char* const argv[], const char* const envp[]); /** * Simplified interface to popen2_arr. * You may close the returned stream with fclose. * Note: the procedure does no signal handling except of signal(SIGPIPE, SIG_IGN); * You should wait(2) after closing the descriptor to collect zombie process or use signal(SIGCHLD, SIG_IGN) * * @arg program program name, can rely on $PATH * @arg argv program arguments, NULL-terminated const char* array * @arg pipe_into_program 1 to be like popen(...,"w"), 0 to be like popen(...,"r") * @return FILE* instance or NULL if error */ FILE* popen_arr(const char* program, const char* const argv[], int pipe_into_program); </code></pre> <p><strong>popen_arr.c</strong></p> <pre><code>#define _GNU_SOURCE // execvpe #include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #include &lt;errno.h&gt; #include &lt;signal.h&gt; #include "popen_arr.h" // Implemented by Vitaly _Vi Shukela in 2013, License=MIT static int popen2_impl(FILE** in, FILE** out, const char* program, const char* const argv[], const char* const envp[], int lookup_path) { int child_stdout = -1; int child_stdin = -1; int to_be_written = -1; int to_be_read = -1; if(in) { int p[2]={-1,-1}; int ret = pipe(p); if(ret!=0) { return -1; } to_be_written=p[1]; child_stdin =p[0]; *in = fdopen(to_be_written, "w"); if (*in == NULL) { close(to_be_written); close(child_stdin); return -1; } } if(out) { int p[2]={-1,-1}; int ret = pipe(p); if(ret!=0) { if (in) { close(child_stdin); fclose(*in); *in = NULL; } return -1; } to_be_read =p[0]; child_stdout=p[1]; *out = fdopen(to_be_read, "r"); } int childpid = fork(); if(!childpid) { if(child_stdout!=-1) { close(to_be_read); dup2(child_stdout, 1); close(child_stdout); } if(child_stdin!=-1) { close(to_be_written); dup2(child_stdin, 0); close(child_stdin); } if (lookup_path) { if (envp) { execvpe(program, (char**)argv, (char**)envp); } else { execvp (program, (char**)argv); } } else { if (envp) { execve(program, (char**)argv, (char**)envp); } else { execv (program, (char**)argv); } } _exit(ENOSYS); } if(child_stdout!=-1) { close(child_stdout); } if(child_stdin!=-1) { close(child_stdin); } return childpid; } int popen2_arr (FILE** in, FILE** out, const char* program, const char* const argv[], const char* const envp[]) { signal(SIGPIPE, SIG_IGN); return popen2_impl(in, out, program, argv, envp, 0); } int popen2_arr_p(FILE** in, FILE** out, const char* program, const char* const argv[], const char* const envp[]) { signal(SIGPIPE, SIG_IGN); return popen2_impl(in, out, program, argv, envp, 1); } FILE* popen_arr(const char* program, const char* const argv[], int pipe_into_program) { FILE* f = NULL; if (pipe_into_program) { popen2_arr_p(&amp;f, NULL, program, argv, NULL); } else { popen2_arr_p(NULL, &amp;f, program, argv, NULL); } return f; } </code></pre> <p>Do you have any advice on promoting it from just a project's code snippet into a reusable little library? Is API good? Shall it provide more features (at expence of being complexier) or more simpler (but a bit tricker to use)? Are there obviously bad parts of the code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T20:52:18.047", "Id": "49466", "Score": "1", "body": "From what I read, you are not asking how to improve it, you are asking how to make it a library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T21:05:58.683", "Id": "49468", "Score": "1", "body": "I see library code as one requiring higher quality than usual application code. So \"making this into a library\" implies \"making good API, removing hacks\". Shall I reformulate the question a bit? I'm not asking how to make it into *.a or *.so or how to create package with it..." } ]
[ { "body": "<p>The function <code>popen_arr</code> would resemble <code>popen</code> more closely if it\ntook a 'mode' parameter in the same way, instead of your <code>pipe_into_program</code>:</p>\n\n<pre><code>FILE* popen_arr(const char* program,\n const char* const argv[], \n const char *mode);\n</code></pre>\n\n<p>where <code>mode</code> is \"r\", \"w\" or \"r+\".</p>\n\n<p>And <code>popen</code> manages bidirectional operation using just one <code>FILE *</code> whereas\nyour <code>popen2_*</code> functions take two. </p>\n\n<p>Personally, I would simplify things by omitting the environment parameters. </p>\n\n<p>The bidirectional link you create is perhaps easier to create with\n<code>socketpair</code>.</p>\n\n<p><code>fdopen</code> failure is caught in the <code>if(in)</code> case but not in the <code>if(out)</code>\ncase.</p>\n\n<p>You also need an analogue of <code>pclose</code> that closes the pipes and waits for the\nchild process to exit (using <code>wait</code> etc).</p>\n\n<p>You also omit any handling of <code>SIGCHLD</code>, which is sent of the death of the child process.</p>\n\n<p>On your formatting, your spacing is inconsistent and there is often\ninsufficient spacing, eg around operators (=, != etc) and after keywords (eg\nafter <code>if</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T11:34:54.843", "Id": "60963", "Score": "0", "body": "BTW am I expected on codereview.SE to edit the question according to the recommendations or leave it as is?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T16:40:02.733", "Id": "61018", "Score": "0", "body": "No don't edit the code in the original question (answers refer to that code)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T17:50:42.383", "Id": "61025", "Score": "0", "body": "How we should handle SIGCHLD? Store old handler, override, handle then restore old handler? Does usual popen deal with SIGCHLD?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T20:26:12.270", "Id": "36990", "ParentId": "31063", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T17:36:48.540", "Id": "31063", "Score": "4", "Tags": [ "c", "linux" ], "Title": "popen with array of arguments" }
31063
<p>In my small application, I need to use a variety of visual themes.</p> <p>The simplified structure of this class:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Theme | .__ menu | | | .__ screenBackground | .__ itemsColor | .__ getRandomItemAnimation() | .__ game | | | .__ screenBackground | .__ gameBoardBackground | .__ getRandomMoveSound() | .__ getRandomStartScreenImage() </code></pre> </blockquote> <p>I want to write code like this:</p> <pre class="lang-none prettyprint-override"><code>setBackground(theme.game.screenBackground) </code></pre> <p>instead of</p> <pre class="lang-none prettyprint-override"><code>setBackground(theme.game().screenBackground()) </code></pre> <p>But in addition to that, I want to use inheritance. However, Java does not seem to allow to override public fields of the parent class in the descendant classes.</p> <p>So I've decided to use the following implementation:</p> <p><strong>Basic classes:</strong></p> <pre class="lang-java prettyprint-override"><code>// All constructors (in the next 3 classes) used to set final class-members by descendants public abstract class Theme { public final MenuTheme menu; public final GameTheme game; public abstract Image getRandomStartScreenImage(); public Theme(MenuTheme menuTheme, GameTheme gameTheme) { this.menuTheme = menuTheme; this.gameTheme = gameTheme; } } public abstract class MenuTheme { public final Image screenBackground; public final Color itemsColor; public abstract Animation getRandomItemAnimation(); public MenuTheme(Image screenBackground, Color itemsColor) { this.screenBackground = screenBackground; this.itemsColor = itemsColor; } } public abstract class GameTheme { public final Image screenBackground; public final Image gameBoardBackground; public abstract Sound getRandomMoveSound(); public GameTheme(Image screenBackground, Image gameBoardBackground) { this.screenBackground = screenBackground; this.gameBoardBackground = gameBoardBackground; } } </code></pre> <p><strong>Using:</strong></p> <pre class="lang-java prettyprint-override"><code>public class Menu { public void setUp() { Theme theme = GameContext.getCurrentTheme(); setBackground(theme.menu.screenBackground); setItemsColor(theme.menu.itemsColor); } public void onClickItem(Item clickedItem) { Theme theme = GameContext.getCurrentTheme(); clickedItem.startAnimation(theme.menu.getRandomItemAnimation()); // Action action = getActionByItem(clickedItem); // action.start(); } } </code></pre> <p><strong>How to add theme:</strong></p> <pre class="lang-java prettyprint-override"><code>public class DarkTheme extends Theme { private Image[] startScreenImages = getStartScreenImages(); public Image getRandomStartScreenImage() { return startScreenImages[getRandomIndex()]; } public DarkTheme() { super(new DarkMenuTheme(), new DarkGameTheme()); } } public class DarkMenuTheme extends MenuTheme { private Animation[] itemAnimations = getItemAnimations(); public Animation getRandomItemAnimation() { return itemAnimations[getRandomIndex()]; } public DarkMenuTheme() { super(getDarkMenuScreenBackground(), getDarkMenuItemsColor()); } } public class DarkGameTheme { private Sound[] moveSounds = getMoveSounds(); public Sound getRandomMoveSound() { return moveSounds[randomIndex()]; } public DarkGameTheme() { super(getDarkGameScreenBackground(), getDarkGameBoardBackground()); } } </code></pre> <p>What do you think about the structure of <code>Theme</code>? Does it look like a good implementation?</p> <p>The structure of <code>Theme</code> does not expect to be changed. There will only be the addition of new themes. Given this, what are the drawbacks and benefits of this code? What improvement or other implementation can you recommend?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T22:06:10.453", "Id": "49552", "Score": "1", "body": "You might find the cons in the first answer relevant: http://programmers.stackexchange.com/questions/190955/using-public-final-rather-than-private-getters" } ]
[ { "body": "<blockquote>\n <p>I want to write code like this: <code>setBackground(theme.game.screenBackground)</code> instead of <code>setBackground(theme.game().screenBackground())</code>.</p>\n</blockquote>\n\n<p>Why would you sacrifice encapsulation (<a href=\"http://www.netobjectives.com/files/Encapsulation_First_Principle_Object_Oriented_Design.pdf\" rel=\"nofollow\">the first principle of object-oriented design</a>) for the minor convenience of not having to type brackets?</p>\n\n<p>I frankly cannot see any real benefits, while I can see several drawbacks : </p>\n\n<ul>\n<li>themes will have to be fully initialized upon construction</li>\n<li>lazy loading or initialising is difficult if not impossible, the nested exposure of fields makes even proxy implementations a difficult option. This is especially painful for fields that refer to heavyweight objects that likely must be read from a file (Images, Sound)</li>\n<li>the API does not communicate that these fields are not mutable.</li>\n</ul>\n\n<p>I believe these points would also be valid in other languages than Java.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T19:44:56.050", "Id": "31072", "ParentId": "31065", "Score": "4" } }, { "body": "<blockquote>\n <p>I want to write code like this:\n setBackground(theme.game.screenBackground) instead of\n setBackground(theme.game().screenBackground())</p>\n</blockquote>\n\n<p>Read this : <a href=\"http://c2.com/cgi/wiki?AccessorsAreEvil\">http://c2.com/cgi/wiki?AccessorsAreEvil</a></p>\n\n<p>The URL is misleading, it is a 'balanced' article, the part I want you to pay particularly attention is this:</p>\n\n<blockquote>\n <p>The examples [...] they are really structures (data), not quite\n objects.</p>\n</blockquote>\n\n<p>Your theme class should really be a structure, and be too simple to have getters.</p>\n\n<p>In response to @bowmore, the Theme should not be responsible for loading resources, the theme should really return resource identifiers.</p>\n\n<p>If it were me, by the way, I would probably go for</p>\n\n<p><code>game.drawBackground()</code></p>\n\n<p>where game knows what the theme is, and gets from theme the resource name for the background which a loader class then loads and a UI class then displays.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T20:30:07.670", "Id": "31074", "ParentId": "31065", "Score": "5" } }, { "body": "<p>A one liner suggestion</p>\n\n<ul>\n<li>Make the constructors of abstract class <code>protected</code> (<a href=\"https://stackoverflow.com/questions/761854/oo-why-should-constructors-on-abstract-classes-be-protected-not-public\">public is pointless</a>).</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T09:50:30.093", "Id": "31091", "ParentId": "31065", "Score": "1" } }, { "body": "<p>Based on the answers you gave, I came to this decision:</p>\n\n<p><strong>Base classes:</strong></p>\n\n<pre><code>// fictional class only to present Id-type here\npublic class Id {\n public static enum image {\n COSMOS,\n SPACEMAN,\n SPACESHIP,\n FROG_ASTRONAUT\n }\n public static enum sound {\n SHOT,\n DETONATION,\n GRUNT\n }\n public static enum color {\n RED,\n GREEN,\n BLUE,\n BLACK,\n WHITE\n }\n public static enum animation {\n DAMPING,\n BLINKING,\n SHAKE\n }\n}\n\npublic abstract class Theme {\n public final MenuTheme menu;\n public final GameTheme game;\n public abstract Id.image startScreenImageId();\n\n protected Theme(MenuTheme menuTheme, GameTheme gameTheme) {\n this.menu = menuTheme;\n this.game = gameTheme;\n }\n}\n\npublic interface MenuTheme {\n Id.image screenBackgroundId();\n Id.color itemColor();\n Id.animation itemAnimationId();\n}\n\npublic interface GameTheme {\n Id.image screenBackgroundId();\n Id.image gameBoardBackgroundId();\n Id.sound moveSoundId();\n}\n</code></pre>\n\n<p><strong>Example of Theme:</strong></p>\n\n<pre><code>public class CosmosTheme extends Theme {\n public CosmosTheme() {\n super(new CosmosMenuTheme(), new CosmosGameTheme());\n }\n\n @Override\n public Id.image startScreenImageId() {\n return Id.image.SPACEMAN;\n }\n}\n\nclass CosmosMenuTheme implements MenuTheme {\n @Override\n public Id.image screenBackgroundId() {\n return Id.image.FROG_ASTRONAUT;\n }\n\n @Override\n public Id.color itemColor() {\n return Id.color.BLUE;\n }\n\n @Override\n public Id.animation itemAnimationId() {\n return Id.animation.SHAKE;\n }\n}\n\nclass CosmosGameTheme implements GameTheme {\n private static final Id.sound[] MOVE_SOUNDS_IDS = {\n Id.sound.DETONATION, Id.sound.SHOT, Id.sound.GRUNT\n };\n\n @Override\n public Id.image screenBackgroundId() {\n return Id.image.COSMOS;\n }\n\n @Override\n public Id.image gameBoardBackgroundId() {\n return Id.image.SPACESHIP;\n }\n\n @Override\n public Id.sound moveSoundId() {\n Random random = new Random();\n random.setSeed(System.nanoTime());\n int randomIndex = random.nextInt(MOVE_SOUNDS_IDS.length);\n return MOVE_SOUNDS_IDS[randomIndex];\n }\n}\n</code></pre>\n\n<p><strong>And:</strong></p>\n\n<pre><code>public class ThemeInfoProvider {\n public String getInfoAbout(Theme theme) {\n StringBuilder info = new StringBuilder();\n String themeName = theme.getClass().getSimpleName();\n appendAllToBuilder(info,\n themeName, \"\\n\",\n \" startScreenImage: \", theme.startScreenImageId().name(), \"\\n\",\n \" menu:\\n\",\n \" screenBackground: \", theme.menu.screenBackgroundId().name(), \"\\n\",\n \" itemColor: \", theme.menu.itemColor().name(), \"\\n\",\n \" itemAnimation: \", theme.menu.itemAnimationId().name(), \"\\n\",\n \" game:\\n\",\n \" screenBackground: \", theme.game.screenBackgroundId().name(), \"\\n\",\n \" gameBoardBackground: \", theme.game.gameBoardBackgroundId().name(), \"\\n\",\n \" moveSound: \", theme.game.moveSoundId().name(), \"\\n\",\n \"\\n\"\n );\n return info.toString();\n }\n\n public void appendAllToBuilder(StringBuilder builder, String... toAppend) {\n for (String each : toAppend) {\n builder.append(each);\n }\n }\n}\n\npublic class Main {\n public static void main(String[] args) {\n ThemeInfoProvider themeInfoProvider = new ThemeInfoProvider();\n System.out.println(themeInfoProvider.getInfoAbout(new CosmosTheme()));\n }\n}\n</code></pre>\n\n<p>That is, I use resource identifiers instead of resources, final-fields I use only for nested themes - access to any of the resource identifiers costs only a single pair of parentheses.</p>\n\n<p>In getters I do not use the prefix get - IMO, so looks better. It seems to me that for a typical data structure (because Theme does not have the behavior), this prefix is superfluous. Or is it not so?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T10:55:57.390", "Id": "31138", "ParentId": "31065", "Score": "1" } } ]
{ "AcceptedAnswerId": "31074", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T19:01:13.143", "Id": "31065", "Score": "2", "Tags": [ "java", "animation" ], "Title": "Using visual themes in a game" }
31065
<p>I'd appreciate some feedback on my latest PHP script. It is supposed to work like this:</p> <ol> <li>When obtained, it checks whether the cache is still up-to-date</li> <li>IF YES, return the cache; IF NOT, reset the cache</li> <li>Get all JS scripts in the parent directory</li> <li>Minimize the code</li> <li>Add it to the cache</li> <li>Return the cache</li> </ol> <p></p> <pre><code>// Script combines &amp; minimizes all .js files in the parent folder // Result is cached until a change to the files is dealt header('Content-type: application/x-javascript'); $cache_path = 'cache.txt'; $index_path = 'cache-index.txt'; function getScriptsInDirectory(){ $array = Array(); $scripts_in_directory = scandir('.'); foreach ($scripts_in_directory as $script_name) { if (preg_match('/(.+)\.js/', $script_name)) { array_push($array, $script_name); } } return $array; } function compilingRequired(){ global $cache_path; global $index_path; if (file_exists($cache_path) &amp;&amp; file_exists($index_path)) { $cache_time = filemtime($cache_path); $files = getScriptsInDirectory(); foreach ($files as $script_name) { if(filemtime($script_name) &gt; $cache_time) { return true; } } $array = explode(PHP_EOL, file_get_contents($index_path)); foreach($array as $name) { if (!file_exists($name)) { return true; } } return false; } return true; } function compressScript($buffer) { $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); $buffer = str_replace(array("\r\n","\r","\n","\t",' ',' ',' '), '', $buffer); $buffer = preg_replace(array('(( )+{)','({( )+)'), '{', $buffer); $buffer = preg_replace(array('(( )+})','(}( )+)','(;( )*})'), '}', $buffer); $buffer = preg_replace(array('(;( )+)','(( )+;)'), ';', $buffer); return $buffer; } if (compilingRequired()) { if (file_exists($cache_path)){ unlink($cache_path); unlink($index_path); } $scripts_in_directory = getScriptsInDirectory(); $file_handler = fopen($cache_path, 'w+'); $cache_handler = fopen($index_path, 'w+'); foreach ($scripts_in_directory as $name) { if (strlen(file_get_contents($cache_path)) &gt; 0){ fwrite($file_handler, str_repeat(PHP_EOL, 2)); } fwrite($file_handler, '/**** ' . $name . ' ****/' . str_repeat(PHP_EOL, 2)); fwrite($file_handler, compressScript(file_get_contents($name))); fwrite($cache_handler, $name . PHP_EOL); } echo file_get_contents($cache_path); } else { echo file_get_contents($cache_path); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T16:33:22.380", "Id": "49534", "Score": "2", "body": "If you are able to use a more recent version of PHP, try refactoring this as OOP, and try functions like `glob` instead of `scandir`, they're cleaner." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T19:05:34.233", "Id": "49543", "Score": "0", "body": "@MMiller - or even SPL (Directory, DirectoryIterator, RecursiveDirectoryIterator) if they can refactor to OOP on a newer PHP version" } ]
[ { "body": "<p>This snippet at the end...</p>\n\n<pre><code>if (compilingRequired())\n{\n if (file_exists($cache_path)){\n unlink($cache_path); \n unlink($index_path);\n }\n\n $scripts_in_directory = getScriptsInDirectory();\n $file_handler = fopen($cache_path, 'w+');\n $cache_handler = fopen($index_path, 'w+');\n\n foreach ($scripts_in_directory as $name)\n {\n if (strlen(file_get_contents($cache_path)) &gt; 0){\n fwrite($file_handler, str_repeat(PHP_EOL, 2));\n }\n\n fwrite($file_handler, '/**** ' . $name . ' ****/' . str_repeat(PHP_EOL, 2));\n fwrite($file_handler, compressScript(file_get_contents($name)));\n fwrite($cache_handler, $name . PHP_EOL);\n }\n\n echo file_get_contents($cache_path);\n}\nelse\n{\n echo file_get_contents($cache_path);\n}\n</code></pre>\n\n<p>If they both end the same, there's really no need for an else case, you can just put the statement after the if statement.</p>\n\n<pre><code>if (compilingRequired())\n{\n if (file_exists($cache_path)){\n unlink($cache_path); \n unlink($index_path);\n }\n\n $scripts_in_directory = getScriptsInDirectory();\n $file_handler = fopen($cache_path, 'w+');\n $cache_handler = fopen($index_path, 'w+');\n\n foreach ($scripts_in_directory as $name)\n {\n if (strlen(file_get_contents($cache_path)) &gt; 0){\n fwrite($file_handler, str_repeat(PHP_EOL, 2));\n }\n\n fwrite($file_handler, '/**** ' . $name . ' ****/' . str_repeat(PHP_EOL, 2));\n fwrite($file_handler, compressScript(file_get_contents($name)));\n fwrite($cache_handler, $name . PHP_EOL);\n }\n}\necho file_get_contents($cache_path);\n</code></pre>\n\n<p>Ideally, though, it'd read something like</p>\n\n<pre><code>if (compilingRequired())\n{\n compile();\n}\nprintCompressedFiles();\n</code></pre>\n\n<p>Because you want to program on the same level of abstraction - high level code is in \"programmer english\", describing the actions that need to be done (basically that list of 6 steps of yours, maybe compressed a bit). Low level code is pretty much regular code - code actually doing the work.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-24T14:13:40.527", "Id": "123756", "ParentId": "31068", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T19:13:00.277", "Id": "31068", "Score": "2", "Tags": [ "php", "php5", "cache" ], "Title": "Combine and minimize all .js files in parent folder" }
31068
<p>I made a small web application with a search box. I wanted to highlight the words found in the search.</p> <pre><code>foreach my $article (@{$search_articles}) { my @result; foreach my $word (split(' ', $article-&gt;{content})) { if ( $word =~ params-&gt;{search} ) { push(@result, '&lt;span style="background: yellow"&gt;' . $word . '&lt;/span&gt;'); } else { push(@result, $word); } } $article-&gt;{content} = join(' ', @result); } </code></pre> <p>It's a little wordy. It is certainly possible to make cleaner, and I'd like to have your opinion.</p>
[]
[ { "body": "<p>Assuming that your search input is plain characters (i.e., no <code>&lt;</code>, <code>&gt;</code>, and likes), this is still problematic as can ruin your HTML code. Let's say I search for \"border\" in a page that contains <code>&lt;table border=\"1\"&gt;</code>, or \"class\" in virtually any page written in the past 5 years,... IMO, this stuff is better done using a DOM parser and then searching just plain text.</p>\n\n<p>Now, to comment the search itself... Let us assume that the word from your search box is contained in the variable <code>$search</code>. I think this is better done like this:</p>\n\n<pre><code>foreach my $article (@{$search_articles}) {\n $article-&gt;{content} =~ s/\\Q$word\\E/&lt;span style=\"background: yellow\"&gt;$&amp;&lt;\\/span&gt;/g\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T20:05:56.457", "Id": "31073", "ParentId": "31069", "Score": "1" } } ]
{ "AcceptedAnswerId": "31073", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T19:13:27.420", "Id": "31069", "Score": "1", "Tags": [ "perl", "search" ], "Title": "Highlight a pattern found" }
31069
<p>This is not, strictly speaking, code review, but I think my question can be asked here.</p> <p>This is a request to find out what seems to be the cleanest. This project is a blog engine that uses the file system. There are still many things to do to improve the code (it's not great). I have such a class article at initialization that will parse actual items and store it in a structure and CHI a cache system. In CHI, I store a table of hash:</p> <pre><code> push( @articles, { title =&gt; $title, tags =&gt; \@tags, date =&gt; $dt, content =&gt; $content, link =&gt; $url } ); </code></pre> <p>I wonder if it would not be better to make a class item and store it in my cache as an object list:</p> <pre><code> package MahewinBlogEngine::Article; use Moo; use Type::Params qw( compile ); use Type::Utils; use Types::Standard qw( Object Str Int ArrayRef ); has title =&gt; ( is =&gt; 'rw', isa =&gt; Str, required =&gt; 1, ); has tags =&gt; ( is =&gt; 'rw', isa =&gt; ArrayRef, required =&gt; 1, ); has date =&gt; ( is =&gt; 'rw', isa =&gt; Object, required =&gt; 1, ); has content =&gt; ( is =&gt; 'ro', isa =&gt; Str, required =&gt; 1, ); has link =&gt; ( is =&gt; 'ro', isa =&gt; Str, required =&gt; 1, ); 1; </code></pre> <p>And:</p> <pre><code> my $article = MahewinBlogEngine::Article-&gt;new( title =&gt; $title, tags =&gt; \@tags, date =&gt; $dt, content =&gt; $content, link =&gt; $url ); push(@articles, $article); </code></pre> <p>This makes objects more maneuverable, powerful and extensible. It also allows you to add methods such as formatting or other things. But at the moment, I see no specific methods. It will simply be a class with attributes and accessors. So, I wonder what is best in terms of quality, performance and memory.</p> <p>Another question: I think CHI already compresses, but do you think it would be wise to use Sereal and compress before storing in the CHI system cache?</p>
[]
[ { "body": "<p>The CHI uses many caching backends and you did not said which one you are using. Fastest is perl's internal arrays, then hashes and then any other implementations. CHI may use persistent files to caching, like Berkeley DB backend or one of mmap implementation to reduce memory usage. When you are using such caching to improve perfomance you may place cache files to tmpfs (or some of ramfs) on *nix systems (linux, *bsd).</p>\n\n<p>So, when I'm storing a lot of data in cache and I need to reduce memory usage I prefer use BDB without CHI. Then I need speed and managing few data in cache I prefer perl's internal structures. In last case you need to remember that Perl uses optimistic memory allocation. Thats means that Perl reallocates and allocates new memory segments and never returns consumed memory back to the OS. It is very important when writing daemons and you need to limit somehow memory usage. In other cases you may use any caching system and do not worry about performance or memory usage. Just use Devel::NYTProf to find bottlenecks.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T14:24:09.813", "Id": "49931", "Score": "0", "body": "Thank you for this very constructive response. For the moment I use CHI memory as backend." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T21:22:48.613", "Id": "31122", "ParentId": "31071", "Score": "2" } } ]
{ "AcceptedAnswerId": "31122", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T19:41:56.270", "Id": "31071", "Score": "0", "Tags": [ "perl" ], "Title": "Complex structure vs object" }
31071
<p>I have the following code. It's purpose is to add up and sort another columns Data. I tweaked it to fulfil my purpose, but I'm sure it can be cleaned up. </p> <p>The only problem I have with its function is it leaves a trailing zero if the last item in the referenced list is text.</p> <p>Can this be changed without altering how it currently reacts to text? Occasionally, I want the zero's if they fall within the middle of the referenced cells, but never if the last cell is text.</p> <p>My VBA skills are very basic. I can generally alter a piece of code to do what I want, but have no idea on how to fix it.</p> <pre><code>Public Sub SumCages() Dim current_row, summary_row, item_total As Integer current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 7) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 7)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 7)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 8) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 8) = Sheet8.Cells(current_row, 7) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 8) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 11) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 11)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 11)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 12) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 12) = Sheet8.Cells(current_row, 11) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 12) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 15) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 15)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 15)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 16) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 16) = Sheet8.Cells(current_row, 15) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 16) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 19) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 19)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 19)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 20) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 20) = Sheet8.Cells(current_row, 19) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 20) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 23) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 23)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 23)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 24) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 24) = Sheet8.Cells(current_row, 23) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 24) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 27) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 27)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 27)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 28) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 28) = Sheet8.Cells(current_row, 27) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 28) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 31) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 31)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 31)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 32) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 32) = Sheet8.Cells(current_row, 31) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 32) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 35) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 35)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 35)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 36) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 36) = Sheet8.Cells(current_row, 35) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 36) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 39) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 39)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 39)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 40) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 40) = Sheet8.Cells(current_row, 39) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 40) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 43) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 43)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 43)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 44) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 44) = Sheet8.Cells(current_row, 43) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 44) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 47) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 47)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 47)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 48) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 48) = Sheet8.Cells(current_row, 47) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 48) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 51) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 51)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 51)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 52) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 52) = Sheet8.Cells(current_row, 51) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 52) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 55) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 55)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 55)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 56) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 56) = Sheet8.Cells(current_row, 55) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 56) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 59) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 59)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 59)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 60) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 60) = Sheet8.Cells(current_row, 59) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 60) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 63) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 63)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 63)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 64) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 64) = Sheet8.Cells(current_row, 63) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 64) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 67) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 67)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 67)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 68) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 68) = Sheet8.Cells(current_row, 67) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 68) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 71) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 71)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 71)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 72) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 72) = Sheet8.Cells(current_row, 71) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 72) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 75) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 75)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 75)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 76) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 76) = Sheet8.Cells(current_row, 75) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 76) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 79) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 79)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 79)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 80) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 80) = Sheet8.Cells(current_row, 79) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 80) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 83) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 83)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 83)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 84) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 84) = Sheet8.Cells(current_row, 83) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 84) = item_total current_row = 45 summary_row = 44 While Sheet8.Cells(current_row, 87) &lt;&gt; "" If IsNumeric(Sheet8.Cells(current_row, 87)) Then item_total = item_total + Val(Sheet8.Cells(current_row, 87)) Else summary_row = summary_row + 1 ' Advance summary_row If item_total &gt; 0 Then Sheet8.Cells(summary_row, 88) = item_total ' Display total current_row = current_row - 1 ' Correct advancement Else Sheet8.Cells(summary_row, 88) = Sheet8.Cells(current_row, 87) ' Copy label End If item_total = 0 ' Reset item_total End If current_row = current_row + 1 ' Advance current_row Wend Sheet8.Cells(summary_row + 1, 88) = item_total End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T22:37:23.820", "Id": "49473", "Score": "0", "body": "At first glance this looks very repetitive; I'll take a deeper look a bit later, but for now I'm pretty sure you can write a function that starts with `current_row = 45` and ends with `Sheet8.Cells(summary_row + 1, column) = item_total`, and call it as many times as you're repeating this code block. Copy+Paste is never a good sign when coding..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T00:24:46.947", "Id": "49476", "Score": "0", "body": "How and where is the sorting taking place?" } ]
[ { "body": "<p>There are many iterative structures in VBA, but I think the one that would be most useful here is <code>For...Next...Step</code>; in your case, looks like <code>Step</code> should be 4, looping from 7 to 87. </p>\n\n<p>All of your code blocks look very, very similar. I would only keep a single block and replace the hard-coded \"magic numbers\" with variables.</p>\n\n<p>Something like this:</p>\n\n<pre><code>Private Const SUMMARY_ROW As Integer = 44\nPrivate Const START_ROW As Integer = 45 'these two never change.\n'...and if they ever do, that's the only place you need to change them.\n\nPublic Sub SumCages()\n Dim c As Integer\n For c = 7 To 87 Step 4 'start at 7 and +4 per iteration, up to 87\n CalculateTotal c\n Next\nEnd Sub\n</code></pre>\n\n<p>The <code>CalculateTotal</code> procedure is nothing more than one of your code blocks, with the hard-coded row numbers replaced by the <code>SumColumn</code> parameter, which comes from the loop above.</p>\n\n<p>Notice variables' names; variables are your friends, whenever you find yourself repeating a given operation (like, <code>Sheet8.Cells(current_row + 1, SumColumn)</code>), you can improve readability by adding a variable - this way at a glance you know two different places are talking about the same thing.</p>\n\n<pre><code>Private Sub CalculateTotal(sumColumn As Integer)\n\n Dim currentRow As Integer\n Dim targetRow As Integer\n Dim columnTotal As Integer\n Dim thisValue As String\n\n currentRow = START_ROW\n targetRow = SUMMARY_ROW\n targetColumn = sumColumn + 1\n\n With Sheet8 ' this avoids having to specify it every time\n\n thisValue = .Cells(currentRow, sumColumn)\n\n While thisValue &lt;&gt; vbNullString\n\n If IsNumeric(thisValue) Then\n\n 'this is where the sum actually takes place:\n columnTotal = columnTotal + Val(thisValue)\n\n Else\n If columnTotal &gt; 0 Then\n\n .Cells(targetRow + 1, targetColumn) = columnTotal\n\n Else\n\n targetRow = targetRow + 1 'not sure I get why this is done...\n currentRow = currentRow - 1 '...and this is even more confusing...\n .Cells(targetRow, targetColumn) = thisValue\n\n End If\n\n 'this is likely throwing off your total!\n columnTotal = 0\n End If\n\n currentRow = currentRow + 1\n thisValue = .Cells(currentRow, SumColumn)\n Wend\n\n .Cells(targetRow, targetColumn) = columnTotal\n\n End With\nEnd Sub\n</code></pre>\n\n<p>It would be nice if you could post a screenshot of what the result looks like, because it's quite confusing (to me, at least) why you're incrementing your write-to row and then decrementing your loop counter, but only when you hit a non-numeric value.</p>\n\n<p>To me it looks like what you have as <code>current_row = current_row - 1 ' Correct advancement</code> should really read <code>summary_row = summary_row - 1 ' Correct advancement</code>, because I would think it's an infinite loop written like this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T22:50:58.970", "Id": "31076", "ParentId": "31075", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T20:48:36.130", "Id": "31075", "Score": "6", "Tags": [ "vba", "excel" ], "Title": "Add up & sort a spreadsheet column" }
31075
<p>I'm trying to brush up on my Dynamic Programming by doing some example problems. I've got the following...</p> <p>Given an array of integers, print the longest decreasing segment.</p> <p>For example <code>{4,3,2,1,5,6,7,6,5,4,3,2,1}</code> would print <code>"7, 6, 5, 4, 3, 2, 1"</code></p> <p>The following is my solution.. I think it looks okay and it has a decent <code>O(n)</code> runtime. However, the space complexity is <code>O(n^2)</code> due to the extra "length" array storing state. Is it possible to get rid of it? Any other problems? </p> <pre><code>int[] segment = {4,3,2,1,5,6,7,6,5,4,3,2,1}; int[] length = {0,0,0,0,0,0,0,0,0,0,0,0,0}; public String getDecreasingSegment(){ int maxStart = 0; int maxEnd = 0; for(int i = 1; i &lt; segment.length; i++){ if(segment[i] &lt; segment[i-1]){ length[i] = length[i-1]+1; if(length[i] &gt; length[maxEnd]){ maxEnd = i; maxStart = maxEnd - length[maxEnd]; } }else{ length[i] = 0; } } StringBuffer buff = new StringBuffer(); for(int i = maxStart; i &lt;= maxEnd; i++){ buff.append(segment[i] + ", "); } return buff.toString(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T04:16:52.050", "Id": "49489", "Score": "2", "body": "Having an extra array doesn't imply a space complexity of O(n^2). Your space complexity is still O(n)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T16:27:38.817", "Id": "49532", "Score": "0", "body": "Just to clarify for OP: With space complexity of O(n^2), if you had 5 elements, your algoritm would use 5*5 = 25 memory used for integers. Since you are only creating two arrays, your memory used would be 5*2 = 10. This makes it linear, not quadratic." } ]
[ { "body": "<p>As said above adding an extra Array does not change the space complexity to n^2. </p>\n\n<ul>\n<li>Another thing is you do not need that extra Array also. All you need is 3 or 4 variables. </li>\n<li>You can store the previous beginIndex and length of and the currentBeginIndex and length and if it crosses the previous maxLength then store the max as the crrentMax else continue with the iteration. </li>\n</ul>\n\n<p>Let me know if you want some code sample.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T07:33:12.157", "Id": "31081", "ParentId": "31078", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T03:42:36.407", "Id": "31078", "Score": "1", "Tags": [ "java", "algorithm" ], "Title": "Print Longest Decreasing Segment" }
31078
<p>The program is behaving like expected, but I think something better can be done since I'm a novice C programmer. I suspect that the interrupt handler can use some other way of calling the hardware instead of direct memory. Can you look and tell me what can be improved?</p> <pre><code>#include &lt;stdio.h&gt; #include "system.h" #include "altera_avalon_pio_regs.h" /* Include header file for alt_irq_register() */ #include "alt_irq.h" extern int initfix_int(void); extern void puttime(int* timeloc); extern void puthex(int time); extern void tick(int* timeloc); extern void delay(int millisec); extern int hexasc(int invalue); #define TRUE 1 #define KEYS4 ( (unsigned int *) 0x840 ) #define NULL_POINTER ( (void *) 0) int timeloc = 0x5957; /* startvalue given in hexadecimal/BCD-code */ int RUN = 1; #define TIMER1 ( (unsigned int *) 0x920 ) #define PERIOD (49999) /* Define addresses etc for de2_pio_keys4 */ volatile int * const de2_pio_keys4_base = (volatile int *) 0x840; volatile int * const de2_pio_keys4_intmask = (volatile int *) 0x848; volatile int * const de2_pio_keys4_edgecap = (volatile int *) 0x84c; const int de2_pio_keys4_intindex = 2; const int de2_pio_keys4_irqbit = 1 &lt;&lt; 2; /* Define address for de2_pio_hex_low28 */ volatile int * de2_pio_hex_low28 = (volatile int *) 0x9f0; /* * The n2_fatal_error function is called for unexpected * conditions which most likely indicate a programming error * somewhere in this file. The function prints "FATAL ERROR" * using out_char_uart_0, lights an "Err" pattern on the * seven-segment display, and then enters an infinite loop. */ void n2_fatal_error() { /* Define the pattern to be sent to the seven-segment display. */ #define N2_FATAL_ERROR_HEX_PATTERN ( 0xcbd7ff ) /* Define error message text to be printed. */ static const char n2_fatal_error_text[] = "FATAL ERROR"; /* Define pointer for pointing into the error message text. */ register const char * cp = n2_fatal_error_text; /* Send pattern to seven-segment display. */ *de2_pio_hex_low28 = N2_FATAL_ERROR_HEX_PATTERN; /* Print the error message. */ while (*cp) { //out_char_uart_0( *cp ); cp = cp + 1; } /* Stop and wait forever. */ while (1) ; } /* * Interrupt handler for de2_pio_keys4. * The parameters are ignored here, but are * required for correct compilation. * The type alt_u32 is an Altera-defined * unsigned integer type. * * To help debugging interruptible interrupt-handlers, * this handler delays a long while when a key is pressed. * However, there is no delay when the key is released. * * We keep a software copy of the LED value, since * the parallel output ports are not program-readable. * * Example: we send out the value 1 on de2_pio_keys4, * by executing *DE2_PIO_KEYS4_BASE = 1; * Then we try to read the port by executing * int test_val = *DE2_PIO_KEYS4_BASE; // WRONG * The value of test_val is now undefined. * The port returns some bits which are not related * to the value we have written. * * The software copy of the LED value * for this interrupt handler * is the global variable myleds, defined above. */ void irq_handler_keys(void * context, alt_u32 irqnum) { alt_u32 save_value; save_value = alt_irq_interruptible(de2_pio_keys4_intindex); /* Read edge capture register of the de2_pio_keys4 device. */ int edges = *de2_pio_keys4_edgecap; *de2_pio_keys4_edgecap = 0; /* If action on KEY0 */ if (edges &amp; 1) { /* If KEY0 is pressed now */ if ((*de2_pio_keys4_base &amp; 1) == 0) { if (RUN == 0) { RUN = 1; } else { RUN = 0; } } /* If KEY0 is released now */ else if ((*de2_pio_keys4_base &amp; 1) != 0) { } alt_irq_non_interruptible(save_value); } else if (edges &amp; 2) { /* If KEY1 is pressed now */ if ((*de2_pio_keys4_base &amp; 2) == 0) { tick(&amp;timeloc); puttime(&amp;timeloc); puthex(timeloc); } /* If KEY1 is released now */ else if ((*de2_pio_keys4_base &amp; 2) != 0) { } alt_irq_non_interruptible(save_value); } else if (edges &amp; 4) { /* If KEY2 is pressed now */ if ((*de2_pio_keys4_base &amp; 4) == 0) { timeloc = 0x0; puttime(&amp;timeloc); puthex(timeloc); } /* If KEY2 is released now */ else if ((*de2_pio_keys4_base &amp; 4) != 0) { } alt_irq_non_interruptible(save_value); } else if (edges &amp; 8) { /* If KEY3 is pressed now */ if ((*de2_pio_keys4_base &amp; 8) == 0) { timeloc = 0x5957; puttime(&amp;timeloc); puthex(timeloc); } /* If KEY3 is released now */ else if ((*de2_pio_keys4_base &amp; 8) != 0) { } alt_irq_non_interruptible(save_value); } } /* * Initialize de2_pio_keys4 for interrupts. */ void keysinit_int(void) { /* Declare a temporary for checking return values * from system-calls and library functions. */ register int ret_val_check; /* Allow interrupts */ *de2_pio_keys4_intmask = 15; /* Set up Altera's interrupt wrapper for * interrupts from the de2_pio_keys4 device. * The function alt_irq_register will enable * interrupts from de2_pio_keys4. * Return value is zero for success, * nonzero for failure. */ ret_val_check = alt_irq_register(de2_pio_keys4_intindex, NULL_POINTER, irq_handler_keys); /* If there was an error, terminate the program. */ if (ret_val_check != 0) n2_fatal_error(); } int main() { /* Remove unwanted interrupts. * initfix_int is supplied by KTH. * A nonzero return value indicates failure. */ if (initfix_int() != 0) n2_fatal_error(); keysinit_int(); int counter = 0; while (1) { delay(1); ++counter; if (counter % 1000 == 0) { IOWR_ALTERA_AVALON_PIO_DATA(DE2_PIO_REDLED18_BASE, timeloc); if (RUN == 1) { tick(&amp;timeloc); puttime(&amp;timeloc); puthex(timeloc); } } } return 0; } int hex7seg(int digit) { int trantab[] = { 0x40, 0x79, 0x24, 0x30, 0x19, 0x12, 0x02, 0x78, 0x00, 0x10, 0x08, 0x03, 0x46, 0x21, 0x06, 0x0e }; register int tmp = digit &amp; 0xf; return (trantab[tmp]); } void puthex(int inval) { unsigned int hexresult; hexresult = hex7seg(inval); hexresult = hexresult | (hex7seg(inval &gt;&gt; 4) &lt;&lt; 7); hexresult = hexresult | (hex7seg(inval &gt;&gt; 8) &lt;&lt; 14); hexresult = hexresult | (hex7seg(inval &gt;&gt; 12) &lt;&lt; 21); IOWR_ALTERA_AVALON_PIO_DATA(DE2_PIO_HEX_LOW28_BASE, hexresult); } </code></pre>
[]
[ { "body": "<p>The interrupt handler looks a little verbose. There are too many comments, most of which are 'noise' (they contribute little, also true elsewhere) and there are many empty sections (key-up detection). Here is a simplified version if the ISR:</p>\n\n<pre><code>void irq_handler_keys(void *context, alt_u32 irqnum) \n{\n const alt_u32 save_value = alt_irq_interruptible(irqnum);\n const unsigned edges = *de2_pio_keys4_edgecap;\n const unsigned keys = ~*de2_pio_keys4_base; // inverted\n\n *de2_pio_keys4_edgecap = 0;\n\n if (edges &amp; PIO_KEYS4_TICK &amp; keys) {\n tick(&amp;timeloc);\n puttime(&amp;timeloc);\n puthex(timeloc);\n } else if (edges &amp; PIO_KEYS4_RUN &amp; keys) {\n RUN ^= 1;\n } else if (edges &amp; PIO_KEYS4_ZERO &amp; keys) {\n timeloc = ZERO_TIME;\n puttime(&amp;timeloc);\n puthex(timeloc);\n } else if (edges &amp; PIO_KEYS4_RESET &amp; keys) {\n timeloc = INITIAL_TIME;\n puttime(&amp;timeloc);\n puthex(timeloc);\n }\n alt_irq_non_interruptible(save_value);\n}\n</code></pre>\n\n<p>The changes are clear, but I'll run through them. </p>\n\n<ul>\n<li>Firstly the call to <code>alt_irq_interruptible</code> needs to be balanced by just one call to <code>alt_irq_non_interruptible</code>, not four. And passing <code>irqnum</code> seems more logical to me than passing your assumed interrupt number. </li>\n<li>The registers seem more like <code>unsigned</code> values than <code>int</code> values (eg you can't add them) and the keys register need only be read at the start of the function. </li>\n<li>I reordered the tests to check the most likely one first. While this makes no significant difference if the ticking occurs once a second (although why is it coming through a key press if it is a clock tick? - maybe I am reading too much into the function-call names), this is an ISR so efficiency is important to bear in mind.</li>\n<li><p>I have removed the redundant conditions to make the body rather simpler (the compiler would do this too so it is not significant at run time). This also changes what the function does (ie. it descends the if-else sequence until it finds a falling edge rather than just any edge) which might not be what you wanted.</p></li>\n<li><p>And I used constants instead of 1,2,4,8 etc. </p></li>\n</ul>\n\n<p>Note that <code>RUN</code> and <code>timeloc</code> should be <code>volatile</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T14:12:25.833", "Id": "49518", "Score": "0", "body": "Thanks a lot for the answer. It is part of the project to increment a tick when pressing a key as well as counting up once per second. So therefore the call to tick is included in the interrupt for one of the keys." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T13:51:46.487", "Id": "31101", "ParentId": "31080", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T06:51:12.240", "Id": "31080", "Score": "1", "Tags": [ "c", "beginner", "fpga" ], "Title": "Hardware interrupts for Nios 2" }
31080
<p>I am trying to use IXMLDOMDocument for XML reading/writing. I am not good COM, and I am not aware that I am doing things right or wrong. I am very unsure that there could be some problems with COM initialization and relase. Here is my code below and let me know If there are any possibles bugs / memory leaks here due to COM. </p> <pre><code>void MyClass::ReadXML(BSTR *pVal) { IXMLDOMDocument * pXMLDoc; IXMLDOMNode * pXDN; HRESULT hr = CoInitialize(NULL); hr = CoCreateInstance(CLSID_DOMDocument, NULL, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument, (void**)&amp;pXMLDoc); if (SUCCEEDED(hr)) { IXMLDOMNode* pEntityNode = CDOMHelpers::InsertDOMElement(pDoc, NULL, L"Person", NULL); if (SUCCEEDED(hr)) { SomeClassObject-&gt;SerializeXML(pXMLDoc, pXDN); pXMLDoc-&gt;get_xml(pVal); pXDN-&gt;Release(); // Is this proper way to release COM? pXDN = NULL; pXMLDoc-&gt;Release(); pXMLDoc = NULL; } } } void SomeOtherClass::SerializeXML(IXMLDOMDocument* pDoc, IXMLDOMNode* pXDN) { CStringW text; IXMLDOMNode* pNewNode; text.Format(L"%u", Name); pNewNode = CDOMHelpers::InsertDOMElement(pDoc, pEntityNode, L"Name", text); text.Format(L"%u", Address); pNewNode = CDOMHelpers::InsertDOMElement(pDoc, pEntityNode, L"Address", text); } </code></pre>
[]
[ { "body": "<p>MSDN documentation for this is a mess and for the most part, inadequate (it's better than MSDN's C++ ADO documentation though). </p>\n\n<p>If you have access to <a href=\"http://msdn.microsoft.com/en-us/library/ms757018%28v=vs.85%29.aspx\" rel=\"noreferrer\">MSXML</a>, then you can use smart pointer wrappers that allow you to avoid worrying about releasing the objects. These smart pointers come with simplified function calls. </p>\n\n<p>For instance, here is the normal function prototype for a <code>IXMLDOMNodeList</code>:</p>\n\n<pre><code>HRESULT IXMLDOMNodeList::get_length(long *listLength);\n</code></pre>\n\n<p>Here is the \"smart\" version of that function for <code>IXMLDOMNodeList</code> object:</p>\n\n<pre><code>long IXMLDOMNodeList::Getlength ();\n</code></pre>\n\n<p>This allows you skip the error checking (it throws an exception on failure).<br>\nYou also have access to the source code for these new functions as well. The source code is in an automatically generated <code>.tli</code> file, so you can always know what they do. The <code>.tli</code> file is usually located in <code>C:\\Users\\*User*\\Local\\Temp\\msxml6.tli</code>. Just looking through this file can help you partially learn how to use <code>IXMLDom</code>. </p>\n\n<p>If you have access to <code>comutil.h</code>, you can use the <a href=\"http://msdn.microsoft.com/en-us/library/zthfhkd6%28v=vs.90%29.aspx\" rel=\"noreferrer\">_bstr_t</a> type instead of <code>BSTR</code> for automatic memory management as well. </p>\n\n<p>Here are a few examples of using the smart pointers. I used standard library containers such as <code>std::string</code> and <code>std::vector</code>, but you could easily change these out with CStrings or other string types. </p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;tchar.h&gt;\n#include &lt;comutil.h&gt;\n#import &lt;msxml6.dll&gt;\n\ntypedef std::basic_string &lt;TCHAR&gt; tstring ;\n\ntypedef MSXML2::IXMLDOMNodePtr NodePtr ;\ntypedef MSXML2::IXMLDOMNodeListPtr NodeListPtr ;\ntypedef MSXML2::IXMLDOMDocumentPtr DocumentPtr ;\ntypedef MSXML2::IXMLDOMElementPtr ElementPtr ;\ntypedef MSXML2::IXMLDOMNamedNodeMapPtr NamedNodeMapPtr ;\n\nDocumentPtr LoadXMLDocument (const tstring &amp;strFile)\n{\n // Call ::CoInitialize or ::CoInitializeEx before this.\n HRESULT hr ;\n DocumentPtr pDoc = NULL ;\n hr = pDoc.CreateInstance (__uuidof (MSXML2::DOMDocument60)) ; \n if (hr != S_OK) {\n // This could happen if ::CoInitialize or ::CoInitializeEx hasn't been called.\n // Throw an exception.\n }\n\n pDoc-&gt;async = VARIANT_FALSE ;\n pDoc-&gt;validateOnParse = VARIANT_FALSE ;\n pDoc-&gt;resolveExternals = VARIANT_FALSE ;\n\n VARIANT_BOOL vbOk = pDoc-&gt;load (_variant_t (strFile.data ())) ;\n\n if (vbOk == VARIANT_FALSE) {\n // Throw an exception.\n }\n\n return pDoc ;\n}\n\ntstring GetAttribute (const NamedNodeMapPtr &amp;pAttrs, const tstring &amp;strKey)\n{\n tstring str ;\n\n NodePtr pAttr = pAttrs-&gt;getNamedItem (_bstr_t (strKey.data ())) ;\n if (pAttr == NULL) {\n // Throw an exception.\n }\n\n _variant_t var = pAttr-&gt;GetnodeValue () ;\n if (var.vt == VT_BSTR) {\n str = (TCHAR *) (_bstr_t) var ;\n\n } else {\n // Throw an exception.\n }\n\n return str ;\n}\n\ntstring GetAttribute (const NodePtr &amp;pNode, const tstring &amp;strKey)\n{\n NamedNodeMapPtr pAttrs = pNode-&gt;Getattributes () ;\n return GetAttribute (pAttrs, strKey) ;\n}\n\ntstring GetSubElementText (const ElementPtr &amp;pNode, const tstring &amp;strSubElement)\n{\n NodePtr pSub = pNode-&gt;selectSingleNode (_bstr_t (strSubElement.data ())) ;\n if (pSub == NULL) {\n // Throw an exception.\n }\n\n _bstr_t bsRoot = pSub-&gt;Gettext () ;\n tstring strText = (TCHAR *) bsRoot ;\n return strText ;\n}\n\nvoid GetAttributes (const NodePtr &amp;pNode, const std::vector &lt;tstring&gt; &amp;vecKeys, std::vector &lt;tstring&gt; &amp;vecValues, const tstring &amp;strDefault)\n{\n NamedNodeMapPtr pAttrs = pNode-&gt;Getattributes () ;\n for (unsigned n = 0; n &lt; vecKeys.size (); ++n) {\n const tstring &amp;strKey = vecKeys [n] ;\n tstring str = BVLib::GetAttribute (pAttrs, strKey) ;\n vecValues.push_back (str) ;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T22:21:09.347", "Id": "35947", "ParentId": "31084", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T08:38:13.453", "Id": "31084", "Score": "4", "Tags": [ "c++", "memory-management", "dom", "com" ], "Title": "Proper way of using IXMLDOMDocument" }
31084
<p>I'm relatively new to PHP and have recently created a small website for friends and family to upload and share photos, protected by a very simple login system.</p> <p>While I'm aware what I'm doing isn't best practice and you'd never use this in a "published" site, I'd like to use this as learning experience to improve my coding, and would appreciate any pointers as to best practice and efficiency/security improvements.</p> <p>The website contains no sensitive information and the login was purely to prevent unwanted uploading of files. The username isn't checked against anything and is only used to log who's uploaded a file. The password is shared for all users.</p> <p>This script, login.php, is included at the top of each page and checks if the user is logged in - if not then redirect to homepage where the login form is displayed. If already logged in, then display some internal links instead of form.</p> <pre><code>if(!isset($_SESSION)){ session_start(); } /***********************************************************/ //check if home page if (/*code to check if outside root directory*/) }{$notHomePage = true;} if($notHomePage and ($_SESSION['allow'] == false or !isset($_SESSION['allow'])) ) { $_SESSION['error'] = 'Please enter your name and password!'; header('Location: index.php'); exit(); } /***********************************************************/ function readCookie() { if (isset($_COOKIE["username"])) { $name = $_COOKIE["username"]; } return $name; } /***********************************************************/ function loginForm() { if($_SESSION['allow']) { //display internal links and logout link echo "&lt;p&gt;&lt;a href=\"login.php?logout\"&gt;Logout&lt;/a&gt;&lt;/p&gt;"; } else { if(isset($_SESSION['error'])) { echo "&lt;div&gt;" . $_SESSION['error'] . "&lt;/div&gt;"; unset($_SESSION['error']); } $name = readCookie(); echo "&lt;form method=\"post\" action=\"login.php\"&gt; &lt;input type=\"text\" value=\"$name\" name=\"name\"&gt;&lt;label&gt;Name&lt;/label&gt; &lt;input type=\"password\" name=\"password\"&gt;&lt;label&gt;Password&lt;/label&gt; &lt;button type=\"submit\" name=\"submit\"&gt;Login&lt;/button&gt; &lt;/form&gt;"; } } /***********************************************************/ function login() { $days = 30; if(trim($_POST['name']) == "" || trim($_POST['password']) == "") { $_SESSION['error'] = 'Please enter your name and password!'; header('Location: index.php'); exit(); } $name = $_POST['name']; $password = $_POST['password']; $pass = "password"; //passsword goes here if ($password != $pass) { $_SESSION['error'] = 'Please enter the correct password!'; header('Location: index.php'); exit(); } else { $_SESSION['allow'] = true; header('Location: index.php'); } if($days) $expire = time()+60*60*24*$days; setcookie("username", $name, $expire,"/"); } /***********************************************************/ if($_SERVER['REQUEST_METHOD'] == "POST") { login(); } if($_SERVER['QUERY_STRING'] == "logout") { $_SESSION['allow'] = false; header("Location: index.php"); exit; } ?&gt; </code></pre>
[]
[ { "body": "<p>I'd like to think security as a thing that at first refuses everything, and after that permits something specific. Your code does the opposite at the moment. It checks that if the user is NOT logged in, and if the condition does not pass, the user is permitted to view the page.</p>\n\n<p>I'd do the opposite. I would first check that if the user IS logged in, and only after that permit the user to view the page if the condition pass. It is more strict when it comes to potential bugs, which means that if something goes wrong, the user will not be permitted anyhow.</p>\n\n<p>Second thing, you really do not want to tell the browser the user name in the cookie you set. Instead you should hash it with some <a href=\"http://en.wikipedia.org/wiki/Salt_%28cryptography%29\" rel=\"nofollow\">secret salt</a> if it really is necessary to send it to the browser. Remember, every detail you send to the browser is a potential security risk that someone (<a href=\"http://en.wikipedia.org/wiki/Man-in-the-middle_attack\" rel=\"nofollow\">man-in-the-middle attack</a>, viruses, other malware) might abuse.</p>\n\n<p>And then, if that is a php script you include at the top of every page, why do you include the login form there? It seems to me that you only display it when you are on index.php. It is not needed elsewhere. Of course this is not a big issue, but it's the tiny little seed of bloated software that will grow in time if not treated carefully. And by this I mean that if you begin to add lots and lots of thing that is being used in only one place, it will make the script run so much slower.</p>\n\n<p>Also, I see a potential bug there. If you ever wanted to add a POST form (say, a guestbook or chat or shoutbox or your own forum) on your website, you will trigger the login() function every time when ANY of those POST forms get submitted. The login() function will not then find the correct data in the POST variable, and will refuse to display the page.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T11:25:33.807", "Id": "31096", "ParentId": "31087", "Score": "1" } }, { "body": "<p><strong>1.)</strong> I see you using a mix of single and double quotes, but it looks rather arbitrary.</p>\n<p>The difference between the two is, that you can use variables in double quoted strings (<a href=\"https://www.php.net/manual/en/language.types.string.php\" rel=\"nofollow noreferrer\">String</a> Interpolation):</p>\n<pre class=\"lang-php prettyprint-override\"><code>$username = 'Jon';\necho &quot;Hello, $username. See what's new:&quot;;\n</code></pre>\n<p>This isn't possible with single quoted strings. Therefor single quoted string have slightly better performance and are more readable (since you already know that theres not going to be a variable hidden inside).</p>\n<p>So you should generally use single quouted strings as a default and double quoted strings for interpolation.</p>\n<p>But there's more:</p>\n<pre class=\"lang-php prettyprint-override\"><code>echo &quot;&lt;form method=\\&quot;post\\&quot; action=\\&quot;login.php\\&quot;&gt;\n &lt;input type=\\&quot;text\\&quot; value=\\&quot;$name\\&quot; name=\\&quot;name\\&quot;&gt;&lt;label&gt;Name&lt;/label&gt;\n &lt;input type=\\&quot;password\\&quot; name=\\&quot;password\\&quot;&gt;&lt;label&gt;Password&lt;/label&gt;\n &lt;button type=\\&quot;submit\\&quot; name=\\&quot;submit\\&quot;&gt;Login&lt;/button&gt;\n &lt;/form&gt;&quot;;\n</code></pre>\n<p>See how you need to escape every single double quotation mark?\nNow try the same with single quotes:</p>\n<pre class=\"lang-php prettyprint-override\"><code>echo '&lt;form method=&quot;post&quot; action=&quot;login.php&quot;&gt;\n &lt;input type=&quot;text&quot; value=&quot;'.$name.'&quot; name=&quot;name&quot;&gt;&lt;label&gt;Name&lt;/label&gt;\n &lt;input type=&quot;password&quot; name=&quot;password&quot;&gt;&lt;label&gt;Password&lt;/label&gt;\n &lt;button type=&quot;submit&quot; name=&quot;submit&quot;&gt;Login&lt;/button&gt;\n &lt;/form&gt;';\n</code></pre>\n<p>It's much cleaner, eventhough you now need to concatenate <code>$name</code>.</p>\n<p><strong>2.)</strong> Also, I'd recommend using the strict comparision <code>===</code>, see: <a href=\"https://stackoverflow.com/questions/80646/how-do-the-php-equality-double-equals-and-identity-triple-equals-comp\">PHP equality vs. identity comparision</a>.</p>\n<p><strong>3.)</strong> What does <code>readCookie</code> return, if the cookie isn't set?\nI think using the <a href=\"https://stackoverflow.com/questions/34571330/php-ternary-operator-vs-null-coalescing-operator\">PHP null coalescing operator <code>??</code></a> to specify a default is cleaner:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function readCookie() {\n return $_COOKIE[&quot;username&quot;] ?? '&lt;UNKNOWN&gt;';\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-04T00:16:33.990", "Id": "244981", "ParentId": "31087", "Score": "1" } } ]
{ "AcceptedAnswerId": "31096", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T09:10:28.000", "Id": "31087", "Score": "4", "Tags": [ "php", "security" ], "Title": "Very simple login script review" }
31087
<p>I'm try to implement the <a href="https://ece.uwaterloo.ca/~z70wang/research/ssim/" rel="nofollow">SSIM</a> method. This method has already been implemented in Python (<a href="http://isit.u-clermont1.fr/~anvacava/code.html" rel="nofollow">source code</a>), but my goal is implement it with using only Python and NumPy.</p> <p>My goal is also to use this method on big images (1024x1024 and above). But <code>filter2</code> works very slow (approx. 62 sec. for 1024x1024). cProfile gives me information that <strong>_methods.py:16(_sum)</strong>, <strong>fromnumeric.py:1422(sum)</strong>, and <strong>method 'reduce' of 'numpy.ufunc' objects</strong> eat main part time of run.</p> <pre><code>import numpy def filter2(window, x): range1 = x.shape[0] - window.shape[0] + 1 range2 = x.shape[1] - window.shape[1] + 1 res = numpy.zeros((range1, range2), dtype=numpy.double) x1 = as_strided(x,((x.shape[0] - 10)/1 ,(x.shape[1] - 10)/1 ,11,11), (x.strides[0]*1,x.strides[1]*1,x.strides[0],x.strides[1])) * window for i in xrange(range1): for j in xrange(range2): res[i,j] = x1[i,j].sum() return res def ssim(img1, img2): window = numpy.array([\ [0.0000, 0.0000, 0.0000, 0.0001, 0.0002, 0.0003, 0.0002, 0.0001, 0.0000, 0.0000, 0.0000],\ [0.0000, 0.0001, 0.0003, 0.0008, 0.0016, 0.0020, 0.0016, 0.0008, 0.0003, 0.0001, 0.0000],\ [0.0000, 0.0003, 0.0013, 0.0039, 0.0077, 0.0096, 0.0077, 0.0039, 0.0013, 0.0003, 0.0000],\ [0.0001, 0.0008, 0.0039, 0.0120, 0.0233, 0.0291, 0.0233, 0.0120, 0.0039, 0.0008, 0.0001],\ [0.0002, 0.0016, 0.0077, 0.0233, 0.0454, 0.0567, 0.0454, 0.0233, 0.0077, 0.0016, 0.0002],\ [0.0003, 0.0020, 0.0096, 0.0291, 0.0567, 0.0708, 0.0567, 0.0291, 0.0096, 0.0020, 0.0003],\ [0.0002, 0.0016, 0.0077, 0.0233, 0.0454, 0.0567, 0.0454, 0.0233, 0.0077, 0.0016, 0.0002],\ [0.0001, 0.0008, 0.0039, 0.0120, 0.0233, 0.0291, 0.0233, 0.0120, 0.0039, 0.0008, 0.0001],\ [0.0000, 0.0003, 0.0013, 0.0039, 0.0077, 0.0096, 0.0077, 0.0039, 0.0013, 0.0003, 0.0000],\ [0.0000, 0.0001, 0.0003, 0.0008, 0.0016, 0.0020, 0.0016, 0.0008, 0.0003, 0.0001, 0.0000],\ [0.0000, 0.0000, 0.0000, 0.0001, 0.0002, 0.0003, 0.0002, 0.0001, 0.0000, 0.0000, 0.0000]\ ], dtype=numpy.double) K = [0.01, 0.03] L = 65535 C1 = (K[0] * L) ** 2 C2 = (K[1] * L) ** 2 mu1 = filter2(window, img1) mu2 = filter2(window, img2) mu1_sq = numpy.multiply(mu1, mu1) mu2_sq = numpy.multiply(mu2, mu2) mu1_mu2 = numpy.multiply(mu1, mu2) sigma1_sq = filter2(window, numpy.multiply(img1, img1)) - mu1_sq sigma2_sq = filter2(window, numpy.multiply(img2, img2)) - mu2_sq sigma12 = filter2(window, numpy.multiply(img1, img2)) - mu1_mu2 ssim_map = numpy.divide(numpy.multiply((2*mu1_mu2 + C1), (2*sigma12 + C2)), numpy.multiply((mu1_sq + mu2_sq + C1),(sigma1_sq + sigma2_sq + C2))) return numpy.mean(ssim_map) def calc_ssim(): img1 = numpy.array(numpy.zeros((1024,1024)),dtype=numpy.double) img2 = numpy.array(numpy.zeros((1024,1024)),dtype=numpy.double) return ssim(img1, img2) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-08T18:37:12.853", "Id": "395687", "Score": "0", "body": "Can this be updated to Python 3?" } ]
[ { "body": "<p>In your strided <code>filter2</code>, <code>x1</code> is <code>(1014, 1014, 11, 11)</code>. You are iterating over the 1st 2 dimensions in order to sum on on the last 2. Let <code>sum</code> do all the work for you, <code>res = x1.sum((2,3))</code></p>\n\n<pre><code>def filter2(window, x):\n range1 = x.shape[0] - window.shape[0] + 1\n range2 = x.shape[1] - window.shape[1] + 1\n x1 = as_strided(x,((x.shape[0] - 10)/1 ,(x.shape[1] - 10)/1 ,11,11), (x.strides[0]*1,x.strides[1]*1,x.strides[0],x.strides[1])) * window\n res = x1.sum((2,3))\n return res\n</code></pre>\n\n<p>In my tests this gives a 6x speed improvement.</p>\n\n<p>With <code>numpy</code> iteration, especially nested ones over large dimensions like <code>1014</code> is a speed killer. You want to vectorize this kind of thing as much as possible.</p>\n\n<p>Traditionally Matlab had the same speed problems, but newer versions recognize and compile loops like yours. That's why your numpy is so much slower.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-30T05:34:08.310", "Id": "51118", "Score": "0", "body": "thank you, for explanation! On my machine execute time reduced to ~4.3 s." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-26T06:07:29.610", "Id": "31840", "ParentId": "31089", "Score": "2" } } ]
{ "AcceptedAnswerId": "31840", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T09:34:55.793", "Id": "31089", "Score": "6", "Tags": [ "python", "numpy" ], "Title": "Using the SSIM method for large images" }
31089
<p>The idea is to write a function that reads string of unknown size from <code>stdin</code>, keep it in dynamically allocated array of unknown size and return a copy of that array.</p> <p>Is this the right approach? Could I be more clear? Would reading the input char-by-char be better than getting bigger chunks at once?</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;stdio.h&gt; char * read_string(void) { int buff_size = 11; /* size of temporary buffer */ char temp[11]; /* temporary input buffer */ char *output; /* pointer to allocated memory */ char *copy; /* copy of input string to be returned */ char *iterator; /* pointer to beginning of an array, used when searching for \n in input string */ output = malloc(10*sizeof(char)); /* allocates 10 bytes for first part of input */ if(output == NULL) return NULL; size_t size = 10*sizeof(char); /* keeps track of actual size of output */ //*output = '\0'; /* places NUL at the beginning of output, to make it empty string */ while(fgets(temp, buff_size,stdin) != NULL) /* read max 10 chars from input to temp */ { strcat(output,temp); /* append read input to output, without \0 char */ if(strlen(temp) != 10 || temp[9] == '\n') /* if buffer wasn't full or last char was \n-stop because it reached the end of input string */ break; size += buff_size - 1; /* if didn' reach end of input increase size of output*/ output = realloc(output,size); if(output == NULL) { return NULL; } } iterator = output; /* search for \n in output and replace it with \0 */ while(*iterator != '\n') iterator++; *iterator='\0'; copy=malloc(strlen(output) + 1); /* allocate memory for copy of output +1 for \0 char */ if(copy == NULL) return NULL; strcpy(copy, output); /* strcpy output to copy */ free(output); /* free memory taken by output */ return copy; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T12:06:22.790", "Id": "49511", "Score": "2", "body": "I edited your code to make it more readable. Also, note that `sizeof(char)` is 1 by definition, so multiplying by it is redundant." } ]
[ { "body": "<p>It would be wise to check if the reallocation of the memory worked.</p>\n\n<p>Also, this:</p>\n\n<pre><code>copy=malloc(strlen(output)+1); /* allocate memory for copy of output +1 for \\0 char */\nif(copy==NULL)\n return NULL;\nstrcpy(copy, output); /* strcpy output to copy */\nfree(output); /* free memory taken by output */\nreturn copy;\n</code></pre>\n\n<p>Why making a copy of <code>output</code>, freeing <code>output</code>, and then returning <code>copy</code>? Why not just returning <code>output</code>?</p>\n\n<p>Here is a chunk of code I wrote a few years ago, which I find a bit simpler than your code:</p>\n\n<pre><code>char * read_string(void) {\n char *big = NULL, *old_big;\n char s[11] = {0};\n int len = 0, old_len;\n\n do {\n old_len = len;\n old_big = big;\n scanf(\"%10[^\\n]\", s);\n if (!(big = realloc(big, (len += strlen(s)) + 1))) {\n free(old_big);\n fprintf(stderr, \"Out of memory!\\n\");\n return NULL;\n }\n strcpy(big + old_len, s);\n } while (len - old_len == 10);\n return big;\n}\n</code></pre>\n\n<p>This was just a learning example, which I have never really used. In practice, I'd suggest working with a larger <code>s</code> (<code>char s[1025]</code>, <code>%1024[^\\n]</code> in <code>scanf</code>, and <code>len - old_len == 1024</code> in the condition of the <code>do...while</code> loop) to reduce the number of <code>realloc</code> calls which can be very slow if the user gets unlucky. This also answers your last question: char-by-char might get very slow and is in no way better than chunks.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T13:00:20.153", "Id": "49515", "Score": "0", "body": "This is also a learning example, copy is part of assignment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T14:34:54.567", "Id": "49522", "Score": "0", "body": "@zubergu Are you sure it was meant to be inside the function? Maybe it was meant to be called like this: `output = read_string(); copy = malloc(strlen(output)+1); strcpy(copy, output); free(output);`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T14:36:22.947", "Id": "49523", "Score": "0", "body": "Btw, I've edited reporting of an error in my code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T14:38:47.623", "Id": "49524", "Score": "0", "body": "task: \"Write a function that reads a string from the standard input and returns a copy of the string in dynamically allocated memory. The funcion may not impose any limit on the size of the string being read. \" English isn't my native l. but think i got it correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T14:44:04.490", "Id": "49525", "Score": "0", "body": "ATM I'm really proud that you didn't find any serious flaws, that would prove me entirely wrong and my code to be gibberish." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T14:46:45.663", "Id": "49526", "Score": "0", "body": "The `output` variable already holds the copy of the string from the input. ;-) And no, I have found no bugs, just some things than might be improved (memory check I've mentioned, the `iterator` part of the code seems redundant, and the `copy` part)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T12:53:39.293", "Id": "31098", "ParentId": "31095", "Score": "2" } }, { "body": "<p>Here are a few comments on your function:</p>\n\n<ul>\n<li><p>Firstly, <code>read_line</code> seems a more accurate name, as you read up until the next \\n.</p></li>\n<li><p>Reading 10 chars at a time is an odd. Unless that is part of the requirement I think you should allocate a bigger buffer and read as many chars as fit, extending the buffer each time round the loop by <strong>doubling</strong> its size (instead of adding 11). </p></li>\n<li><p>As you have it, your <code>fgets</code> call overwrites the char <strong>after</strong> the end of the buffer with \\0. You should pass the actual size of the buffer to <code>fgets</code>. </p></li>\n<li><p>Your fgets/strcat/strlen sequence is inefficient. You should be reading directly into the target buffer rather than reading and then copying. And the strcat call has to traverse the whole length of the accumulated string to concatenate the new part.</p>\n\n<pre><code>char *p = buf;\nsize_t len = 0;\n\nwhile (fgets(p, size - len, stdin) != NULL) {\n len += strlen(p);\n if (buf[len-1] == '\\n') {\n buf[len-1] = '\\0';\n break;\n }\n ...\n}\n</code></pre></li>\n<li><p>Your reallocation call leaks memory if it fails to allocate - you need a temporary variable to hold the return value from realloc:</p>\n\n<pre><code>size *= 2;\nif ((p = realloc(buf, size)) == NULL) {\n break; // and then return an error if `p == NULL` or `ferror`\n}\nbuf = p;\np += len;\n</code></pre></li>\n<li><p>Your loop exits when <code>fgets</code> returns NULL, but you do not check for an error.<br>\nYou must call <code>ferror</code> to be sure that an error did not occur. </p></li>\n<li><p>And your looping at the end to find the \\n seems wasteful when you have already located the end of line/string in the main loop.</p></li>\n<li><p>From the task statement you posted, copying the dynamic string is not required.</p></li>\n</ul>\n\n<p>Note that reading character at a time is not necessarily a slower solution. As you are doing it (with all that the copying and string traversal), I would expect a well written character-at-a-time function to be faster. I encourage you to try both and compare the execution speed (using a <strong>very</strong> big test file as input).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T14:57:01.270", "Id": "31106", "ParentId": "31095", "Score": "3" } } ]
{ "AcceptedAnswerId": "31098", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T11:18:59.947", "Id": "31095", "Score": "4", "Tags": [ "c", "strings", "memory-management", "beginner" ], "Title": "Reading unlimited input strings in C" }
31095
<p>This is my solution for an exercise from a book. It's a simple <code>Golf</code> class with member variables <code>fullname</code> and <code>handicap</code>. The constructor sets the variables to the provided name and handicap using values passed as arguments. The <code>setgolf()</code> function solicits name and handicap from user, creates a temporary <code>Golf</code> object and assigns it to the invoking object. </p> <p>Is this a proper solution? I'm particularly interested in the <code>setgolf()</code> method.</p> <p><strong>golf.h:</strong></p> <pre><code>#include &lt;string&gt; class Golf { private: std::string fullname; int handicap; public: Golf(); Golf(const std::string name, int hc); int setgolf(); void sethandicap(int hc); void showgolf(); }; </code></pre> <p><strong>golf.cpp:</strong></p> <pre><code>#include "golf.h" #include &lt;cstring&gt; #include &lt;iostream&gt; Golf::Golf(const std::string name, int hc) { fullname = name; handicap = hc; } int Golf::setgolf() { std::string name; int hc; std::cout &lt;&lt; "Enter the name: "; getline(cin, name); if (name == "") return 0; std::cout &lt;&lt; "Enter the handicap: "; std::cin &gt;&gt; hc; *this = Golf(name, hc); return 1; } </code></pre>
[]
[ { "body": "<ul>\n<li>Lose the <code>private</code>, <code>class</code> members are private by default.</li>\n<li><p><code>setGolf()</code>: Instead of returning 1 or 0, you can apply <em>exceptions management</em> here. Also, you're doing double jobs by <code>*this = Golf(name, hc);</code>. You call a constructor that creates an instance of <code>Golf</code> and then assign that instance to <code>*this</code> when you don't even have an assignment operator defined. Don't worry, a default version is already generated.</p>\n\n<p>You can fix that by doing this:</p>\n\n<pre><code>this-&gt;fullname = name;\nthis-&gt;handicap = hc;\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T19:11:09.393", "Id": "49544", "Score": "1", "body": "I think explicitly making members `private` just makes it a bit clearer and doesn't really have any drawbacks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T20:45:29.097", "Id": "49549", "Score": "0", "body": "@Tharwen: Agreed. I think it's also helpful in case you have both `public` and `private` functions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T14:43:38.700", "Id": "31104", "ParentId": "31100", "Score": "2" } }, { "body": "<p>It's hard to say whether the solution is proper when there isn't a problem to solve. How a class should be designed depends on how it will be used; a class in isolation is hard to judge. Even if you want to focus on some specific aspect, try to fit it into the context of a larger problem.</p>\n\n<p>Back to the code: I suspect <code>showgolf</code> should be a <code>const</code> function. I don't see why printing a <code>Golf</code> would change it. You probably also meant to pass your constructor a <code>const std::string&amp;</code>. Finally, are you sure a <code>showgolf</code> member function is really what you want -- why not an <code>operator&lt;&lt;</code> overload?</p>\n\n<p>Moving on to the <code>Golf::setgolf</code> function specifically, I don't think such a function is meaningful. An <code>operator&gt;&gt;</code> overload or a free <code>queryGolf</code> function sound significantly more sensible to me. More specifically, the usage:</p>\n\n<pre><code>Golf golf;\ngolf.setgolf();\n</code></pre>\n\n<p>Why not just <code>auto golf = queryGolf();</code>? It's simpler, it means you can't forget to check whether things succeeded, and given <code>setGolf</code>'s implementation it is likely to be just as efficient.</p>\n\n<p>Speaking of checking whether things succeeded, why not throw an exception if the input is invalid? There are valid reasons, but it's certainly a solution you should consider. (By the way, if my previous solution sounded bad due to the need for exceptions, have no fear: <code>boost::optional</code> fits the use-case very well.)</p>\n\n<p>And, in a similar vein: it sounds like you're trying to prevent the creation of invalid <code>Golf</code>s. However, your default constructor does exactly that. Are you sure default-construction is more valuable than guaranteed validity? Again, depending on what you do with the class, the answer varies.</p>\n\n<p>All in all, I'd suggest dropping <code>showgolf</code> and writing:</p>\n\n<pre><code>Golf promptGolf() {\n Golf golf;\n // read into fullname and handicap. promptGolf may be a friend.\n if (/* golf is not valid, std::cin died, etc. */)\n throw TerribleError{};\n return golf;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T14:48:07.633", "Id": "31105", "ParentId": "31100", "Score": "4" } }, { "body": "<ul>\n<li><p>You're not using <code>&lt;cstring&gt;</code> specifically in your implementation, so remove it.</p></li>\n<li><p>If you're not defining <code>sethandicap()</code> anywhere, remove the declaration.</p></li>\n<li><p>The constructor is only initializing data members, so it can be an <a href=\"http://www.cprogramming.com/tutorial/initialization-lists-c++.html\" rel=\"nofollow\">initializer list</a>:</p>\n\n<pre><code>Golf::Golf(std::string name, int hc) : fullname(name), handicap(hc) {}\n</code></pre></li>\n<li><p>Although I agree with @Anton Golov about <code>setgolf()</code>, I'll address some things in it anyway:</p>\n\n<pre><code>std::cout &lt;&lt; \"Enter the name: \";\nstd::string name; // put declaration here to maintain a closer scope\ngetline(std::cin, name); // don't forget the \"std::\"\n\nif (name.empty()) return 0; // empty() is more readable than \"\"\n\nstd::cout &lt;&lt; \"Enter the handicap: \";\nstd::cin.ignore(); // getline() is used prior, so add this\nint hc; // put declaration here to maintain a closer scope\nstd::cin &gt;&gt; hc;\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:59:48.047", "Id": "49611", "Score": "0", "body": "Setters need not break encapsulation; there's no reason the class interface shouldn't have some property that the user may change the value of. For instance, if we have a lexer class, setting the current line number may be a valid operation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T16:03:57.327", "Id": "49613", "Score": "0", "body": "@AntonGolov: Okay. I suppose I'm still unsure about what exactly breaks encapsulation and what doesn't. Many different contradictions, it seems." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T15:28:29.597", "Id": "31109", "ParentId": "31100", "Score": "2" } } ]
{ "AcceptedAnswerId": "31109", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T13:49:22.167", "Id": "31100", "Score": "3", "Tags": [ "c++", "algorithm", "classes" ], "Title": "Simple class exercise using the \"this\" pointer" }
31100
<p>I'm working in my project with the following script:</p> <pre><code>;(function($, doc, win) { "use strict"; // cache the window object var jQuerywindow = $(window); $('section[data-type="background"]').each(function(){ // declare the variable to affect the defined data-type var jQueryscroll = $(this); $(window).scroll(function() { // HTML5 proves useful for helping with creating JS functions! // also, negative value because we're scrolling upwards var yPos = -(jQuerywindow.scrollTop() / jQueryscroll.data('speed')); // background position var coords = '50% '+ yPos + 'px'; // move the background jQueryscroll.css({ backgroundPosition: coords }); }); // end window scroll }); // end section function })(jQuery, document, window); </code></pre> <p>The script allows me to have several sections with parallax background effect. So, I can have one or ten in a page. I'm a bit concern about performance. Can the script be improved?</p>
[]
[ { "body": "<p>First of all, your code looks quite good. You've encapsulated the plugin well, and cached all your jQuery instances, which are, in my experience, the most common pitfalls. </p>\n\n<p>One thing I noticed is that you create a <code>scroll</code> event handler for every <code>section[data-type=\"background\"]</code> element. Performance wise, this might not be optimal since the scroll event fires quite often. Instead of creating multiple scroll events, something like the following could be done:</p>\n\n<pre><code>var backgrounds = [];\n$('section[data-type=\"background\"]').each(function(){\n backgrounds.push($(this));\n}\n\n$(window).scroll(function() {\n for(var i=0; i &lt; backgrounds.length; i++) {\n var $elem = backgrounds[i];\n var yPos = -(jQuerywindow.scrollTop() / $elem.data('speed'));\n var coords = '50% '+ yPos + 'px';\n $elem.css({ backgroundPosition: coords }); \n }\n});\n</code></pre>\n\n<p>John Resig <a href=\"http://ejohn.org/blog/learning-from-twitter/\" rel=\"nofollow\">wrote about <code>scroll</code> event performance</a> quite some time ago, and it's still a good read (including the comments!). You might want to check that out too, and choose a technique of your liking.</p>\n\n<p>And one more, very personal opinion: <code>jQuerywindow</code> is not a variable name I would choose. If you're determined to prepend every jQuery variable with <code>jQuery</code>, then write <code>jQueryWindow</code>, but I would suggest just using <code>$window</code>. I actually don't know where I got this from, but prepending every jQuery variable (including function parameters) with <code>$</code> makes for very easily readable code (again, this is only a personal opinion).</p>\n\n<hr>\n\n<p><strong>Edit</strong>: Oh, and you probably should cache the <code>jQueryscroll.data('speed')</code> invocation, so that you don't have to read from the DOM every time a scroll event happens.</p>\n\n<p><strong>Edit2</strong>: And it is generally a good idea to do a little profiling when you're having performance problems, as guessing what <em>might</em> be the bottleneck is usually not very effective. Most modern browsers have some kind of JavaScript profiler available.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T02:25:56.750", "Id": "49569", "Score": "0", "body": "Thanks for your answer. However, I'm still learning JS and I'm having trouble to put all you said together. Would you mind to be more clear on the example?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T09:09:59.480", "Id": "49580", "Score": "0", "body": "Sure. What is it that you don't understand? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T09:20:10.553", "Id": "49581", "Score": "0", "body": "How to implement your suggestions on the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:23:26.823", "Id": "49604", "Score": "0", "body": "I've updated the example to make the approach clearer, but honestly, you could've figured that out by yourself ;)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T16:48:18.113", "Id": "31114", "ParentId": "31102", "Score": "2" } } ]
{ "AcceptedAnswerId": "31114", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T14:18:15.663", "Id": "31102", "Score": "1", "Tags": [ "javascript", "optimization", "jquery", "parallax" ], "Title": "jQuery parallax plugin" }
31102
<p>I'm learning F# and I'm trying the following exercise (exercise 4.10 of <a href="http://rads.stackoverflow.com/amzn/click/1107684064" rel="nofollow">Functional Programming Using F#</a>).</p> <blockquote> <p>Declare an F# function <code>prefix</code>: <code>'a list -&gt; 'a list -&gt; bool when a:equality</code>. The value of the expression <code>prefix[x_0;x_1;...;x_m] [y_0;y_1;...;y_n]</code> is <code>true</code> if <code>m&lt;=n</code> and <code>x_i=y_i</code> for <code>0&lt;=i&lt;=m</code>, and <code>false</code> otherwise.</p> </blockquote> <p>I wanted to use pattern matching on the two inputs, but wasn't sure how to do this with a curried function (as opposed to a function taking a 2-tuple). So I wrote:</p> <pre><code>let rec prefix a b = (function | ([], _) -&gt; true | (_, []) -&gt; false | (x0::xst,y0::yst) -&gt; x0 = y0 &amp;&amp; prefix xst yst) (a,b);; </code></pre> <p>I wasn't very happy with this, because I thought it would be better (clearer and more efficient) if the inner function called itself, so I tried declaring the inner function locally.</p> <pre><code>let prefix a b = let rec prefixt = function | ([], _) -&gt; true | (_, []) -&gt; false | (x0::xst,y0::yst) -&gt; x0 = y0 &amp;&amp; prefixt (xst,yst) prefixt (a,b);; </code></pre> <p>Is this the right way to approach such a problem in F#?</p>
[]
[ { "body": "<p>You can use the <code>match … with …</code> syntax:</p>\n\n<pre><code>let rec prefix a b =\n match (a, b) with\n | ([], _) -&gt; true\n | (_, []) -&gt; false\n | (x0::xst,y0::yst) -&gt; x0 = y0 &amp;&amp; prefix xst yst\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T16:51:43.737", "Id": "31115", "ParentId": "31112", "Score": "1" } } ]
{ "AcceptedAnswerId": "31115", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T16:12:18.787", "Id": "31112", "Score": "2", "Tags": [ "f#" ], "Title": "How to use pattern matching within curried function" }
31112
<p>Is there a more reliable way of getting the content elements for each SVG element?</p> <pre><code>#----------------------------------------------------------------------- # Get Element content from SVG specification from: # http://www.w3.org/TR/2011/REC-SVG11-20110816/single-page.html # Philip R Brenan at gmail dot com, Appa Apps Ltd, 2013 #----------------------------------------------------------------------- use feature ":5.16"; use warnings FATAL =&gt; qw(all); use strict; use Carp; use Data::Dump qw(dump); use HTML::TreeBuilder; my $f = "svgSpecification.html"; open(my $F, "&lt;:encoding(UTF-8)", $f) or die "Cannot open $f for unicode input"; my $t = HTML::TreeBuilder-&gt;new-&gt;parse_file($F); my @t; #----------------------------------------------------------------------- # Extract relevant nodes #----------------------------------------------------------------------- sub list {my ($t, $d) = @_; # Element, stack if (ref($t)) {push @$d, $t-&gt;tag; for($t-&gt;content_list) {list($_, $d); } pop @$d; } elsif (@$d &gt;= 5) {my $T = join("_", @$d) ."=". ($t =~ s/[\x{2018}\x{2019}]//gr); if ($T =~ /html_body_div_div_dl_dd_ul_li_span_a_span/ or $T =~ /html_body_div_div_dl_dt/ or $T =~ /html_body_div_div_div_span/ or $T =~ /html_body_div_div_dl_dd_ul_li_a_span/ # Linear gradient ) {push @t, $T; } } } list($t, []); #----------------------------------------------------------------------- # Compile content list #----------------------------------------------------------------------- my $c; if (1) {my $s = 0; my $e; for(@t) {if ($s == 0 and /html_body_div_div_div_span=([\w_:-]+)/) {$e = $1; $s = 1; } elsif ($s == 1 and /html_body_div_div_dl_dt=Content model:/) {$s = 2; } elsif ($s == 2) {if (/(?:html_body_div_div_dl_dd_ul_li_span_a_span|html_body_div_div_dl_dd_ul_li_a_span)=([\w_:-]+)/) {push @{$c-&gt;{$e}}, $1; } elsif (/html_body_div_div_dl_dt=Attributes:/) {$s = 0; $e = undef; } } } } say dump($c); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T22:47:13.620", "Id": "49554", "Score": "0", "body": "Isn't this exactly the kind of problem that [`XML::XPath`](http://search.cpan.org/~msergeant/XML-XPath-1.13/) solves?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T22:58:42.500", "Id": "49556", "Score": "0", "body": "@200_success Yes, this problem can be solved with XPath, once a DOM is created from the HTML. However, the specifics are more complex than a single XPath expression. If you scroll to the bottom of my answer, you'll see a solution with CSS selectors, which is only slightly more complicated than a hypothetical XPath solution." } ]
[ { "body": "<p>First a general code review, not specific to your “is there a more reliable way”. Later, I will show a superiour solution. But first, a lengthy rant.</p>\n\n<p>I see you have a very unique coding style. This is not good: Every piece of code has two audiences: The computer, and a maintainer. Everybody can write code a computer understands, but writing for humans is an <em>art</em>. Do the maintainer a favour and write understandable, easy code – it could be you! In fact, your coding style slightly reminds me of the horrors of the “perlish coding style” which is neither perlish, nor recommendable, although completely logical. See here for an <a href=\"https://metacpan.org/source/DOMIZIO/CGI-Builder-1.36/lib/CGI/Builder.pm\" rel=\"nofollow\">example</a>. Do not imitate! Your single-space indent isn't recommendable either.</p>\n\n<p>You have a knack for single letter variable names. Heck, you even have a comment explaining what each variable means: <code>my ($t, $d) = @_; # Element, stack</code>. This is completely and utterly silly, just name them <code>my ($element, $stack)</code> already. Code ought to be self-documenting.</p>\n\n<p>Otherwise, comments explaining what you are doing is suspiciously absent.</p>\n\n<p>When opening a file, always include the reason for failure <code>$!</code> in the error message, or use automatic error handling with the <code>autodie</code> pragma.</p>\n\n<p>UTF-8 is not the default encoding for HTML documents. If your document is guaranteed to be encoded in UTF-8, then opening the file with such a layer is the correct thing. Otherwise, you can pass the filename to the <code>parse_file</code> method. You should check if the return value of <code>parse_file</code> is defined. If not, you'll find a reason for failure in <code>$!</code>.</p>\n\n<p>You can shorten the <code>:encoding(UTF-8)</code> layer as <code>:uft8</code>. Technically, they are slightly different. Most importantly, the latter is more relaxed.</p>\n\n<p>I see how you used a recursive solution for your misnomed <code>list</code> sub, which traverses the document. You should comment this more thoroughly – it took me a moment to realize that <code>if (ref $t)</code>, then it is a tag, possibly with childs, otherwise a text node.</p>\n\n<p>You have two stacks: <code>@t</code> and <code>$d</code>. Why do you carry one around as an argument, but not the other? Your code is actually quite hard to grok, because different branches in the tree append elements to the same <code>$d</code> arrayref. If I understand your code correctly, then a tree like</p>\n\n<pre><code> html\n / \\\nhead body\n / \\\n div div\n / \\ /|\\\n h1 p p p p\n |\n em\n</code></pre>\n\n<p>would produce the flattening <code>$d = [qw/html head body div h1 p div p p em p/]</code>.</p>\n\n<p>[<em>type type type</em>] Now I see I don't understand the code correctly – you always pop the last element of the stack after traversing into childs. As each child also pops one element of the stack, each node removes itself. I think this is utterly silly, and it would be better to pass each recursion a copy of the stack. Otherwise, comment this shit! Recursion has the advantage that it is easier to reason about code. You loose this advantage when you use mutable variables.</p>\n\n<p>Another problem is that your search is too wide. First, you want the HTML element. Then only the body. Then all divs. Then another one. Then a definition list or another div. However, you search the <em>whole</em> tree. This is wasteful.</p>\n\n<p>You have a magic number in that code: <code>5</code>. Which is wrong, because your regexes can only match starting at positions 6 tags deep! Oh, and all those regexes could be combined into one, which would be more efficient. You can also anchor the match at the beginning of the string with the <code>^</code> or <code>\\A</code> operators, which lets the regex fail faster. You also might want to assert that your path ends with a <code>=</code> (or, if you heed the advice of the next paragraph, with the end of the string <code>$</code> or <code>\\z</code>).</p>\n\n<p>You combine the element path and the text value by concatenating them with an <code>=</code> in between. Later, you use captures to fiddle that value out again. I would rather use an two-element arrayref.</p>\n\n<p>But why even have the <code>@t</code> stack? If you look closely, you'll see that there is a lot repeated code, e.g. regexes in the <code>else</code> path of <code>list</code>, and the <code>if(1)</code> later. You could just do the processing right there, and save that memory.</p>\n\n<p>Why is there an <code>if(1)</code>? If you, for some reason, want to enter a new scope, just use a plain block:</p>\n\n<pre><code>my $x = 1; { my $x = 2 } say $x; # 1\n</code></pre>\n\n<p>This is Ok on the statement level. On the expression level, you can use a <code>do {BLOCK}</code> to include more complex calculations. This evaluates to the result of the last statement in the block.</p>\n\n<hr>\n\n<p>Here is a refactoring of your code. It tries to fix many issues mentioned above.</p>\n\n<pre><code># tested, works\nuse strict; use warnings; use 5.016;\nuse autodie;\nuse Data::Dump;\nuse HTML::TreeBuilder;\n\nopen my $fh, \"&lt;:utf8\", \"svgSpecification.html\";\nmy $tree_builder = HTML::TreeBuilder-&gt;new;\nmy $document = $tree_builder-&gt;parse_file($fh) or die $!;\n\nmy (%elements, $element);\nmy $state = 0;\n# state = 0: want element\n# state = 1: want dt \"Content model\"\n# state = 2: want value\n\nfind($document, {\n body =&gt; { div =&gt; { div =&gt; {\n div =&gt; { span =&gt; sub {\n return unless $state == 0;\n $element = shift-&gt;as_trimmed_text =~ s/\\pP//gr;\n $state++;\n }},\n dl =&gt; {\n dt =&gt; sub {\n my $content = shift-&gt;as_trimmed_text;\n if ($state == 1 and $content =~ /Content model:/) {\n $state++;\n } elsif ($content =~ /Attributes:/) {\n $state = 0;\n }\n },\n dd =&gt; { ul =&gt; { li =&gt; {\n span =&gt; { a =&gt; { span =&gt; sub {\n return unless $state == 2;\n push @{ $elements{$element} }, shift-&gt;as_trimmed_text =~ s/\\pP//gr;\n }}},\n a =&gt; { span =&gt; sub {\n return unless $state == 2;\n push @{ $elements{$element} }, shift-&gt;as_trimmed_text =~ s/\\pP//gr;\n }},\n }}},\n },\n }}},\n});\n\ndd \\%elements;\n\nsub find {\n my ($tag, $path) = @_;\n for my $child ($tag-&gt;content_list) {\n next unless ref $child; # skip text contents\n next unless my $nextpath = $path-&gt;{$child-&gt;tag};\n if (ref($nextpath) eq 'CODE') {\n $nextpath-&gt;($child);\n } else {\n find($child, $nextpath);\n }\n }\n}\n</code></pre>\n\n<p>As you see, the actual recursion logic is decoupled from your data extraction. The <code>find</code> function is guided by a hashes-of-hashes data structure, which keeps the search space minimal. The formerly implicit state machine is now documented and quite explicit. No unneccessary regexes are used.</p>\n\n<p>One problem with my solution is that the data structure is extremely verbose. I used unusual formatting to battle insanely deep intendation, and it does have a slightly DSL-esque feeling. However, automatic formatting will destroy this.</p>\n\n<hr>\n\n<p>Of course, such recursion is absolutely silly in this day and age. Modules like <a href=\"https://metacpan.org/module/Mojo%3a%3aDOM\" rel=\"nofollow\"><code>Mojo::DOM</code></a> and <code>Web::Query</code> allow us to use CSS selectors, which makes this a breeze.</p>\n\n<pre><code># tested, works\nuse strict; use warnings; use 5.016;\nuse Data::Dump;\nuse File::Slurp;\nuse Mojo::DOM;\n\nmy $contents = read_file \"svgSpecification.html\", { binmode =&gt; \":utf8\" };\nmy $dom = Mojo::DOM-&gt;new($contents) or die \"Can't parse input\";\n\nmy %elems;\n\nfor my $summary ($dom-&gt;find('.element-summary')-&gt;each) {\n\n my $name = $summary-&gt;at('.element-summary-name')-&gt;all_text;\n $name =~ s/[\\pP\\s]//g; # remove all punctuation and spaces\n\n # Getting the correct section is tricky, as it is only identified by text.\n # We get around this by filtering manually for the correct text,\n # then continuing with the next sibling node\n my ($child_headline) = grep { $_-&gt;all_text =~ /Content model/ } $summary-&gt;find('dt')-&gt;each;\n next unless $child_headline;\n\n my @childs = map { $_-&gt;all_text =~ s/[\\pP\\s]//gr } $child_headline-&gt;next-&gt;find('.element-name')-&gt;each;\n push @{ $elems{$name} }, @childs;\n}\n\ndd \\%elems;\n</code></pre>\n\n<p>Both of these solutions have the same speed. The 2nd solution will also put elements without childs into the hash, while the first solution ignores them. My scripts were tested with the <a href=\"http://www.w3.org/TR/SVG/single-page.html\" rel=\"nofollow\">SVG 1.1 spec on a single page</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T14:55:04.133", "Id": "49598", "Score": "0", "body": "I should have mentioned that I am on Windows, and so far, after an hour or so, I have been unable to install Mojo on Windows - for all the usual reason - no module at activeState, strange errors from gnu make when one tries to install from cpan etc. I am thus forced to use the tools at hand. So I would like to use Mojo, but the cost of dumping the existing environment is too high." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:14:03.157", "Id": "49599", "Score": "0", "body": "@phil Indeed, it seems that [AS only provides Mojo builds up to perl 5.10](http://code.activestate.com/ppm/Mojo/). That does suck. (On Windows, I always use [Strawberry Perl](http://strawberryperl.com/), which comes with a complete toolchain). You could try [Web::Query](http://code.activestate.com/ppm/Web-Query/) instead which has a nearly identical API to Mojo::DOM." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T21:50:42.947", "Id": "31126", "ParentId": "31118", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T18:21:46.120", "Id": "31118", "Score": "0", "Tags": [ "perl", "svg" ], "Title": "Perl hash mapping SVG elements to content elements" }
31118
<p>Is there a more reliable way of building a hash of the attributes associated with each SVG element?</p> <pre><code> #----------------------------------------------------------------------- # Hash of SVG elements, attributes,animation from: # http://www.w3.org/TR/2011/REC-SVG11-20110816/attindex.html # Philip R Brenan at gmail dot com, 2013 #----------------------------------------------------------------------- use v5.16; use warnings FATAL =&gt; qw(all); use strict; use Carp; use Data::Dump qw(dump); #----------------------------------------------------------------------- # Load elements and attributes by parsing the table supplied by W3C #----------------------------------------------------------------------- my $e; # Element, Attribute = animation my $a; # Attributes for(split(/\n/, &amp;data)) {s/[‘’\t,]/ /g; s/\A\s+//; s/\s+\Z//; my @w = split /\s+/; my $E = shift @w; $a-&gt;{$E}++; # element my $A = do {if ($w[-1] eq "?") {pop @w; 1} else {0}}; for(@w) {$e-&gt;{$_}{$E} = $A; # Attribute to element $a-&gt;{$_}++; # attribute } } #----------------------------------------------------------------------- # Add presentation attributes #----------------------------------------------------------------------- for my $E(&amp;presentationElements) {for my $A(&amp;presentationAttributes) {$e-&gt;{$E}{$A} = 1; # They seem to be all animatable } } $$a{$_}++ for &amp;presentationAttributes; #----------------------------------------------------------------------- # Convert to camelCase #----------------------------------------------------------------------- sub cc($) {my ($a) = @_; $a =~ s/[:_-]([a-z])/\u$1/gr} my $A = {map {cc($_)=&gt;$_} keys %$a}; my $E; for my $k(keys %$e) {for(keys %{$e-&gt;{$k}}) {$E-&gt;{cc($k)}{cc($_)} = $e-&gt;{$k}{$_}; } } sub comment($) {my ($t) = @_; my $c = "#".("-"x71)."\n"; say "\n$c# $t\n$c"; } comment("SVG attribute name from perl camel case name"); say "sub attributesFromCamelCase {+", dump($A), "}"; comment("Element, attribute, animation"); say "sub elementAttributesAnimation {+", dump($E), "}"; #----------------------------------------------------------------------- # http://www.w3.org/TR/2011/REC-SVG11-20110816/attindex.html#PresentationAttributes #----------------------------------------------------------------------- sub data() {&lt;&lt;'END'}; ‘accent-height’ ‘font-face’ ‘accumulate’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’ ‘additive’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’ ‘alphabetic’ ‘font-face’ ‘amplitude’ ‘feFuncA’, ‘feFuncB’, ‘feFuncG’, ‘feFuncR’ ? ‘arabic-form’ ‘glyph’ ‘ascent’ ‘font-face’ ‘attributeName’ ‘animate’, ‘animateColor’, ‘animateTransform’, ‘set’ ‘attributeType’ ‘animate’, ‘animateColor’, ‘animateTransform’, ‘set’ ‘azimuth’ ‘feDistantLight’ ? ‘baseFrequency’ ‘feTurbulence’ ? ‘baseProfile’ ‘svg’ ‘bbox’ ‘font-face’ ‘begin’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘set’ ‘bias’ ‘feConvolveMatrix’ ? ‘by’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’ ‘calcMode’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’ ‘cap-height’ ‘font-face’ ‘class’ ‘a’, ‘altGlyph’, ‘circle’, ‘clipPath’, ‘defs’, ‘desc’, ‘ellipse’, ‘feBlend’, ‘feColorMatrix’, ‘feComponentTransfer’, ‘feComposite’, ‘feConvolveMatrix’, ‘feDiffuseLighting’, ‘feDisplacementMap’, ‘feFlood’, ‘feGaussianBlur’, ‘feImage’, ‘feMerge’, ‘feMorphology’, ‘feOffset’, ‘feSpecularLighting’, ‘feTile’, ‘feTurbulence’, ‘filter’, ‘font’, ‘foreignObject’, ‘g’, ‘glyph’, ‘glyphRef’, ‘image’, ‘line’, ‘linearGradient’, ‘marker’, ‘mask’, ‘missing-glyph’, ‘path’, ‘pattern’, ‘polygon’, ‘polyline’, ‘radialGradient’, ‘rect’, ‘stop’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘title’, ‘tref’, ‘tspan’, ‘use’ ? ‘clipPathUnits’ ‘clipPath’ ? ‘contentScriptType’ ‘svg’ ‘contentStyleType’ ‘svg’ ‘cx’ ‘circle’ ? ‘cx’ ‘ellipse’ ? ‘cx’ ‘radialGradient’ ? ‘cy’ ‘circle’ ? ‘cy’ ‘ellipse’ ? ‘cy’ ‘radialGradient’ ? ‘d’ ‘path’ ? ‘d’ ‘glyph’, ‘missing-glyph’ ‘descent’ ‘font-face’ ‘diffuseConstant’ ‘feDiffuseLighting’ ? ‘divisor’ ‘feConvolveMatrix’ ? ‘dur’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘set’ ‘dx’ ‘altGlyph’ ? ‘dx’ ‘feOffset’ ? ‘dx’ ‘glyphRef’ ‘dx’ ‘text’ ? ‘dx’ ‘tref’, ‘tspan’ ? ‘dy’ ‘altGlyph’ ? ‘dy’ ‘feOffset’ ? ‘dy’ ‘glyphRef’ ‘dy’ ‘text’ ? ‘dy’ ‘tref’, ‘tspan’ ? ‘edgeMode’ ‘feConvolveMatrix’ ? ‘elevation’ ‘feDistantLight’ ? ‘end’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘set’ ‘exponent’ ‘feFuncA’, ‘feFuncB’, ‘feFuncG’, ‘feFuncR’ ? ‘externalResourcesRequired’ ‘a’, ‘altGlyph’, ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘circle’, ‘clipPath’, ‘cursor’, ‘defs’, ‘ellipse’, ‘feImage’, ‘filter’, ‘font’, ‘foreignObject’, ‘g’, ‘image’, ‘line’, ‘linearGradient’, ‘marker’, ‘mask’, ‘mpath’, ‘path’, ‘pattern’, ‘polygon’, ‘polyline’, ‘radialGradient’, ‘rect’, ‘script’, ‘set’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘tref’, ‘tspan’, ‘use’, ‘view’ ‘fill’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘set’ ‘filterRes’ ‘filter’ ? ‘filterUnits’ ‘filter’ ? ‘font-family’ ‘font-face’ ‘font-size’ ‘font-face’ ‘font-stretch’ ‘font-face’ ‘font-style’ ‘font-face’ ‘font-variant’ ‘font-face’ ‘font-weight’ ‘font-face’ ‘format’ ‘altGlyph’ ‘format’ ‘glyphRef’ ‘from’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’ ‘fx’ ‘radialGradient’ ? ‘fy’ ‘radialGradient’ ? ‘g1’ ‘hkern’, ‘vkern’ ‘g2’ ‘hkern’, ‘vkern’ ‘glyph-name’ ‘glyph’ ‘glyphRef’ ‘altGlyph’ ‘glyphRef’ ‘glyphRef’ ‘gradientTransform’ ‘linearGradient’ ? ‘gradientTransform’ ‘radialGradient’ ? ‘gradientUnits’ ‘linearGradient’ ? ‘gradientUnits’ ‘radialGradient’ ? ‘hanging’ ‘font-face’ ‘height’ ‘filter’ ? ‘height’ ‘foreignObject’ ? ‘height’ ‘image’ ? ‘height’ ‘pattern’ ? ‘height’ ‘rect’ ? ‘height’ ‘svg’ ? ‘height’ ‘use’ ? ‘height’ ‘feBlend’, ‘feColorMatrix’, ‘feComponentTransfer’, ‘feComposite’, ‘feConvolveMatrix’, ‘feDiffuseLighting’, ‘feDisplacementMap’, ‘feFlood’, ‘feGaussianBlur’, ‘feImage’, ‘feMerge’, ‘feMorphology’, ‘feOffset’, ‘feSpecularLighting’, ‘feTile’, ‘feTurbulence’ ? ‘height’ ‘mask’ ? ‘horiz-adv-x’ ‘font’ ‘horiz-adv-x’ ‘glyph’, ‘missing-glyph’ ‘horiz-origin-x’ ‘font’ ‘horiz-origin-y’ ‘font’ ‘id’ ‘a’, ‘altGlyph’, ‘altGlyphDef’, ‘altGlyphItem’, ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘circle’, ‘clipPath’, ‘color-profile’, ‘cursor’, ‘defs’, ‘desc’, ‘ellipse’, ‘feBlend’, ‘feColorMatrix’, ‘feComponentTransfer’, ‘feComposite’, ‘feConvolveMatrix’, ‘feDiffuseLighting’, ‘feDisplacementMap’, ‘feDistantLight’, ‘feFlood’, ‘feFuncA’, ‘feFuncB’, ‘feFuncG’, ‘feFuncR’, ‘feGaussianBlur’, ‘feImage’, ‘feMerge’, ‘feMergeNode’, ‘feMorphology’, ‘feOffset’, ‘fePointLight’, ‘feSpecularLighting’, ‘feSpotLight’, ‘feTile’, ‘feTurbulence’, ‘filter’, ‘font’, ‘font-face’, ‘font-face-format’, ‘font-face-name’, ‘font-face-src’, ‘font-face-uri’, ‘foreignObject’, ‘g’, ‘glyph’, ‘glyphRef’, ‘hkern’, ‘image’, ‘line’, ‘linearGradient’, ‘marker’, ‘mask’, ‘metadata’, ‘missing-glyph’, ‘mpath’, ‘path’, ‘pattern’, ‘polygon’, ‘polyline’, ‘radialGradient’, ‘rect’, ‘script’, ‘set’, ‘stop’, ‘style’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘title’, ‘tref’, ‘tspan’, ‘use’, ‘view’, ‘vkern’ ‘ideographic’ ‘font-face’ ‘in’ ‘feBlend’, ‘feColorMatrix’, ‘feComponentTransfer’, ‘feComposite’, ‘feConvolveMatrix’, ‘feDiffuseLighting’, ‘feDisplacementMap’, ‘feGaussianBlur’, ‘feMorphology’, ‘feOffset’, ‘feSpecularLighting’, ‘feTile’ ? ‘in2’ ‘feBlend’ ? ‘in2’ ‘feComposite’ ? ‘in2’ ‘feDisplacementMap’ ? ‘intercept’ ‘feFuncA’, ‘feFuncB’, ‘feFuncG’, ‘feFuncR’ ? ‘k’ ‘hkern’, ‘vkern’ ‘k1’ ‘feComposite’ ? ‘k2’ ‘feComposite’ ? ‘k3’ ‘feComposite’ ? ‘k4’ ‘feComposite’ ? ‘kernelMatrix’ ‘feConvolveMatrix’ ? ‘kernelUnitLength’ ‘feConvolveMatrix’ ? ‘kernelUnitLength’ ‘feDiffuseLighting’ ? ‘kernelUnitLength’ ‘feSpecularLighting’ ? ‘keyPoints’ ‘animateMotion’ ‘keySplines’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’ ‘keyTimes’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’ ‘lang’ ‘glyph’ ‘lengthAdjust’ ‘text’, ‘textPath’, ‘tref’, ‘tspan’ ? ‘limitingConeAngle’ ‘feSpotLight’ ? ‘local’ ‘color-profile’ ‘markerHeight’ ‘marker’ ? ‘markerUnits’ ‘marker’ ? ‘markerWidth’ ‘marker’ ? ‘maskContentUnits’ ‘mask’ ? ‘maskUnits’ ‘mask’ ? ‘mathematical’ ‘font-face’ ‘max’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘set’ ‘media’ ‘style’ ‘method’ ‘textPath’ ? ‘min’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘set’ ‘mode’ ‘feBlend’ ? ‘name’ ‘color-profile’ ‘name’ ‘font-face-name’ ‘numOctaves’ ‘feTurbulence’ ? ‘offset’ ‘stop’ ? ‘offset’ ‘feFuncA’, ‘feFuncB’, ‘feFuncG’, ‘feFuncR’ ? ‘onabort’ ‘svg’ ‘onactivate’ ‘a’, ‘altGlyph’, ‘circle’, ‘defs’, ‘ellipse’, ‘foreignObject’, ‘g’, ‘image’, ‘line’, ‘path’, ‘polygon’, ‘polyline’, ‘rect’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘tref’, ‘tspan’, ‘use’ ‘onbegin’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘set’ ‘onclick’ ‘a’, ‘altGlyph’, ‘circle’, ‘defs’, ‘ellipse’, ‘foreignObject’, ‘g’, ‘image’, ‘line’, ‘path’, ‘polygon’, ‘polyline’, ‘rect’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘tref’, ‘tspan’, ‘use’ ‘onend’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘set’ ‘onerror’ ‘svg’ ‘onfocusin’ ‘a’, ‘altGlyph’, ‘circle’, ‘defs’, ‘ellipse’, ‘foreignObject’, ‘g’, ‘image’, ‘line’, ‘path’, ‘polygon’, ‘polyline’, ‘rect’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘tref’, ‘tspan’, ‘use’ ‘onfocusout’ ‘a’, ‘altGlyph’, ‘circle’, ‘defs’, ‘ellipse’, ‘foreignObject’, ‘g’, ‘image’, ‘line’, ‘path’, ‘polygon’, ‘polyline’, ‘rect’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘tref’, ‘tspan’, ‘use’ ‘onload’ ‘a’, ‘altGlyph’, ‘circle’, ‘defs’, ‘ellipse’, ‘foreignObject’, ‘g’, ‘image’, ‘line’, ‘path’, ‘polygon’, ‘polyline’, ‘rect’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘tref’, ‘tspan’, ‘use’ ‘onload’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘set’ ‘onmousedown’ ‘a’, ‘altGlyph’, ‘circle’, ‘defs’, ‘ellipse’, ‘foreignObject’, ‘g’, ‘image’, ‘line’, ‘path’, ‘polygon’, ‘polyline’, ‘rect’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘tref’, ‘tspan’, ‘use’ ‘onmousemove’ ‘a’, ‘altGlyph’, ‘circle’, ‘defs’, ‘ellipse’, ‘foreignObject’, ‘g’, ‘image’, ‘line’, ‘path’, ‘polygon’, ‘polyline’, ‘rect’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘tref’, ‘tspan’, ‘use’ ‘onmouseout’ ‘a’, ‘altGlyph’, ‘circle’, ‘defs’, ‘ellipse’, ‘foreignObject’, ‘g’, ‘image’, ‘line’, ‘path’, ‘polygon’, ‘polyline’, ‘rect’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘tref’, ‘tspan’, ‘use’ ‘onmouseover’ ‘a’, ‘altGlyph’, ‘circle’, ‘defs’, ‘ellipse’, ‘foreignObject’, ‘g’, ‘image’, ‘line’, ‘path’, ‘polygon’, ‘polyline’, ‘rect’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘tref’, ‘tspan’, ‘use’ ‘onmouseup’ ‘a’, ‘altGlyph’, ‘circle’, ‘defs’, ‘ellipse’, ‘foreignObject’, ‘g’, ‘image’, ‘line’, ‘path’, ‘polygon’, ‘polyline’, ‘rect’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘tref’, ‘tspan’, ‘use’ ‘onrepeat’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘set’ ‘onresize’ ‘svg’ ‘onscroll’ ‘svg’ ‘onunload’ ‘svg’ ‘onzoom’ ‘svg’ ‘operator’ ‘feComposite’ ? ‘operator’ ‘feMorphology’ ? ‘order’ ‘feConvolveMatrix’ ? ‘orient’ ‘marker’ ? ‘orientation’ ‘glyph’ ‘origin’ ‘animateMotion’ ‘overline-position’ ‘font-face’ ‘overline-thickness’ ‘font-face’ ‘panose-1’ ‘font-face’ ‘path’ ‘animateMotion’ ‘pathLength’ ‘path’ ? ‘patternContentUnits’ ‘pattern’ ? ‘patternTransform’ ‘pattern’ ? ‘patternUnits’ ‘pattern’ ? ‘points’ ‘polygon’ ? ‘points’ ‘polyline’ ? ‘pointsAtX’ ‘feSpotLight’ ? ‘pointsAtY’ ‘feSpotLight’ ? ‘pointsAtZ’ ‘feSpotLight’ ? ‘preserveAlpha’ ‘feConvolveMatrix’ ? ‘preserveAspectRatio’ ‘feImage’, ‘image’, ‘marker’, ‘pattern’, ‘svg’, ‘symbol’, ‘view’ ? ‘primitiveUnits’ ‘filter’ ? ‘r’ ‘circle’ ? ‘r’ ‘radialGradient’ ? ‘radius’ ‘feMorphology’ ? ‘refX’ ‘marker’ ? ‘refY’ ‘marker’ ? ‘rendering-intent’ ‘color-profile’ ‘repeatCount’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘set’ ‘repeatDur’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘set’ ‘requiredExtensions’ ‘a’, ‘altGlyph’, ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘circle’, ‘clipPath’, ‘cursor’, ‘defs’, ‘ellipse’, ‘foreignObject’, ‘g’, ‘image’, ‘line’, ‘mask’, ‘path’, ‘pattern’, ‘polygon’, ‘polyline’, ‘rect’, ‘set’, ‘svg’, ‘switch’, ‘text’, ‘textPath’, ‘tref’, ‘tspan’, ‘use’ ‘requiredFeatures’ ‘a’, ‘altGlyph’, ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘circle’, ‘clipPath’, ‘cursor’, ‘defs’, ‘ellipse’, ‘foreignObject’, ‘g’, ‘image’, ‘line’, ‘mask’, ‘path’, ‘pattern’, ‘polygon’, ‘polyline’, ‘rect’, ‘set’, ‘svg’, ‘switch’, ‘text’, ‘textPath’, ‘tref’, ‘tspan’, ‘use’ ‘restart’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘set’ ‘result’ ‘feBlend’, ‘feColorMatrix’, ‘feComponentTransfer’, ‘feComposite’, ‘feConvolveMatrix’, ‘feDiffuseLighting’, ‘feDisplacementMap’, ‘feFlood’, ‘feGaussianBlur’, ‘feImage’, ‘feMerge’, ‘feMorphology’, ‘feOffset’, ‘feSpecularLighting’, ‘feTile’, ‘feTurbulence’ ? ‘rotate’ ‘altGlyph’ ? ‘rotate’ ‘animateMotion’ ‘rotate’ ‘text’ ? ‘rotate’ ‘tref’, ‘tspan’ ? ‘rx’ ‘ellipse’ ? ‘rx’ ‘rect’ ? ‘ry’ ‘ellipse’ ? ‘ry’ ‘rect’ ? ‘scale’ ‘feDisplacementMap’ ? ‘seed’ ‘feTurbulence’ ? ‘slope’ ‘font-face’ ‘slope’ ‘feFuncA’, ‘feFuncB’, ‘feFuncG’, ‘feFuncR’ ? ‘spacing’ ‘textPath’ ? ‘specularConstant’ ‘feSpecularLighting’ ? ‘specularExponent’ ‘feSpecularLighting’ ? ‘specularExponent’ ‘feSpotLight’ ? ‘spreadMethod’ ‘linearGradient’ ? ‘spreadMethod’ ‘radialGradient’ ? ‘startOffset’ ‘textPath’ ? ‘stdDeviation’ ‘feGaussianBlur’ ? ‘stemh’ ‘font-face’ ‘stemv’ ‘font-face’ ‘stitchTiles’ ‘feTurbulence’ ? ‘strikethrough-position’ ‘font-face’ ‘strikethrough-thickness’ ‘font-face’ ‘string’ ‘font-face-format’ ‘style’ ‘a’, ‘altGlyph’, ‘circle’, ‘clipPath’, ‘defs’, ‘desc’, ‘ellipse’, ‘feBlend’, ‘feColorMatrix’, ‘feComponentTransfer’, ‘feComposite’, ‘feConvolveMatrix’, ‘feDiffuseLighting’, ‘feDisplacementMap’, ‘feFlood’, ‘feGaussianBlur’, ‘feImage’, ‘feMerge’, ‘feMorphology’, ‘feOffset’, ‘feSpecularLighting’, ‘feTile’, ‘feTurbulence’, ‘filter’, ‘font’, ‘foreignObject’, ‘g’, ‘glyph’, ‘glyphRef’, ‘image’, ‘line’, ‘linearGradient’, ‘marker’, ‘mask’, ‘missing-glyph’, ‘path’, ‘pattern’, ‘polygon’, ‘polyline’, ‘radialGradient’, ‘rect’, ‘stop’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘title’, ‘tref’, ‘tspan’, ‘use’ ‘surfaceScale’ ‘feDiffuseLighting’ ? ‘surfaceScale’ ‘feSpecularLighting’ ? ‘systemLanguage’ ‘a’, ‘altGlyph’, ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘circle’, ‘clipPath’, ‘cursor’, ‘defs’, ‘ellipse’, ‘foreignObject’, ‘g’, ‘image’, ‘line’, ‘mask’, ‘path’, ‘pattern’, ‘polygon’, ‘polyline’, ‘rect’, ‘set’, ‘svg’, ‘switch’, ‘text’, ‘textPath’, ‘tref’, ‘tspan’, ‘use’ ‘tableValues’ ‘feFuncA’, ‘feFuncB’, ‘feFuncG’, ‘feFuncR’ ? ‘target’ ‘a’ ? ‘targetX’ ‘feConvolveMatrix’ ? ‘targetY’ ‘feConvolveMatrix’ ? ‘textLength’ ‘text’ ? ‘textLength’ ‘textPath’, ‘tref’, ‘tspan’ ? ‘title’ ‘style’ ‘to’ ‘set’ ‘to’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’ ‘transform’ ‘a’, ‘circle’, ‘clipPath’, ‘defs’, ‘ellipse’, ‘foreignObject’, ‘g’, ‘image’, ‘line’, ‘path’, ‘polygon’, ‘polyline’, ‘rect’, ‘switch’, ‘text’, ‘use’ ? ‘type’ ‘animateTransform’ ‘type’ ‘feColorMatrix’ ? ‘type’ ‘feTurbulence’ ? ‘type’ ‘script’ ‘type’ ‘style’ ‘type’ ‘feFuncA’, ‘feFuncB’, ‘feFuncG’, ‘feFuncR’ ? ‘u1’ ‘hkern’, ‘vkern’ ‘u2’ ‘hkern’, ‘vkern’ ‘underline-position’ ‘font-face’ ‘underline-thickness’ ‘font-face’ ‘unicode’ ‘glyph’ ‘unicode-range’ ‘font-face’ ‘units-per-em’ ‘font-face’ ‘v-alphabetic’ ‘font-face’ ‘v-hanging’ ‘font-face’ ‘v-ideographic’ ‘font-face’ ‘v-mathematical’ ‘font-face’ ‘values’ ‘feColorMatrix’ ? ‘values’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’ ‘version’ ‘svg’ ‘vert-adv-y’ ‘font’ ‘vert-adv-y’ ‘glyph’, ‘missing-glyph’ ‘vert-origin-x’ ‘font’ ‘vert-origin-x’ ‘glyph’, ‘missing-glyph’ ‘vert-origin-y’ ‘font’ ‘vert-origin-y’ ‘glyph’, ‘missing-glyph’ ‘viewBox’ ‘marker’, ‘pattern’, ‘svg’, ‘symbol’, ‘view’ ? ‘viewTarget’ ‘view’ ‘width’ ‘filter’ ? ‘width’ ‘foreignObject’ ? ‘width’ ‘image’ ? ‘width’ ‘pattern’ ? ‘width’ ‘rect’ ? ‘width’ ‘svg’ ? ‘width’ ‘use’ ? ‘width’ ‘feBlend’, ‘feColorMatrix’, ‘feComponentTransfer’, ‘feComposite’, ‘feConvolveMatrix’, ‘feDiffuseLighting’, ‘feDisplacementMap’, ‘feFlood’, ‘feGaussianBlur’, ‘feImage’, ‘feMerge’, ‘feMorphology’, ‘feOffset’, ‘feSpecularLighting’, ‘feTile’, ‘feTurbulence’ ? ‘width’ ‘mask’ ? ‘widths’ ‘font-face’ ‘x’ ‘altGlyph’ ? ‘x’ ‘cursor’ ? ‘x’ ‘fePointLight’ ? ‘x’ ‘feSpotLight’ ? ‘x’ ‘filter’ ? ‘x’ ‘foreignObject’ ? ‘x’ ‘glyphRef’ ‘x’ ‘image’ ? ‘x’ ‘pattern’ ? ‘x’ ‘rect’ ? ‘x’ ‘svg’ ? ‘x’ ‘text’ ? ‘x’ ‘use’ ? ‘x’ ‘feBlend’, ‘feColorMatrix’, ‘feComponentTransfer’, ‘feComposite’, ‘feConvolveMatrix’, ‘feDiffuseLighting’, ‘feDisplacementMap’, ‘feFlood’, ‘feGaussianBlur’, ‘feImage’, ‘feMerge’, ‘feMorphology’, ‘feOffset’, ‘feSpecularLighting’, ‘feTile’, ‘feTurbulence’ ? ‘x’ ‘mask’ ? ‘x’ ‘tref’, ‘tspan’ ? ‘x-height’ ‘font-face’ ‘x1’ ‘line’ ? ‘x1’ ‘linearGradient’ ? ‘x2’ ‘line’ ? ‘x2’ ‘linearGradient’ ? ‘xChannelSelector’ ‘feDisplacementMap’ ? ‘xlink:actuate’ ‘a’ ‘xlink:actuate’ ‘altGlyph’, ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘color-profile’, ‘cursor’, ‘feImage’, ‘filter’, ‘font-face-uri’, ‘glyphRef’, ‘image’, ‘mpath’, ‘pattern’, ‘script’, ‘set’, ‘use’ ‘xlink:arcrole’ ‘a’, ‘altGlyph’, ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘color-profile’, ‘cursor’, ‘feImage’, ‘filter’, ‘font-face-uri’, ‘glyphRef’, ‘image’, ‘linearGradient’, ‘mpath’, ‘pattern’, ‘radialGradient’, ‘script’, ‘set’, ‘textPath’, ‘tref’, ‘use’ ‘xlink:href’ ‘a’ ? ‘xlink:href’ ‘altGlyph’ ‘xlink:href’ ‘color-profile’ ‘xlink:href’ ‘cursor’ ? ‘xlink:href’ ‘feImage’ ? ‘xlink:href’ ‘filter’ ? ‘xlink:href’ ‘font-face-uri’ ‘xlink:href’ ‘glyphRef’ ‘xlink:href’ ‘image’ ? ‘xlink:href’ ‘linearGradient’ ? ‘xlink:href’ ‘mpath’ ‘xlink:href’ ‘pattern’ ? ‘xlink:href’ ‘radialGradient’ ? ‘xlink:href’ ‘script’ ‘xlink:href’ ‘textPath’ ? ‘xlink:href’ ‘use’ ? ‘xlink:href’ ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘set’ ‘xlink:href’ ‘tref’ ? ‘xlink:role’ ‘a’, ‘altGlyph’, ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘color-profile’, ‘cursor’, ‘feImage’, ‘filter’, ‘font-face-uri’, ‘glyphRef’, ‘image’, ‘linearGradient’, ‘mpath’, ‘pattern’, ‘radialGradient’, ‘script’, ‘set’, ‘textPath’, ‘tref’, ‘use’ ‘xlink:show’ ‘a’ ‘xlink:show’ ‘altGlyph’, ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘color-profile’, ‘cursor’, ‘feImage’, ‘filter’, ‘font-face-uri’, ‘glyphRef’, ‘image’, ‘mpath’, ‘pattern’, ‘script’, ‘set’, ‘use’ ‘xlink:title’ ‘a’, ‘altGlyph’, ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘color-profile’, ‘cursor’, ‘feImage’, ‘filter’, ‘font-face-uri’, ‘glyphRef’, ‘image’, ‘linearGradient’, ‘mpath’, ‘pattern’, ‘radialGradient’, ‘script’, ‘set’, ‘textPath’, ‘tref’, ‘use’ ‘xlink:type’ ‘a’, ‘altGlyph’, ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘color-profile’, ‘cursor’, ‘feImage’, ‘filter’, ‘font-face-uri’, ‘glyphRef’, ‘image’, ‘linearGradient’, ‘mpath’, ‘pattern’, ‘radialGradient’, ‘script’, ‘set’, ‘textPath’, ‘tref’, ‘use’ ‘xml:base’ ‘a’, ‘altGlyph’, ‘altGlyphDef’, ‘altGlyphItem’, ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘circle’, ‘clipPath’, ‘color-profile’, ‘cursor’, ‘defs’, ‘desc’, ‘ellipse’, ‘feBlend’, ‘feColorMatrix’, ‘feComponentTransfer’, ‘feComposite’, ‘feConvolveMatrix’, ‘feDiffuseLighting’, ‘feDisplacementMap’, ‘feDistantLight’, ‘feFlood’, ‘feFuncA’, ‘feFuncB’, ‘feFuncG’, ‘feFuncR’, ‘feGaussianBlur’, ‘feImage’, ‘feMerge’, ‘feMergeNode’, ‘feMorphology’, ‘feOffset’, ‘fePointLight’, ‘feSpecularLighting’, ‘feSpotLight’, ‘feTile’, ‘feTurbulence’, ‘filter’, ‘font’, ‘font-face’, ‘font-face-format’, ‘font-face-name’, ‘font-face-src’, ‘font-face-uri’, ‘foreignObject’, ‘g’, ‘glyph’, ‘glyphRef’, ‘hkern’, ‘image’, ‘line’, ‘linearGradient’, ‘marker’, ‘mask’, ‘metadata’, ‘missing-glyph’, ‘mpath’, ‘path’, ‘pattern’, ‘polygon’, ‘polyline’, ‘radialGradient’, ‘rect’, ‘script’, ‘set’, ‘stop’, ‘style’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘title’, ‘tref’, ‘tspan’, ‘use’, ‘view’, ‘vkern’ ‘xml:lang’ ‘a’, ‘altGlyph’, ‘altGlyphDef’, ‘altGlyphItem’, ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘circle’, ‘clipPath’, ‘color-profile’, ‘cursor’, ‘defs’, ‘desc’, ‘ellipse’, ‘feBlend’, ‘feColorMatrix’, ‘feComponentTransfer’, ‘feComposite’, ‘feConvolveMatrix’, ‘feDiffuseLighting’, ‘feDisplacementMap’, ‘feDistantLight’, ‘feFlood’, ‘feFuncA’, ‘feFuncB’, ‘feFuncG’, ‘feFuncR’, ‘feGaussianBlur’, ‘feImage’, ‘feMerge’, ‘feMergeNode’, ‘feMorphology’, ‘feOffset’, ‘fePointLight’, ‘feSpecularLighting’, ‘feSpotLight’, ‘feTile’, ‘feTurbulence’, ‘filter’, ‘font’, ‘font-face’, ‘font-face-format’, ‘font-face-name’, ‘font-face-src’, ‘font-face-uri’, ‘foreignObject’, ‘g’, ‘glyph’, ‘glyphRef’, ‘hkern’, ‘image’, ‘line’, ‘linearGradient’, ‘marker’, ‘mask’, ‘metadata’, ‘missing-glyph’, ‘mpath’, ‘path’, ‘pattern’, ‘polygon’, ‘polyline’, ‘radialGradient’, ‘rect’, ‘script’, ‘set’, ‘stop’, ‘style’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘title’, ‘tref’, ‘tspan’, ‘use’, ‘view’, ‘vkern’ ‘xml:space’ ‘a’, ‘altGlyph’, ‘altGlyphDef’, ‘altGlyphItem’, ‘animate’, ‘animateColor’, ‘animateMotion’, ‘animateTransform’, ‘circle’, ‘clipPath’, ‘color-profile’, ‘cursor’, ‘defs’, ‘desc’, ‘ellipse’, ‘feBlend’, ‘feColorMatrix’, ‘feComponentTransfer’, ‘feComposite’, ‘feConvolveMatrix’, ‘feDiffuseLighting’, ‘feDisplacementMap’, ‘feDistantLight’, ‘feFlood’, ‘feFuncA’, ‘feFuncB’, ‘feFuncG’, ‘feFuncR’, ‘feGaussianBlur’, ‘feImage’, ‘feMerge’, ‘feMergeNode’, ‘feMorphology’, ‘feOffset’, ‘fePointLight’, ‘feSpecularLighting’, ‘feSpotLight’, ‘feTile’, ‘feTurbulence’, ‘filter’, ‘font’, ‘font-face’, ‘font-face-format’, ‘font-face-name’, ‘font-face-src’, ‘font-face-uri’, ‘foreignObject’, ‘g’, ‘glyph’, ‘glyphRef’, ‘hkern’, ‘image’, ‘line’, ‘linearGradient’, ‘marker’, ‘mask’, ‘metadata’, ‘missing-glyph’, ‘mpath’, ‘path’, ‘pattern’, ‘polygon’, ‘polyline’, ‘radialGradient’, ‘rect’, ‘script’, ‘set’, ‘stop’, ‘style’, ‘svg’, ‘switch’, ‘symbol’, ‘text’, ‘textPath’, ‘title’, ‘tref’, ‘tspan’, ‘use’, ‘view’, ‘vkern’ ‘y’ ‘altGlyph’ ? ‘y’ ‘cursor’ ? ‘y’ ‘fePointLight’ ? ‘y’ ‘feSpotLight’ ? ‘y’ ‘filter’ ? ‘y’ ‘foreignObject’ ? ‘y’ ‘glyphRef’ ‘y’ ‘image’ ? ‘y’ ‘pattern’ ? ‘y’ ‘rect’ ? ‘y’ ‘svg’ ? ‘y’ ‘text’ ? ‘y’ ‘use’ ? ‘y’ ‘feBlend’, ‘feColorMatrix’, ‘feComponentTransfer’, ‘feComposite’, ‘feConvolveMatrix’, ‘feDiffuseLighting’, ‘feDisplacementMap’, ‘feFlood’, ‘feGaussianBlur’, ‘feImage’, ‘feMerge’, ‘feMorphology’, ‘feOffset’, ‘feSpecularLighting’, ‘feTile’, ‘feTurbulence’ ? ‘y’ ‘mask’ ? ‘y’ ‘tref’, ‘tspan’ ? ‘y1’ ‘line’ ? ‘y1’ ‘linearGradient’ ? ‘y2’ ‘line’ ? ‘y2’ ‘linearGradient’ ? ‘yChannelSelector’ ‘feDisplacementMap’ ? ‘z’ ‘fePointLight’ ? ‘z’ ‘feSpotLight’ ? ‘zoomAndPan’ ‘svg’, ‘view’ END #----------------------------------------------------------------------- # Presentation attributes #----------------------------------------------------------------------- sub presentationAttributes() {qw(alignment-baseline baseline-shift clip-path clip-rule clip color-interpolation-filters color-interpolation color-profile color-rendering color cursor direction display dominant-baseline enable-background fill-opacity fill-rule fill filter flood-color flood-opacity font-family font-size-adjust font-size font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events shape-rendering stop-color stop-opacity stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width stroke text-anchor text-decoration text-rendering unicode-bidi visibility word-spacing writing-mode) } #----------------------------------------------------------------------- # Elements which accept presentation attributes #----------------------------------------------------------------------- sub presentationElements() {qw(a altGlyph animate animateColor circle clipPath defs ellipse feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feFlood feGaussianBlur feImage feMerge feMorphology feOffset feSpecularLighting feTile feTurbulence filter font foreignObject g glyph glyphRef image line linearGradient marker mask missing-glyph path pattern polygon polyline radialGradient rect stop svg switch symbol text textPath tref tspan use) } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T20:03:41.777", "Id": "49547", "Score": "1", "body": "Why do you want to parse SVG (XML) in Perl? Also: http://search.cpan.org/~msergeant/XML-Parser-2.36/Parser.pm" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-11T15:53:05.867", "Id": "176545", "Score": "0", "body": "I am reopening this question, again, because it is not a duplciate of [this question](https://codereview.stackexchange.com/questions/31118/perl-hash-mapping-svg-elements-to-content-elements)" } ]
[ { "body": "<p>Houston, we have a problem. I'm going to be blunt, not because I enjoy saying mean things to fellow programmers, but because there really isn't any way to sugar-coat it. This is unintentionally obfuscated Perl, the kind that gives the language a bad reputation.</p>\n\n<p>Before continuing, I'd like to ask, What is the purpose of this code?</p>\n\n<ol>\n<li>If you want an SVG validator, consider using some standard XML DTD or schema validation tools. (XML validation is a solved problem; don't reinvent the wheel.)</li>\n<li>Do you want the resulting data structure to be used in, say, an SVG authoring tool? If that's the case, your question is about how to best represent a complex data structure as a Perl code literal.</li>\n<li>Are you doing this as an exercise in transforming the original W3C specification document into a more useful data structure? In that case, your question is mainly about screen scraping or text processing.</li>\n</ol>\n\n<p>A key contributing factor to the unreadability of your code is naming. You have…</p>\n\n<ul>\n<li><code>$a</code>, <code>$e</code></li>\n<li><code>$A</code>, <code>$E</code> (<code>$E</code> is used twice in the global scope. <code>$A</code> is used inside your first <code>for</code> loop as a boolean meaning \"animatable\", then as an iteration dummy variable for presentation attributes, then as a hashref to a data structure for all attributes.)</li>\n<li><code>cc()</code></li>\n<li><code>data()</code></li>\n</ul>\n\n<p>It's not 1960, where every byte counts. Just saying <code>camelCase()</code> instead of <code>cc()</code> would help reduce mental workload. Short, cryptic variable names should only be used as iteration dummy variables in simple loops where it is absolutely obvious what it means. Your code doesn't qualify for that.</p>\n\n<hr>\n\n<p>Let's assume your motivation is (3). Your <code>for</code> loop desperately needs a comment — not a two-line comment, but an essay. Something like…</p>\n\n<pre><code># Process the W3C SVG 1.1 Spec, Appendix M (Attribute Index)\n# http://www.w3.org/TR/2011/REC-SVG11-20110816/attindex.html\n# into two data structures, $a and $e.\n#\n# Each line of the input contains:\n# Attribute-name (first word)\n# Elements on which the attribute may be specified (subsequent words)\n# '?' as the last word if the attribute is animatable\n#\n# The resulting data structure $a is a hashref whose keys are …\n# and whose values are …\n#\n# The resulting data structure $e is a hashref whose keys are …\n# and whose values are …\n</code></pre>\n\n<p>Instead of a here-doc string, try putting your data at the end of your code, after a <code>__DATA__</code> marker, and reading from the <code>&lt;DATA&gt;</code> filehandle.</p>\n\n<hr>\n\n<p>If, on the other hand, your motivation is (2), then I would suggest a different approach altogether. I would encode the data structure as</p>\n\n<pre><code>$regular_attributes = {\n non_anim('accent-height') =&gt; [qw(font-face)],\n non_anim('accumulate') =&gt; [qw(animate animateColor animateMotion animateTransform)],\n non_anim('additive') =&gt; [qw(animate animateColor animateMotion animateTransform)],\n non_anim('alphabetic') =&gt; [qw(font-face)],\n anim('amplitude') =&gt; [qw(feFuncA feFuncB feFuncG feFuncR)],\n # etc...\n};\n</code></pre>\n\n<p>Alternatively, you could write it as a <a href=\"http://yaml.org\">YAML</a> data structure inside your <code>__DATA__</code> section, then load it using a YAML parser. One useful feature of YAML is that it supports <a href=\"http://www.yaml.org/spec/1.2/spec.html#id2801681\">multiple streams</a>, so you can have several YAML documents in your <code>__DATA__</code> section. Another nice feature is that it lets you <a href=\"http://www.yaml.org/spec/1.2/spec.html#id2786196\">mark and reference previously mentioned chunks of data</a>:</p>\n\n<pre><code>__DATA__\naccent-height:\n anim: false\n elements:\n - font-face\naccumulate:\n anim: false\n elements: &amp;animElements\n - animate\n - animateColor\n - animateMotion\n - animateTransform\nadditive:\n anim: false\n elements: *animElements\n# etc...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T22:26:22.437", "Id": "31127", "ParentId": "31120", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T18:49:14.617", "Id": "31120", "Score": "0", "Tags": [ "perl", "svg" ], "Title": "Perl Hash mapping SVG elements to their attributes" }
31120
<p>I'm just getting started with XNA and game development in general. I followed <a href="http://msdn.microsoft.com/en-us/library/bb203893.aspx" rel="nofollow">these instructions</a> to create a basic game, then <a href="http://www.berecursive.com/2008/c/sprite-sheets-in-xna-the-basics" rel="nofollow">this article</a> to get sprite animations working.</p> <p>Now, I'm trying to abstract my design, in particular the stuff with sprite animations. Before I get much deeper, I want to make sure I have a good foundation to work with.</p> <p>First, I have a <code>Sprite</code> class:</p> <pre><code>public class Sprite { public Sprite() { // Default values for public members Position = Vector2.Zero; Scale = 1f; LayerDepth = 0f; } public IAnimation Animation { get; set; } public IMovement Movement { get; set; } public string AssetName { get; set; } public Texture2D Texture { get; set; } public Vector2 Position { get; set; } public Rectangle Frame { get; set; } public float Scale { get; set; } public float LayerDepth { get; set; } public void Update( GameTime gameTime ) { if ( Animation != null ) { Frame = Animation.GetNextFrame( gameTime, Frame ); } if ( Movement != null ) { Position = Movement.GetNextPosition( gameTime, Position ); } } public void Draw( SpriteBatch spriteBatch ) { spriteBatch.Draw( Texture, Position, Frame, Color.White, 0f, Vector2.Zero, Scale, SpriteEffects.None, LayerDepth ); } } </code></pre> <p>I have a <code>SpriteGroup</code> class for keeping groups of sprites organized and making them easy to use:</p> <pre><code>public class SpriteGroup { public IList&lt;Sprite&gt; Sprites { get; set; } public void Update( GameTime gameTime ) { foreach ( var sprite in Sprites ) { sprite.Update( gameTime ); } } public void Draw( SpriteBatch spriteBatch ) { foreach ( var sprite in Sprites ) { sprite.Draw( spriteBatch ); } } } </code></pre> <p>This is inherited by the <code>Character</code> class (nothing special there), of which I have several static instances:</p> <pre><code>public static class Characters { public static Character Tycho = new Character { Sprites = new List&lt;Sprite&gt; { new Sprite { Animation = new Animation { FirstFrame = 2, LastFrame = 9 }, AssetName = "characters/walkcycle/BODY_male", Position = new Vector2( 100, 100 ), Frame = new Rectangle( 64, 64, 64, 64 ), LayerDepth = 1f }, new Sprite { Animation = new Animation { FirstFrame = 2, LastFrame = 9 }, AssetName = "characters/walkcycle/LEGS_pants_greenish", Position = new Vector2( 100, 100 ), Frame = new Rectangle( 64, 64, 64, 64 ), LayerDepth = 0f } } }; // Several more static Characters... } </code></pre> <p>I plan to have other static objects that inherit from <code>SpriteGroup</code> as well such as scenery, buildings, etc.</p> <p>Here are the relevant bits of my <code>Game</code> class (or rather the class that inherits the <code>Game</code> class from the XNA library):</p> <pre><code>private IList&lt;Sprite&gt; sprites { get; set; } protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch( GraphicsDevice ); sprites = new List&lt;Sprite&gt;(); var characters = new List&lt;Character&gt; { Characters.Aradesh, Characters.Ian, Characters.Tycho }; foreach ( var character in characters ) { foreach ( var sprite in character.Sprites ) { sprite.Texture = Content.Load&lt;Texture2D&gt;( sprite.AssetName ); sprites.Add( sprite ); } } } protected override void Update( GameTime gameTime ) { foreach ( var sprite in sprites ) { sprite.Update( gameTime ); } // Other uninteresting stuff... } protected override void Draw( GameTime gameTime ) { spriteBatch.Begin( SpriteSortMode.BackToFront, BlendState.AlphaBlend ); foreach ( var sprite in sprites ) { sprite.Draw( spriteBatch ); } spriteBatch.End(); // Etc... } </code></pre> <p>Is this a good foundation for an XNA project? Are there any glaring flaws or design traps I'm likely to run into with what I have so far? Replace XNA with MonoGame where applicable. Either way, I'm just looking for general design advice. I haven't decided if I will make the switch to MonoGame or something else yet.</p> <p>Ideally, I'd like to build up a reusable base class library for other projects moving forward, or for others to use or fork or whatever.</p> <p>In case it helps, you can browse the code on <a href="https://github.com/davidkennedy85/MyFirstGame" rel="nofollow">GitHub</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T04:42:18.180", "Id": "49570", "Score": "2", "body": "Hm, you should consider moving to an other technology because [XNA is dead](http://www.gamasutra.com/view/news/185894/Its_official_XNA_is_dead.php). I think MonoGame is the new open source implementation of XNA to fill the void a little, but there's probably better and up-to-date stuff for game dev." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:43:01.437", "Id": "49609", "Score": "0", "body": "That really sucks, because I did a lot of research ahead of time that suggested XNA is the way to go (at least to start). I heard that Microsoft was discontinuing XNA development but thought it was just a rumor. I can't imagine why they would abandon it, since Xbox seems like a high priority for them these days along with Windows Phone and Tablet. Any idea what I should try next?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:58:31.000", "Id": "49610", "Score": "0", "body": "Also, what about the design in general? Any suggestions? (I updated it since you last commented.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-19T02:51:01.317", "Id": "88190", "Score": "0", "body": "XNA is dead, but MonoGame is alive and well. The community is active and lots of solid games are being made with it everyday." } ]
[ { "body": "<ol>\n<li><p>I would move the inner loop which loads the texture into the <code>SpriteGroup</code> class as well as moving the texture loading for the single sprite into the <code>Sprite</code> class:</p>\n\n<pre><code>public class Sprite\n{\n ....\n public void LoadTexture()\n {\n Texture = Content.Load&lt;Texture2D&gt;(AssetName);\n }\n}\n\npublic class SpriteGroup\n{\n ...\n public void LoadTextures()\n {\n foreach (var s in Sprites)\n {\n s.LoadTexture();\n }\n }\n}\n</code></pre></li>\n<li>In general you should try to not expose how stuff is stored internally in a class directly (e.g. don't make your <code>Sprites</code> list a public property). If you ever consider changing the internal implementation then this could mean a lot of work to change existing code. You could make <code>SpriteGroup</code> either <code>IEnumerable&lt;Sprite&gt;</code> or simply not give public access to the underlying sprite collection at all.\n\n<ul>\n<li>Consider adding a constructor for <code>SpriteGroup</code> taking an <code>IEnumerable&lt;Sprite&gt;</code> which are added to the internal sprite list by the constructor code.</li>\n<li>If you need to add/remove sprites on the fly then add Add/Remove methods.</li>\n</ul></li>\n<li>Your <code>Game</code> class should not deal with sprites directly but rather with the \"world\" objects.\n\n<ul>\n<li>Call <code>Update</code> and <code>Draw</code> on the character/sprite group objects and let them forward it to the internal sprites (you have some of that code in there anyway) </li>\n</ul></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T20:31:39.027", "Id": "60912", "Score": "0", "body": "Sorry for neglecting your answer for so long. I have implemented changes 1 and 3 in my new project [here](https://github.com/davidkennedy85/RpgTown). As for no. 2, the reason I make everything public on entities is so I can use object initializers, but I'm starting to wonder if I need to give those up." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-15T10:39:58.037", "Id": "32706", "ParentId": "31124", "Score": "3" } }, { "body": "<p>Since you superficially asked about abstracting the design, in particular the stuff with sprite animations let me talk about that. </p>\n\n<p>My concern comes from the Single responsibility principle (SRP) and the Open/closed principle (OCP) in the SOLID principles way of thinking <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)</a></p>\n\n<p>Before you added animation and movement your Sprite class fit SRP pretty well. Unfortunately, now you've said that the Sprite class is also responsible for Animation. When your animation code changes (and it will) the sprite class will also need changing (this violates the OCP rule).</p>\n\n<p>Okay, so how do you fix it?</p>\n\n<p>Well, it seems to me that Sprites are about Drawing and Animations are about Updating over time. Therefore, you should split the Update method out into an Animation class.</p>\n\n<p>Consider this:</p>\n\n<pre><code>public interface IFrameable\n{\n Rectangle Frame { get; set; }\n}\n\npublic class Animation\n{\n private IFrameable _target;\n\n public Animation(IFrameable target)\n {\n _target = target;\n }\n\n public void Update( GameTime gameTime )\n {\n _target.Frame = GetNextFrame( gameTime, _target.Frame );\n }\n}\n</code></pre>\n\n<p>What I've created here is essentially a \"framed animation\" class based on your code that can take any type of IFrameable object in it's constructor. Your Sprite class could of course implement IFrameable and become the target for this type of Animation. </p>\n\n<p>Doing something like this removes the Animation responsibility from the Sprite class and let's it deal with Drawing (what it's good at). It then allows you to implement different types of animations (e.g. movement, rotation, scale or color) and chain them together ultimately making the animation code more flexible.</p>\n\n<p>It also allows you to \"compose\" objects of Sprites, Animations and whatever else you can think of without the need to change too many existing classes. </p>\n\n<p>There's lot's more I could talk about on this subject, it's something I've thought about a lot in my own games, but for now I'll just leave it as food for thought :)</p>\n\n<p>Happy coding!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-19T03:35:29.297", "Id": "51107", "ParentId": "31124", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-11T21:26:42.350", "Id": "31124", "Score": "7", "Tags": [ "c#", "object-oriented", "design-patterns", "animation", "xna" ], "Title": "Sprite animation for a game" }
31124
<p>Below is the code for my templated callback implementation. Currently it works for a single parameter. One thing I was going to try and do next was increase the argument to the function from 1..N arguments. Ideally this would be as simple as adding Args... everywhere using variadic templates. I don't have a lot of experience yet with variadic templates so any advice on this is helpful.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; template &lt;typename R, typename Arg&gt; class Callback { public: typedef R (*FuncType)(void*, Arg); Callback (FuncType f, void* subscription) : f_(f), subscription_(subscription) { } R operator()(Arg a) { (*f_)(subscription_,a); } private: FuncType f_; void* subscription_; }; template &lt;typename R, typename Arg, typename T, R (T::*Func)(Arg)&gt; R CallbackWrapper (void* o, Arg a) { return (static_cast&lt;T*&gt;(o)-&gt;*Func)(a); } class Pricer { public: typedef Callback&lt;void,unsigned int&gt; CbType; void attach ( CbType cb ) { callbacks_.emplace_back(cb); } void receivePrice ( double price ) { broadcast(static_cast&lt;unsigned int&gt;(price*100)); } void broadcast (unsigned int price) { for ( auto&amp; i : callbacks_) { i(price); } } private: std::vector&lt;CbType&gt; callbacks_; }; class Strategy { public: Strategy(Pricer* p) : p_(p) { p-&gt;attach(Callback&lt;void,unsigned int&gt;(&amp;CallbackWrapper&lt;void,unsigned int, Strategy, &amp;Strategy::update&gt;, static_cast&lt;void *&gt;(this))); } void update(unsigned int price) { //update model with price std::cout &lt;&lt; "Received price: " &lt;&lt; price / 100.0 &lt;&lt; std::endl; } private: Pricer* p_; }; int main ( int argc, char *argv[]) { Pricer p; Strategy s(&amp;p); p.receivePrice(105.67); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T05:48:09.850", "Id": "49574", "Score": "0", "body": "Sure. But why would I use this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T07:56:05.867", "Id": "49695", "Score": "0", "body": "Some of the code wasn't pasted originally. The code shows the usage where you would have any object register it's member function for a call back. See strategy registering to get notified for prices. It would be a generic call back system that would handle member functions and functions with a single Callback/CallbackWrapper class. Also using templates in this way will give runtime information of the types at compile time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T08:15:47.600", "Id": "49700", "Score": "0", "body": "Also what are your thoughts on the void * and performance in this case otherwise I would have a add a type T to the Callback and have one for each Callback type" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T08:21:23.427", "Id": "49833", "Score": "0", "body": "Is this an exercise just so you can practice? Fortunately what you are trying to do is already covered by std::function<>. So this is nothing that you should ever use in real code." } ]
[ { "body": "<p>The functionality you are trying to create already exists in <code>std::function&lt;&gt;</code> using <code>std::bind&lt;&gt;</code> to help.</p>\n\n<h3>Comments on the rest of the code:</h3>\n\n<p>Here you use emplace back:</p>\n\n<pre><code> void attach ( CbType cb )\n {\n callbacks_.emplace_back(cb);\n }\n</code></pre>\n\n<p>Emplace back is usually used when you have the arguments and want to build the object in place using the arguments. By passing the object you are going to just invoke the copy constructor. As a result there is no benefit from using it. Though there is nothing wrong with using it either. Currently I am still working out when to use <code>emplace_back()</code> over <code>push_back()</code> but this is one situation where I would still use <code>push_back()</code>.</p>\n\n<p>Also because you pass the argument by value you are copying the object into the function then using the copy constructor to put it in the array resulting in another copy. So here I would pass by reference.</p>\n\n<pre><code> void attach(CbType const&amp; cb)\n {\n callbacks_.push_back(cb);\n }\n</code></pre>\n\n<p>Don't use unnecessary casts</p>\n\n<pre><code>broadcast(static_cast&lt;unsigned int&gt;(price*100));\n\n// This is easier to read as:\n\nbroadcast(price*100); // double is auto converted to unsigned int\n</code></pre>\n\n<p>Use standard types:</p>\n\n<pre><code>typedef Callback&lt;void,unsigned int&gt; CbType;\n\n// Replace with:\n\ntypedef std::function&lt;void(unsigned int)&gt; CbType;\n</code></pre>\n\n<p>If you use the standard function then the equivalent to creation becomes much simpler</p>\n\n<pre><code> p.attach(std::bind(&amp;Strategy::update,this, _1));\n</code></pre>\n\n<p>Don't use pointers where a reference is a better choice:</p>\n\n<pre><code>Strategy(Pricer* p) : p_(p) \n</code></pre>\n\n<p>You are passing a pointer and not checking for NULL. Actually the code never checks for NULL so you must use a valid pointer. In this case you may as well pass a reference. If you want to store this internally as a pointer then take its address inside your object.</p>\n\n<pre><code>Strategy(Pricer&amp; p) : p_(&amp;p) // p can never be invalid. \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T18:02:46.997", "Id": "50222", "Score": "0", "body": "Thanks for the help I need to review how to do this using std::function and std::bind. I was using templates to help with registering the objects at compile versus runtime." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T18:09:46.120", "Id": "50223", "Score": "0", "body": "Do you have some code that uses std::bind and std::function to do equivalent? I think I need to review something like that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T18:12:01.283", "Id": "50224", "Score": "0", "body": "With the emplace_back I thought it would just do a __move__ of the copied argument object in place instead of a copy. Is this not the case? This is the reason why I was calling emplace_back to try and remove the copy" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T18:16:43.737", "Id": "50225", "Score": "0", "body": "Also the `R CallbackWrapper (void* o, Arg a)` is used to hide the member function details to create a generic function pointer can I just get rid of this using std::bind then? I think an example would help me out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T18:19:00.387", "Id": "50226", "Score": "0", "body": "with regards to my move comment I guess I was thinking it would be a copy elision situation." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T08:42:12.577", "Id": "31307", "ParentId": "31128", "Score": "4" } } ]
{ "AcceptedAnswerId": "31307", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T03:02:12.180", "Id": "31128", "Score": "4", "Tags": [ "c++", "template", "callback" ], "Title": "Fast templated call back implementation" }
31128
<p>I was trying to write code which does a validation for the below wildcards:</p> <blockquote> <ul> <li><p>'?' ------> The question mark indicates there is zero or one of the preceding element. For example, colou?r matches both "color" and "colour".</p></li> <li><p>'*' ------> The asterisk indicates there is zero or more of the preceding element. For example, ab*c matches "ac", "abc", "abbc", "abbbc", and so on.</p></li> <li><p>'+' ------> The plus sign indicates there is one or more of the preceding element. For example, ab+c matches "abc", "abbc", "abbbc", and so on, but not "ac".</p></li> </ul> </blockquote> <p>I know that Java does provide pattern matching with wild cards out of box, but this is more of an exercise to understand the crux by not using libraries.</p> <pre><code>static boolean matches(String pattern, String text) { if (text == null &amp;&amp; pattern == null) { return true; } if (text == null || pattern == null) { return false; } if (text.equals(EMPTY_STRING) &amp;&amp; pattern.equals(EMPTY_STRING)) { return true; } if (text.equals(EMPTY_STRING) || pattern.equals(EMPTY_STRING)) { return false; } char[] p = pattern.toCharArray(); char[] t = text.toCharArray(); int indexP1 = 0, indexP2 = 1, indexT = 0; while (true) { if (indexP1 == p.length &amp;&amp; indexT == t.length){ return true; } else if (indexP1 == p.length || indexT == t.length){ return false; } else { if (indexP2 &lt; p.length &amp;&amp; p[indexP2] == '*'){//case: a* while (t[indexT] == p[indexP1]) { indexT++; if(indexT==t.length)break; } indexP1 = indexP1 + 2; indexP2 = indexP2 + 2; } else if (indexP2 &lt; p.length &amp;&amp; p[indexP2] == '+') {//case: a+ if(t[indexT] != p[indexP1]){ return false; } while (t[indexT] == p[indexP1]) { indexT++; if(indexT==t.length)break; } indexP1 = indexP1 + 2; indexP2 = indexP2 + 2; } else if (indexP2 &lt; p.length &amp;&amp; p[indexP2] == '?') {//case: a? if (t[indexT] == p[indexP1]) { indexT++; } indexP1 += 2; indexP2 += 2; } else {//case: a if (t[indexT] != p[indexP1]) { return false; } indexP1++; indexP2++; indexT++; } } } } </code></pre>
[]
[ { "body": "<p>Right away, I see two bugs:</p>\n\n<p>First, it is not valid to say</p>\n\n<pre><code>if (text.equals(EMPTY_STRING) || pattern.equals(EMPTY_STRING)) {\n return false;\n}\n</code></pre>\n\n<p>… because a non-empty pattern can certainly match an empty string.</p>\n\n<p>Second, it takes a state machine to do regular expression matching properly; all I saw in your code were a few pointers. (What are <code>indexP1</code>, <code>indexP2</code>, and <code>indexT</code> supposed to stand for? Is there some invariant stateabout them that you could write out in a comment?) It seems that you are matching <code>*</code> and <code>+</code> greedily. That can't be right; sometimes you might need to backtrack and consider another possibility in order to get a match.</p>\n\n<p>I didn't analyze the code too deeply, but those two serious concerns suggest that you will need to work at this code a lot more anyway.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T06:02:07.103", "Id": "31455", "ParentId": "31129", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T03:14:36.470", "Id": "31129", "Score": "1", "Tags": [ "java", "strings", "regex" ], "Title": "Wildcard pattern-matching algorithm" }
31129
<p>There is an e-commerce site that I'm working on that has thousands of pages in it (mostly product pages). I've got some jQuery that I'm running on about 1300 of these products. Only specific products need the code to run so what I've done is set up the product codes (which display in the URL of the product) in a JSON data sheet and I'm looping through the JSON data like this:</p> <pre><code>$(document).ready(function(){ $.getJSON('js/round.js', function(data) { var location_var = "location.pathname.indexOf('/product-p/main-product.htm')" for(i=0; i&lt;data.records.length-1; i++){ var location_var = location_var + " || location.pathname.indexOf('" + data.records[i].productcode + "')"; } if (location_var != -1){ //DO SOMETHING TO THESE SPECIFIC PAGES } }); }); </code></pre> <p>Now this functions but obviously it has to handle the 1300 hundred rows, check and then run my code. This causes a slight lag and unfortunately that lag will run on all of the pages because it has to determine if the page is correct for every page that it goes through.</p> <p>This is the only way I could think of doing this (my Javascript is a bit limited at this point) so I'm curious if anybody knows of a way to do this more efficiently and to make the query faster.</p> <p>Thanks for your help!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-14T06:03:36.340", "Id": "52241", "Score": "2", "body": "Your code makes no sense. You are just concatenating strings together, `location_var` will never equal `-1`. Please provide a better explanation of what you are trying to achieve and what is `data`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-14T19:20:40.957", "Id": "52281", "Score": "0", "body": "-1 is used when you are targeting a URL. It's very common when you are tried to run code on a specific page. Data is the response returned when running the getJSON function. It makes plenty of sense." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T14:09:13.920", "Id": "57139", "Score": "0", "body": "What do you expect the type of location_var will be? Do you think you can compare it to the typeof -1 ?" } ]
[ { "body": "<p>What exactly do you have in the javascript (json) file? Can you get the product code from anywhere other than the the path?</p>\n\n<p>Here is what I suggest:</p>\n\n<ol>\n<li><p>Just include the javascript file. Don't bother pulling it via JSON. Doing so just adds overhead you don't need since you are checking this file on every page anyway.</p></li>\n<li><p>Within the javascript file store the product codes in an array. </p>\n\n<pre><code>var productCodes = ['code1', 'code2', 'etc...']\n</code></pre></li>\n<li><p>Put the test in a separate function.</p>\n\n<pre><code>function pageNeedsProcessing() {\n // add any special rules here to avoid checks when not needed.\n if (location.pathname.indexOf('/product-p/main-product.htm')) {\n return true;\n }\n\n // do whatever you need to get the product code. This may require parsing the path.\n var prodCode = ???;\n\n // if the product code is in array (established in #2) then return true.\n return $.inArray(prodCode, productCodes) \n}\n</code></pre></li>\n<li><p>Add your code to be processed.</p>\n\n<pre><code>if (pageNeedsProcessing()) {\n //DO SOMETHING TO THESE SPECIFIC PAGES\n}\n</code></pre></li>\n</ol>\n\n<p>One caveat here is that doing it exactly like this will introduce some variables into global scope. But there are ways around that. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T05:51:26.703", "Id": "31132", "ParentId": "31130", "Score": "1" } }, { "body": "<p>In general,</p>\n\n<p>the native <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow\">[].forEach()</a> will work faster than your own iteration, at the very least you ought to pre-calculate the length of <code>data.records</code>.</p>\n\n<p>You should also profile your JavaScript using for example the Chrome Developer tools so that you can find out where most time is spent. I kind of doubt it would be <code>indexOf</code>. Can you provide the actual code for <code>//Do something to these specific pages</code> ?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-13T13:25:33.000", "Id": "35292", "ParentId": "31130", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T03:53:16.813", "Id": "31130", "Score": "0", "Tags": [ "javascript", "jquery", "json" ], "Title": "More Efficient Javascript indexOf query" }
31130
<p>Question 1: functionxxx_as_string() is used below. How else could it be more elegantly named?</p> <p>Question 2: Is the static char* array method adopted below the only solution? Best solution? Any suggestions?</p> <p>Generally, I have this issue where my list of enums will be from 3 - say 50 items, mostly less than 20 items and they are fairly static.</p> <pre><code> #include &lt;iostream&gt; enum thing_type { DTypeAnimal, DTypeMineral, DTypeVegetable, DTypeUnknown }; class thing { public: thing(thing_type type) : type_(type) {} const thing_type get_state() const { return type_; } const char* get_state_as_string() const { static const char* ttype[] = { "Animal", "Mineral", "Vegetable", "Unknown" }; return ttype[type_]; } private: thing_type type_; }; int main() { thing th(DTypeMineral); std::cout &lt;&lt; "this thing is a " &lt;&lt; th.get_state_as_string() &lt;&lt; std::endl; return 0; } </code></pre> <p>I am preferring to remove all the printing stuff from the class interface and use the operator&lt;&lt; overloading idea in 200_success answer like this:</p> <pre><code>#include &lt;iostream&gt; enum thing_type { DTypeUnknown, DTypeAnimal, DTypeMineral, DTypeVegetable }; const char* type2string(thing_type ttype) { static const char* thtype[] = { "Unknown", "Animal", "Mineral", "Vegetable" }; return ttype &lt; sizeof(thtype) ? thtype[ttype] : thtype[0]; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const thing_type type) { os &lt;&lt; type2string(type); return os; } class thing { public: thing(thing_type type) : type_(type) {} const thing_type get_type() const { return type_; } private: thing_type type_; }; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const thing&amp; th) { os &lt;&lt; "This is a " &lt;&lt; type2string(th.get_type()); return os; } int main() { thing th(DTypeMineral); std::cout &lt;&lt; th &lt;&lt; std::endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T10:35:46.843", "Id": "49583", "Score": "0", "body": "In general, the values of an enum are not required to be unique, e.g. `enum light { red, yellow, green, stop = 0, go = 2 };`. That makes the name for a given value plural." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T10:55:29.617", "Id": "49584", "Score": "0", "body": "I find the way .net has it is awesome - xxxxToString? (But I'm biased :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T02:58:56.340", "Id": "49677", "Score": "1", "body": "Also see: http://codereview.stackexchange.com/a/14315/507" } ]
[ { "body": "<p>You should use one of the preprocessor macro-based solutions proposed in <a href=\"https://stackoverflow.com/questions/147267\">StackOverflow Question 147267</a>. For example, here is a solution using X() macros. I've also rewritten your <code>get_state_as_string()</code> as a stringifier for iostream.</p>\n\n<pre><code>#include &lt;iostream&gt;\n\n#define X_THINGS \\\n X(DTypeAnimal, \"Animal\") \\\n X(DTypeMineral, \"Mineral\") \\\n X(DTypeVegetable, \"Vegetable\") \\\n X(DTypeUnknown, \"Unknown\")\n\ntypedef enum {\n# define X(Enum, String) Enum,\n X_THINGS\n# undef X\n} thing_type;\n\nclass Thing {\n public:\n Thing(thing_type type) : type_(type) {}\n const thing_type get_state() const { return type_; }\n friend std::ostream &amp;operator&lt;&lt;(std::ostream&amp;, const Thing&amp;);\n\n private:\n thing_type type_;\n};\n\nstd::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, const Thing &amp;t) {\n switch (t.get_state()) {\n# define X(Enum, String) \\\n case Enum: os &lt;&lt; String; break;\n X_THINGS\n# undef X\n }\n return os;\n}\n\nint main() {\n Thing th(DTypeMineral);\n std::cout &lt;&lt; \"this thing is a \" &lt;&lt; th &lt;&lt; std::endl;\n\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T12:18:19.640", "Id": "49586", "Score": "0", "body": "I'd paste at least one of the examples here to make this answer more valuable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T17:49:32.247", "Id": "49623", "Score": "0", "body": "Yes I don't like all the as_string functions. I prefer overloading operator<< - and taking the printing stuff out of the class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T03:06:36.797", "Id": "49678", "Score": "4", "body": "Since this is C++ proposing a C solution is probably not a good idea. The same affective can be done much better using language features in C++." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T10:14:24.773", "Id": "31137", "ParentId": "31136", "Score": "1" } }, { "body": "<p>//I lost original answer I wanted to post on stackoverflow...</p>\n\n<blockquote>\n <p>Question 1: functionxxx_as_string() is used below. How else could it be more elegantly named?</p>\n</blockquote>\n\n<pre><code> const char *to_string(thing_type type);\n</code></pre>\n\n<p>It doesn't have to be class member.</p>\n\n<blockquote>\n <p>Question 2: Is the static char* array method adopted below the only solution? Best solution? Any suggestions?</p>\n</blockquote>\n\n<p>Not the only solution, may or may not be the best solution.</p>\n\n<p>Potential problems - if your enum has \"holes\" <code>enum Asdf{a = 1, b = 48, c}</code>, array of names won't work.</p>\n\n<p>You'll need to use array of pairs, std::map or plain old switch/case.</p>\n\n<p>//warning: I haven't compiled the code, there might be typos.</p>\n\n<p>array of pairs:</p>\n\n<pre><code>const char *tOstring(thing_type type){\n struct Data{\n thing_type type;\n const char *name;\n };\n\n static const Data data[] = {\n {thing, \"thing\"},\n ....\n {unusued_value, 0)\n };\n\n //if you use binary search here, it'll be faster\n for (const Data* cur = data[]; data-&gt;name; data++){\n if (cur-&gt;type == type)\n return cur-&gt;name;\n }\n return 0;\n}\n</code></pre>\n\n<p>std::map:</p>\n\n<pre><code>typedef std::map&lt;thing_type, std::string&gt; NameMap;\nNameMap nameMap;//somewhere\nstd::string toString(thing_type type){\n NameMap::const_iterator found = nameMap.find(type);\n if (found == nameMap.end())\n return std::string; //or throw exception\n return found.second;\n}\n</code></pre>\n\n<p>You can make array of pairs static const, but std::map will need to be initialized somewhere. However, with std::map you can add/remove values at runtime. static const array of pairs and switch/case can't be changed at runtime.</p>\n\n<blockquote>\n <p>Any suggestions?</p>\n</blockquote>\n\n<p>You should probably use macros to initialize your array. Practical example (using switch/case):</p>\n\n<pre><code>const char* glErrorString(GLuint error){\n switch (error){\n#define BRANCH(p) case(p): return #p; \n BRANCH(GL_NO_ERROR)\n BRANCH(GL_INVALID_ENUM)\n BRANCH(GL_INVALID_VALUE)\n BRANCH(GL_INVALID_OPERATION)\n BRANCH(GL_STACK_OVERFLOW)\n BRANCH(GL_STACK_UNDERFLOW)\n BRANCH(GL_OUT_OF_MEMORY)\n BRANCH(GL_TABLE_TOO_LARGE )\n default:\n return \"Unknown error\\n\";\n#undef BRANCH\n };\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T12:58:15.353", "Id": "31141", "ParentId": "31136", "Score": "1" } }, { "body": "<blockquote>\n <p>Question 1: functionxxx_as_string() is used below. How else could it be more elegantly named?</p>\n</blockquote>\n\n<p>How about:</p>\n\n<pre><code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; str, thing const&amp; data);\n</code></pre>\n\n<blockquote>\n <p>Question 2: Is the static char* array method adopted below the only solution? Best solution? Any suggestions?</p>\n</blockquote>\n\n<p>You will need a static char array (or equivalent (like a switch)) somewhere as there is no built in way to convert enum values (which are integers) to a string.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T09:17:53.237", "Id": "49703", "Score": "0", "body": "I feel a bit bad about changing my mind but only just seen byour answer. Agree overloading operator<< is better approach. See my update above." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T03:02:22.607", "Id": "31216", "ParentId": "31136", "Score": "4" } } ]
{ "AcceptedAnswerId": "31216", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T09:52:09.890", "Id": "31136", "Score": "6", "Tags": [ "c++", "enum" ], "Title": "Converting enum values to strings in C++" }
31136
<p>Can the below <code>foreach</code> loop be improved? Since I use the same method twice, maybe use <code>continue</code> or <code>break</code>?</p> <pre><code>int? index = null; int count = 0; foreach (Break b in breaks) { if (index.HasValue) { if (index == count) b.Remove(); } else { b.Remove(); } count++; } </code></pre> <p>So I turned it into this:</p> <pre><code>foreach (Break b in breaks) { if ((index.HasValue &amp;&amp; index == count) || !index.HasValue) { b.Remove(); } count++; } </code></pre> <p>Which is the same. Any other optimizations possible?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T17:06:43.263", "Id": "49615", "Score": "6", "body": "`index` is always `null`, so why not simply remove it? `int count = 0; foreach(Break b in breaks { b.Remove(); count++ }`? What value does having `index` serve?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T19:40:29.593", "Id": "49633", "Score": "2", "body": "I’ve always wondered why so many languages lack a Boolean “implies” operator `a ==> b` equivalent to `(a && b) || !a`, or perhaps `let x = a in (x && b) || !x` in the presence of side effects. Moreover, where’s my `let`-`in` expression?" } ]
[ { "body": "<p>How about removing the loop at all like:</p>\n\n<pre><code>if (!index.HasValue)\n{\n breaks.Clear();\n}\nelse\n{\n breaks.RemoveAt((int)index);\n}\n</code></pre>\n\n<p>if you want/need to keep the loop, i would change your second way like:</p>\n\n<pre><code>foreach (Break b in breaks)\n{\n if (!index.HasValue || index == count)\n {\n b.Remove();\n }\n count++;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T12:46:32.930", "Id": "31140", "ParentId": "31139", "Score": "15" } }, { "body": "<p>Leaving aside the question of why you have <code>index</code> in the first place, you don't need to check for nullity before you use a comparison operator. If you have </p>\n\n<pre><code>int x = whatever;\nint? y = whatever;\nbool b = x == y;\n</code></pre>\n\n<p>Then <code>b</code> will be <code>true</code> if <code>y</code> has a value equal to <code>x</code> and <code>false</code> otherwise. You don't have to say something like:</p>\n\n<pre><code>bool b = y.HasValue ? x == y.Value : false;\n</code></pre>\n\n<p>The compiler will generate that code on your behalf. This feature is called <em>lifting to nullable</em> and it applies to most of the operators in C#.</p>\n\n<p>If the subject of how the compiler analyzes and generates code for lifted operators interests you, I wrote a long series of articles explaining it in detail. See </p>\n\n<p><a href=\"http://ericlippert.com/2012/12/20/nullable-micro-optimizations-part-one/\">http://ericlippert.com/2012/12/20/nullable-micro-optimizations-part-one/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T17:10:01.767", "Id": "31155", "ParentId": "31139", "Score": "11" } } ]
{ "AcceptedAnswerId": "31140", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T12:19:41.473", "Id": "31139", "Score": "4", "Tags": [ "c#" ], "Title": "Can this foreach loop be improved?" }
31139
<p>I am creating a performant C# socket server. I'd like it to be able to accept as many simultaneous connections as possible. I've tested with 100 clients and all clients are fine. With 1000 however, clients begin to stop connecting. Is it possible to improve something to increase the number of simultaneous connections? </p> <p>Of course, general code review would also be appreciated.</p> <p><strong>Server:</strong></p> <pre><code>class Listener { public readonly int Port; private readonly TcpListener _tcpListener; private readonly Task _listenTask; public Listener(int port) { Port = port; _tcpListener = new TcpListener(IPAddress.Any, Port); _tcpListener.Start(); _listenTask = Task.Factory.StartNew(() =&gt; ListenLoop()); } private async void ListenLoop() { for (; ; ) { var socket = await _tcpListener.AcceptSocketAsync(); if (socket == null) break; var client = new Client(socket); Task.Factory.StartNew(client.Do); } } } class Client { private readonly Socket _socket; private readonly NetworkStream _networkStream; private readonly MemoryStream _memoryStream = new MemoryStream(); private readonly StreamReader _streamReader; public Client(Socket socket) { _socket = socket; _networkStream = new NetworkStream(socket, true); _streamReader = new StreamReader(_memoryStream); } public async void Do() { byte[] buffer = new byte[4096]; int bytesRead = await _networkStream.ReadAsync(buffer, 0, buffer.Length); Console.WriteLine("Doing some awesome work that takes 5 seconds."); Thread.Sleep(5000); Console.WriteLine("Finished doing work."); await _networkStream.WriteAsync(buffer, 0, buffer.Length); await _networkStream.FlushAsync(); } } </code></pre> <p><strong>Client:</strong></p> <pre><code>class Program { static void Main(string[] args) { Thread.Sleep(5000); Console.WriteLine("Connecting..."); TcpClient client = new TcpClient("localhost", 6666); Console.WriteLine("Connected."); try { Stream stream = client.GetStream(); Byte[] messageToSend = new Byte[3]; messageToSend[0] = 1; messageToSend[1] = 3; Byte[] messageReceived = new Byte[3]; stream.WriteAsync(messageToSend, 0, 3); stream.Flush(); stream.Read(messageReceived, 0, 3); // Echo Console.WriteLine(messageReceived[0] + messageReceived[1]); stream.Close(); } finally { client.Close(); } } } </code></pre>
[]
[ { "body": "<p>You are holding on to some <code>IDisposable</code> resources that you shouldn't be, which will impact scalability, GC pressure and likely performance. Here's the augmented <code>Listener</code> class:</p>\n\n<pre><code>internal sealed class Listener : IDisposable\n{\n private readonly int port;\n\n private readonly TcpListener tcpListener;\n\n private readonly IList&lt;Client&gt; clients = new List&lt;Client&gt;();\n\n public Listener(int port)\n {\n this.port = port;\n this.tcpListener = new TcpListener(IPAddress.Any, this.port);\n this.tcpListener.Start();\n Task.Factory.StartNew(this.ListenLoop);\n }\n\n public int Port\n {\n get\n {\n return this.port;\n }\n }\n\n public void Dispose()\n {\n foreach (var client in this.clients)\n {\n client.Dispose();\n }\n }\n\n private async void ListenLoop()\n {\n while (true)\n {\n var socket = await this.tcpListener.AcceptSocketAsync();\n\n if (socket == null)\n {\n break;\n }\n\n var client = new Client(socket, this.ClientDisconnected);\n\n this.clients.Add(client);\n await Task.Factory.StartNew(client.Do);\n }\n }\n\n private void ClientDisconnected(Client client)\n {\n if (client == null)\n {\n return;\n }\n\n client.Dispose();\n this.clients.Remove(client);\n }\n}\n</code></pre>\n\n<p>Here's the augmented <code>Client</code> class:</p>\n\n<pre><code>internal delegate void ClientDisconnectedDelegate(Client client);\n\ninternal sealed class Client : IDisposable\n{\n private readonly Socket socket;\n\n private readonly ClientDisconnectedDelegate doDisconnect;\n\n private readonly Stream networkStream;\n\n private readonly Stream memoryStream = new MemoryStream();\n\n private readonly TextReader streamReader;\n\n public Client(Socket socket, ClientDisconnectedDelegate doDisconnect)\n {\n this.socket = socket;\n this.doDisconnect = doDisconnect;\n Task.Factory.StartNew(this.CheckForConnection);\n this.networkStream = new NetworkStream(this.socket, true);\n this.streamReader = new StreamReader(this.memoryStream);\n }\n\n public void Dispose()\n {\n this.streamReader.Dispose();\n this.networkStream.Dispose();\n this.socket.Dispose();\n this.memoryStream.Dispose();\n }\n\n public async void Do()\n {\n var buffer = new byte[4096];\n var bytesRead = await this.networkStream.ReadAsync(buffer, 0, buffer.Length);\n\n Console.WriteLine(\"Doing some awesome work that takes 5 seconds.\");\n Thread.Sleep(5000);\n Console.WriteLine(\"Finished doing work.\");\n\n await this.networkStream.WriteAsync(buffer, 0, bytesRead);\n await this.networkStream.FlushAsync();\n }\n\n private void CheckForConnection()\n {\n while (true)\n {\n bool isDisconnected;\n\n try\n {\n isDisconnected = this.socket.Poll(1, SelectMode.SelectRead) &amp;&amp; (this.socket.Available == 0);\n }\n catch (SocketException)\n {\n isDisconnected = true;\n }\n\n if (isDisconnected &amp;&amp; (this.doDisconnect != null))\n {\n this.doDisconnect(this);\n return;\n }\n\n Thread.Sleep(100);\n }\n }\n}\n</code></pre>\n\n<p>And here's the augmented Client program:</p>\n\n<pre><code>internal static class Program\n{\n private static void Main()\n {\n Thread.Sleep(5000);\n\n Console.WriteLine(\"Connecting...\");\n\n using (var client = new TcpClient(\"localhost\", 6666))\n {\n Console.WriteLine(\"Connected.\");\n\n using (var stream = client.GetStream())\n {\n var messageToSend = new byte[3];\n\n messageToSend[0] = 1;\n messageToSend[1] = 3;\n\n var messageReceived = new byte[3];\n\n stream.WriteAsync(messageToSend, 0, 3);\n\n stream.Flush();\n\n stream.Read(messageReceived, 0, 3);\n\n // Echo\n Console.WriteLine(messageReceived[0] + messageReceived[1]);\n Console.ReadLine();\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T22:47:13.600", "Id": "74152", "Score": "0", "body": "In your server, why aren't you disposing your client? Is it not necessary?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T02:07:57.347", "Id": "74170", "Score": "0", "body": "@Felix Excellent question. Let me get back to you on that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T04:21:30.730", "Id": "74203", "Score": "0", "body": "@Felix Updated the answer to dispose of clients necessary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-15T13:56:27.687", "Id": "184647", "Score": "0", "body": "So OP wanted to deal with multiple clients, but by having the server listener loop await'ing client.Do() surely your sample code above can only service one client at a time? Why do you think you need that await?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-15T15:40:37.977", "Id": "184666", "Score": "0", "body": "@piers7 that's truly not how `await` works at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-31T07:04:58.663", "Id": "255707", "Score": "0", "body": "The `Do()` method is async so why are you using `await Task.Factory.StartNew(client.Do);` instead of just `await client.Do()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-31T13:53:52.870", "Id": "255750", "Score": "0", "body": "Copy/paste of OP code?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T14:54:47.210", "Id": "31149", "ParentId": "31143", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T13:42:44.243", "Id": "31143", "Score": "7", "Tags": [ "c#", "socket", "tcp", "server", "client" ], "Title": "Performant C# Socket server" }
31143
<p>Here's my version of singly linked list. Any constructive criticism is highly appreciated.<br> First header file "sll.h":</p> <pre><code>#ifndef _SLL_H_ #define _SLL_H_ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; /* declaration of node in Singly linked list */ typedef struct node{ int value; struct node * next; }NODE; /* declaration of head (pointer to node) */ extern NODE * head; /* declaration for functions working on sll */ /*creating a list, freeing previously used memory */ void create_list(NODE ** head); /* adding node at the end of sll */ int add_at_end(NODE **another, int val); /*printing all nodes in list one after another */ void print_list(NODE * another); /* counting nodes in list */ int count_nodes(NODE * another); /* locating value in node in sll */ NODE * locate(NODE * another, int val); /* adding node in growing order of valued */ int add_at_order(NODE **another, int val); /* remove node with given value */ void remove_node(NODE **another, int val); #endif </code></pre> <p>Next comes "singly.c" containing all functions definitions used by the list:</p> <pre><code>#include "sll.h" /* returns 1 if node is created, 0 if not */ int add_at_end(NODE **another, int val) { while(*another!=NULL) another=&amp;(*another)-&gt;next; *another=malloc(sizeof(NODE)); if(*another==NULL) return 0; (*another)-&gt;value=val; (*another)-&gt;next=NULL; return 1; } /* adds not as list was ordered */ int add_at_order(NODE ** another, int val) { NODE * new; while(*another!=NULL &amp;&amp; (*another)-&gt;value&lt;val) another=&amp;(*another)-&gt;next; new=malloc(sizeof(NODE)); if(new==NULL) return 0; new-&gt;value=val; new-&gt;next=(*another); *another=new; } /* counds nodes in the list */ int count_nodes(NODE * another) { int count=0; while(another!=NULL) { count++; another=another-&gt;next; } return count; } /* sets head of list to NULL, frees memory if there was previous list */ void create_sll(NODE **node) { NODE * prev; NODE * nxt; nxt=*node; while(nxt!=NULL) { prev=nxt; nxt=prev-&gt;next; printf("Removing node with val: %d\n\n", prev-&gt;value); free(prev); } *node=NULL; } /* checks if nodes is in the list, returns pointer to the node */ NODE * locate(NODE * another, int val) { while(another!=NULL) { if(another-&gt;value==val) return another; another=another-&gt;next; } return another; } /* prints out all nodes in the list */ void print_list(NODE * another) { if(another!=NULL) { while(another!=NULL) { printf("node val: %d\n", another-&gt;value); another=another-&gt;next; } putchar('\n'); } else printf("List is currently empty.\n\n"); } /* removes node from list */ void remove_node(NODE **another, int val) { NODE *temp; while(*another!=NULL &amp;&amp; (*another)-&gt;value!=val) another=&amp;(*another)-&gt;next; if(*another==NULL) printf("Node not found or empty list.\n\n"); else { temp=*another; *another=(*another)-&gt;next; printf("Removing node with value : %d\n\n", temp-&gt;value); free(temp); } } </code></pre> <p>And last is "main.c" that provides simple interface for the list, just for testing list, so it's rather poor.</p> <pre><code>#include "sll.h" void print_menu(void); /* this will show menu */ int get_menu(void); /* this will get answer from user */ void clear_input(void); /* clears input buffer */ int main(void) { NODE * head=NULL; int option; int node_val; while((option=get_menu())!='8') { switch (option) { case '1': printf("Creating new list, removing previous list, if existed\n\n"); create_sll(&amp;head); break; case '2': printf("Input integer value for node: "); scanf("%d", &amp;node_val); add_at_order(&amp;head, node_val); clear_input(); break; case '3': printf("Input integer value for node: "); scanf("%d", &amp;node_val); add_at_end(&amp;head, node_val); clear_input(); break; case '4': printf("Input integer value for node to be removed: "); scanf("%d", &amp;node_val); remove_node(&amp;head, node_val); clear_input(); break; case '5': print_list(head); break; case '6': printf("Number of nodes in the list: %d\n\n",count_nodes(head)); break; case '7': printf("Input integer value for node to be located in the list: "); scanf("%d", &amp;node_val); if(locate(head, node_val)) printf("Node found\n\n"); else printf("Node not in the list.\n\n"); clear_input(); break; default: printf("I should never get in here!\n"); break; } } return EXIT_SUCCESS; } void clear_input(void) { while(getchar()!='\n') continue; } void print_menu(void) { printf("******************************\n"); printf("* 1) create new list *\n"); printf("* 2) add ordered node *\n"); printf("* 3) add unordered node *\n"); printf("* 4) remove node *\n"); printf("* 5) print all nodes *\n"); printf("* 6) count all nodes *\n"); printf("* 7) locate node *\n"); printf("* 8) quit *\n"); printf("******************************\n"); } int get_menu(void) { int answer; while(print_menu(), (answer=getchar())!=EOF &amp;&amp; (answer&gt;'8' || answer&lt;'1')) { clear_input(); printf("I didn't understand, select option 1-8\n\n"); } clear_input(); return answer; } </code></pre> <p>And that's all. I did some testing myself, it compiles and seems to be working. Feel free to test it, read it, and comment here. As mentioned before main goal is to get professional opinion on list itself. Do I have the right approach, is header file and singly.c clear enough? Is this the way I should write my code next time? </p>
[]
[ { "body": "<p>Some minor comments.</p>\n\n<p><code>add_at_order</code> is missing a return value. Also the comment to the function\nseems wrong and the function name is awkward. </p>\n\n<p><code>create_sll</code> is named <code>create_list</code> in the header file. Either way it seems\nto be misnamed as it in fact destroys the list supplied.</p>\n\n<p>Where a call parameter is unmodified by a function, the parameter should\nmarked <code>const</code>.</p>\n\n<p>Capitalized names are normally used for #define constants, not for types.\nYour <code>NODE</code> type might be better as <code>Node</code>. Or just left as <code>struct node</code>\nwith no typedef. </p>\n\n<p>As a personal preference, I would rename the parameter <code>another</code> as <code>node</code> or\neven just <code>n</code>. I find <code>another</code> unsatisfying.</p>\n\n<p>Braces are often recommended on single-line statements to avoid a class of\nerrors caused by unthinking editing or macro use:</p>\n\n<pre><code>while(*another!=NULL) {\n another=&amp;(*another)-&gt;next;\n}\n</code></pre>\n\n<p>In <code>print_list</code> I would handle the empty list first - it gets rather lost at\nthe end there.</p>\n\n<p>In the header you have <code>extern NODE * head;</code> but <code>head</code> is defined local to\n<code>main</code>. So the header declaration is redundant.</p>\n\n<p>It is often best to put <code>main</code> last so as to avoid the need for prototypes.\nNote that it is normal to make local functions <code>static</code> (those that do not\nneed external linkage such as <code>clear_input</code>, <code>print_menu</code>, <code>get_menu</code>). This\navoids polluting the global name space and improves the possibilities for\noptimization.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T01:17:49.473", "Id": "36479", "ParentId": "31144", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T13:47:51.527", "Id": "31144", "Score": "4", "Tags": [ "c", "linked-list", "beginner" ], "Title": "Singly linked list in C" }
31144
<p>I am writing an open-source application for real-time messaging in web. In my application clients from browser can subscribe on channels. But every channel belongs to a certain namespace which determines channel's settings:</p> <pre><code>client.subscribe('/football/news', function(message) { // message from channel received }); </code></pre> <p>where <code>football</code> is namespace name and <code>news</code> is channel name. <code>football</code> can be a default namespace for project and in this case we can write in this way:</p> <pre><code>client.subscribe('/news', function(message) { // message from channel received }); </code></pre> <p>i.e. without namespace name. This is how it works right now.</p> <p>But my question is about <code>/</code> path separator. Is it ok? We need the way do separate namespace name and channel name. <code>/</code> usage was influenced by <code>Bayeux</code> protocol spec. But maybe it would be more simple and correct to write in such manner:</p> <pre><code>client.subscribe('football', 'news', function(message) { // message from channel received }); </code></pre> <p>or with default namespace:</p> <pre><code>client.subscribe(null, 'news', function(message) { // message from channel received }); </code></pre> <p>or even:</p> <pre><code>client.subscribe('news', function(message) { // message from channel received }); </code></pre> <p>I personally feel that the second way is better. But before refactoring I decided to ask for your opinion.</p>
[]
[ { "body": "<p>An opinion question, always tough to answer.</p>\n\n<p>I like the first way better, 1 less parameter and it is easier to grok for me. </p>\n\n<p>Incidentally, ABAP uses forward slashes for namespaces as well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T21:36:44.280", "Id": "49646", "Score": "0", "body": "btw, I think using '\\' makes creating full path harder for end user - we must properly concatenate strings - namespace and channel." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T21:57:42.560", "Id": "49647", "Score": "0", "body": "How about '/sports/football/news' ( 2 levels ), how would you do that with approach 2?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T05:39:40.387", "Id": "49687", "Score": "0", "body": "in my app only 1 level is allowed. I don't see any serious advantages in using hierarchy channels. Wildcards maybe? But are they really necessary?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T17:31:26.197", "Id": "31157", "ParentId": "31145", "Score": "1" } }, { "body": "<p>If you always have two levels, then passing two parameters has its advantages.</p>\n\n<p>If the channels form an arbitrarily deep hierarchy, then a <code>/path/to/the/channel</code> makes more sense.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T23:51:53.883", "Id": "31196", "ParentId": "31145", "Score": "1" } } ]
{ "AcceptedAnswerId": "31157", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T14:12:13.183", "Id": "31145", "Score": "1", "Tags": [ "javascript", "api", "interface" ], "Title": "Client's method for channel subscribing" }
31145
<p>I was wondering what would be the most appealing way of achieving this goal.</p> <p>I have a blackbox. I give it a <code>supported type</code> and it returns a random value base off of the type.</p> <p>For my supported types, I have an <code>enum</code> defined as follows:</p> <pre><code>public enum Types { INTEGER, DOUBLE, BIGINTEGER, BIGDECIMAL, STRING, BOOLEAN, CHAR } </code></pre> <p>I thought the easiest way would be to create a static function which returns an Object based off of the <code>Type</code></p> <pre><code>public static Object getRandomValue(Types type) { switch(type) { case INTEGER: return randomInt(); case DOUBLE: return randomDouble(); case BIGINTEGER: return randomBigInt(); case BIGDECIMAL: return randomBigDecimal(); case STRING: return randomString(); case BOOLEAN: return randomBool(); case CHAR: return randomChar(); } } </code></pre> <p>The problem is that an additional cast would have to be made each time that I want to retrieve a random value based off of this method.</p> <p>I've looked into the design patterns <code>abstract factory</code> and <code>factory</code>, and I can't decide if there's an advantage into implementing either of those. Or if there's a different design pattern that seems to be more appropriate. </p> <p>Assume that all my <code>random</code> methods are defined. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T21:02:39.210", "Id": "49643", "Score": "1", "body": "See the Command pattern to avoid countless if-else-if statements: http://stackoverflow.com/a/4480360/59087" } ]
[ { "body": "<p>1) I don't think you need to define an enum since you can use Boolean.class, Integer.class, etc.</p>\n\n<p>2) </p>\n\n<pre><code>public static &lt;T&gt; T getRandom(Class&lt;T&gt; classs) {\n if (classs.equals(Boolean.class)) {\n return (T) randomBool();\n } else if (classs.equals(Integer.class) {\n return (T) randomInt();\n // etc.\n } else\n // Edit: original \"else\" was: \"return null;\" changed to:\n throw new IllegalStateException(\"Cannot generate a random \" + classs.toString());\n}\n</code></pre>\n\n<p><strong>EDIT</strong><br>\nThere is also the solution below, but that would still require casting:</p>\n\n<pre><code> public enum Type {\n INTEGER {\n @Override public Integer getRandom() {\n return new randomInt();\n }\n }; // BOOLEAN, etc. \n\n public abstract Object getRandom();\n}\n</code></pre>\n\n<p>That is basically the same as the original OP code, but where the random method call is within the enum instead of being in a separate method with a switch-statement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:14:39.960", "Id": "49600", "Score": "0", "body": "The purpose of the enum is enforce that the function only exists for certain types." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:17:10.243", "Id": "49601", "Score": "1", "body": "Then instead of returning null, you could throw an exception when the class is of an unknown type." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:18:11.383", "Id": "49602", "Score": "0", "body": "@toto2 This is exactly what I was writing up, including the Exception... +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:26:31.533", "Id": "49606", "Score": "0", "body": "Your second variant requires casting in the calling code again. I liked your (our) first variant better..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:28:17.000", "Id": "49608", "Score": "0", "body": "@tobias_k Yes, I added that fact in the text. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T17:19:03.160", "Id": "49616", "Score": "0", "body": "Agreed, the first implementation is better IMO." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:13:56.790", "Id": "31150", "ParentId": "31146", "Score": "3" } }, { "body": "<p>Firstly if you are going to be passing objects of type <code>Object</code> around I guess you best be prepared to do a few casts here and there. You can achieve this using a simple interface and templates quite easily. </p>\n\n<p>Interface:</p>\n\n<pre><code>public interface RandomGenerator &lt;T&gt; {\n T getRandom();\n}\n</code></pre>\n\n<p>Implementation:</p>\n\n<pre><code>public class DoubleRandomGenerator implements RandomGenerator&lt;Double&gt; {\n\n @Override\n public Double getRandom() {\n //do what you do\n return 0d;\n }\n}\n</code></pre>\n\n<p>Next, don't try to return every type of Object from the one Switch statement, it will always be ugly. In order to work out the next step maybe you could elaborate on what is happening outside the blackbox, e.g. if the calling code wants a Double you could add that into your enum:</p>\n\n<pre><code>public enum Types \n{\n INTEGER(new IntegerRandomGenerator()),\n DOUBLE(new DoubleRandomGenerator()),\n BIGINTEGER(...),\n BIGDECIMAL(...),\n STRING(...),\n BOOLEAN(...),\n CHAR(...);\n\n private RandomGenerator generator;\n\n private Types(RandomGenerator generator) {\n this.generator = generator;\n }\n\n public RandomGenerator getGenerator() {\n return generator;\n }\n}\n</code></pre>\n\n<p>The main difference here is that you have deferred the creation of the random value to the callers end. The calling code will also be required to either use generics too:</p>\n\n<pre><code>RandomGenerator&lt;Double&gt; g = Types.DOUBLE.getGenerator();\nDouble d = g.getRandom();\n</code></pre>\n\n<p>Or generate warnings and cast the result:</p>\n\n<pre><code>RandomGenerator g = Types.DOUBLE.getGenerator();\nDouble d = (Double)g.getRandom();\n</code></pre>\n\n<p>Finally, you say you have read about the factory pattern, that is ultimately what you are playing with here.</p>\n\n<p><strong>Note</strong>. I think Enum naming should use the singular (Type) rather than the plural (Types), you are not selecting an Object of type Types as your Object (Types.DOUBLE) represents just one type.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:22:51.557", "Id": "49603", "Score": "0", "body": "This will still require some casting in the calling code, won't it? Either you have to cast the returned `RandomGenerator` itself, or the result of the call to the generator." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:27:02.293", "Id": "49607", "Score": "0", "body": "Yes, I'll clarify my comment that meant exactly that, the code is neater but you still require either a cast or to add the generic type at the calling end." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:20:08.587", "Id": "31151", "ParentId": "31146", "Score": "4" } } ]
{ "AcceptedAnswerId": "31151", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T14:46:19.387", "Id": "31146", "Score": "3", "Tags": [ "java", "design-patterns" ], "Title": "Method Of Retrieving Random Value Depending on Type" }
31146
<p>How to improve this kind of redundancy?</p> <pre><code>$nid = isset( $_GET['nid'] ) ? $_GET['nid'] : 0; </code></pre> <p>I want to avoid to repeat $_GET['nid']</p> <p>Example of useful use case:</p> <pre><code>$nid = isset( $node-&gt;field_mymodule_extended_nid['und'][0]['target_id'] ) ? $node-&gt;field_mymodule_extended_nid['und'][0]['target_id'] : 0; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T09:12:05.067", "Id": "49702", "Score": "1", "body": "Couldn't you just create a helper function for that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T11:38:49.383", "Id": "49707", "Score": "0", "body": "yes but it would be so handy directly" } ]
[ { "body": "<p>By <a href=\"http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary\" rel=\"nofollow noreferrer\">reading the manual</a>:</p>\n\n<blockquote>\n <p>Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.</p>\n</blockquote>\n\n<p>So in short:</p>\n\n<pre><code>$nid = $_GET['nid'] ?: 0;\n</code></pre>\n\n<p>Would work, but PHP will trigger a notice if <code>$_GET['nid']</code> is not set. The logic <code>||</code> operator won't help, either. The closest you can get is:</p>\n\n<pre><code>(($nid = $_GET['nid']) || ($nid = o));\n</code></pre>\n\n<p>But that's not exactly shorter, nor does it solve the <em>Notice</em> issue.<br/>\nThe <em>\"best\"</em> as in shortest, moste un-maintainable and horrible looking code <em>I</em> can think of is this:</p>\n\n<pre><code>$nid = 0;//default\nforeach($_GET as $name =&gt; $val)\n{\n $$name = $val;\n}\nvar_dump($nid);\n</code></pre>\n\n<p>This turns all keys that were present in the <code>$_GET</code> array into var names. If you simply declare the vars you're after (names must be identical to keys, though) and assign them a default value, this loop takes care of the rest.<Br/>\nTo map certain keys to another variable name, you could use another array:</p>\n\n<pre><code>$nid = 0;\n$map = array('new_id' =&gt; 'nid');\nforeach($_GET as $k =&gt; $v)\n{\n if (isset($map[$k]))\n {\n $k = $map[$k];\n }\n $$k = $v;\n}\n</code></pre>\n\n<p>But honestly, maintaining code like this is going to be a nightmare. Though request objects add a lot of overhead for a task as simple as this, their <code>get</code> methods make it all worth while:</p>\n\n<pre><code>public function get($name, $default = null)\n{\n if (!isset($_GET[$name]))\n {\n return $default;\n }\n return $_GET[$name];\n}\n</code></pre>\n\n<p>This is easy to read/understand and easy to use:</p>\n\n<pre><code>$nid = $getInstance-&gt;get('nid', 0);\n</code></pre>\n\n<p>Assignes the GET param, or 0 to <code>$nid</code>... which makes your code tidier, easier to maintain and a lot easier to understand. Based on the use-case you posted, I take it you're not using the ternary on just request variables. Well, in that case: use objects with getters/setters that define a default return value (or allow for one to be specified @call-time). If needs must, implement the <code>ArrayAccess</code> or some <code>Traversable</code> interface, so you can use it as an array, too. <br/>\nGranted, it'll take some time/effort to do this, but once you've done that, any new code you write will be cleaner (no ternaries), debugging will be a doddle and type-hinting will become your best friend. <a href=\"https://stackoverflow.com/questions/18785847/how-to-avoid-the-disadvantages-of-positional-arguments-in-phps-functions/18786119#18786119\">check this answer</a> for some examples and considerations on getters and setters, along <a href=\"https://stackoverflow.com/questions/17696289/pre-declare-all-private-local-variables/17696356#17696356\">with this answer</a> on the importance of pre-declaring properties (and thus implementing getters/setters).</p>\n\n<p>If you're still up for it after that, <a href=\"https://codereview.stackexchange.com/questions/29617/is-this-a-bad-way-of-setting-properties-inside-of-a-class-php/29643#29643\">refer to this answer</a> to see why and how you should avoid object overloading (in PHP, at least) as much as possible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T14:36:20.513", "Id": "49713", "Score": "0", "body": "@pico34: Made quite a few edits, and please, don't be ungreatful... your comment isn't goign to make me more keen on getting back to your question, as it is rather blunt. You can point out oversights/omissions without exclamation marks or _\"come on\"_'s. Just like I can (and indeed did) answer your question politely, instead of opening with _\"Mais putain, lisez les documents sur PHP.net:\"_" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T16:30:52.933", "Id": "49856", "Score": "0", "body": "@pico34: Not sure if I understand you last comment, but the drupal `variable_get` function is just another prime example of terrible code (and there's quite a bit of bad code in drupal). It uses a `global $config` variable, for starters... don't, just create your own object, it'll be far more performant" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T07:28:30.003", "Id": "31225", "ParentId": "31148", "Score": "3" } }, { "body": "<p>This snippet of code is from <a href=\"http://kohanaframework.org/\" rel=\"nofollow\">Kohanaphp framework.</a></p>\n\n<p>I have found this the easiest and most flexible way to do what you want.\nIt's not a lot less code then what you have, but at least you are not repeating the array key part.</p>\n\n<p>The name of the function get() isn't my preferred naming as I feel it is confused with $_GET, but it is part of the framework, so I have left as is. My preference would be to call it val() (a bit of jquery influence there)</p>\n\n<p>It is in it's own class here, but that is not essential. </p>\n\n<pre><code>class Arr {\n public static function get($array, $key, $default = NULL)\n {\n return isset($array[$key]) ? $array[$key] : $default;\n }\n}\n\n// Use like this\n$nid = Arr::get($_GET, 'nid', 0);\n\n// or assume null by default\n$nid = Arr::get($_GET, 'nid');\n\n// or check for a post value\n$nid = Arr::get($_POST, 'nid');\n\n// or as per your example\n// although multidimensional arrays would get an error notice if ['und'][0] doesn't exist\n$nid = Arr::get($node-&gt;field_mymodule_extended_nid['und'][0], 'target_id', 0);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T16:28:14.593", "Id": "49854", "Score": "0", "body": "Jesus... this snippet shows just how much the `static` keyword is being abused... the function here is just a global in drag. That's not what statics are for. If you need a global function, use a global function. If you need an object, use an object... I know you didn't write it, but IMO, it's bad code" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T17:55:09.080", "Id": "31249", "ParentId": "31148", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T14:53:31.547", "Id": "31148", "Score": "2", "Tags": [ "php" ], "Title": "PHP test isset and instantiate in one shot. Possible in PHP?" }
31148
<p>This program calculates the min and the max value and the average of the items of a vector. It's an exercise from a book so I can't change the header file. </p> <p>Is this code proper? </p> <p>sales.h</p> <pre><code>#include &lt;vector&gt; class Sales { private: std::vector&lt;double&gt; sales; double average; double maximum; double minimum; double calcAvg(); public: Sales(const std::vector&lt;double&gt; ar); void setSales(); void showSales() const; }; </code></pre> <p>sales.cpp</p> <pre><code>#include "sales.h" #include &lt;iostream&gt; #include &lt;algorithm&gt; Sales::Sales(const std::vector&lt;double&gt; ar) { sales = ar; minimum = *std::min_element(sales.begin(), sales.end()); maximum = *std::max_element(sales.begin(), sales.end()); average = calcAvg(); } void Sales::setSales() { std::vector&lt;double&gt; temp; std::cout &lt;&lt; "Enter values separated by a space: "; for (int i = 0; i &lt; 4; i++) { int item; std::cin &gt;&gt; item; temp.push_back(item); } *this = Sales(temp); } void Sales::showSales() const { for(std::size_t i = 0; i &lt; sales.size(); i++) std::cout &lt;&lt; "Item " &lt;&lt; i &lt;&lt;" = " &lt;&lt; sales.at(i) &lt;&lt; std::endl; std::cout &lt;&lt; "Average: " &lt;&lt; average &lt;&lt; std::endl; std::cout &lt;&lt; "Min, max: " &lt;&lt; minimum &lt;&lt; " , " &lt;&lt; maximum &lt;&lt; std::endl; } double Sales::calcAvg() { double sum; for(std::size_t i = 0; i &lt; sales.size(); i++) sum += sales.at(i); return sum/sales.size(); } </code></pre> <p>program.cpp</p> <pre><code>#include "sales.h" #include &lt;vector&gt; int main() { std::vector&lt;double&gt; ar; ar.push_back(4); ar.push_back(5); ar.push_back(23); Sales s1(ar); s1.showSales(); Sales s2; s2.setSales(); s2.showSales(); return 0; } </code></pre>
[]
[ { "body": "<ul>\n<li><p>The program won't compile with the default <code>Sales s2</code>. This is because you're calling the default constructor, which you no longer have as it's been overloaded.</p>\n\n<p>Add this to the header:</p>\n\n<pre><code>Sales();\n</code></pre>\n\n<p></p>\n\n<p>Add this to the implementation:</p>\n\n<pre><code>Sales::Sales() {}\n</code></pre></li>\n<li><p>Prefer to loop through an <code>std::vector</code> (or any standard container) with its iterators. There are <a href=\"https://stackoverflow.com/a/409396/1950231\">different ways</a> to do this.</p>\n\n<p>Here's one way, using a range-based <code>for</code>-loop (requires C++11):</p>\n\n<pre><code>std::vector&lt;double&gt; temp(4); // declare with the starting size\n\nfor (auto&amp; iter : temp)\n{\n int item;\n std::cin &gt;&gt; item;\n iter = item; // vector already sized; no need for push_back()\n}\n</code></pre></li>\n<li><p>I agree with @Anton Golov about <code>std::accumulate</code>. I would even consider it <em>necessary</em> since your function currently returns <code>nan</code> (\"not a number\").</p>\n\n<p>This will simplify the function and solve the problem:</p>\n\n<pre><code>double Sales::calcAvg() const\n{\n // just pass in sale's iterators and start the accumulator at 0\n double sum = std::accumulate(sales.cbegin(), sales.cend(), 0);\n return sum / sales.size();\n}\n</code></pre>\n\n<p>This function should also be <code>const</code> since it isn't modifying the vector.</p></li>\n<li><p>You don't need to update the entire object in <code>setSales()</code>:</p>\n\n<blockquote>\n<pre><code>*this = Sales(temp);\n</code></pre>\n</blockquote>\n\n<p>You're currently dereferencing the current object (<code>*this</code>) with a <em>temporary</em> object (an object with no name) given this new vector. However, you only need to update the vector. If you were defining <code>operator=</code>, <em>then</em> you would use <code>*this</code>.</p>\n\n<p>Just update the vector by itself:</p>\n\n<pre><code>sales = temp;\n</code></pre></li>\n<li><p>Consider having two separate display functions in case the user doesn't want everything displayed at once (it also makes sense to only display <code>sales</code> in <code>showSales()</code>):</p>\n\n<p>Sales:</p>\n\n<pre><code>void Sales::showSales() const\n{\n // use std::size_type for STL containers\n // no guarantee that all use std::size_t\n std::vector&lt;double&gt;::size_type i;\n\n for (i = 0; i != sales.size(); ++i)\n {\n // use i+1, otherwise it'll display \"Item 0\"\n std::cout &lt;&lt; \"Item \" &lt;&lt; i+1 &lt;&lt; \" = \" &lt;&lt; sales[i] &lt;&lt; \"\\n\";\n }\n}\n</code></pre>\n\n<p>Min/max/average:</p>\n\n<pre><code>void Sales::showMinMaxAvg() const\n{\n std::cout &lt;&lt; \"Average: \" &lt;&lt; average;\n std::cout &lt;&lt; \"\\nMin: \" &lt;&lt; minimum;\n std::cout &lt;&lt; \"\\nMax: \" &lt;&lt; maximum;\n}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T17:00:24.323", "Id": "31153", "ParentId": "31152", "Score": "2" } }, { "body": "<p>First, of all, this class has a <code>setSales</code> member much like the <code>setgolf</code> member of the class you posted in your last question. I think it suffers from all the same <a href=\"https://codereview.stackexchange.com/a/31105/22222\">issues that I've mentioned</a>; there's not really anything I can add, so I'll leave those comments to represent this, too.</p>\n\n<p>Now to the main issue, which I'd say is the <code>calcAvg</code> member. It should in any case be <code>const</code>; finding and caching the average of a vector doesn't change external state, and were you to ever print the vector (without first modifying it) you'd come to the same result.</p>\n\n<p>As things are, <code>calcAvg</code> doesn't need access to most of the members of <code>Sales</code>. It looks to me like you should just write a free <code>average</code> function template that takes an <code>std::vector&lt;T&gt; const&amp;</code> and returns the average (of type <code>T</code>).</p>\n\n<p>Also, about the caching: whether you should do this or not depends on how the class is used. I wouldn't expect this class to be used as such, but you know better. I would delay it until the thing is printed; in that case, you'd have to make your <code>minimum</code>, <code>average</code> and <code>maximum</code> all <code>mutable</code>, and probably also of type <a href=\"http://en.cppreference.com/w/cpp/atomic/atomic\" rel=\"nofollow noreferrer\"><code>std::atomic&lt;double&gt;</code></a>. This isn't necessarily better: look at the usage and choose.</p>\n\n<p>Finally, as a minor detail, there's no need to use <code>at</code> when you can easily prove that the index is in-bounds anyway, and you can use <a href=\"http://en.cppreference.com/w/cpp/algorithm/accumulate\" rel=\"nofollow noreferrer\"><code>std::accumulate</code></a> for calculating the average.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T17:21:02.240", "Id": "49617", "Score": "0", "body": "I'm not qualified to fully judge on `mutable`, but I'd think it's best to only use it when necessary. I could be wrong, though. Also, isn't `average` used in the constructor?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T17:23:32.157", "Id": "49618", "Score": "0", "body": "I do agree about `std::accumulate`, though. For whatever reason, the outputted `average` with the OP's code shows \"nan\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T17:26:15.800", "Id": "49620", "Score": "0", "body": "@Jamal: If changing the value of a variable doesn't change the class' external state (which it shouldn't here), it may be `mutable`. In this case, the actual average/minimum/maximum are given by the `sales` member, the rest are just an optimization to not walk `sales` every time they are needed." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T17:13:12.037", "Id": "31156", "ParentId": "31152", "Score": "3" } }, { "body": "<pre><code>Sales(const std::vector&lt;double&gt;**&amp;** ar);\n</code></pre>\n\n<p>use reference, when pass parameters. Your vector may be big enough,\nso why do extra copy, if this book contains ctor signature without reference,\nthis should be a typo.</p>\n\n<pre><code>minimum = *std::min_element(sales.begin(), sales.end());\nmaximum = *std::max_element(sales.begin(), sales.end());\naverage = calcAvg();\n</code></pre>\n\n<p>to calc three parameters, you use 3 cycles, this may decrease your performance by 3 times, for example on my machine your code for </p>\n\n<pre><code> std::vector&lt;double&gt; sales(10000000);:\n</code></pre>\n\n<p>take 33 ms (in Release Mode), while simple function:</p>\n\n<pre><code> std::tuple&lt;double, double, double&gt; calc_min_max_average(const std::vector&lt;double&gt;&amp; v)\n {\n if (v.empty())\n return std::make_tuple(0., 0., 0.);\n double minimum = v[0];\n double maximum = v[0];\n double average = v[0];\n const size_t N = v.size();\n for (size_t i = 1; i &lt; N; ++i) {\n minimum = std::min(v[i], minimum);\n maximum = std::max(v[i], maximum);\n average += v[i];\n }\n average /= double(N);\n return std::make_tuple(minimum, maximum, average);\n }\n</code></pre>\n\n<p>take 11ms.</p>\n\n<p>So, why force CPU do extra work, while in calcAvg you can calculate all three parameters, while return only one.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T02:06:03.513", "Id": "31267", "ParentId": "31152", "Score": "1" } }, { "body": "<ul>\n<li><p>Ensure genericness whenever possible with no hard-coded value.</p>\n\n<pre><code>for (int i = 0; i &lt; 4; i++)\n</code></pre></li>\n<li><p>Since avg, max, min are not affected by new sales after initialization or <code>setSales</code>, i.e its required only during <code>showSales()</code>; its better to remove the member variables and calculate and show the result (max, min, avg) in <code>showSales()</code> itself. This would allow vector manipulation without even after initialisation.</p></li>\n<li>Consider a <strong>vector with no elements, i.e size 0</strong>. The constructor is called on that and your <code>calcAvg</code> has a divide by zero error.</li>\n<li>Can't we do away with <code>std::</code> everywhere. Its redundant as the import exists. Do check it.</li>\n<li>Variable names: <code>ar</code>, <code>temp</code> should be sales.</li>\n<li>Calculation of avg, max, min should be done in one loop instead of 3 loops as pointed by user1034749.</li>\n<li><p>Since you only have one constructor i.e with the vector as argument, you should be using it in the second case s2 as well. This will avoid creation of temp and adding default constructor which is non-existent after the custom constructor creation. Also, your code allows me to call setSales for s1 as well (which is wrong). So have it like this:\n // Program.cpp\n std::vector sales2;\n Sales s2(sales2);</p>\n\n<pre><code>// Sales.cpp\nvoid Sales::setSales()\n{\n int input_size;\n cout &lt;&lt; \"Enter the input size: \";\n cin &gt;&gt; input_size;\n\n cout &lt;&lt; \"Enter values separated by a space: \";\n for (int i = 0; i &lt; input_size; i++)\n {\n int item;\n std::cin &gt;&gt; item;\n sales.push_back(item);\n }\n}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-14T04:30:26.477", "Id": "73586", "ParentId": "31152", "Score": "0" } } ]
{ "AcceptedAnswerId": "31156", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T16:18:50.483", "Id": "31152", "Score": "3", "Tags": [ "c++", "classes", "vectors" ], "Title": "Simple class exercise - min, max, and average of vector items" }
31152
<p>i have an <code>vector&lt;tuple&lt;A,b&gt; &gt; v</code> and want to make a <code>map&lt;A,B&gt;</code> from it i came up with 3 variants:</p> <pre><code>std::transform(v.begin(),v.end(), std::inserter(map,map.begin()),[](std::tuple&lt;int,char&gt; t){ return std::make_pair(std::get&lt;0&gt;(t),std::get&lt;1&gt;(t)); }); </code></pre> <p> </p> <pre><code>std::for_each(v.begin(), v.end(), [](std::tuple&lt;int,char&gt; t){ map.insert(std::make_pair(std::get&lt;0&gt;(t),std::get&lt;1&gt;(t))); }); </code></pre> <p> </p> <pre><code>for (auto t : v) { map.insert(std::make_pair(std::get&lt;0&gt;(t),std::get&lt;1&gt;(t))); } </code></pre> <p>is <code>shorter is better</code> the way to go here? could one simplify the <code>tuple</code>=><code>pair</code> conversion? thanks</p>
[]
[ { "body": "<p>I would use the last as the simplest, yes. I'd probably write a <code>pair_from_tuple</code> helper function to not have to write out the <code>std::get</code> explicitly.</p>\n\n<p>The first and second both require you to write out the tuple type. This will change soon, but not everyone will immediately have C++14. Also, they're easier to get wrong; I think you mean to specify capture-by-reference in example 2, for example.</p>\n\n<p>With <code>pair_from_tuple</code>, I suppose</p>\n\n<pre><code>using std::begin;\nusing std::end;\nstd::transform(begin(v), end(v), std::inserter{map, map.begin()}, pair_from_tuple&lt;int, char&gt;);\n</code></pre>\n\n<p>would be okay (you can avoid the <code>&lt;int, char&gt;</code> by making <code>pair_from_tuple</code> a functor). Still less nice than</p>\n\n<pre><code>for (auto const&amp; e : v)\n map.insert(pair_from_tuple(e));\n</code></pre>\n\n<p>, though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T00:56:12.013", "Id": "49812", "Score": "1", "body": "Cool: Never seen pair_from_tuple before. :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T09:52:27.483", "Id": "49837", "Score": "0", "body": "@Loki: I'm suggesting he write it. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T18:44:45.047", "Id": "31160", "ParentId": "31158", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T18:14:34.557", "Id": "31158", "Score": "3", "Tags": [ "c++", "vectors", "container" ], "Title": "vector<tuple<A,B> > to map<A,B>" }
31158
<p>So I came up with a problem In C. Our compiler is pre c99 and wasn't identifying functions that are never called. So I ended up writing this script and decided to post it up to be critiqued and to help people who might be in the same predicament. The script works great for me and finished the job that I needed it to do. I just felt that it could be done better.</p> <pre><code>from sys import exit import re import os ,fnmatch #"(static BOOL|BOOL|static void|void)\s+([A-Z a-z]+)(\(.*?\)\;)" pattern = "(static BOOL|BOOL|static void|void|static BYTE|BYTE|static int|int)\s+([A-Z a-z]+)(\(.*?\)\;)" compiled = re.compile(pattern) commentend = re.compile("\*/") commentbegin = re.compile("/\*.*") #|\}/s/\*.* extra pattern count = 0 directory =" " def menu():#menu function global directory print "what would you like to do" print "1. Enter directory of .c and .h files you want searched" print "2. Display possibly unused functions" #not used print "Any other key exit program" selection = raw_input("&gt; ") if selection == '1':#this menu starts the search process print "you selected search" print "what is the file name" directory = raw_input("&gt; ") openfiles() elif selection == '2':#this selection is not currently used print "displaying matching functions" print count else: exit(0) def openfiles(): #gets a list of file names and then passes the name to search for function to open for root,dirs,files in os.walk(directory): for pat in ['*.c','*.h']: for current_file in fnmatch.filter(files,pat): searchforfunction(current_file) def searchforfunction(file_name): global directory print file_name with open(os.path.join(directory,file_name) ,"r" ,1) as f: for line in f: matchfun(line) def matchfun(line): #This searches for a function looking for specific definition then checks how many times the function occurs global count name_func = compiled.match(line) if name_func: name_func = name_func.group(2) count = searchfilesecond(name_func) if count &lt;= 2: print name_func," was called",count,"times" if count == 2: writefunc_twice(name_func) if count == 1: writefunc_one(name_func) count = 0 def writefunc_one(name_func): with open("occur_once_func.txt", "a") as myfile: myfile.write(name_func+" was called 1 time\n") def writefunc_twice(name_func): with open("occur_twice_func.txt", "a") as myfile: myfile.write(name_func + " was called 2 times\n") def searchfilesecond(name_func): #walks the directory again and searches for a match by passing it so secondsearch global count global directory for root,dirs,files in os.walk(directory): for pat in ['*.c','*.h']: for current_file in fnmatch.filter(files,pat): count = secondsearch(name_func,current_file) return count def secondsearch(name_func,current_file): #this function searches for any instances of the function global count global directory in_comment = False secondpatern = re.compile(name_func) with open(os.path.join(directory,current_file) ,"r" ,1) as f: for line in f: if commentbegin.search(line):#This statement searches for the /* part of a comment in_comment = True if commentend.search(line):#This statement searches for the */ part of a comment in_comment = False elif in_comment == False: name_func1 = secondpatern.search(line) if name_func1: count += 1 else: pass return count while(1): menu() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:37:31.227", "Id": "49625", "Score": "1", "body": "Have you tried, with gcc, to compile with `-ffunction-sections` and link with `--gc-sections`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:53:33.537", "Id": "49626", "Score": "0", "body": "Do you use VIM? There is a plugin called `Pyflakes` that can do this for you (among other things). If a function is defined but never called or a library imported but never used `Pyflakes` puts break lines underneath the names." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T20:04:10.587", "Id": "49637", "Score": "1", "body": "What you're looking for is code coverage. I've never done it for C, but [this question on SO](http://stackoverflow.com/questions/3893090/code-coverage-tools-for-c) looks like a good place to start." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T13:37:57.123", "Id": "49784", "Score": "0", "body": "See [this question](http://stackoverflow.com/q/9091397/68063) on Stack Overflow." } ]
[ { "body": "<p>Two major points:</p>\n\n<ul>\n<li>The parsing is very fragile and only works when the code is laid out in a certain way. You should look for a proper parser and leverage that.</li>\n<li>It is rather inefficient to scan all the files every time you encounter a function declaration. You could use dictionaries to keep track of functions so one pass over the files would suffice.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T18:12:36.977", "Id": "35771", "ParentId": "31159", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T15:27:25.630", "Id": "31159", "Score": "5", "Tags": [ "python" ], "Title": "Searching for unused functions" }
31159
<p>This solves an algorithm that we have. The script is used by an ArcGIS tool as well as another tool that takes this script and cycles through roughly 6,000 bridges.</p> <p><strong>Note:</strong> I didn't separate the code intentionally into configs and testing code for you to review the whole thing in one screen.</p> <pre><code>""" This file solves the algorithm to develop a redundancy index """ import doctest import unittest as unittest # CONSTANTS # DEBUG VARIABLE # Runs testing if set to True DEBUG = False ROAD_TYPES = ('ARTERIAL', 'COLLECTOR', 'NATIONAL') MAJOR_EXPECTED_LIFE = 75 STANDARD_EXPECETD_LIFE = 50 UNIT_COST_BRIDGE_OVER_ROADWAY = 3000 UNIT_COST_BRIDGE_OVER_WATER_WITHOUT_PIER = 4500 UNIT_COST_BRIDGE_OVER_WATER_WITH_PIER = 5500 BRIDGE_TYPOGRAPHY_ALWAYS_REDUNDANT = ('NOT IN USE') BRIDGE_TYPOGRAPHY_SHOW_BLOCKER = ('COVERED', 'HERITAGE', 'NO DETOUR', 'LIFELINE', 'LANDMARK') BRIDGE_BELOW_TYPE = {'ROADWAY': 3000, 'WATER WITH PIER': 5500, 'WATER WITHOUT PIER': 4500} CURRENT_YEAR = 2013 ROAD_CLASS_INDEX = {'ARTERIAL': 5, 'COLLECTOR': 4, 'LOCAL NUMBERED': 2, 'LOCAL NAMED': 1} YEARS_SINCE_LAST_REHAB = 10 # TODO change the following to include all CS that buses go on BUS_ROUTES = (1., 2., 7., 15., 16., 8.001, 8.002, 11.001, 11.002, 11.003, 11.004, 11.005, 11.006, 11.007, 11.008, 11.009) # The following are Constant Assumptions that are made by the initial model: MILEAGE_COST_PER_KM = 0.5 ASSUMED_HOURLY_WAGE_PER_HOUR = 25 DETOUR_DEFAULT_SPEED = 60 # the following are the weighting for each subindex of the redundancy index B_OVER_C_WEIGHTING = 30 BCI_WEIGHTING = 25 AGE_INDEX_WEIGHTING = 20 ROAD_CLASS_INDEX_WEIGHTING = 5 LOAD_RATING_INDEX_WEIGHTING = 15 BUS_ROUTE_INDEX_WEIGHTING = 10 RECENT_REHAB_INDEX_WEIGHTING = 5 # End of Constants Section def route_class(route_number): """ returns the road classification based on its number and control section roads &gt;= 200 --&gt; Local numbered named --&gt; local named roads &lt; 100 --&gt; Arterial roads &gt;= 100 and &lt; 200: collector """ if type(route_number) is str: return 'local named' elif type(route_number) is int: if 1 &lt;= route_number &lt; 100: return 'arterial' elif 100 &lt;= route_number &lt; 200: return 'collector' elif route_number &gt;= 200: return 'local numbered' def structure_class(route_classification): """ if the road that the bridge is on is a 'collector' or 'arterial' then it's considered major. The bridge is considered 'standard' in all other cases """ if route_classification.upper() in ROAD_TYPES: return 'major' else: return 'standard' def expected_life(structure_class): """ if structure class of the bridge is major, then the expected life is 75 else, the expected life is 50 """ if structure_class.upper() == 'MAJOR': return MAJOR_EXPECTED_LIFE else: return STANDARD_EXPECETD_LIFE def potentially_redundant(bridge_typography): """ NOTE: In the algorithm, this is called "initial_criteria if the bridge is 'NOT IN USE' then it's redundant If the bridge is covered, heritage, no detour, lifeline, or landmark then it is NOT REDUNDANT All Other bridges should be considered for redundancy """ if bridge_typography.upper() in BRIDGE_TYPOGRAPHY_ALWAYS_REDUNDANT: return 'redundant' elif bridge_typography.upper() in BRIDGE_TYPOGRAPHY_SHOW_BLOCKER: return 'not redundant' else: return "potentially redundant" def unit_cost(below_bridge): """ if below the bridge is a roadway, then unit cost is 3000 if below the bridge is a waterway with no piers, then the unit cost is 4500 if below the bridge is waterway with piers, then the unit cost is 500 """ return BRIDGE_BELOW_TYPE[below_bridge.upper()] def benefit_over_cost(detour_distance, AADT, life, mileage_cost, assumed_hourly_wage, detour_speed, deck_area, unit_cost): """ Equation developed by the algorithm writers to return the benefit over cost of a bridge """ return detour_distance * AADT * 365 * life * \ (float(mileage_cost) + (assumed_hourly_wage / float(detour_speed))) / \ (deck_area * float(unit_cost)) def age(year_built): """ return how old the bridge is based on current year """ # TODO what happens if current year is &lt; year built? # TODO how does M&amp; T define bridges with no ages? return CURRENT_YEAR - year_built def load_rating(load_rating): """ return True if there is a Load Rating """ # TODO test for load_rating == None return (load_rating != "") def bus_route(route, control_section=0): """ if route 1, 2, 7, 15, 16, 11 (CS 001-&gt;009), 8 (CS 001-002) """ if control_section and route + (float(control_section) / 1000) in BUS_ROUTES: return True elif control_section == 0 and route in BUS_ROUTES: return True else: return False def BCR_index(BCR, max_BCR, weighting): """ returns the first index that the algorithm needs. BCR = Benefit over cost ratio of bridge max_BCR = max BCR in the system (highest BCR) """ return float(BCR) / (float(max_BCR) * float(weighting)) def BCI_index(BCI, weighting): """ Returns the second index that the algorithm needs """ return BCI * (float(weighting) / 100) def age_index(expected_life, age, weighting): """ Third index that the algorithm requires age_index = [()expected life - age) / expected_life] * weighting max_age_index = weighting and min_age_index = 0 """ # NOTE I can use numpy for age_index MAX and MIN but I don't want to # import a whole library jut for one small equation age_index = ((float(expected_life) - float(age)) / float(expected_life)) * float(weighting) if 0 &lt; age_index &gt;= weighting: return weighting elif age_index &lt; 0: return 0 else: return age_index def road_class_index(road_type): """ fourth index that the algorithm requires Road class index, arterial =5, collector = 5, local named = 2, local numbered = 1 Note: this classification doesn't make much sense but it is what the algorithm is recommending Note 2: The reason there is no weighting variable here as it is built into the result """ return ROAD_CLASS_INDEX[road_type.upper()] def load_rating_index(load_rating, weighting=0): """ fifth index that the algorithm requires if there is a load rating, then assign maximum weighting if there is no load rating, then the rating is 0 """ if load_rating: return weighting else: return 0 def bus_route_index(bus_route, weighting=0): """ Sixth index that the algorithm needed if the road is a bus route, then assign maximum weighting if the road isn't a bus route, then rating is 0 """ if bus_route: return weighting else: return 0 def recent_rehab_index(rehab_year, weighting=0): """ seventh index that the model needs if a recent rehab occurred in the previous 10 years then assign maximum weighting else assign 0 """ if CURRENT_YEAR - rehab_year &lt;= YEARS_SINCE_LAST_REHAB: return weighting else: return 0 def redundancy_index(BCR, BCI, age_index, road_class_index, load_rating_index, bus_route_index, recent_rehab_index): """ redundancy index = 100 - sum of all seven indicies """ return 100 - (BCR + BCI + age_index + road_class_index + load_rating_index + bus_route_index + recent_rehab_index) def main(input_data): # Step 1: Calculate bridge Benefit over cost bridge_route_class = route_class(input_data['route']) bridge_structure_class = structure_class(bridge_route_class) bridge_expected_life = expected_life(bridge_structure_class) bridge_unit_cost = unit_cost(input_data['below bridge']) bridge_b_over_c = benefit_over_cost(input_data['detour_distance'], input_data['AADT'], bridge_expected_life, MILEAGE_COST_PER_KM, ASSUMED_HOURLY_WAGE_PER_HOUR, DETOUR_DEFAULT_SPEED, input_data['area'], bridge_unit_cost) # Step 2: calculate if bridge is potentially redundant bridige_potentially_redundant = potentially_redundant( input_data['initial criteria']) # Step 3: Calculate redundancy index bridge_bcr = BCR_index(bridge_b_over_c, input_data['max BCR'], B_OVER_C_WEIGHTING) bridge_bci = BCI_index(input_data['BCI'], BCI_WEIGHTING) bridge_age = age(input_data['year built']) bridge_age_index = age_index(bridge_expected_life, bridge_age, AGE_INDEX_WEIGHTING) bridge_road_class_index = road_class_index(bridge_route_class) bridge_load_rating_index = load_rating_index( input_data['load rating'], LOAD_RATING_INDEX_WEIGHTING) on_bus_route = bus_route(input_data['route']) bridge_bus_route_index = bus_route_index(on_bus_route, BUS_ROUTE_INDEX_WEIGHTING) bridge_recent_rehab_index = recent_rehab_index(input_data['rehab year'], RECENT_REHAB_INDEX_WEIGHTING) bridge_redundancy_index = redundancy_index(bridge_bcr, bridge_bci, bridge_age_index, bridge_road_class_index, bridge_load_rating_index, bridge_bus_route_index, bridge_recent_rehab_index) return bridige_potentially_redundant, bridge_b_over_c, bridge_redundancy_index #"bridge potentially redundant: %s, b/c: %s, and redundancy index: %s" % \ # tests class TestBridgeEliminationAlgorithm(unittest.TestCase): maxDiff = None def test_structure_class(self): self.assertEqual(structure_class('arterial'), 'major') self.assertEqual(structure_class('colLector'), 'major') self.assertEqual(structure_class('naTIOnal'), 'major') self.assertEqual(structure_class('banana'), 'standard') def test_expected_life(self): self.assertEqual(expected_life('majOr'), 75) self.assertEqual(expected_life('StandArd'), 50) def test_potentially_redundant(self): self.assertEqual(potentially_redundant('not IN use'), 'redundant') self.assertEqual(potentially_redundant('cOVered'), 'not redundant') self.assertEqual(potentially_redundant('HerITage'), 'not redundant') self.assertEqual(potentially_redundant('LANDmark'), 'not redundant') self.assertEqual(potentially_redundant('no Detour'), 'not redundant') self.assertEqual(potentially_redundant('lifeLine'), 'not redundant') self.assertEqual( potentially_redundant('banana'), 'potentially redundant') def test_unit_cost(self): self.assertEqual(unit_cost('roadway'), 3000) self.assertEqual(unit_cost('water with pier'), 5500) self.assertEqual(unit_cost('water without pier'), 4500) def test_benefit_over_cost(self): self.assertAlmostEqual( benefit_over_cost(10, 500, 20, 0.5, 16, 70, 150, 3000), 59.095, 3) def test_age(self): self.assertEqual(age(2000), 13) def test_route_class(self): self.assertEqual(route_class(1), 'arterial') self.assertEqual(route_class(50), 'arterial') self.assertEqual(route_class(99), 'arterial') self.assertEqual(route_class(100), 'collector') self.assertEqual(route_class(150), 'collector') self.assertEqual(route_class(199), 'collector') self.assertEqual(route_class(200), 'local numbered') self.assertEqual(route_class(650), 'local numbered') self.assertEqual(route_class(9052412), 'local numbered') self.assertEqual(route_class("banana"), 'local named') def test_load_rating(self): self.assertEqual(load_rating('blabla'), True) self.assertEqual(load_rating(''), False) self.assertEqual(load_rating('stuff'), True) def test_bus_routes(self): self.assertEqual(bus_route(1), True) self.assertEqual(bus_route(2), True) self.assertEqual(bus_route(7), True) self.assertEqual(bus_route(15), True) self.assertEqual(bus_route(16), True) self.assertEqual(bus_route(17, 1), False) self.assertEqual(bus_route(17), False) self.assertEqual(bus_route(11, 1), True) self.assertEqual(bus_route(11, 2), True) self.assertEqual(bus_route(11, 3), True) self.assertEqual(bus_route(11, 89), False) self.assertEqual(bus_route(8, 1), True) self.assertEqual(bus_route(8, 5), False) def test_BCR_index(self): self.assertAlmostEqual(BCR_index(50, 85, 30), 0.0196, 4) def test_BCI_index(self): self.assertEqual(BCI_index(35.4, 60), 21.24) def test_age_index(self): self.assertEqual(age_index(60, 6, 5), 4.5) self.assertEqual(age_index(30, 15, 0.85), 0.425) self.assertEqual(age_index(30, 15, -1), 0) self.assertEqual(age_index(30, 15, 75), 37.5) def test_road_class_index(self): self.assertEqual(road_class_index('arterial'), 5) self.assertEqual(road_class_index('collector'), 4) self.assertEqual(road_class_index('local numbered'), 2) self.assertEqual(road_class_index('local named'), 1) def test_load_rating_index(self): self.assertEqual(load_rating_index('5000', .5), .5) self.assertEqual(load_rating_index(True, .8), .8) self.assertEqual(load_rating_index(False), 0) self.assertEqual(load_rating_index(''), False) def test_bus_route_index(self): self.assertEqual(bus_route_index('5000', .5), .5) self.assertEqual(bus_route_index(True, .8), .8) self.assertEqual(bus_route_index(False), 0) self.assertEqual(bus_route_index(''), False) def test_recent_rehab_index(self): self.assertEqual(recent_rehab_index(2005, 45), 45) self.assertEqual(recent_rehab_index(1998, 45), 0) self.assertEqual(recent_rehab_index(2013, 45), 45) self.assertEqual(recent_rehab_index(2003, 45), 45) if __name__ == '__main__': if DEBUG: suite_bridge_elim = unittest.TestLoader().loadTestsFromTestCase( TestBridgeEliminationAlgorithm) unittest.TextTestRunner(verbosity=2).run(suite_bridge_elim) doctest.testmod() else: input_data = {'id': 3514, 'alpha_id': "M444", 'year built': 1935, 'route': 134, 'area': 800, 'initial criteria': '', 'detour_distance': 30, 'AADT': 1500, 'below bridge': 'roadway', 'BCI': 43, 'max BCR': 30, 'load rating': False, 'rehab year': 1998 } print main(input_data) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T21:09:19.320", "Id": "49645", "Score": "0", "body": "`if 0 < age_index >= weighting:` - shouldn't it be just `if age_index >= weighting:`?" } ]
[ { "body": "<p>Although people are often advised to break down their code into functions more, my main comment would be that you have lots of functions not doing very much. This might be worthwhile in some cases if there is a possibility of expanding the code and re-using those functions. As it is it just makes the code more complicated and harder to read and probably debug.</p>\n\n<p>e.g. you find the route class of the inputted route, then check its structure class, but you only use the latter to check the expected life, which is a very simple function of the structure class.</p>\n\n<p>In particular there is not much point in having a function that simply looks something up in a dictionary.</p>\n\n<p>You store a lot of data in constants that I would tend to put together with the logic in the functions, unless you are likely to change the constants without having to change any other part of the functions. You are also passing global constants as arguments to functions, which seems pointless.</p>\n\n<p>You define a weight for <code>road_class_index</code> but never apply it; is this a bug?</p>\n\n<p>I would apply weightings to each of the indices in the main loop rather than within the functions that calculate each index. This is more transparent and you don't have to pass the weightings to the functions, and you can do it easily using something like <code>sum(weight * index for weight, index in zip(weights, indices))</code>.</p>\n\n<p>Your note concerning <code>max</code> and <code>min</code> seems to be confused - these are <a href=\"http://docs.python.org/2/library/functions.html#max\" rel=\"nofollow\">built-in python functions</a> so you don't need numpy for that.</p>\n\n<p>I don't see much call for OOP in this programme, except that it might be useful to have a simple class <code>Route</code> which takes in the route data and stores some characteristics of the route.</p>\n\n<p>I would tend to remove a lot of the simpler functions and write something like this:</p>\n\n<pre><code>class Route:\n \"\"\" Classifies a route based on its number \"\"\"\n def __init__(self, route_number):\n if type(route_number) is str:\n self.type = 'local named'\n self.index = 1\n elif type(route_number) is int:\n if 1 &lt;= route_number &lt; 100:\n self.type = 'arterial'\n self.index = 5\n elif 100 &lt;= route_number &lt; 200:\n self.type = 'collector'\n self.index = 4\n elif route_number &gt;= 200:\n self.type = 'local numbered'\n self.index = 2\n if self.type in ('collector', 'arterial'):\n self.life = 75\n else:\n self.life = 50\n self.bus = route_number in BUS_ROUTES\n\ndef get_potentially_redundant(bridge_typography):\n \"\"\"\n NOTE: In the algorithm, this is called \"initial_criteria\n if the bridge is 'NOT IN USE' then it's redundant\n If the bridge is covered, heritage, no detour, lifeline, or landmark then\n it is NOT REDUNDANT\n All Other bridges should be considered for redundancy\n \"\"\"\n if bridge_typography.upper() in BRIDGE_TYPOGRAPHY_ALWAYS_REDUNDANT:\n return 'redundant'\n elif bridge_typography.upper() in BRIDGE_TYPOGRAPHY_SHOW_BLOCKER:\n return 'not redundant'\n else:\n return \"potentially redundant\"\n\ndef get_b_over_c(detour_distance, AADT, life, deck_area, below_bridge):\n \"\"\"\n Equation developed by the algorithm writers to return the benefit\n over cost of a bridge\n \"\"\"\n if below_bridge.lower() == 'roadway':\n unit_cost = 3000\n elif below_bridge.lower() == 'water with pier':\n unit_cost = 5500\n elif below_bridge.lower() == 'water without pier':\n unit_cost = 4500\n return (detour_distance * AADT * 365 * life * \n (float(MILEAGE_COST_PER_KM) +\n (ASSUMED_HOURLY_WAGE_PER_HOUR / float(DETOUR_DEFAULT_SPEED))) / \n (deck_area * float(unit_cost)))\n\ndef age_index(route, year_built):\n \"\"\"\n Third index that the algorithm requires\n age_index = [()expected life - age) / expected_life] * weighting\n max_age_index = weighting and min_age_index = 0\n \"\"\"\n age = CURRENT_YEAR - year_built\n index = float(route.life - age) / route.life\n return max(min(index, 1), 0)\n\ndef main(input_data):\n # Step 1: Calculate bridge Benefit over cost\n route = Route(input_data['route'])\n b_over_c = get_b_over_c(input_data['detour_distance'],\n input_data['AADT'],\n route.life,\n input_data['area'],\n input_data['below_bridge'])\n\n # Step 2: calculate if bridge is potentially redundant\n potentially_redundant = get_potentially_redundant(input_data['initial criteria'])\n\n # Step 3: Calculate redundancy index\n indices = {\n 'bcr': b_over_c / float(input_data['max BCR']),\n 'bci': float(input_data['BCI']) / 100,\n 'route': route.index,\n 'load rating': input_data['load rating'] != '',\n 'age': age_index(route, float(input_data['year built'])),\n 'bus': route.bus,\n 'recent rehab': CURRENT_YEAR - rehab_year &lt;= YEARS_SINCE_LAST_REHAB\n }\n weights = {\n 'bcr': 1.0 / 30,\n 'bci': 25,\n 'age': 20,\n 'route': 5,\n 'load rating': 15,\n 'bus': 10,\n 'recent rehab': 5\n }\n redundancy_index = 100 - sum(indices[k] * weights[k] for k in indices.keys())\n return potentially_redundant, b_over_c, redundancy_index\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T22:51:48.890", "Id": "31170", "ParentId": "31162", "Score": "1" } }, { "body": "<p>With all those bridge_... variables, how about moving the logic into a class representing a bridge? There is much to be done with this code but the basic restructuring is done.</p>\n\n<p><strong>EDIT:</strong> Refactored the code somewhat</p>\n\n<pre><code>\"\"\"\nThis file solves the algorithm to develop a redundancy index\n\"\"\"\n\n# CONSTANTS \nBRIDGE_BELOW_TYPE = {'ROADWAY': 3000, 'WATER WITH PIER': 5500, 'WATER WITHOUT PIER': 4500}\nCURRENT_YEAR = 2013\nYEARS_SINCE_LAST_REHAB = 10\n\n# TODO change the following to include all CS that buses go on\nBUS_ROUTES = (\n 1., 2., 7., 15., 16., 8.001, 8.002, 11.001, 11.002, \n 11.003, 11.004, 11.005, 11.006, 11.007, 11.008, 11.009\n)\n\n# The following are Constant Assumptions that are made by the initial model:\nMILEAGE_COST_PER_KM = 0.5\nASSUMED_HOURLY_WAGE = 25.0\nDETOUR_DEFAULT_SPEED = 60.0\n\n# the following are the weighting for each subindex of the redundancy index\nB_OVER_C_WEIGHTING = 30.0\nBCI_WEIGHTING = 0.25\nAGE_INDEX_WEIGHTING = 20\nROAD_CLASS_INDEX_WEIGHTING = 5\nLOAD_RATING_INDEX_WEIGHTING = 15\nBUS_ROUTE_INDEX_WEIGHTING = 10\nRECENT_REHAB_INDEX_WEIGHTING = 5\n\nclass Bridge(object):\n def __init__(self, **kwargs):\n self.id = kwargs['id']\n self.route = kwargs['route']\n self.detour_distance = kwargs['detour_distance']\n self.AADT = kwargs['AADT']\n self.deck_area = kwargs['area']\n self.initial_criteria = kwargs['initial criteria'].upper()\n self.max_bcr = kwargs['max BCR']\n self.bci = kwargs['BCI']\n self.load_rating = kwargs['load rating']\n self.rehab_year = kwargs['rehab year']\n self.unit_cost = BRIDGE_BELOW_TYPE[kwargs['below bridge'].upper()]\n self.age = CURRENT_YEAR - kwargs['year built']\n\n if isinstance(self.route, basestring):\n self.route_class = 'LOCAL NAMED'\n self.road_class_index = 1\n self.structure_class = 'standard'\n self.expected_life = 50\n elif isinstance(self.route, int):\n if self.route &lt; 100:\n self.route_class = 'ARTERIAL'\n self.road_class_index = 5\n self.structure_class = 'major'\n self.expected_life = 75\n elif self.route &lt; 200:\n self.route_class = 'COLLECTOR'\n self.road_class_index = 4\n self.structure_class = 'major'\n self.expected_life = 75\n else:\n self.route_class = 'LOCAL NUMBERED'\n self.road_class_index = 2\n self.structure_class = 'standard'\n self.expected_life = 50\n\n remaining_life = max(0, self.expected_life - self.age)\n self.age_index = min(max(0, (remaining_life / self.expected_life)), 1)\n\n if self.initial_criteria in ('NOT IN USE'):\n self.potentially_redundant = 'redundant'\n elif self.initial_criteria in ('COVERED', 'HERITAGE', 'NO DETOUR', 'LIFELINE', 'LANDMARK'):\n self.potentially_redundant = 'not redundant'\n else:\n self.potentially_redundant = \"potentially redundant\"\n\n self.recent_rehab = (CURRENT_YEAR - self.rehab_year &lt;= YEARS_SINCE_LAST_REHAB)\n\n \"\"\"if route 1, 2, 7, 15, 16, 11 (CS 001-&gt;009), 8 (CS 001-002)\"\"\"\n control_section = 0\n self.on_bus_route = (control_section and self.route + (float(control_section) / 1000) in BUS_ROUTES) or (control_section == 0 and self.route in BUS_ROUTES)\n self.cost = self.deck_area * self.unit_cost\n\n def benefit(self):\n \"\"\"Equation developed by the algorithm writers to return the benefit of a bridge\"\"\"\n return self.detour_distance * self.AADT * 365 * self.expected_life * (MILEAGE_COST_PER_KM + (ASSUMED_HOURLY_WAGE / DETOUR_DEFAULT_SPEED))\n\n def benefit_over_cost(self):\n return self.benefit() / self.cost\n\n def bcr_index(self):\n \"\"\"\n BCR = Benefit over cost ratio of bridge\n max_BCR = max BCR in the system (highest BCR)\n \"\"\"\n return self.benefit_over_cost() / (self.max_bcr * B_OVER_C_WEIGHTING)\n\n def redundancy_index(self):\n \"\"\"redundancy index = 100 - weighted sum of all seven indicies\"\"\"\n return 100 - (\n self.bcr_index() + \n self.bci * BCI_WEIGHTING + \n self.age_index * AGE_INDEX_WEIGHTING + \n self.road_class_index + \n self.load_rating * LOAD_RATING_INDEX_WEIGHTING + \n self.on_bus_route * BUS_ROUTE_INDEX_WEIGHTING + \n self.recent_rehab * RECENT_REHAB_INDEX_WEIGHTING\n )\n\n\ndef main(input_data):\n for bridge in input_data:\n bridge = Bridge(**bridge)\n print (bridge.potentially_redundant, bridge.benefit_over_cost(), bridge.redundancy_index())\n\nif __name__ == '__main__':\n input_data = [{\n 'id': 3514,\n 'alpha_id': \"M444\",\n 'year built': 1935,\n 'route': 134,\n 'area': 800,\n 'initial criteria': '',\n 'detour_distance': 30,\n 'AADT': 1500,\n 'below bridge': 'roadway',\n 'BCI': 43,\n 'max BCR': 30,\n 'load rating': False,\n 'rehab year': 1998\n }]\n main(input_data)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T23:30:12.767", "Id": "31195", "ParentId": "31162", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T20:27:51.757", "Id": "31162", "Score": "2", "Tags": [ "python" ], "Title": "Solving an algorithm to develop a redundancy index" }
31162
XNA is a free set of game development tools from Microsoft that facilitate game development for Xbox 360, Windows Phone, Zune and Windows platforms.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T20:30:51.590", "Id": "31164", "Score": "0", "Tags": null, "Title": null }
31164
<p>I worked on a Red-Black tree implementation in C++, and it works as it should. However, I want to see what else I can do to make this code faster/more clean, etc.</p> <p>Any particular suggestions?</p> <p>Edit: code I want most looked at is below (insertion into the RBtree)</p> <pre><code>/****************************** RBInsert Purpose: Insert a new datum into tree *******************************/ template &lt;class T&gt; void RBTree&lt;T&gt;::RBinsert(T data) { RBNode&lt;T&gt;* x; RBNode&lt;T&gt;* y; RBNode&lt;T&gt;* temp = RBTree::search(data); if(temp != RBTree::nil) { cout &lt;&lt; "Node already in Tree!" &lt;&lt; endl; return; } RBNode&lt;T&gt;* z = new RBNode&lt;T&gt;(); z-&gt;data = data; y = this-&gt;RBTree::nil; x = this-&gt;root; while(x != RBTree::nil) { y = x; if (z-&gt;data &lt; x-&gt;data) x = x-&gt;left; else x = x-&gt;right; } z-&gt;parent = y; if(y == RBTree::RBTree::nil) root = z; else if(z-&gt;data &lt; y-&gt;data) y-&gt;left = z; else y-&gt;right = z; z-&gt;left = RBTree::nil; z-&gt;right = RBTree::nil; z-&gt;changeColor(RBNode&lt;T&gt;::red); RBTree::RBinsertFixup(z); } /****************************** RBinsertFixup Purpose: After inserting, calls this to fix red-black properties of tree *******************************/ template &lt;class T&gt; void RBTree&lt;T&gt;::RBinsertFixup(RBNode&lt;T&gt;* z) { RBNode&lt;T&gt;* y; while(z-&gt;parent-&gt;color == RBNode&lt;T&gt;::red &amp;&amp; z-&gt;parent != RBTree::nil) { if(z-&gt;parent == z-&gt;parent-&gt;parent-&gt;left) { y = z-&gt;parent-&gt;parent-&gt;right; // Case 1 if(y-&gt;color == RBNode&lt;T&gt;::red) { z-&gt;parent-&gt;changeColor(RBNode&lt;T&gt;::black); y-&gt;changeColor(RBNode&lt;T&gt;::black); z-&gt;parent-&gt;parent-&gt;changeColor(RBNode&lt;T&gt;::red); z = z-&gt;parent-&gt;parent; } else { // Case 2 if(z == z-&gt;parent-&gt;right) { z = z-&gt;parent; leftRotate(z); } // Case 3 z-&gt;parent-&gt;changeColor(RBNode&lt;T&gt;::black); z-&gt;parent-&gt;parent-&gt;changeColor(RBNode&lt;T&gt;::red); rightRotate(z-&gt;parent-&gt;parent); } } else { y = z-&gt;parent-&gt;parent-&gt;left; // Case 1 if(y-&gt;color == RBNode&lt;T&gt;::red) { z-&gt;parent-&gt;changeColor(RBNode&lt;T&gt;::black); y-&gt;changeColor(RBNode&lt;T&gt;::black); z-&gt;parent-&gt;parent-&gt;changeColor(RBNode&lt;T&gt;::red); z = z-&gt;parent-&gt;parent; } else { // Case 2 if(z == z-&gt;parent-&gt;left) { z = z-&gt;parent; rightRotate(z); } // Case 3 z-&gt;parent-&gt;changeColor(RBNode&lt;T&gt;::black); z-&gt;parent-&gt;parent-&gt;changeColor(RBNode&lt;T&gt;::red); leftRotate(z-&gt;parent-&gt;parent); } } } root-&gt;changeColor(RBNode&lt;T&gt;::black); } </code></pre> <p>Edit: Adding RBTree class declaration:</p> <pre><code>#include &lt;fstream&gt; #include &lt;iostream&gt; #include "RBNode.h" using std::ifstream; template &lt;class T&gt; class RBTree { public: RBTree(); ~RBTree(); void RBwrite(RBNode&lt;T&gt;*); void RBread(); void RBinsert(T); void RBdelete(T); RBNode&lt;T&gt;* getRoot() { return root; } private: bool treeCreated = false; RBNode&lt;T&gt;* nil; RBNode&lt;T&gt;* root; RBNode&lt;T&gt;* minimum(RBNode&lt;T&gt;*); void RBinsert(typename RBNode&lt;T&gt;::Color, T); void RBinsertFixup(RBNode&lt;T&gt;*); void RBdeleteFixup(RBNode&lt;T&gt;*); void transplant(RBNode&lt;T&gt;*, RBNode&lt;T&gt;*); void leftRotate(RBNode&lt;T&gt;*); void rightRotate(RBNode&lt;T&gt;*); void deleteHelper(RBNode&lt;T&gt;* temp); RBNode&lt;T&gt;* search(T); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T17:30:05.957", "Id": "49741", "Score": "1", "body": "Note: You do realize that std::set is usually implemented as a Red/Black tree." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T17:34:22.220", "Id": "49742", "Score": "0", "body": "Yes, I know that (and I think some other std:: structures are too). But what I needed to do (for an honors project) was to implement a RB tree myself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T08:48:33.713", "Id": "49781", "Score": "4", "body": "why are you prefixing every member function with `RB`? it's redundant and overly verbose." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T16:03:18.783", "Id": "49791", "Score": "0", "body": "You're right. I only did it because that is how my class's book's implementation is done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-31T19:41:57.253", "Id": "137061", "Score": "0", "body": "Take a look at my [C++ intrusive red-black tree](https://gist.github.com/pallas/10697727), which also implements node removal (called `prune` here). If you don't like intrusive trees, it is trivial (but an exercise for the reader) to make a non-intrusive container out of this container." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-31T20:33:57.003", "Id": "137076", "Score": "0", "body": "I would change the argument type `T` to `T const&` in several of the functions: `RBInert`, `RBDelete`, and `search`." } ]
[ { "body": "<p>Its hard to review because you did not provide enough to compile.</p>\n\n<p>DON'T use <code>using</code> in a header file that is just the global namespace.</p>\n\n<pre><code>using std::ifstream;\n</code></pre>\n\n<p>This would have been fine if you had placed your stuff in your own namespace. But because it is in global namespace your choices affect other people. ie. Your code could potentially break my code.</p>\n\n<p>The prefix RB is unnecessary and very C like. You should really use your own namespace <code>RB</code> as this resolves the same issue that you are trying to avoid. I notice from the above comments that you got this idea from a book. I would advice this book is way out of date as modern C++ books would not use this style.</p>\n\n<h3>Interface:</h3>\n\n<pre><code>void RBwrite(RBNode&lt;T&gt;*);\n</code></pre>\n\n<p>I don't understand what this is for.<br>\nAre you asking this tree to write out another tree? If you are asking the class to serialize the tree then I migth see it but then I would make the function static. But then I have to ask write it to where? You should be providing a location to stream the data.</p>\n\n<p>Personally I would replace the above call with:</p>\n\n<pre><code>friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, RBTree&lt;T&gt; const&amp; data)\n{\n // write tree to stream\n // Internally you can call RBWrite() but passing a stream\n // I would make RBWrite private\n} \n</code></pre>\n\n<p>Then the converse:</p>\n\n<p>void RBread();</p>\n\n<p>Again where are you reading from? Again I would change the interface:</p>\n\n<pre><code>friend std::istream&amp; operator&gt;&gt;(std::istream&amp; stream, RBTree&lt;T&gt;&amp; data)\n{\n // read tree from stream\n // Internally you can call RBRead() but passing a stream\n // I would make RBRead private\n} \n</code></pre>\n\n<p>With the changes in the interface you are more C++ like.</p>\n\n<h3>Potential Syntax Errors;</h3>\n\n<pre><code> bool treeCreated = false;\n</code></pre>\n\n<p>This does not compile in C++98 (though it is valid C++11). But worse it suggests that a tree can be in an uncreated state. Once the constructor is finished the object should be fully formed and ready for use. If the constructor fails you should throw an exception to make sure that you do not have an invalid object.</p>\n\n<h3>Design:</h3>\n\n<pre><code>RBNode&lt;T&gt;* nil;\n</code></pre>\n\n<p>Is this supposed to represent a NULL pointer?<br>\nIf so prefer <code>NULL</code>. Or if you are using C++11 or later then use <code>nullptr</code>.</p>\n\n<h3>Usage</h3>\n\n<pre><code>void RBTree&lt;T&gt;::RBinsert(T data) {\n RBNode&lt;T&gt;* x;\n RBNode&lt;T&gt;* y;\n</code></pre>\n\n<p>Declare variables where they are used. Declaring variables at the top of the function is a <code>C style</code>. In C++ you declare variables at the point they are being used (or as close to that point as possible).</p>\n\n<p>Two line initialization?</p>\n\n<pre><code>RBNode&lt;T&gt;* z = new RBNode&lt;T&gt;();\nz-&gt;data = data;\n</code></pre>\n\n<p>Your constructor for a RBNode can be passed the data object and allow one line initialization. Reading further into the function I would go even further. This whole function can be simplified by moving the node initialization into its construtor of RBNode.</p>\n\n<pre><code>void RBTree&lt;T&gt;::RBinsert(T data)\n{\n RBNode&lt;T&gt;* temp = RBTree::search(data);\n\n if(temp != RBTree::nil) {\n cout &lt;&lt; \"Node already in Tree!\" &lt;&lt; endl;\n return;\n }\n\n RBNode&lt;T&gt;* y = this-&gt;RBTree::nil;\n RBNode&lt;T&gt;* x = this-&gt;root;\n\n while(x != RBTree::nil) {\n y = x;\n x = (data &lt; x-&gt;data) ? x-&gt;left : x-&gt;right;\n }\n\n RBNode&lt;T&gt;* z = new RBNode&lt;T&gt;(data, y); // Node knows to set itself to RED if\n // y is not NULL Green otherwise\n if(y == RBTree::RBTree::nil) {\n root = z;\n } else {\n RBTree::RBinsertFixup(z); // Only re-balance if not the first node\n }\n}\n</code></pre>\n\n<p>I forget how to do the rotation for a Red/Black tree (that's why I have a copy of Knuth). But it looks fine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T00:08:52.247", "Id": "49807", "Score": "0", "body": "Thank you for all of this. I agree with all of it except I have a comment about one thing: the \"nil\" RBNode pointer is not supposed to be NULL, it was just an unfortunate name that my algorithms book decided to call that pointer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T02:41:47.603", "Id": "49814", "Score": "0", "body": "@user473973 the pointer is NULL, it is not pointing anywhere. This is why all null pointer of the same color regardless of their parents" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-05T16:48:27.667", "Id": "195423", "Score": "0", "body": "The nil node is used so it can be treated as any other node simplifying the the code's logic. The CLRS book uses this sentinel for convenience." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T23:59:26.570", "Id": "31289", "ParentId": "31166", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T20:51:55.723", "Id": "31166", "Score": "5", "Tags": [ "c++", "tree" ], "Title": "My Red-Black Tree Implementation" }
31166
<p>In computer science, <a href="http://en.wikipedia.org/wiki/Conditional_%28programming%29" rel="nofollow">conditional statements</a>, conditional expressions and conditional constructs are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false.</p> <p>Apart from the case of branch predication, this is always achieved by selectively altering the control flow based on some condition.</p> <ul> <li>In <strong>imperative programming</strong> languages, the term "conditional statement" is usually used.</li> <li>In <strong>functional programming</strong> languages, the terms "conditional expression" or "conditional construct" are preferred, because these terms all have distinct meanings.</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T22:33:05.547", "Id": "31168", "Score": "0", "Tags": null, "Title": null }
31168
Boolean expressions that can involve logical operators, used for branching execution paths, which increases cyclomatic complexity.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T22:33:05.547", "Id": "31169", "Score": "0", "Tags": null, "Title": null }
31169
Methods that extend a given type, adding functionality to any instance of that type, even if the type in question is defined in a separate assembly. For example, a "Disemvowel" extension method could be written to add disemvoweling functionality to any "String" object.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T22:51:53.627", "Id": "31172", "Score": "0", "Tags": null, "Title": null }
31172
A compiled set of exposed objects that isn't directly executable, but that can be referenced and used by other code.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T22:54:41.263", "Id": "31174", "Score": "0", "Tags": null, "Title": null }
31174
<h1>Macros</h1> <h2>Summary</h2> <p>A macro in computer science is a rule or pattern that specifies how a certain input sequence (often a sequence of characters) should be mapped to a replacement output sequence (also often a sequence of characters) according to a defined procedure.</p> <p><strong><em>Do not use this tag for questions regarding Microsoft's Visual Basic for Applications. <a href="/questions/tagged/vba" class="post-tag" title="show questions tagged &#39;vba&#39;" rel="tag">vba</a> evolved from an early macro language, but is not a macro language.</em></strong></p> <h2>Links</h2> <ul> <li><a href="http://en.wikipedia.org/wiki/Macro_(computer_science)" rel="nofollow">Wikipedia Article on Macros</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T22:57:51.980", "Id": "31175", "Score": "0", "Tags": null, "Title": null }
31175
A macro in computer science is a rule or pattern that specifies how a certain input sequence (often a sequence of characters) should be mapped to a replacement output sequence (also often a sequence of characters) according to a defined procedure. Do not use this tag for questions regarding Microsoft's Visual Basic for Applications. VBA evolved from an early macro language, but is not a macro language itself.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-09-12T22:57:51.980", "Id": "31176", "Score": "0", "Tags": null, "Title": null }
31176
One of the four pillars of object-oriented programming (OOP), inheritance establishes a "is-a" relationship between objects. For example, a "Cat" object can be treated in code as any other "Animal" object because a "Cat" is-a "Animal".
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T23:02:35.423", "Id": "31178", "Score": "0", "Tags": null, "Title": null }
31178
<p><strong>Tag Recommendation</strong></p> <p>Error handling can be subdivided into <a href="https://en.wikipedia.org/wiki/Error_detection_and_correction" rel="nofollow noreferrer">Error Detection &amp; Correction</a> and <a href="https://en.wikipedia.org/wiki/Exception_handling" rel="nofollow noreferrer">Exception Handling</a>. Use this tag for either subdivision.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-09-12T23:05:53.687", "Id": "31179", "Score": "0", "Tags": null, "Title": null }
31179
The various techniques used for maintaining stable program state in circumstances that, if not taken care of ("handled"), could cause serious issues, including logical bugs and abrupt execution termination.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T23:05:53.687", "Id": "31180", "Score": "0", "Tags": null, "Title": null }
31180
In MVC architecture (Model-View-Controller), the object responsible for passing and receiving data to and from views, acting as a bridge between the "Model" and the "View".
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T23:07:40.773", "Id": "31182", "Score": "0", "Tags": null, "Title": null }
31182
Delegates can refer to several concepts. An object can rely on another (a delegate) to perform a function. Delegation can also refer to programming language feature making use of the method lookup rules for dispatching self-calls. In C#, a delegate defines which method to call when an event is triggered.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T23:10:04.890", "Id": "31184", "Score": "0", "Tags": null, "Title": null }
31184
**This tag is in the process of being removed from the site. Please avoid using it.** The art of properly calling a cat, a cat; naming is often governed by various conventions. Poor naming can make code harder to read, good naming easier.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T23:14:01.017", "Id": "31186", "Score": "0", "Tags": null, "Title": null }
31186
Use this tag for reviews of concepts that aren't specific to any particular programming language, or for concepts that are common to all programming languages.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T23:16:34.090", "Id": "31188", "Score": "0", "Tags": null, "Title": null }
31188
The Model-View-ViewModel design pattern, which separates presentation from data and logic.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T23:21:40.127", "Id": "31190", "Score": "0", "Tags": null, "Title": null }
31190
The part of the application that users directly interact with. Use this tag for reviews of code that defines how an application's user interface works and looks.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T23:27:02.213", "Id": "31192", "Score": "0", "Tags": null, "Title": null }
31192
Use this tag for reviews of code that performs file system operations, such as creating, deleting, renaming, moving, copying, reading, and writing files.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-12T23:29:06.033", "Id": "31194", "Score": "0", "Tags": null, "Title": null }
31194
<p>Concurrency is a property of systems in which several computations can be in progress simultaneously, and potentially interacting with each other. The computations may be executing on multiple cores in the same chip, preemptively time-shared threads on the same processor, or executed on physically separated processors. </p> <p>A number of mathematical models have been developed for general concurrent computation including Petri nets, process calculi, the Parallel Random Access Machine model, the Actor model and the Reo Coordination Language.</p> <h2>Issues</h2> <p>Because computations in a concurrent system can interact with each other while they are executing, the number of possible execution paths in the system can be extremely large, and the resulting outcome can be indeterminate. Concurrent use of shared resources can be a source of indeterminacy leading to issues such as <a href="http://en.wikipedia.org/wiki/Deadlock" rel="nofollow">deadlock</a>, and <a href="http://en.wikipedia.org/wiki/Resource_starvation" rel="nofollow">starvation</a>.</p> <h3>Performance</h3> <p>A common misconception is that increasing concurrency will always improve performance. While it can improve throughput for CPU bound processes by using more CPUs, and IO bound tasks by amortising the latency of each task, there is many situation where more concurrency hurts performance. Even when it improves performance it can reduce maintainability.</p> <p>Examples of where concurrency doesn't help</p> <ul> <li>The overhead of using multiple threads, exceeds the potential improvement. e.g. You have a very short task, but it takes a long time to pass it (and the data associated with it) to another thread. <ul> <li>e.g. the cost of locking a resource exceeds the time taken in the protected operation. A single threaded task might perform much better (and be simpler)</li> </ul></li> <li>You are already using a shared resource to it's maximum extent. e.g. all your CPUs, hard drives, network connection are fully utilised. In this case, the overhead can increase decreasing overall performance.</li> <li>You don't need a performance increase, but adding concurrency increases the complexity of your application. A common argument is; you have to use all your CPUs because they are there (even if there is nothing to gain and everything to lose)</li> </ul> <hr> <h2>References</h2> <ul> <li><a href="http://en.wikipedia.org/wiki/Concurrency_%28computer_science%29" rel="nofollow">Concurrency on Wikipedia</a></li> <li><a href="http://en.wikipedia.org/wiki/Concurrency_%28computer_science%29#Models" rel="nofollow">Models for concurrent systems</a></li> <li><a href="http://en.wikipedia.org/wiki/Concurrency_control" rel="nofollow">Concurrency control</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T00:30:49.543", "Id": "31197", "Score": "0", "Tags": null, "Title": null }
31197
In computer science, concurrency is a property of systems in which multiple computations can be performed in overlapping time periods. The computations may be executing on multiple cores in the same chip, preemptively time-shared threads on the same processor, or executed on physically separated processors.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T00:30:49.543", "Id": "31198", "Score": "0", "Tags": null, "Title": null }
31198
<p>VBScript (Visual Basic Scripting Edition) is an active scripting language developed by Microsoft that is modeled on Visual Basic. It is designed as a <em>lightweight</em> language with a fast interpreter for use in a wide variety of Microsoft environments.</p> <p>It uses the Component Object Model (COM) to access elements of the environment within which it is running; for example, the <code>FileSystemObject</code> (FSO) is used to create, read, update and delete files.</p> <p>It has been installed by default in every desktop release of Microsoft Windows since Windows 98; in Windows Server since Windows NT 4.0 Option Pack; and optionally with Windows CE (depending on the device it is installed on).</p> <p>A VBScript script must be executed within a host environment, of which there are several provided with Microsoft Windows, including: Windows Script Host (WSH), Internet Explorer (IE), and Internet Information Services (IIS).</p> <p>Additionally, the VBScript hosting environment is embeddable in other programs, through technologies such as the Microsoft Script Control (msscript.ocx).</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T00:32:38.567", "Id": "31199", "Score": "0", "Tags": null, "Title": null }
31199
VBScript is Microsoft's Visual Basic Scripting runtime.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T00:32:38.567", "Id": "31200", "Score": "0", "Tags": null, "Title": null }
31200
<p>I'm learning C and have made this very simple function to compare two strings. I would like to know how it can be improved:</p> <pre><code>int match(char* string1, char* string2) { size_t i = 0; while (string1[i] != '\0' || string2[i] != '\0') { if (string1[i] != string2[i]) { return 0; } ++i; } return 1; } </code></pre> <p>I figured it will only do 2 comparisons per iteration, and 3 in the last iteration. Also, I believe it won't go beyond the end of any array because it will return before iterating beyond the null terminator.</p>
[]
[ { "body": "<p>In your <code>while</code> loop, you check whether <code>string1[i]</code> <em>or</em> <code>string2[i]</code> are <em>not</em> null. If they are of unequal lengths, they will have their null terminators at different values of <code>i</code>; because at least one is non-null at each point, your while loop would then continue forever. To fix this, all you have to do is change <code>||</code> to <code>&amp;&amp;</code>, because you need to make sure that <em>both</em> of your characters are valid.</p>\n\n<p>Another improvement that I would consider would be changing the return value to be zero if they are equal; this would match the built-in <code>strcmp</code> function. Then, you could return i as the place at which the two strings diverge, also matching <code>strcmp</code>. This provides the programmer with more useful information from one function call without a loss in value, because <code>0</code> is false and everything else is true.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T05:33:26.323", "Id": "49686", "Score": "0", "body": "Don't worry, the termination works fine. If they are unequal length, the if-comparison inside the while-loop will be triggered, and return 0." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T19:53:50.927", "Id": "49750", "Score": "0", "body": "Right, I didn't consider that. In any case, it would be more readable for a `&&` operator. Also, if OP cares about performance, he should know that `&&` is short-circuiting: It will only evaluate the right operand if the left operand is true, providing some (small) performance gain." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T21:05:43.063", "Id": "49756", "Score": "0", "body": "Once you change `||` to `&&`, it no longer works correctly. When one string begins with the other, it would report them as being equal." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T04:04:31.853", "Id": "31220", "ParentId": "31201", "Score": "1" } }, { "body": "<p>Your parameters should be <code>const</code> and your loop need only to check one string for the terminator. For example in the following loop, if <code>*s1</code> is 0 the loop stops because of the first condition. If <code>*s1</code> is not 0 but <code>*s2</code> <strong>is</strong> 0, the loop stops because of the 2nd condition.</p>\n\n<pre><code>int match(const char *s1, const char *s2)\n{\n while (*s1 &amp;&amp; (*s1++ == *s2++)) {\n // nothing\n }\n return *s1 - *s2;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T09:23:45.023", "Id": "31228", "ParentId": "31201", "Score": "4" } } ]
{ "AcceptedAnswerId": "31228", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T00:37:40.453", "Id": "31201", "Score": "2", "Tags": [ "optimization", "c", "array" ], "Title": "Improving function that compares two strings" }
31201
Use this tag for reviews of code where type safety is a concern, for example code involving type conversions or casting which may result in type errors at run-time.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T00:42:16.327", "Id": "31203", "Score": "0", "Tags": null, "Title": null }
31203
Use this tag for code reviews of, or involving methods that create a new instance of a given type, often with parameters that determine how the instance gets created.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T00:46:56.753", "Id": "31205", "Score": "0", "Tags": null, "Title": null }
31205
A mocking framework, used in unit tests for injecting "fake" implementations of interfaces as dependencies of the system under test. Use this tag for code reviews of unit testing methods that use this specific mocking framework.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T00:52:34.667", "Id": "31207", "Score": "0", "Tags": null, "Title": null }
31207
Use this tag for reviews of code that addresses localization/globalization concerns, which make an application be displayable in multiple languages.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T00:55:50.790", "Id": "31210", "Score": "0", "Tags": null, "Title": null }
31210
Microsoft's well-known operating system. Use this tag for code reviews where the code is targeted specifically for this platform, when no other more specific tags exist.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T02:13:00.350", "Id": "31213", "Score": "0", "Tags": null, "Title": null }
31213
Use this tag for code reviews of or involving Linq to SQL classes, mappings and associations, or for code reviews of or involving querying a System.Data.Linq.DataContext object with Linq statements.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T02:22:45.517", "Id": "31215", "Score": "0", "Tags": null, "Title": null }
31215
<pre><code>if (progressBar1.Value == 1) { progressLabel.Text = "1%"; } if (progressBar1.Value == 10) { progressLabel.Text = "10%"; } if (progressBar1.Value == 20) { progressLabel.Text = "20%"; } if (progressBar1.Value == 30) { progressLabel.Text = "30%"; } if (progressBar1.Value == 40) { progressLabel.Text = "40%"; } if (progressBar1.Value == 50) { progressLabel.Text = "50%"; } if (progressBar1.Value == 60) { progressLabel.Text = "60%"; } if (progressBar1.Value == 70) { progressLabel.Text = "70%"; } if (progressBar1.Value == 80) { progressLabel.Text = "80%"; } if (progressBar1.Value == 90) { progressLabel.Text = "90%"; } if (progressBar1.Value == 100) { progressLabel.Text = "100%"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T14:43:29.687", "Id": "49715", "Score": "0", "body": "I like dreza's answer, if you wanted to make this code more efficient you could use `if..else if` rather than several `if` statements. it would hit one, show it and exit the code until the next iteration of the code" } ]
[ { "body": "<p>Why can't you do:</p>\n\n<pre><code>progressLabel.Text = string.Format(\"{0}%\", progressBar1.Value)\n</code></pre>\n\n<p>As @MNZ pointed out I potentially didn't answer the question exactly how the OP asked. So here's a slightly modified alternative option:</p>\n\n<pre><code>progressLabel.Text = FormatProgress(progressBar1.Value, progressLabel.Text)\n\nprivate string FormatProgress(int currentProgress, string progressDisplayed)\n{\n if (currentProgress &lt; 0 || currentProgress &gt; 100)\n throw new ArgumentOutOfRangeException(\"Current progress is not in a valid percentage range of 0 to 100\");\n\n if (currentProgress == 1) \n return FormatProgress(currentProgress);\n\n return currentProgress % 10 == 0 ? \n FormatProgress(currentProgress) : \n progressDisplayed;\n}\n\nprivate string FormatProgress(int progress)\n{\n return string.Format(\"{0}%\", progress);\n}\n</code></pre>\n\n<p>And a unit test to confirm:</p>\n\n<pre><code>[TestMethod]\npublic void Test()\n{\n Assert.AreEqual(\"1%\", FormatProgress(1, \"0%\"));\n Assert.AreEqual(\"0%\", FormatProgress(0, \"5%\"));\n Assert.AreEqual(\"10%\", FormatProgress(10, \"6%\"));\n Assert.AreEqual(\"80%\", FormatProgress(85, \"80%\"));\n Assert.AreEqual(\"100%\", FormatProgress(100, \"90%\"));\n Assert.AreNotEqual(\"75%\", FormatProgress(75, \"70%\")); \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T00:16:26.193", "Id": "49768", "Score": "0", "body": "Although this code is not exactly same as the code in question. It must have an if satement to check if progressLabel.Value is one of 1,10,20,30,40,50,60,70,80,90 or 100." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T03:43:36.970", "Id": "31218", "ParentId": "31217", "Score": "16" } }, { "body": "<p>Use a switch statement...</p>\n\n<pre><code>switch(progressBar.Value)\n{\ncase 1:\nprogressLabel.Text = \"1%\"; \nbreak;\n\ncase 10:\nprogressLabel.Text = \"10%\"; \nbreak;\n\ncase 20:\nprogressLabel.Text = \"20%\"; \nbreak;\n\ncase 30:\nprogressLabel.Text = \"30%\"; \nbreak;\n}\n</code></pre>\n\n<p>etc...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T14:41:24.567", "Id": "49714", "Score": "0", "body": "this would be more code than the if statements. it wouldn't be shorter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T15:00:17.917", "Id": "49717", "Score": "0", "body": "@Malachi indeed, but it does address the multiple condition evaluation that you pointed out in your comment to the question, and is more elegant than a bunch of `else` blocks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T15:06:12.433", "Id": "49720", "Score": "0", "body": "that is almost a toss up, but I think I am going to have to agree with you on that @retailcoder." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T15:28:32.507", "Id": "49725", "Score": "3", "body": "Switch Statements are much more efficient than an else if. Else if statements force each if statement to be tested before finding the correct one. Case statements only test once. Plus it gives you more flexibility than drezas answer, although drezas IS much shorter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T16:17:32.447", "Id": "49738", "Score": "0", "body": "@CodeSlinger and that's what got you my upvote ;) ...although it *is* overkill in this specific case." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T14:05:55.797", "Id": "31233", "ParentId": "31217", "Score": "1" } }, { "body": "<pre><code>if (progressBar1.Value == 1 || progressBar.Value % 10 == 0)\n progressLabel.Text = progressBar1.Value.ToString() + \"%\";\n</code></pre>\n\n<p>Assuming that you are using a standard WinForms progress bar, you shouldn't have to worry about the progressBar.Value being &lt;0 or >100.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T22:43:05.510", "Id": "31333", "ParentId": "31217", "Score": "1" } } ]
{ "AcceptedAnswerId": "31218", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T03:34:32.673", "Id": "31217", "Score": "3", "Tags": [ "c#", "winforms" ], "Title": "How to write this code without using 11 if-statements?" }
31217
<p>I have just made a simple script which spawns an alien that chases the player. I want to move as much of the script into functions so as to minimize the amount of code, to make it run better when my game gets a lot bigger. I am new to functions and classes, and I want to know what can be turned into a class in another script and how to go about doing it. I do not want just code, I want to be able to understand what I'm doing with it as well.</p> <pre><code>import pygame, sys, random, time, math from pygame.locals import * pygame.init() bifl = 'screeing.jpg' milf = 'character.png' alien = 'alien_1.png' screen = pygame.display.set_mode((640, 480)) background = pygame.image.load(bifl).convert() mouse_c = pygame.image.load(milf).convert_alpha() nPc = pygame.image.load(alien).convert_alpha() x, y = 0, 0 movex, movey = 0, 0 z, w = random.randint(10, 480), random.randint(10, 640) movez, movew = 0, 0 while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_w: movey = - 4 elif event.key == K_s: movey = + 4 elif event.key == K_a: movex = - 4 elif event.key == K_d: movex = + 4 if event.type == KEYUP: if event.key == K_w: movey = 0 elif event.key == K_s: movey = 0 elif event.key == K_a: movex = 0 elif event.key == K_d: movex = 0 if w &lt; x: movew =+ 0.4 if w &gt; x: movew =- 0.4 if z &lt; y: movez =+ 0.4 if z &gt; y: movez =- 0.4 x += movex y += movey w += movew z += movez print('charecter pos: ' + str(x) + str(y)) print('alien pos: ' + str(w) + str(z)) chpos = x + y alpos = w + z print(alpos, chpos) if chpos == alpos: pygame.quit() sys.exit() screen.blit(background, (0, 0)) screen.blit(mouse_c, (x, y)) screen.blit(nPc, (w, z)) pygame.display.update() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T13:07:25.313", "Id": "49712", "Score": "0", "body": "Not into Python but if you can put a name on a concept and picture that concept having properties and/or exposing methods or functions, you have a candidate for a class. As for functions, they should be *doing as little as possible*, which makes them easier to name and reuse." } ]
[ { "body": "<p>You can create a class called <code>AlienGame(object)</code>.</p>\n\n<ol>\n<li><p>Put all the initialization code in a <code>def __init__</code> function.</p></li>\n<li><p>Put all creation of characters in a <code>def create_characters</code> function.</p></li>\n<li><p>Put the chase part of the code in a <code>def chase_player</code> function.</p></li>\n</ol>\n\n<p>This segregation of your code will make it more readable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T18:34:14.923", "Id": "31250", "ParentId": "31230", "Score": "0" } }, { "body": "<p>Long multiple choice decisions in python work well as dictionaries, rather than elifs. </p>\n\n<pre><code>def handle_event(event):\n OnKeyDown = {K_w:(0, 4), K_s:(0,-4), K_a:(-4, 0), K_d:(4,0)}\n OnKeyUp = {K_w:(False, True), K_s:(False, True), K_a:(True, False), K_d:(True, False)}\n\n if event.type == KEYUP:\n delta = OnKeyDown[event]\n movex += delta[0]\n movey += delta[1]\n elif event.type == KEYDOWN:\n delta = OnKeyUp[event]\n if delta[0]: movex = 0\n if delta[1]: movey = 0\n\n x += movex\n y += movey\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T09:52:42.113", "Id": "49782", "Score": "0", "body": "this is very good, but what would sort of code would i need to use these funtions to make the player move" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T20:47:08.447", "Id": "49797", "Score": "0", "body": "This function would replace the core if/elif block in your code above. You could probably just replace that whole section with this function ." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T21:33:46.563", "Id": "31259", "ParentId": "31230", "Score": "3" } } ]
{ "AcceptedAnswerId": "31259", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T11:14:46.900", "Id": "31230", "Score": "3", "Tags": [ "python", "pygame" ], "Title": "Spawning an alien to chase the player" }
31230
<p>I've been playing around and reading up on some sorting algorithms, and I've decided to try writing my own. It turned out to be quite fast (compared to the others shown in the image below).</p> <p>I'm very curious to know a little bit about it:</p> <ul> <li>Does my algorithm already have a name?</li> <li>What are the downsides to it (other than it being really stupid to sort { 900000, 1 } with it)?</li> <li>Why is it not a good solution in general?</li> <li>Any suggestions for optimisation?</li> </ul> <p></p> <pre><code>static int[] MySort(int[] input) { int minValue = input.Min() - 1; int[] tempArr = new int[input.Max() - minValue]; //{1,3,3,5} becomes: //{1,0,2,0,1} one 1's, two 3's, one 5's. for (int i = 0; i &lt; input.Length; i++) tempArr[input[i] - minValue - 1] += 1; //AddNumbers to old array. and add minValue. int g = 0; for (int j = 0; j &lt; tempArr.Length; j++) { if (tempArr[j] != 0) { for (int i = 0; i &lt; tempArr[j]; i++) { input[g] = j + minValue + 1; g++; } } } return input; } </code></pre> <p>Performance screenshot:</p> <p><img src="https://i.stack.imgur.com/L3mHp.png" alt="enter image description here"></p>
[]
[ { "body": "<blockquote>\n <p>Does my algorithm already have a name?</p>\n</blockquote>\n\n<p>It's called <a href=\"https://en.wikipedia.org/wiki/Counting_sort\">counting sort</a>.</p>\n\n<blockquote>\n <p>What are the downsides to it? (Other than it is really stupid to sort { 900000, 1 } with it.)</p>\n</blockquote>\n\n<p>That's exactly the major disadvantage of the algorithm: it doesn't work well if the range of values is large.</p>\n\n<blockquote>\n <p>Why is it not a good solution in general?</p>\n</blockquote>\n\n<p>Because it can sort only integers. You can't use it to sort floating point numbers, strings or any other type that doesn't behave as an integer.</p>\n\n<blockquote>\n <p>Any suggestions for optimization?</p>\n</blockquote>\n\n<p>The condition <code>if (tempArr[j] != 0)</code> is completely useless. If you leave it out, the code will work exactly the same.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T16:16:02.467", "Id": "31244", "ParentId": "31235", "Score": "16" } }, { "body": "<p>I know this is a fairly old question, but I'd like to point something out.</p>\n\n<p>While <code>i</code> and <code>j</code> are commonly used as \"counter\" variables, they only serve to obfuscate the code in this case. By time we make it to <code>g</code>, it's very difficult indeed to tell which variable stands for what. These should all have meaningful names for Mr. Maintainer's sake. </p>\n\n<p>This is a little more verbose, but (I think) a little easier to understand. Particularly considering that it's easy to see now that the <code>i</code> in the initial loop, is not the same <code>i</code> as the one nested in the second loop.</p>\n\n<pre><code>static int[] MySort(int[] input)\n{\n int minValue = input.Min() - 1;\n int[] tempArr = new int[input.Max() - minValue];\n //{1,3,3,5} becomes:\n //{1,0,2,0,1} one 1's, two 3's, one 5's.\n for (int inputCounter = 0; inputCounter &lt; input.Length; inputCounter++)\n tempArr[input[inputCounter] - minValue - 1] += 1;\n //AddNumbers to old array. and add minValue.\n\n int itemCounter = 0;\n for (int tempCounter = 0; tempCounter &lt; tempArr.Length; tempCounter++)\n {\n if (tempArr[tempCounter] != 0)\n {\n for (int i = 0; i &lt; tempArr[tempCounter]; i++)\n {\n input[itemCounter] = tempCounter + minValue + 1;\n itemCounter++;\n }\n }\n }\n return input;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-16T17:01:10.643", "Id": "54406", "ParentId": "31235", "Score": "2" } } ]
{ "AcceptedAnswerId": "31244", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T14:56:36.890", "Id": "31235", "Score": "12", "Tags": [ "c#", "performance", "algorithm", ".net", "sorting" ], "Title": "Attempt at a sorting algorithm" }
31235
<p>The class is responsible for wrapping requests to a WCF Data Service, which tidies up calling code. Transactions are implicitly supported. It should efficiently send just updates to the services (only changed values). The next step is to modify it and allow named properties to be queried, rather than all fields.</p> <p>Please review this.</p> <pre><code>using System; using System.Data.EntityClient; using System.Data.Objects; using System.Data.Services.Client; using System.Data.Services.Common; using System.Threading.Tasks; internal class ServiceWrapper&lt;T&gt; { private DataServiceContext context; public ServiceWrapper(Uri uri, string collection) { context = new DataServiceContext(uri, DataServiceProtocolVersion.V3); CollectionName = collection; } public string CollectionName { get; private set; } public DataServiceContext Context { get { return context; } } public DataServiceQuery&lt;T&gt; QueryAll { get { return Context.CreateQuery&lt;T&gt;(CollectionName); } } public DataServiceQuery&lt;T&gt; InvokeMethod(string opName, params Tuple&lt;string,object&gt;[] args) { DataServiceQuery&lt;T&gt; query = Context.CreateQuery&lt;T&gt;(opName); foreach (Tuple&lt;string, object&gt; pair in args) { query = query.AddQueryOption(pair.Item1, pair.Item2); } return query; } public void Add(T entity) { context.AddObject(CollectionName, entity); } public void Update(T entity) { context.AttachTo(CollectionName, entity); context.UpdateObject(entity); } public void Delete(T entity) { context.AttachTo(CollectionName, entity); context.DeleteObject(entity); } public async Task CommitAsync() { await Task.Run(() =&gt; context.SaveChanges(SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch)); } } </code></pre>
[]
[ { "body": "<p>Some initial thoughts off the top of my head. I personally like immutability in my class data where possible. You have such available:</p>\n\n<pre><code>private readonly DataServiceContext context;\n\nprivate readonly string collectionName;\n\npublic ServiceWrapper(Uri uri, string collection)\n{\n context = new DataServiceContext(uri, DataServiceProtocolVersion.V3);\n collectionName = collection;\n}\n\npublic string CollectionName { get { return collectionName; } }\n</code></pre>\n\n<p>Also, if you have LINQ available to you, you can simplify <code>InvokeMethod()</code>:</p>\n\n<pre><code>public DataServiceQuery&lt;T&gt; InvokeMethod(string opName, params Tuple&lt;string,object&gt;[] args)\n{\n return args.Aggregate(\n Context.CreateQuery&lt;T&gt;(opName),\n (current, pair) =&gt; current.AddQueryOption(pair.Item1, pair.Item2));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-12T12:21:14.350", "Id": "62747", "ParentId": "31241", "Score": "3" } } ]
{ "AcceptedAnswerId": "62747", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T15:46:38.090", "Id": "31241", "Score": "4", "Tags": [ "c#", "entity-framework" ], "Title": "WCF client class" }
31241
<p>I have been teaching myself programming, mainly in Java, for about 6 months. I'm looking for some feedback on this implementation of the Game of Life, which runs entirely in the terminal. Specifically, where does it not follow best practices, is it over-engineered, etc?</p> <p>The entry point:</p> <pre><code>public class GameOfLife { public static void main(String[] args) { Seed seed = new OscillatorSeed(); //could be any object implementing seed interface LifeBoard gameOfLife = new LifeBoard(seed); } } </code></pre> <p>Seed interface defines specific behavior of concrete seeds:</p> <pre><code>public interface Seed { /* *pattern for seed files *must have a "board" made of a 2d boolean array *board is not required to be rectangular */ public int getHeight(); public int getWidth(); public boolean[][] getSeed(); } </code></pre> <p>Here are some concrete seeds:</p> <pre><code>public class OscillatorSeed implements Seed { public boolean[][] seed = { {false, false, false, false, false}, {false, false, false, false, false}, {false, true, true, true, false}, {false, false, false, false, false}, {false, false, false, false, false} }; public int height = 5; public int width = 5; public int getHeight() { return height; } public int getWidth() { return width; } public boolean[][] getSeed() { return seed; } } public class GliderSeed implements Seed { public boolean[][] seed = { {false, false, false, false, false}, {false, false, false, true, false}, {false, true, false, true, false}, {false, false, true, true, false}, {false, false, false, false, false} }; public int height = 25; public int width = 40; public int getHeight() { return height; } public int getWidth() { return width; } public boolean[][] getSeed() { return seed; } } </code></pre> <p><code>BoardPrinter</code> has one static method, print, to paint the game board in the terminal after each generation. It is tailored to my specific console, and clips large boards to fit or inserts blank space for small boards, so the output at each refresh is exactly my console's number of lines-1 each refresh, makes it look smoother. This is my attempt to separate the UI/display code from the model of the game. IS this a reasonable way to do it?</p> <pre><code>public class BoardPrinter { public static int TERM_ROWS = 24; //xterm leaves last line blank, remember to -1 num_rows static void print(boolean[][] state) { // debugging code only: System.out.println("" + state.length + state[0].length); if (state.length &lt;= TERM_ROWS) { for (int row = 0; row &lt; state.length; row++) { for (int position = 0; position &lt; state[row].length; position++) { if (state[row][position] == true) { System.out.print("*"); } else { System.out.print("~"); } } System.out.print("\n"); } } else { for (int row = 0; row &lt; TERM_ROWS-1; row++) { for (int position = 0; position &lt; state[row].length; position++) { if (state[row][position] == true) { System.out.print("*"); } else { System.out.print("~"); } } System.out.print("\n"); } } try { //100 ms delay = 20 fps Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } } </code></pre> <p>The actual implementation of the game, rules, etc. I know the block of <code>if</code> statements should be made more efficient. I would like to do it with a loop of some sort but am still figuring out how to do that. I'm considering making an array with each of the 8 enums in it to use in a <code>for</code>-loop. Is the use of enum even a reasonable way to do the direction-search? What else am I not considering?</p> <pre><code>public class LifeBoard { public boolean[][] oldState; public boolean[][] newState; public boolean[][] blankState; private boolean gameRunning = true; public LifeBoard(Seed seed) { oldState = new boolean[seed.getHeight()][seed.getWidth()]; newState = new boolean[oldState.length][oldState[0].length]; for (int i = 0; i &lt; seed.getSeed().length; i++) { for (int n = 0; n &lt; seed.getWidth(); n++) { System.arraycopy(seed.getSeed()[i], 0, oldState[i], 0, seed.getSeed().length); } } blankState = new boolean[oldState.length][oldState[0].length]; run(); } public void run() { //game runs forever, evaluateCells() should switch the game off when it detects no change for consecutive generations, but I haven't figured out how to implement that yet gameRunning = true; while (gameRunning) { BoardPrinter.print(oldState); gameRunning = evaluateCells(); for (int n = 0; n &lt; oldState.length; n++) { System.arraycopy(newState[n], 0, oldState[n], 0, oldState.length); } for (int t = 0; t &lt; newState.length; t++) { System.arraycopy(blankState[t], 0, newState[t], 0, newState.length); } } BoardPrinter.print(oldState); System.out.println("game over"); } public boolean evaluateCells() { for (int row = 0; row &lt; oldState.length; row++) { for (int position = 0; position &lt; oldState[row].length; position++) { newState[row][position] = evaluateCell(row,position); } } //return true while life is still evolving, when board is static, return false //feature not yet implemented return true; } public boolean evaluateCell(int row, int position) { int score = 0; //evaluate each neighboring cell if (getCell(row, position, Direction.ToRight)) { score += 1; } if (getCell(row, position, Direction.ToLeft)) { score += 1; } if (getCell(row, position, Direction.ToTop)) { score += 1; } if (getCell(row, position, Direction.ToBottom)) { score += 1; } if (getCell(row, position, Direction.ToBottomRight)) { score += 1; } if (getCell(row, position, Direction.ToBottomLeft)) { score += 1; } if (getCell(row, position, Direction.ToTopRight)) { score += 1; } if (getCell(row, position, Direction.ToTopLeft)) { score += 1; } //evaluate total of score against rules of the game //implimentation of game rules if ((oldState[row][position] == true) &amp;&amp; (score &lt; 2)) { return false; //die of loneliness } else if ((oldState[row][position] == true) &amp;&amp; (score == 2 || score == 3)) { return true; //continue to live } else if ((oldState[row][position] == true) &amp;&amp; (score &gt; 3)) { return false; //die of overcrowding } else if ((oldState[row][position] == false) &amp;&amp; (score == 3)) { return true; //life is born } else { return false; } } public boolean getCell(int row, int position, Direction direction) { int newY = row+direction.getYDir(); int newX = position+direction.getXDir(); if (newX &lt; 0 || newX &gt;= oldState[row].length) { return false; } if (newY &lt; 0 || newY &gt;= oldState.length) { return false; } return oldState[newY][newX]; } public enum Direction { ToRight(1,0), ToLeft(-1,0), ToBottom(0,1), ToTop(0,-1), ToTopRight(1,-1), ToTopLeft(-1,-1), ToBottomRight(1,1), ToBottomLeft(-1,1); private int xDir; private int yDir; private Direction(int xDir, int yDir) { this.xDir = xDir; this.yDir = yDir; } public int getXDir() { return xDir; } public int getYDir() { return yDir; } } } </code></pre> <p>All this code runs on my machine, no obvious problems, and I get the expected results. In the future I would like to add a <code>SeedFactory</code> that takes a CSV text file and builds a <code>Seed</code> from that, rather than compiling a separate class for each seed. I would specify <code>java GameOfLife seedfile.seed</code>, instantiate the factory in the <code>GameOfLife</code> class, and pass the arg to the factory, let it return a Seed, and pass that to the LifeBoard. A bloated way of doing it?</p>
[]
[ { "body": "<p>First of all, I think your code is very nice for 6 months of training. The following tips are mainly regarding style and object orientation. </p>\n\n<ol>\n<li>If you want to truly separate the implementation from the user interface, you should not call <code>BoardPrinter.print()</code> from within your <code>LifeBoard</code> class. A good way to achieve separation is, for example, to create an interface (for instance <code>IBoardOutput</code>), which has a method <code>print(boolean[][] state)</code>. Then, you can add a method to your <code>LifeBoard</code> class, which allows you to set an <code>BoardOutput</code>, so <code>BoardOutput.print(...)</code> can be called. Finally, let <code>BoardPrinter</code> implement the interface <code>IBoardOutput</code>. So, the output method can be changed without touching the <code>LifeBoard</code> class. This is called <strong>strategy pattern</strong> or <strong>dependency injection</strong>, if you want to do further research. </li>\n<li>Be careful with data encapsulation. Your <code>BoardPrinter</code> class receives <code>oldGamefield</code>, which enables the <code>BoardPrinter</code> class to modify your gamefield! If you implement the approach above, an implementation of <code>BoardOutput</code> could modify the gamefield by accident. Passing a copy of the gamefield to <code>BoardOutput</code> is possible solution, passing an instance of <code>LifeBoard</code> istself and accessing the <code>getCell</code> method is another one (add an overload without the direction parameter for this). </li>\n<li>Do the <code>evaluateCell</code> and <code>evaluateCells</code> methods really have to be public? </li>\n<li>Your implementation of <code>Direction</code> is nice, if you have to access methods which depend on the <code>Direction</code> class from outside. However, I only see this class being used internally. In such a case, two nested for loops from -1 to 1 for searching directions would be fine, too, especially if performance is important. If you need a code sample on how to do this, just leave a comment. </li>\n<li>Instead of <code>if(state[row][position] == true)</code> use <code>if(state[row][position])</code>.</li>\n<li>If you want a small pause between the steps of the simulation, DON'T pause the thread in the <code>BoardPrinter</code> class. Do it in your <code>LifeBoard</code> class. Why? Because the <code>BoardPrinter</code> is for printing the board, not for controlling the simulation. </li>\n<li>Implementing a <code>SeedFactory</code> is a valid way of doing so, and will probably be a nice exercise. </li>\n<li>Your <code>OscillatorSeed</code> class exposes variables as public (<code>public int width;</code>). You have getters for that and should make them private (or even const/final, since these values are not supposed to change any more). </li>\n</ol>\n\n<p>Fun tip: You can even use the mentioned Strategy pattern to make the set of rules used for the game exchangeable. </p>\n\n<p>Have fun!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T22:32:01.360", "Id": "31260", "ParentId": "31245", "Score": "3" } }, { "body": "<p>I thought it would be fun if I modified your program the way I would do it and posted that code. I haven't really interacted with other programmers so I don't really know if what I am doing is normal, but I will explain my reasoning. </p>\n\n<h1><code>GameOfLife</code></h1>\n\n<p>Let's start with the main class:</p>\n\n<pre><code>public class GameOfLife {\n\n public static void main(String[] args) {\n Seed seed = new OscillatorSeed(); //could be any object implementing seed interface \n LifeBoard lifeBoard = new LifeBoard(seed);\n while (true) {\n lifeBoard.iterate();\n BoardPrinter.print(lifeBoard);\n waitForNextFrame();\n }\n }\n\n static private void waitForNextFrame() {\n try {\n //100 ms delay = 20 fps\n Thread.sleep(100);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n}\n</code></pre>\n\n<p>There are a few things I did here. </p>\n\n<p>First, I renamed our <code>LifeBoard</code> object <code>lifeBoard</code>. Previously it was named <code>gameOfLife</code>. The old name doesn't make sense because the object is of type <code>LifeBoard</code> and not of type <code>GameOfLife</code>. Choosing bad names for objects can make the code confusing so watch out for that. </p>\n\n<p>Second, I have moved the logic of controlling the simulation out into the main <code>GameOfLife</code> class. This is because the object that is responsible for iterating the system should not also be responsible for figuring out when and for how long it should iterate, and it should not be responsible for determining when it should draw itself.</p>\n\n<p>A third thing I did was to extract waiting for the next frame into its own function. This is because it is a conceptually simple thing that can be separated out easily.</p>\n\n<h1><code>Seed</code></h1>\n\n<p>Next let's look at the seed interface:</p>\n\n<pre><code>public interface Seed {\n\n /*\n *pattern for seed files\n *must have a \"board\" made of a 2d boolean array\n *board is not required to be rectangular\n */\n public int getNumRows();\n\n public int getNumColumns();\n\n public boolean[][] getSeed();\n\n}\n</code></pre>\n\n<p>All I have done here is to change the names of the getters to <code>getNumRows()</code> and <code>getNumColumns()</code>. Before it was <code>getHeight()</code> and <code>getWidth()</code>. I choose the new names because I want everything to be referred to by rows and columns uniformly throughout the whole program. Before you had width, x and position, where now I will just say column, and you had height, y, and row, where now I will just say row.</p>\n\n<h1><code>OscillatorSeed</code></h1>\n\n<pre><code>public class OscillatorSeed implements Seed {\n\n public boolean[][] seed = {\n {false, false, false, false, false},\n {false, false, false, false, false},\n {false, true, true, true, false},\n {false, false, false, false, false},\n {false, false, false, false, false}\n };\n private final int numRows = 5;\n private final int numColumns = 5;\n\n @Override\n public int getNumRows() {\n return numRows;\n }\n\n @Override\n public int getNumColumns() {\n return numColumns;\n }\n\n @Override\n public boolean[][] getSeed() {\n return seed;\n }\n\n}\n</code></pre>\n\n<p>Besides changing the names of the variables, I have also made them private and final, since they aren't supposed to be changed, and we can access them with the getters. I did the same thing for <code>GliderSeed</code>, so I won't post the code for <code>GliderSeed</code> here. <code>seed</code> should probably also be private and final.</p>\n\n<h1><code>BoardPrinter</code></h1>\n\n<p>Let's move on to the <code>BoardPrinter</code> class</p>\n\n<pre><code>public class BoardPrinter {\n\n public static int TERM_ROWS = 24;\n //xterm leaves last line blank, remember to -1 num_rows\n\n static public void print(LifeBoard lifeBoard) {\n // debugging code only: System.out.println(\"\" + state.length + state[0].length);\n final int numRowsPrinted = Math.min(lifeBoard.getNumRows(), TERM_ROWS);\n final int numColumns = lifeBoard.getNumColumns();\n\n Cell currentCell = new Cell(0, 0);\n for (currentCell.row = 0; currentCell.row &lt; numRowsPrinted; currentCell.row++) {\n for (currentCell.column = 0; currentCell.column &lt; numColumns; currentCell.column++) {\n final boolean isAlive = lifeBoard.isAlive(currentCell);\n printCell(isAlive);\n }\n endLine();\n }\n }\n\n static private void printCell(boolean isAlive) {\n if (isAlive) {\n System.out.print(\"*\");\n } else {\n System.out.print(\"~\");\n }\n }\n\n static private void endLine() {\n System.out.println(\"\\n\");\n }\n\n}\n</code></pre>\n\n<p>The first thing you can see is that I am now passing the whole <code>lifeBoard</code> object to the method. This way we don't have to expose the boolean array, which Emiswelt said would be a bad idea. I will show how I access the values of the array when I get to explaining that part.</p>\n\n<p>The next thing is I got rid of your outer if by figuring out how many rows I wanted to print first. Then I just use that number. A good way to tell that your outer if was probably not the best way of doing things is that the body of the if black was the same as the body of the else block. That kind of code duplication is a sure sign that something can be improved.</p>\n\n<p>You can see I created a Cell class to encapsulate a pair of <code>int</code>s. I will talk about this later. I use an object of this class to access the boolean array in <code>lifeBoard</code>. Since I am using a getter which returns a <code>boolean</code>, there is no chance of me altering the state of <code>lifeBoard</code>.</p>\n\n<p>The next thing I did was to extract <code>printCell</code> to be its own method. This separates the logic of looping through the cells from the logic of deciding which character to draw. It also makes the <code>print</code> function look more manageable, and the name of the method tells you what is going on, which would be harder to tell just from looking at the <code>if-else</code> the way you had it. Notice I have gotten rid of two levels of indentation, which makes the method easier to read.</p>\n\n<p>Then I did something kind of crazy, which was to extract printing the newline character to its own function. The idea is if printing characters should have its own when I am printing the cell, then it should have its own method when I print a newline. Doing it this way has the benefit of saying why I am printing the newline character. It's because I am ending the line. This is a minor point.</p>\n\n<h1><code>LifeBoard</code></h1>\n\n<p>Last but not least we get to the <code>LifeBoard</code> class.</p>\n\n<pre><code> public class LifeBoard {\n\n static public class Cell {\n\n public int row;\n public int column;\n\n public Cell(int row, int column) {\n this.row = row;\n this.column = column;\n }\n\n public Cell getNeighbor(Direction direction) {\n return new Cell(row + direction.getRowChange(), column + direction.getColumnChange());\n }\n\n }\n\n static public enum Direction {\n\n RIGHT(1, 0),\n LEFT(-1, 0),\n DOWN(0, 1),\n UP(0, -1),\n UP_RIGHT(1, -1),\n UP_LEFT(-1, -1),\n DOWN_RIGHT(1, 1),\n DOWN_LEFT(-1, 1);\n private final int columnChange;\n private final int rowChange;\n\n private Direction(int columnChange, int rowChange) {\n this.columnChange = columnChange;\n this.rowChange = rowChange;\n }\n\n public int getColumnChange() {\n return columnChange;\n }\n\n public int getRowChange() {\n return rowChange;\n }\n\n }\n\n private final boolean[][] oldState;\n private final boolean[][] newState;\n private final int numRows, numColumns;\n\n public LifeBoard(Seed seed) {\n numRows = seed.getNumRows();\n numColumns = seed.getNumColumns();\n oldState = new boolean[numRows][numColumns];\n newState = new boolean[numRows][numColumns];\n for (int row = 0; row &lt; seed.getNumRows(); row++) {\n System.arraycopy(seed.getSeed()[row], 0, oldState[row], 0, seed.getNumColumns());\n }\n }\n\n public void iterate() {\n updateCells();\n copyNewToOld();\n }\n\n private void copyNewToOld() {\n for (int row = 0; row &lt; numRows; row++) {\n System.arraycopy(newState[row], 0, oldState[row], 0, numColumns);\n }\n }\n\n public boolean updateCells() {\n Cell currentCell = new Cell(0, 0);\n for (currentCell.row = 0; currentCell.row &lt; numRows; currentCell.row++) {\n for (currentCell.column = 0; currentCell.column &lt; numColumns; currentCell.column++) {\n updateCell(currentCell);\n }\n }\n //return true while life is still evolving, when board is static, return false\n //feature not yet implemented\n return true;\n }\n\n public void updateCell(Cell cell) {\n final int numLivingNeighbors = numLivingNeighbors(cell);\n updateCellWithNeighbors(cell, numLivingNeighbors);\n }\n\n private int numLivingNeighbors(Cell cell) {\n int numLivingNeighbors = 0;\n for (Direction direction : Direction.values()) {\n if (isNeighborAlive(cell, direction)) {\n numLivingNeighbors++;\n }\n }\n return numLivingNeighbors;\n }\n\n private boolean isNeighborAlive(Cell cell, Direction direction) {\n final Cell neighborCell = cell.getNeighbor(direction);\n if (isInBounds(neighborCell)) {\n return isAlive(neighborCell);\n } else {\n return false;\n }\n }\n\n public boolean isInBounds(Cell cell) {\n final boolean isRowInBounds = (cell.row &gt;= 0) &amp;&amp; (cell.row &lt; numRows);\n final boolean isColumnInBounds = (cell.column &gt;= 0) &amp;&amp; (cell.column &lt; numColumns);\n return isRowInBounds &amp;&amp; isColumnInBounds;\n }\n\n private void updateCellWithNeighbors(Cell cell, int numLivingNeighbors) {\n //evaluate total of score against rules of the game\n //implimentation of game rules\n if (isAlive(cell)) {\n if (numLivingNeighbors &lt; 2) {\n clearCell(cell); //die of loneliness\n } else if (numLivingNeighbors &gt; 3) {\n clearCell(cell); //die of overcrowding\n } else {\n setCell(cell); //continue to live\n }\n } else if (numLivingNeighbors == 3) {\n setCell(cell);\n } else {\n clearCell(cell);\n }\n }\n\n private void setCell(Cell cell) {\n newState[cell.row][cell.column] = true;\n }\n\n private void clearCell(Cell cell) {\n newState[cell.row][cell.column] = false;\n }\n\n public boolean isAlive(Cell cell) {\n return isAlive(cell.row, cell.column);\n }\n\n public boolean isAlive(int row, int column) {\n return oldState[row][column];\n }\n\n public int getNumRows() {\n return numRows;\n }\n\n public int getNumColumns() {\n return numColumns;\n }\n\n}\n</code></pre>\n\n<p>First I have added a static nested class called <code>Cell</code>. This class is convenient because rows and columns go together. Putting these two things together into one object will simplify method signatures, reducing clutter. I also added a method which takes a direction and returns the neighbor in that direction. I thought the <code>Cell</code> class was a good place to put that because the method doesn't rely on any of the logic in the rest of the class.</p>\n\n<p>In the Direction Enum, I changed Top to Up and bottom to down, since up and down are more nearly directions than top and bottom. It seems like a small thing but having good names can really make coding easier.</p>\n\n<p>I changed the fields of the class. I removed <code>blankState</code> because it was never used. I got rid of <code>gameRunning</code> because a <code>LifeBoard</code> object shouldn't be responsible for keeping track of when it is running. I added <code>final int</code>s for the number of rows and columns so we would never have to look those up again.</p>\n\n<p>In the constructor, I got rid of the inner for loop, which was unnecessary, since you are copying the whole row at once instead of entry by entry.</p>\n\n<p>Next is my <code>iterate</code> method, which roughly replaces your <code>run</code> method. Except my <code>iterate</code> method does much less. It is not responsible for drawing or waiting for the next frame or looping indefinitely. It just populates the <code>newState</code> boolean array with its new values and then copies that to the <code>oldState</code> array. I have cleanly split the function into these two parts. The implementation of the copy method is simple.</p>\n\n<p>The <code>updateCells</code> method is easy to understand: I loop through all cells and update them one by one. Notice prefer a void <code>updateCell</code> method instead of having it return a boolean which I then use in an assignment with <code>newState</code>, which is the way you did it in <code>evaluateCells</code>. I am not sure if one is better, but at least the way I did it is another option.</p>\n\n<p><code>updateCell</code>, which is your equivalent of <code>evaluateCell</code> was cleanly broken in two peices. In the first I calculate the number of living neighbors of the given cell, and in the second I update the cell using that information.</p>\n\n<p>The <code>numLivingNeighbors</code> method shows you how to loop over the values of an <code>Enum</code>. You were asking about this. I think this is a fine way to do it. Notice how <code>numLivingNeighbors</code> calls <code>isNeighborAlive</code> and <code>isNeighborAlive</code> calls <code>isInBounds</code>. Doing it this way keeps the methods short and easy to understand which is a good thing.</p>\n\n<p>The last non-trivial method is <code>updateCellWithNeighbors</code> which still looks complicated, but the <code>if</code>s are a little simplier because I have used nesting. There is one branch for if the cell is alive and one for if it isn't. </p>\n\n<p>The remaining methods are just simple methods to make the syntax nicer.</p>\n\n<p>Overall, I thought the design was good. As you can see I didn't add any new classes or change the responsibilities of the classes except to make the main class responsible for controlling the <code>LifeBoard</code>. I thought the code was really good for someone six months in. I think the take home messages here is that it is good to choose good names for variables, it is good to break big functions down into many little functions, and java has a special for each for loop syntax you can use (this is the one you use to iterate over values of enums). If you have any questions ask.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-21T05:26:14.980", "Id": "31610", "ParentId": "31245", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T16:33:03.013", "Id": "31245", "Score": "6", "Tags": [ "java", "game-of-life" ], "Title": "Game of Life implementation ran in the terminal" }
31245
<p>The following program is intended to "watchdog" a child process, <em>and all subprocesses the child spawns</em>.</p> <p>The intended behavior is:</p> <ul> <li>A child process (as specified on the command line) is run in a dedicated process group.</li> <li>If that process exits, or if it stops producing heartbeat output, the entire process group is killed off and restarted. <ul> <li>But if the child exits successfully <em>and</em> has just printed a particular sentinel string, the job is done and the watchdog should just exit.</li> </ul></li> <li>If the watchdog process receives certain fatal signals (TERM, INT, QUIT) it is to pass them along to the monitored process group and then exit itself.</li> </ul> <p>I have endeavored to code this as defensively as possible, but I could use a second opinion particularly on the following aspects:</p> <ul> <li><p>Is this use of process groups safe and reliable? (This program will not be run as a background job in an interactive shell; however, it may be run from a <em>noninteractive</em> shell script with no controlling terminal.)</p></li> <li><p>Note the comment immediately above the pair of calls to <code>pselect</code>. Is my workaround actually reliable on all systems?</p></li> <li><p>Is the signal handling sufficiently defensive? How about the process creation code?</p></li> <li><p>Have I neglected any portability issues? (Assume POSIX.1-2001 + <code>strsignal</code>.)</p></li> </ul> <p></p> <pre><code>/* * Usage: watchdog worker args ... * Runs 'worker' and all its subprocesses in a dedicated process group. * If 'worker' exits, or if it produces no output (on either stdout or * stderr) for five minutes, the entire process group is killed off and * restarted. * * We consider 'worker' to be done with its work, and do not restart * it, if it exits successfully *and* the last six characters of its * output are exactly "\nDONE\n". */ /* The most exotic features this program requires are pselect(), which is in POSIX.1-2001, and strsignal(), which is only in POSIX.1-2008 (!) */ #define _POSIX_C_SOURCE 200809L #include &lt;sys/types.h&gt; #include &lt;sys/select.h&gt; #include &lt;sys/stat.h&gt; #include &lt;sys/wait.h&gt; #include &lt;errno.h&gt; #include &lt;fcntl.h&gt; #include &lt;limits.h&gt; #include &lt;signal.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;time.h&gt; #include &lt;unistd.h&gt; #ifdef __GNUC__ #define NORETURN void __attribute__((noreturn)) #else #define NORETURN void #endif #if !defined EWOULDBLOCK &amp;&amp; !defined EAGAIN #error "Neither EAGAIN nor EWOULDBLOCK is defined" #elif defined EWOULDBLOCK &amp;&amp; !defined EAGAIN #define EAGAIN EWOULDBLOCK #elif !defined EWOULDBLOCK &amp;&amp; defined EAGAIN #define EWOULDBLOCK EAGAIN #endif /* Called on the child side of fork(); report a system error and exit specially (this will cause the parent not to retry). Does not return. Deliberately ignores all errors. */ static NORETURN child_startup_err(int fd, const char *msg1, const char *msg2) { #define IGNORE_ERRORS(expr) if (expr) do {} while (0) const char *err = strerror(errno); IGNORE_ERRORS(write(fd, msg1, strlen(msg1))); if (msg2) { IGNORE_ERRORS(write(fd, ": ", 2)); IGNORE_ERRORS(write(fd, msg2, strlen(msg2))); } IGNORE_ERRORS(write(fd, ": ", 2)); IGNORE_ERRORS(write(fd, err, strlen(err))); IGNORE_ERRORS(write(fd, "\n", 1)); _exit(127); #undef IGNORE_ERRORS } static sigset_t original_sigmask; /* Called on the child side of a fork(). Does not return under any circumstances. Indicates low-level failures by writing error messages to the 'output_fd' and exiting specially. Relies on parent taking care to set every fd close-on-exec, since Linux still doesn't have closefrom(), sigh. */ static NORETURN child_startup(int devnull_fd, int output_fd, char **argv) { if (dup2(devnull_fd, 0) != 0) child_startup_err(output_fd, "&lt;child&gt;: setting stdin", 0); if (dup2(output_fd, 1) != 1) child_startup_err(output_fd, "&lt;child&gt;: setting stdout", 0); if (dup2(output_fd, 2) != 2) child_startup_err(output_fd, "&lt;child&gt;: setting stderr", 0); if (setpgid(0, 0)) child_startup_err(output_fd, "&lt;child&gt;: setpgid", 0); if (sigprocmask(SIG_SETMASK, &amp;original_sigmask, 0)) child_startup_err(output_fd, "&lt;child&gt;: reset sigmask", 0); execvp(argv[0], argv); child_startup_err(output_fd, argv[0], "execvp"); } struct child_state { pid_t pid; int out_fd; }; /* Parent-side child preparation work. Returns the child PID and the read end of a pipe connected to the child's stdout+stderr, or { -1, -1 } on failure. */ static struct child_state child_spawn(char **argv) { int opipe[2], spipe[2]; int devnull_fd; int flags; char syncbuf[1]; struct child_state rv = { -1, -1 }; /* 'opipe' will feed output from the child to the parent. We only want the read end of the output pipe to be nonblocking, but both ends should be close-on-exec. */ if (pipe(opipe)) { perror("creating output pipe"); return rv; } flags = fcntl(opipe[0], F_GETFL); if (flags == -1 || fcntl(opipe[0], F_SETFL, flags | O_NONBLOCK) == -1 || fcntl(opipe[0], F_SETFD, FD_CLOEXEC) == -1 || fcntl(opipe[1], F_SETFD, FD_CLOEXEC) == -1) { perror("setting output pipe to nonblocking + close-on-exec"); close(opipe[0]); close(opipe[1]); return rv; } /* 'devnull_fd' will be the child's stdin. */ devnull_fd = open("/dev/null", O_RDONLY); if (devnull_fd == -1 || fcntl(devnull_fd, F_SETFD, FD_CLOEXEC) == -1) { perror("/dev/null"); close(opipe[0]); close(opipe[1]); return rv; } /* 'spipe' is used to synchronize parent and child after the fork. */ if (pipe(spipe) || fcntl(spipe[0], F_SETFD, FD_CLOEXEC) == -1 || fcntl(spipe[1], F_SETFD, FD_CLOEXEC) == -1) { perror("creating synchronization pipe"); close(devnull_fd); close(opipe[0]); close(opipe[1]); return rv; } rv.pid = fork(); if (rv.pid == -1) { perror("fork"); close(spipe[0]); close(spipe[1]); close(devnull_fd); close(opipe[0]); close(opipe[1]); return rv; } if (rv.pid == 0) child_startup(devnull_fd, opipe[1], argv); /* does not return */ /* If we get here, we are the parent, and these file descriptors are no longer required. */ close(spipe[1]); close(devnull_fd); close(opipe[1]); /* Wait for the child to complete its setup and call execve() or _exit(). In either case, the read end of 'spipe' will be automatically closed in the child, and this read() call will return. */ if (read(spipe[0], syncbuf, 1) != 0) perror("synchronization pipe read"); close(spipe[0]); rv.out_fd = opipe[0]; return rv; } static void report_exit(pid_t exited_child, pid_t expected_child, int status) { /* special case: don't print anything if this is the expected child and it exited with code 127, because that will already have been covered by child_startup_err */ if (exited_child == expected_child &amp;&amp; WIFEXITED(status) &amp;&amp; WEXITSTATUS(status) == 127) return; if (exited_child == expected_child) fputs("monitored child ", stderr); else fprintf(stderr, "unexpected child %lu ", (unsigned long)exited_child); if (status == 0) fputs("exited successfully\n", stderr); else if (WIFEXITED(status)) fprintf(stderr, "exited unsuccessfully (code %u)\n", (unsigned)WEXITSTATUS(status)); else if (WIFSIGNALED(status)) fprintf(stderr, "killed by signal: %s%s\n", strsignal(WTERMSIG(status)), #ifdef WCOREDUMP WCOREDUMP(status) ? " (core dumped)" : #endif ""); else fprintf(stderr, "produced un-decodable wait status %04x\n", (unsigned) status); } /* Signal handler used in conjunction with pselect() in the main loop below. */ static volatile sig_atomic_t got_SIGHUP, got_SIGINT, got_SIGQUIT, got_SIGTERM, got_SIGXCPU, got_SIGCHLD; static void interrupt_signal(int signal) { switch (signal) { case SIGHUP: got_SIGHUP = 1; break; case SIGINT: got_SIGINT = 1; break; case SIGQUIT: got_SIGQUIT = 1; break; case SIGTERM: got_SIGTERM = 1; break; case SIGXCPU: got_SIGXCPU = 1; break; case SIGCHLD: got_SIGCHLD = 1; break; default: abort(); } } /* Terminate both this process and the monitored process group with the specified fatal signal. Does not return. */ static NORETURN exit_on_signal(int signo, const struct child_state *child) { sigset_t unblocker; if (child-&gt;pid &gt; 1) { if (kill(-child-&gt;pid, signo)) perror("killpg"); } else { if (child-&gt;pid != -1) { fprintf(stderr, "warning: cannot kill pgrp %ld\n", (long)child-&gt;pid); } } /* Flush output, since we're about to force an abnormal termination. */ fflush(0); /* Before raising the signal, we have to reset it to default behavior and unblock it, or nothing will happen. If any of the following system calls fail, there's no use reporting the error, just fall through to the abort(). */ sigemptyset(&amp;unblocker); sigaddset(&amp;unblocker, signo); signal(signo, SIG_DFL); sigprocmask(SIG_UNBLOCK, &amp;unblocker, 0); raise(signo); /* should not get here */ abort(); } /* Copy all output from 'fd' to our stdout. Record the last six characters of the cumulative output in 'donebuf'. */ static void process_output(int fd, char donebuf[6]) { char block[PIPE_BUF]; ssize_t count; char *p; size_t n; for (;;) { count = read(fd, block, sizeof block); if (count == 0) break; /* EOF */ if (count == -1) { if (errno == EINTR) continue; /* this shouldn't happen but let's be defensive */ /* Report the error, unless it's "would block", in which case we're done */ if (errno != EAGAIN &amp;&amp; errno != EWOULDBLOCK) perror("read"); break; } for (p = block; p &lt; block + count; ) { n = fwrite(p, 1, count - (p - block), stdout); if (n == 0) { perror("fwrite"); break; } p += n; } fflush(stdout); if (count &gt;= 6) memcpy(donebuf, block + count - 6, 6); else { /* When 0 &lt; count &lt; 6, we want to slide the existing contents of 'donebuf' down by 'count' positions and copy the entire block into place after them. Example: count = 2: ------v before [x][x][1][2][3][4] after [1][2][3][4][a][b] */ memmove(donebuf, donebuf + count, 6 - count); memcpy(donebuf + (6 - count), block, count); } } } int main(int argc, char **argv) { struct sigaction sa; sigset_t all_blocked, handled_unblocked; struct child_state child; fd_set readfds; int ready; struct timespec timeout, zero_timeout; int retries; int child_died, child_done; char donebuf[7]; if (argc &lt; 2) { fprintf(stderr, "usage: %s program-to-monitor args...\n", argv[0]); return 2; } /* Establish signal handlers before doing anything else. */ sigfillset(&amp;all_blocked); sigdelset(&amp;all_blocked, SIGABRT); sigdelset(&amp;all_blocked, SIGBUS); sigdelset(&amp;all_blocked, SIGFPE); sigdelset(&amp;all_blocked, SIGILL); sigdelset(&amp;all_blocked, SIGIOT); sigdelset(&amp;all_blocked, SIGSEGV); sigdelset(&amp;all_blocked, SIGSYS); sigdelset(&amp;all_blocked, SIGTRAP); if (sigprocmask(SIG_SETMASK, &amp;all_blocked, &amp;original_sigmask)) { perror("sigprocmask"); return 1; } memset(&amp;sa, 0, sizeof sa); memcpy(&amp;sa.sa_mask, &amp;all_blocked, sizeof(sigset_t)); sa.sa_handler = interrupt_signal; sa.sa_flags = 0; /* deliberate non-use of SA_RESTART; we want these signals to interrupt pselect() */ memcpy(&amp;handled_unblocked, &amp;all_blocked, sizeof(sigset_t)); sigdelset(&amp;handled_unblocked, SIGCHLD); if (sigaction(SIGCHLD, &amp;sa, 0)) { perror("sigaction(SIGCHLD)"); return 1; } /* These signals might have been ignored at a higher level, in which case we need to keep it that way */ #define maybe_establish_signal_handler(signo) do { \ struct sigaction osa; \ if (sigaction(signo, &amp;sa, &amp;osa)) { \ perror("sigaction(" #signo ")"); \ return 1; \ } \ if (osa.sa_handler == SIG_IGN) { \ if (sigaction(signo, &amp;osa, 0)) { \ perror("sigaction(" #signo ")"); \ return 1; \ } \ } else { \ sigdelset(&amp;handled_unblocked, signo); \ } \ } while (0) maybe_establish_signal_handler(SIGHUP); maybe_establish_signal_handler(SIGINT); maybe_establish_signal_handler(SIGQUIT); maybe_establish_signal_handler(SIGTERM); maybe_establish_signal_handler(SIGXCPU); /* Unlike select, pselect is guaranteed not to modify 'timeout'. */ timeout.tv_sec = 5 * 60; timeout.tv_nsec = 0; zero_timeout.tv_sec = 0; zero_timeout.tv_nsec = 0; retries = 0; do { memset(donebuf, 0, sizeof donebuf); child_died = 0; child_done = 0; if (retries &gt;= 10) { fputs("failed to start child 10 times; giving up\n", stderr); return 1; } child = child_spawn(argv+1); if (child.pid == -1) { retries++; continue; } do { FD_ZERO(&amp;readfds); FD_SET(child.out_fd, &amp;readfds); got_SIGHUP = 0; got_SIGINT = 0; got_SIGQUIT = 0; got_SIGTERM = 0; got_SIGXCPU = 0; got_SIGCHLD = 0; /* Some OSes' versions of pselect() will not unblock signals if any file descriptors are ready upon entry, even if some of the signals that would be unblocked are already pending. And a pipe at EOF (i.e. all writers have closed their end) is always ready to read. Therefore, if we don't take special care, we might get stuck in an infinite loop between pselect() and read(), with signals never getting delivered -- including the SIGCHLD we are waiting for, before closing our end of the pipe! The workaround is to do two pselect calls, the first of which is strictly a poll for signals. */ ready = pselect(0, 0, 0, 0, &amp;zero_timeout, &amp;handled_unblocked); if (ready == 0) ready = pselect(child.out_fd + 1, &amp;readfds, 0, 0, &amp;timeout, &amp;handled_unblocked); if (ready == -1 &amp;&amp; errno != EINTR) perror("pselect"); /* Order of operations here is critical. First read everything we can from the pipe; then check for SIGCHLD; then check for other signals. */ if (ready &gt; 0) /* We know by construction that there's only one fd that can be ready. */ process_output(child.out_fd, donebuf); if (got_SIGCHLD) /* It is necessary to loop through waitpid() until it either returns 0 or fails with ECHILD, otherwise we may miss exits. This should theoretically not be an issue since there *should* only be one child to wait for at any time, but let's be careful anyway. */ for (;;) { pid_t exited_child; int status; exited_child = waitpid((pid_t)-1, &amp;status, WNOHANG); if (exited_child == 0) break; if (exited_child == -1) { if (errno != ECHILD) perror("waitpid"); break; } report_exit(exited_child, child.pid, status); if (exited_child == child.pid) { /* Try one last time to read remaining output from the pipe. */ process_output(child.out_fd, donebuf); close(child.out_fd); child_died = 1; if (status == 0) child_done = !strcmp(donebuf, "\nDONE\n"); else { child_done = 0; if (WIFEXITED(status) &amp;&amp; WEXITSTATUS(status) == 127) /* startup failure after fork() */ retries++; } /* Zot the process group, in case there's anything still hanging around. */ if (child.pid &gt; 1) kill(-child.pid, SIGTERM); child.out_fd = -1; child.pid = -1; } } /* If we have received a signal that should cause us to exit, pass the signal along to the entire child process group if the child is running, then unblock and reraise that signal. */ if (got_SIGQUIT) exit_on_signal(SIGQUIT, &amp;child); if (got_SIGXCPU) exit_on_signal(SIGXCPU, &amp;child); if (got_SIGINT) exit_on_signal(SIGINT, &amp;child); if (got_SIGHUP) exit_on_signal(SIGHUP, &amp;child); if (got_SIGTERM) exit_on_signal(SIGTERM, &amp;child); /* If we timed out waiting for I/O and the child process is still running, kill it and loop; the subsequent iteration will detect termination and restart it. */ if (ready == 0 &amp;&amp; !child_died) kill(-child.pid, SIGTERM); } while (!child_died); } while (!child_done); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T20:00:02.170", "Id": "49751", "Score": "0", "body": "You're likely already aware of it, and it doesn't monitor quite as aggressively as your program does, but it might be worth looking at daemontools: http://cr.yp.to/daemontools.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T20:14:32.963", "Id": "49752", "Score": "0", "body": "@Corbin Yeah, I'm already aware of it. The larger situation is specialized enough that I feel safest writing my own watchdog that does exactly what I need it to do." } ]
[ { "body": "<p>I am not familiar enough with process control to find any of the problems you seek, so treat this as a general review, for what it is worth, starting from the top:</p>\n\n<hr>\n\n<p>I don't know what advantage your <code>IGNORE_ERRORS</code> macro has over a simple\n<code>(void)</code> cast for an ignored return value.</p>\n\n<p>I imagine you have a good reason for using <code>_exit</code> in <code>child_startup_err</code>\nrather than the normal <code>exit</code>, but it escapes me at the moment.</p>\n\n<p>Your <code>child_startup</code> errors are logged to <code>output_fd</code> rather than to <code>stderr</code>.\nI'm not sure if this is an issue but maybe I'll come back to it...</p>\n\n<p>Why do you set <code>opipe[1]</code> and <code>devnull_fd</code> to close-on-exec. These are\ncreated and duped for the child stdio descriptors, so why would you want them\nclosed on exec of the child process? And is there an advantage in assigning <code>/dev/null</code> to stdin instead of just closing it?</p>\n\n<p><code>child_spawn</code> could benefit from a <code>goto</code> for failure handling. Also I don't\nsee the point of the synchronization pipe between parent and child. It is\nclever, but what does it achieve? Your parent times-out if it fails to get a\nheartbeat every 5 minutes but there's little risk that the child will not have\nstarted up in that time.</p>\n\n<p>In <code>exit_on_signal</code>, which re-raise the signal instead of just exiting?</p>\n\n<p>The endless loop in <code>process_output</code>:</p>\n\n<pre><code>for (;;) {\n count = read(fd, block, sizeof block);\n if (count == 0)\n break; /* EOF */\n</code></pre>\n\n<p>might be better expressed as:</p>\n\n<pre><code>while ((count = read(fd, block, sizeof block)) != 0) {\n</code></pre>\n\n<p>The subordinate loop:</p>\n\n<pre><code> for (p = block; p &lt; block + count; ) {\n n = fwrite(p, 1, count - (p - block), stdout);\n if (n == 0) {\n perror(\"fwrite\");\n break;\n }\n p += n;\n }\n</code></pre>\n\n<p>looks unnecessary. You are using buffered stdio so a single <code>fwrite</code> should\nsuffice. And if the write fails to write all bytes requested there was an\nerror (not just if it returns 0).</p>\n\n<p>The embedded constant 6 in the function might be better replaced by a #define</p>\n\n<p>In <code>main</code>:</p>\n\n<p>It is rather big. It seems like some functionality could be extracted to\nfunctions. You have loops nested 3 deep...</p>\n\n<p>Many variables could be defined at or nearer to their place of first use.</p>\n\n<p>I'd rather see all <code>memcpy</code>s use the size of the target buffer\nrather than the size of the type.</p>\n\n<p>Could the condition you are guarding against with the two <code>pselect</code> calls\noccur between the calls?</p>\n\n<p>When a <code>SIGCHILD</code> signal has occurred, why loop calling <code>waitpid</code> with <code>WNOHANG</code>\ninstead of just waiting in <code>waitpid</code> for the termination to conclude? Does\nthis really lessen the chance of missing an exit - does that possibility\nreally exist?</p>\n\n<p>Also I don't see the advantage in the 'sentinel' sent by the child as opposed\nto it just exiting cleanly (<code>EXIT_SUCCESS</code>). The sentinel just complicates the\ncode. And why use 127 for failure and not <code>EXIT_FAILURE</code>?</p>\n\n<p>You are checking the child pid against the expected pid, but you only have one\nchild, so how would you get the wrong pid? Is there a way the pid can be\nwrong (do children of the child get propagated?)?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T14:48:06.980", "Id": "60829", "Score": "0", "body": "This is helpful. I wish I could respond point-by-point, because several of the things you've called out as questionable are necessary. For instance, on the child side of a `fork`, one must not touch `stdout`, hence nearly all the oddities of `child_startup(_err)`. The sentinel string is needed because the specific program being monitored is not entirely under my control; I can ensure that it produces the sentinel under exactly the right conditions, but its exit code is meaningless. 127 instead of `EXIT_FAILURE` is to distinguish failure before `exec` from failure afterward. And so on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T16:08:34.443", "Id": "60851", "Score": "1", "body": "Perhaps you would edit the answer above to correct things (put your comments in brackets perhaps?) . I thought your code was excellent and had trouble finding anything wrong - so some of my points were more indicative of my not understanding than problems in the code :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T03:14:24.813", "Id": "36939", "ParentId": "31252", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T19:23:07.703", "Id": "31252", "Score": "5", "Tags": [ "c", "unix", "portability", "child-process" ], "Title": "Portability and \"dark corner\" gotchas in this \"watchdog\" program" }
31252
<p>I just completed K&amp;R (2nd Ed.) ex 1-18. I'm fairly new to C, but have had experience in other languages (Perl, C++, Java, Common Lisp, PHP, etc) and really want to learn the C idiom as opposed to translating the idioms I already know.</p> <p>What do you think about this approach to 1-18?</p> <pre><code>/* Exercise 1-18 in K&amp;R 2nd Edition Removes trailing blanks &amp; tabs &amp; blank lines from each line of input Written by Z. Bornheimer (provided as is without warranty). */ #include &lt;stdio.h&gt; #define MAXLINE 1000 /* removes trailing blanks and tabs...deletes null lines */ main() { int len; /* current line length */ int i = -1, j; /* two counters */ int c; /* current char */ char line[MAXLINE]; /* current input line */ while ((c=getchar()) != EOF) { line[++i] = c; if (c == '\n') { j = i + 1; while (line[--j] == ' ' || line[j] == '\n' || line[j] == '\t') line[j] = '\0'; printf("%s", line); for (j = 0; j &lt;= i; j++) line[j] = '\0'; i = -1; } } return 0; } </code></pre> <p><a href="https://github.com/zachbornheimer/programming-exercises/blob/master/c/1-18.c" rel="nofollow">https://github.com/zachbornheimer/programming-exercises/blob/master/c/1-18.c</a></p> <p>Thank you for your help!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T16:05:29.423", "Id": "49848", "Score": "0", "body": "For those of us who don't have K&R handy, please state the exercise question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T16:07:30.457", "Id": "49850", "Score": "0", "body": "The Exercise goal is stated on the second line of comments: Remove trailing blanks & tabs & blank lines from each line of input" } ]
[ { "body": "<p>First the obvious: if a line is too long, your program will seriously fail (unknown memory gets overwritten, or the program crashes). Without dynamic memory allocation, I see no way to fix it. However, you could improve the situation significantly.</p>\n\n<p>Since you're reading the input character by character, and you need to remove only trailing blanks and tabs, you can printout any character that is not one of these, and put only blanks and tabs in the string. Once you encounter another non-(blank or tab), you printout that string, and reset it back to a blank string. If <code>\\n</code> is encountered, you write it out without the content of the string, as these are the trailing blanks and tabs.</p>\n\n<p>You'll also need to keep track of printout and, in case nothing was printed in the line (i.e., there were no non-(blanks or tabs)), you also skip printing of <code>\\n</code>, to delete the entirely blank lines.</p>\n\n<p>If you had to remove only the trailing blanks (or only the trailing tabs), you wouldn't need a string at all -- just a counter of how many of those you've encountered. Unfortunately, your task is a bit more complex, and so is a solution.</p>\n\n<p>My modification does not solve the \"line is too long\" problem, but it does reduce it to \"a line has more than 1000 blanks+tabs in a row\" problem.</p>\n\n<p>Now, I give you some comments on your actual code.</p>\n\n<p>First, I have one simple remark:</p>\n\n<pre><code> int i = -1, j; /* two counters */\n ...\n while ((c=getchar()) != EOF) {\n line[++i] = c;\n if (c == '\\n') {\n j = i + 1;\n ...\n i = -1;\n</code></pre>\n\n<p>I think this would be more natural if <code>i</code> was the next character to be written to (instead of the last), i.e.,</p>\n\n<pre><code> int i = 0, j; /* two counters */\n ...\n while ((c=getchar()) != EOF) {\n line[i++] = c;\n if (c == '\\n') {\n j = i;\n ...\n i = 0;\n</code></pre>\n\n<p>I think that this is also more customary approach when working on strings, since after the loop you often get to do something like <code>s[i] = '\\0'</code> instead of <code>s[i+1] = '\\0'</code>. This also makes it possible to use the unsigned variable, although I don't see much practical use for that.</p>\n\n<p>Second, this is unnecessary:</p>\n\n<pre><code> while (line[--j] == ' ' || line[j] == '\\n' || line[j] == '\\t')\n line[j] = '\\0';\n</code></pre>\n\n<p>You simply need to remember the value of <code>i</code> when you encounter blank or tab the first time after you encountered a character that is not one of these. You can do so easily by keeping the old value of <code>c</code> in a variable, let's call it <code>oc</code>:</p>\n\n<pre><code> oc = 'x'; /* anything non-(blank or tab), so it works properly for the empty lines */\n while ((c=getchar()) != EOF) {\n line[i++] = c;\n if ((c == ' ' || c == '\\t') &amp;&amp; (oc != ' ' &amp;&amp; oc != '\\t'))\n start_of_trailing_blanks_and_tabs = i;\n ...\n c = 'x';\n }\n</code></pre>\n\n<p>You could event replace <code>oc</code> by a properly set Boolean flag (in C, this is, of course, of type <code>int</code>).</p>\n\n<p>And, as my last remark, this is also unnecessary:</p>\n\n<pre><code> for (j = 0; j &lt;= i; j++)\n line[j] = '\\0';\n</code></pre>\n\n<p>You set the end of string elsewhere in the code, and it's only the first <code>\\0</code> that counts.</p>\n\n<p>I also have one suggestion on the style: I'd make a function to identify these characters, or just use <a href=\"http://www.tutorialspoint.com/c_standard_library/c_function_isspace.htm\" rel=\"nofollow\"><code>isspace()</code></a> from the <code>ctype</code> library. The later is not exactly what you need, as it also identifies the feed and the carriage return, but I think it is in the spirit of what is asked in the exercise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T14:55:41.797", "Id": "49785", "Score": "0", "body": "Awesome! About your paradigm, why would it be better to keep track of blanks/tabs as opposed to removing them off the string. Is that so it doesn't have to store the whole string in memory? If that's the case, would it be better to just use `putchar(c)` and buffer the characters then print them, if necessary, if a non-(' '|'\\n'|'\\t') was entered?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T15:21:19.090", "Id": "49786", "Score": "1", "body": "Yes, the reason is exactly to reduce the amount of data being saved, thus making it harder to reach overflow during a real-life use. This should, IMO, also increase the speed of your program (I haven't tested this!). As for `putchar`, I wouldn't expect buffering to be the aimed solution in such an early exercise. Also, I know of no portable buffer-purging function in C. You have `fpurge` and `__fpurge`, but neither are standard nor portable (see [here](http://manpages.courier-mta.org/htmlman3/fpurge.3.html))." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T01:01:05.190", "Id": "31264", "ParentId": "31262", "Score": "3" } }, { "body": "<p>I think your basic approach is wrong. You have written a program that does what the exercise wants, but the program mixes I/O with program logic in <code>main</code>. Most programming tasks in C (and similar languages) come down to writing functions - very little work is usually done in <code>main</code>. So you should write a function <code>get_line</code> that gets a line from <code>stdin</code> into a buffer and strips trailing whitespace. The caller can then print each line returned. So <code>main</code> would be something like:</p>\n\n<pre><code>int main(void) \n{\n char buf[MAXLINE];\n while (get_line(buf, sizeof buf)) {\n if (buf[0] != '\\0') {\n printf(\"%s\\n\", buf);\n }\n }\n}\n</code></pre>\n\n<p>So here we have <code>get_line</code> returning NULL if it reaches EOF on a non-empty line and otherwise returning the input buffer. In <code>main</code> we then check whether the line is empty and print it if not. <code>get_line</code> should check to make sure it does not write beyond the end of its buffer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T16:06:06.467", "Id": "49849", "Score": "0", "body": "Thanks for the tip. I consciously decided to use a bottom-up approach here because of the simplicity of the task, for something more complex, I probably would have used a top-down approach. I understand using top-down for code maintainability, but wouldn't it create some superfluous overhead for the program?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T18:59:17.390", "Id": "49873", "Score": "0", "body": "Overhead from the function call? It is not an issue. The compiler will optimise it away if you enable optimisation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-22T14:10:28.710", "Id": "50499", "Score": "0", "body": "Cool. Thanks for the tip. I found Linus Torvals's Style Guide for the Kernel and he says something similar. Thanks!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T15:37:03.210", "Id": "31316", "ParentId": "31262", "Score": "1" } } ]
{ "AcceptedAnswerId": "31264", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T23:48:02.600", "Id": "31262", "Score": "3", "Tags": [ "c" ], "Title": "Style and Suggestions for K&R2 1-18" }
31262
<p>This is one of my first real apps I've made with javascript(jQuery) so I know my approach probably isn't the best and my lengthy code shows. I created this simple app that spits out what customers can expect to pay if they purchase our software, but it has a TON of price points and with my limited knowledge this was the only way I could think of to do it.</p> <p><a href="http://codepen.io/ajrdesign/pen/BdHrl" rel="nofollow">http://codepen.io/ajrdesign/pen/BdHrl</a></p> <p>JS:</p> <pre><code>/* I'm a HUGE js noob so if there is a better DRY way to do this PLEASE let me know. */ $(document).ready(function() { /* COST ARRAYS */ var standardCost = [179, 159, 139, 129, 119, 109, 99, 89, 79, 69]; var standardMaintenance = [228, 198, 168, 156, 144, 132, 120, 108, 96, 84]; var standardSavings = [0, 20, 40, 50, 60, 70, 80, 90, 100, 110]; var standardMaintenanceSavings = [0, 30, 60, 72, 84, 96, 108, 120, 132, 144]; var cadCost = [239, 199, 179, 159, 149, 129, 119, 109, 99, 89]; var cadMaintenance = [298, 248, 212, 190, 178, 156, 144, 132, 120, 108]; var cadSavings = [0, 30, 60, 80, 90, 100, 110, 120, 130, 140]; var cadMaintenanceSavings = [0, 50, 86, 108, 120, 142, 154, 166, 178, 190]; var extremeCost = [299, 249, 219, 199, 179, 159, 149, 129, 119, 109]; var extremeMaintenance = [368, 308, 268, 238, 214, 192, 180, 156, 144, 132]; var extremeSavings = [0, 50, 80, 100, 120, 140, 150, 170, 180, 190]; var extremeMaintenanceSavings = [0, 60, 100, 130, 154, 166, 188, 212, 224, 236]; var calculateCosts = function() { var value = $("#seats").val(); var cost = standardCost[0]; var savings = 0; var edition = $("#edition").val(); /* STANDARD VALUES */ if(value &gt; 4 &amp;&amp; edition === "standard") { var cost = standardCost[1]; var savings = standardSavings[1]; } if(value &gt; 9 &amp;&amp; edition === "standard") { var cost = standardCost[2]; var savings = standardSavings[2]; } if(value &gt; 24 &amp;&amp; edition === "standard") { var cost = standardCost[3]; var savings = standardSavings[3]; } if(value &gt; 49 &amp;&amp; edition === "standard") { var cost = standardCost[4]; var savings = standardSavings[4]; } if(value &gt; 99 &amp;&amp; edition === "standard") { var cost = standardCost[5]; var savings = standardSavings[5]; } if(value &gt; 199 &amp;&amp; edition === "standard") { var cost = standardCost[6]; var savings = standardSavings[6]; } if(value &gt; 349 &amp;&amp; edition === "standard") { var cost = standardCost[7]; var savings = standardSavings[7]; } if(value &gt; 499 &amp;&amp; edition === "standard") { var cost = standardCost[8]; var savings = standardSavings[8]; } if(value &gt; 999 &amp;&amp; edition === "standard") { var cost = standardCost[9]; var savings = standardSavings[9]; } /* ==== Standard with maintenance =====*/ if(edition === "standard" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = standardMaintenance[0]; var savings = standardMaintenanceSavings[0]; } if(value &gt; 4 &amp;&amp; edition === "standard" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = standardMaintenance[1]; var savings = standardMaintenanceSavings[1]; } if(value &gt; 9 &amp;&amp; edition === "standard" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = standardMaintenance[2]; var savings = standardMaintenanceSavings[2]; } if(value &gt; 24 &amp;&amp; edition === "standard" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = standardMaintenance[3]; var savings = standardMaintenanceSavings[3]; } if(value &gt; 49 &amp;&amp; edition === "standard" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = standardMaintenance[4]; var savings = standardMaintenanceSavings[4]; } if(value &gt; 99 &amp;&amp; edition === "standard" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = standardMaintenance[5]; var savings = standardMaintenanceSavings[5]; } if(value &gt; 199 &amp;&amp; edition === "standard" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = standardMaintenance[6]; var savings = standardMaintenanceSavings[6]; } if(value &gt; 349 &amp;&amp; edition === "standard" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = standardMaintenance[7]; var savings = standardMaintenanceSavings[7]; } if(value &gt; 499 &amp;&amp; edition === "standard" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = standardMaintenance[8]; var savings = standardMaintenanceSavings[8]; } if(value &gt; 999 &amp;&amp; edition === "standard" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = standardMaintenance[9]; var savings = standardMaintenanceSavings[9]; } /* CAD VALUES */ if(edition === "cad") { var cost = cadCost[0]; var savings = cadSavings[0]; } if(value &gt; 4 &amp;&amp; edition === "cad") { var cost = cadCost[1]; var savings = cadSavings[1]; } if(value &gt; 9 &amp;&amp; edition === "cad") { var cost = cadCost[2]; var savings = cadSavings[2]; } if(value &gt; 24 &amp;&amp; edition === "cad") { var cost = cadCost[3]; var savings = cadSavings[3]; } if(value &gt; 49 &amp;&amp; edition === "cad") { var cost = cadCost[4]; var savings = cadSavings[4]; } if(value &gt; 99 &amp;&amp; edition === "cad") { var cost = cadCost[5]; var savings = cadSavings[5]; } if(value &gt; 199 &amp;&amp; edition === "cad") { var cost = cadCost[6]; var savings = cadSavings[6]; } if(value &gt; 349 &amp;&amp; edition === "cad") { var cost = cadCost[7]; var savings = cadSavings[7]; } if(value &gt; 499 &amp;&amp; edition === "cad") { var cost = cadCost[8]; var savings = cadSavings[8]; } if(value &gt; 999 &amp;&amp; edition === "cad") { var cost = cadCost[9]; var savings = cadSavings[9]; } /* ==== CAD with maintenance =====*/ if(edition === "cad" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = cadMaintenance[0]; var savings = cadMaintenanceSavings[0]; } if(value &gt; 4 &amp;&amp; edition === "cad" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = cadMaintenance[1]; var savings = cadMaintenanceSavings[1]; } if(value &gt; 9 &amp;&amp; edition === "cad" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = cadMaintenance[2]; var savings = cadMaintenanceSavings[2]; } if(value &gt; 24 &amp;&amp; edition === "cad" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = cadMaintenance[3]; var savings = cadMaintenanceSavings[3]; } if(value &gt; 49 &amp;&amp; edition === "cad" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = cadMaintenance[4]; var savings = cadMaintenanceSavings[4]; } if(value &gt; 99 &amp;&amp; edition === "cad" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = cadMaintenance[5]; var savings = cadMaintenanceSavings[5]; } if(value &gt; 199 &amp;&amp; edition === "cad" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = cadMaintenance[6]; var savings = cadMaintenanceSavings[6]; } if(value &gt; 349 &amp;&amp; edition === "cad" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = cadMaintenance[7]; var savings = cadMaintenanceSavings[7]; } if(value &gt; 499 &amp;&amp; edition === "cad" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = cadMaintenance[8]; var savings = cadMaintenanceSavings[8]; } if(value &gt; 999 &amp;&amp; edition === "cad" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = cadMaintenance[9]; var savings = cadMaintenanceSavings[9]; } /* EXTRME VALUES */ if(edition === "extreme") { var cost = extremeCost[0]; var savings = extremeSavings[0]; } if(value &gt; 4 &amp;&amp; edition === "extreme") { var cost = extremeCost[1]; var savings = extremeSavings[1]; } if(value &gt; 9 &amp;&amp; edition === "extreme") { var cost = extremeCost[2]; var savings = extremeSavings[2]; } if(value &gt; 24 &amp;&amp; edition === "extreme") { var cost = extremeCost[3]; var savings = extremeSavings[3]; } if(value &gt; 49 &amp;&amp; edition === "extreme") { var cost = extremeCost[4]; var savings = extremeSavings[4]; } if(value &gt; 99 &amp;&amp; edition === "extreme") { var cost = extremeCost[5]; var savings = extremeSavings[5]; } if(value &gt; 199 &amp;&amp; edition === "extreme") { var cost = extremeCost[6]; var savings = extremeSavings[6]; } if(value &gt; 349 &amp;&amp; edition === "extreme") { var cost = extremeCost[7]; var savings = extremeSavings[7]; } if(value &gt; 499 &amp;&amp; edition === "extreme") { var cost = extremeCost[8]; var savings = extremeSavings[8]; } if(value &gt; 999 &amp;&amp; edition === "extreme") { var cost = extremeCost[9]; var savings = extremeSavings[9]; } /* ==== EXTREME with maintenance =====*/ if(edition === "extreme" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = extremeMaintenance[0]; var savings = extremeMaintenanceSavings[0]; } if(value &gt; 4 &amp;&amp; edition === "extreme" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = extremeMaintenance[1]; var savings = extremeMaintenanceSavings[1]; } if(value &gt; 9 &amp;&amp; edition === "extreme" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = extremeMaintenance[2]; var savings = extremeMaintenanceSavings[2]; } if(value &gt; 24 &amp;&amp; edition === "extreme" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = extremeMaintenance[3]; var savings = extremeMaintenanceSavings[3]; } if(value &gt; 49 &amp;&amp; edition === "extreme" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = extremeMaintenance[4]; var savings = extremeMaintenanceSavings[4]; } if(value &gt; 99 &amp;&amp; edition === "extreme" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = extremeMaintenance[5]; var savings = extremeMaintenanceSavings[5]; } if(value &gt; 199 &amp;&amp; edition === "extreme" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = extremeMaintenance[6]; var savings = extremeMaintenanceSavings[6]; } if(value &gt; 349 &amp;&amp; edition === "extreme" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = extremeMaintenance[7]; var savings = extremeMaintenanceSavings[7]; } if(value &gt; 499 &amp;&amp; edition === "extreme" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = extremeMaintenance[8]; var savings = extremeMaintenanceSavings[8]; } if(value &gt; 999 &amp;&amp; edition === "extreme" &amp;&amp; $('#checkMaintenance').is(':checked')) { var cost = extremeMaintenance[9]; var savings = extremeMaintenanceSavings[9]; } $("#totalCost").text("$" + value * cost); $("#perSeat").text("$" + cost); $("#savings").text("$" + value*savings); }; /* Triggers so it caluclates on both input and select/checkmark */ $("#priceForm").keyup(calculateCosts); $("#priceForm").change(calculateCosts); }); </code></pre> <p>HTML:</p> <pre><code>&lt;link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700' rel='stylesheet' type='text/css'&gt; &lt;h4&gt;I'm looking to buy:&lt;/h4&gt; &lt;div id="priceForm"&gt; &lt;input id="seats" maxlength="6" id="numberOfSeats" type="text" value="1"/&gt; &lt;p&gt;seats of&lt;/p&gt; &lt;select id="edition" name="carlist" form="carform"&gt; &lt;option value="standard"&gt;Standard&lt;/option&gt; &lt;option value="cad"&gt;CAD&lt;/option&gt; &lt;option value="extreme"&gt;eXtreme&lt;/option&gt; &lt;/select&gt; &lt;br /&gt; &lt;label for="maintenance"&gt;Maintenance&lt;/label&gt; &lt;input id="checkMaintenance" type="checkbox" name="maintenance" value="maintenance"&gt; &lt;/div&gt; &lt;hr /&gt; &lt;div class="costs-container"&gt; &lt;h4&gt;Cost Per Seat:&lt;/h4&gt; &lt;p id="perSeat"&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class="costs-container"&gt; &lt;h4&gt;My Total Cost:&lt;/h4&gt; &lt;p id="totalCost"&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class="costs-container"&gt; &lt;h4&gt;My Savings:&lt;/h4&gt; &lt;p id="savings"&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p>Everything functions fine but I just feel like there's gotta be a better way to do this type of thing. Can anyone point me in the right direction? What am I not thinking about?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T02:36:38.100", "Id": "49771", "Score": "1", "body": "I'll gladly retract my downvote (and perhaps even turn it into an upvote) if/when this post gets edited with actual code." } ]
[ { "body": "<p>Step 1: reorganize your variables, nested in a manner resembling the tests you need to do.</p>\n\n<pre><code>var prices = {\n standard: {\n cost: { normal: [ 179 , 159 , 139 , 129 , 119 , 109 , 99 , 89 , 79 , 69 ],\n maintenance: [ 228 , 198 , 168 , 156 , 144 , 132 , 120 , 108 , 96 , 84 ] },\n savings: { normal: [ 0 , 20 , 40 , 50 , 60 , 70 , 80 , 90 , 100 , 110 ],\n maintenance: [ 0 , 30 , 60 , 72 , 84 , 96 , 108 , 120 , 132 , 144 ] }\n }, cad: {\n cost: { normal: [ 239 , 199 , 179 , 159 , 149 , 129 , 119 , 109 , 99 , 89 ],\n maintenance: [ 298 , 248 , 212 , 190 , 178 , 156 , 144 , 132 , 120 , 108 ] },\n savings: { normal: [ 0 , 30 , 60 , 80 , 90 , 100 , 110 , 120 , 130 , 140 ],\n maintenance: [ 0 , 50 , 86 , 108 , 120 , 142 , 154 , 166 , 178 , 190 ] }\n }, extreme: {\n cost: { normal: [ 299 , 249 , 219 , 199 , 179 , 159 , 149 , 129 , 119 , 109 ],\n maintenance: [ 368 , 308 , 268 , 238 , 214 , 192 , 180 , 156 , 144 , 132 ] },\n savings: { normal: [ 0 , 50 , 80 , 100 , 120 , 140 , 150 , 170 , 180 , 190 ],\n maintenance: [ 0 , 60 , 100 , 130 , 154 , 166 , 188 , 212 , 224 , 236 ] }\n }\n};\n</code></pre>\n\n<p>Step 2: consolidate your threshold tests</p>\n\n<pre><code>var thresholds = [ 4, 9, 24, 99, 199, 349, 499, 999 ];\n// this function could be optimized, using a binary search rather than linear.\n// However, it's fixed length, so you don't really need to worry.\nvar getIndexForThreshold = function(value) {\n var l = thresholds.length;\n for (var i = 0; i &lt; l; i++) {\n if (value &lt;= thresholds[i]) { return i; }\n }\n return l;\n};\n</code></pre>\n\n<p>Step 3: put it all together</p>\n\n<pre><code>var calculateCosts = function() {\n\n var value = $(\"#seats\").val();\n var edition = $(\"#edition\").val();\n var maintenance = $('#checkMaintenance').is(':checked') ? 'maintenance' : 'normal';\n\n // These 3 lines here replace the 20-30 if statements in the original implementation\n var thresholdIndex = getIndexForThreshold(value);\n var cost = prices[edition].cost[maintenance][thresholdIndex];\n var savings = prices[edition].savings[maintenance][thresholdIndex];\n\n $(\"#totalCost\").text(\"$\" + value * cost);\n $(\"#perSeat\").text(\"$\" + cost);\n $(\"#savings\").text(\"$\" + value*savings);\n };\n\n /*\n Triggers so it caluclates on both input and select/checkmark\n */\n $(\"#priceForm\").on('keyup change', calculateCosts);\n});\n</code></pre>\n\n<p><a href=\"http://codepen.io/anon/pen/Dvcwe\" rel=\"nofollow\">http://codepen.io/anon/pen/Dvcwe</a></p>\n\n<p>A few final comments: don't declare the same variable name more than once. Use JSHint. Read \"Javascript: The good parts\". Cache your jquery objects. Avoid using IDs, unless you can ensure uniqueness.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T06:20:25.647", "Id": "49779", "Score": "0", "body": "Thanks I'll be sifting through this to see if I can make sense of it all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T11:30:33.747", "Id": "49783", "Score": "0", "body": "Sorry, [we hate fun](http://blog.stackoverflow.com/2010/01/stack-overflow-where-we-hate-fun/)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T01:11:09.363", "Id": "31266", "ParentId": "31263", "Score": "2" } } ]
{ "AcceptedAnswerId": "31266", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T00:47:10.927", "Id": "31263", "Score": "1", "Tags": [ "javascript", "jquery", "form" ], "Title": "Is there a DRYer way to create this jquery quote generator?" }
31263
<p>I am facing a issue with an API to handle dates in Java. I am not a very experienced programmer and my English is very bad.</p> <h2>Problem</h2> <p>I'm working in a large project with many subsystems, and I want to make a Date Utility library to manage all dates in the system.</p> <h2>Requirements</h2> <h3>Platform</h3> <ul> <li>The front end is a JSF page with <code>RichFaces</code></li> <li>The application generate reports with <code>JasperReports</code></li> <li>The back end is a Spring 3.1 Application</li> <li>Is desirable to support <code>Calendar</code> and <code>XMLGregorianCalendar</code> (for Jaxb2 Serialization)</li> </ul> <h3>Business Logic</h3> <ul> <li>The system <strong>must</strong> support six types of dates: <ul> <li>Short date format: dd-MM-yy </li> <li>Date format: dd-MM-yyyy </li> <li>Time format (only hours and minutes): HH:mm </li> <li>Time and date: dd-MM-yyyy HH:mm </li> <li>Time and short date: dd-MM-yy HH:mm</li> </ul></li> <li>The consistency is the most important thing in the design</li> </ul> <p>The long format is for details, and the short is for grids and places with little space.</p> <h3>API</h3> <pre><code>// Format using dd-MM-yy public String asShortDate(@Nullable Date date) ; // Parse using dd-MM-yyy public Date parseShortDate(@Nullable String string) throws ParseException; // Format using dd-MM-yyyy public String asDate(@Nullable Date date); // Parse using dd-MM-yyyy public Date parseDate(@Nullable String string) throws ParseException; // Format using HH:mm public String asTime(@Nullable Date date); // Parse using HH:mm public Date parseTime(@Nullable String string) throws ParseException; // Format using dd-MM-yyyy HH:mm public String asDateTime(@Nullable Date date); // Parse using dd-MM-yyyy HH:mm public Date parseDateTime(@Nullable String string) throws ParseException; // Format using dd-MM-yy HH:mm public String asShortDateTime(@Nullable Date date) ; // Parse using dd-MM-yy HH:mm public Date parseShortDateTime(@Nullable String string) throws ParseException; </code></pre> <h3>Parser and Formatter</h3> <pre><code>protected synchronized String dateToString(Date date, String format) { if (date == null) { return EMPTY_STRING; } return getFormat(format).format(date); } /** * @param string * @return * @throws ParseException */ protected synchronized Date stringToDate(String string, String format) throws ParseException { if (string == null || EMPTY_STRING.equals(string)) { return null; } SimpleDateFormat sdf = getFormat(format); ParsePosition psp = new ParsePosition(0); if (string.length() != format.length()) { throw new ParseException("Imposible parsear", 0); } Date toRet = sdf.parse(string, psp); if (psp.getIndex() != string.length()) { throw new ParseException("Imposible parsear", psp.getIndex()); } return toRet; } /** * Provee un formato * * @param format * @return */ private SimpleDateFormat getFormat(String format) { if (!initialized) { init(); } if (!formats.containsKey(format)) { throw new IllegalArgumentException("Unknow format " + format); } return formats.get(format); } </code></pre> <h3>Other</h3> <pre><code>private synchronized void init() { if (initialized) { return; } initialized = true; formats = new HashMap&lt;String, SimpleDateFormat&gt;(5); formats.put(DATE_FORMAT, new SimpleDateFormat(DATE_FORMAT)); formats.put(DATE_SHORT_FORMAT, new SimpleDateFormat(DATE_SHORT_FORMAT)); formats.put(TIME_FORMAT, new SimpleDateFormat(TIME_FORMAT)); formats.put(DATETIME_FORMAT, new SimpleDateFormat(DATETIME_FORMAT)); formats.put(DATETIME_SHORT_FORMAT, new SimpleDateFormat( DATETIME_SHORT_FORMAT)); for (SimpleDateFormat sdf : formats.values()) { sdf.setLenient(false); } } </code></pre> <h3>Considerations</h3> <ul> <li>I made the methods <code>stringToDate</code>, <code>dateToString</code> and init as synchronized because <code>SimpleDateFormat</code> is not thread-safe, and I only want one initialization.</li> <li>I made the <code>DateFormat</code> not lenient because I don't want to handle wrong format dates</li> <li>The methods names are for enhance readability (as* always return a String, and parse* always return a Date).</li> </ul> <h2>Further develop</h2> <ul> <li>A JSF Date converter to manage automatically all dates.</li> <li>A JSF Phase listener to format all dates.</li> <li>A @Annotation to differentiate between different kinds of types</li> </ul> <h2>My Questions</h2> <ul> <li>Is this approach right and maintainable?</li> <li>My considerations are right?</li> <li>How I can improve this API?</li> <li>Is correct to be restrictive about the <strong>lenient</strong> property, or is a waste of time?</li> </ul> <h2>Source</h2> <ul> <li>Code: <a href="https://gist.github.com/aVolpe/6558296" rel="nofollow noreferrer">https://gist.github.com/aVolpe/6558296</a></li> <li>Current test: <a href="https://gist.github.com/aVolpe/6558316" rel="nofollow noreferrer">https://gist.github.com/aVolpe/6558316</a></li> </ul> <h1>Edit</h1> <p><strong>Observation</strong>: <a href="https://stackoverflow.com/questions/18840265/dateformat-pattern">this question was answered in stack overflow</a></p>
[]
[ { "body": "<p>Dates and Date handling in Java have been a <a href=\"http://www.tns.lcs.mit.edu/manuals/java-1.1.1/api/java.util.Date.html\">problem since the beginning</a> (check out all the deprecated methods in version 1.1). You appear to be running in to the same problems that may Java developers have encountered, and then there are a whole lot of issues that you have not yet encountered.</p>\n\n<p>Unlike other questions in CodeReview, I'm going to deviate from the norm, and tell you to give up.... A lot of people have taken a kick at this can... people smarter than you, and me, and the bottom line is that, even after three attempts, the base Java implementation for Date and Date-like data is still not right.</p>\n\n<p>On the other hand, <a href=\"http://www.joda.org/joda-time/\">JodaTime</a> has somehow managed to be a library that is well maintained, accurate, usable, and just 'gets it'. It is licensed under the Apache2 license, which means there is effectively no restriction on how you can use it, and with few restrictions/requirements when modifying it (not that you would want to).</p>\n\n<p>At this point in the Java ecosystem, there is absolutely no point in building your own Date library.... it leads to weeping and gnashing of teeth.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T10:36:28.337", "Id": "69920", "Score": "1", "body": "`JodaTime` was one of my options, but, at time when I ask this, was impossible to add new Dependencies (for policy decisions). I end up with my specification, and works pretty well, my main problem now if how to make the developers use it!. Cheers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T01:39:38.760", "Id": "40816", "ParentId": "31268", "Score": "7" } }, { "body": "<p>Writing your own code to parse dates (as in performing calculation and validation) would be reinventing the wheel, and therefore a bad idea. However, making some convenience routines to help enforce some consistency in your input and output formats, as you have done, is a <em>good</em> idea.</p>\n\n<hr>\n\n<p>Forcing all of your parsing and formatting routines to be <code>synchronized</code> is an unnecessary burden. To start with, <code>dateToString()</code> and <code>stringToDate()</code> don't need to be <code>synchronized</code>. As it is currently written, <code>getFormat()</code> <em>does</em> need to be <code>synchronized</code>, because <code>formats</code> might change while you call <code>formats.containsKey()</code> or <code>formats.get()</code>. However, even that synchronization could be avoided, since you would only mutate <code>formats</code> during initialization. If you perform the initialization in a static initializer block, then the initialization will happen exactly once at class-loading time, in a thread-safe manner <a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.2\" rel=\"nofollow\">(JLS 12.4.2)</a>.</p>\n\n<p>In summary, initialize <code>formats</code> like this:</p>\n\n<pre><code>static {\n formats = new HashMap&lt;String, SimpleDateFormat&gt;(5);\n formats.put(DATE_FORMAT, new SimpleDateFormat(DATE_FORMAT));\n formats.put(DATE_SHORT_FORMAT, new SimpleDateFormat(DATE_SHORT_FORMAT));\n formats.put(TIME_FORMAT, new SimpleDateFormat(TIME_FORMAT));\n formats.put(DATETIME_FORMAT, new SimpleDateFormat(DATETIME_FORMAT));\n formats.put(DATETIME_SHORT_FORMAT, new SimpleDateFormat(\n DATETIME_SHORT_FORMAT));\n for (SimpleDateFormat sdf : formats.values()) {\n sdf.setLenient(false);\n }\n}\n</code></pre>\n\n<p>… and drop all use of <code>synchronized</code> in your code.</p>\n\n<hr>\n\n<p>In the Java date-time API, a <code>Date</code> isn't really what most people think of as a \"date\" — it's actually a count of milliseconds since the Java epoch (1970-01-01 00:00:00 UTC), analogous to the <code>time_t</code> type in C. Therefore, converting a <code>String</code> such as \"2014-02-04\" into a <code>Date</code> isn't just an act of parsing (as in textual analysis) — it also involves interpreting that timestamp in the context of a particular time zone (the time zone of your server process, by default). Depending on whether your web application's users are geographically concentrated, that may or may not be appropriate. Joda-Time supports a <a href=\"http://www.joda.org/joda-time/key_partial.html\" rel=\"nofollow\">timezone-neutral date/time representation</a>; the Java API doesn't.</p>\n\n<hr>\n\n<p>When you throw a <code>ParseException</code>, it would be better to include the malformed date in the exception message. \"Imposible parsear\" is redundant with <code>ParseException</code> and therefore uninformative.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T19:48:42.537", "Id": "40879", "ParentId": "31268", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T02:43:52.113", "Id": "31268", "Score": "11", "Tags": [ "java", "design-patterns", "api", "datetime" ], "Title": "Date Format provider" }
31268
<p>I have been staring at this code for awhile now and I am thinking there is a way to optimize it (namely the <code>if</code>-<code>else</code> statement with the <code>for</code>-loops). </p> <p>Additionally, this needs to be done with an array list as that is my assignment requirement. I have all my code working, and it is not due for a few days, so I am looking for ways to improve it while extending my learning beyond the classroom. </p> <p>The <code>numberOfContacts</code> variable is fed into the method from the main method, which gets the count from another method that reads through a text file to get the number of contacts.</p> <pre><code>/** * search method searches through the contact list for a given criteria * and displays all results. * @param searchString is type String. * @param type is type String. * @param numberOfContacts is type int. * @param contacts is type Person[]. */ public static void search(String searchString, String type, int numberOfContacts, Person[] contacts) { // Initialize variables for results int found = 0; int[] results = new int[numberOfContacts]; // Determine the type of search if (type.equals("name")) { // Search by name for (int x = 0; x &lt; numberOfContacts; x++) { if (contacts[x].getName().contains(searchString)) { results[found] = x; found++; } } } else { // Search by phone for (int x = 0; x &lt; numberOfContacts; x++) { if (contacts[x].getPhone().contains(searchString)) { results[found] = x; found++; } } } // Display the search results System.out.println("\n\t**************"); System.out.println("\tSearch Results"); System.out.println("\t**************"); System.out.println("Found " + found + " results containing \"" + searchString + "\":"); System.out.println(); if (found &gt; 0) { for (int x = 0; x &lt; found; x++) { System.out.println(contacts[results[x]].getName() + "\t" + contacts[results[x]].getPhone()); } } System.out.println("\n\n\n"); } </code></pre>
[]
[ { "body": "<p>If you are limited to use only Arrays, you can create a interface like this</p>\n\n<pre><code>public static interface Checker {\n public boolean check(Person p, String searchString);\n}\n</code></pre>\n\n<p>Create a Checker for every type of comparison you want.</p>\n\n<p>And compare with the Checker</p>\n\n<pre><code>for (int x = 0; x &lt; numberOfContacts; x++) {\n if (checker.check(contacts[x], searchString)) {\n results[found] = x;\n found++;\n }\n}\n</code></pre>\n\n<p>You can see a working example here (with your classes and methos): <a href=\"http://ideone.com/2C6kei\" rel=\"nofollow\">http://ideone.com/2C6kei</a></p>\n\n<p>Note:\nWith this method is easy to expand the search criteria (as you see in the example, with a anywhere Checker).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T03:33:00.167", "Id": "31271", "ParentId": "31270", "Score": "2" } }, { "body": "<ol>\n<li><p>You should clarify what your homework statement exactly says: a Java \"array list\" is something like</p>\n\n<pre><code>List&lt;Person&gt; persons = new ArrayList&lt;Person&gt;()\n</code></pre>\n\n<p>while <code>Person[] persons</code> is a Java \"array\".</p></li>\n<li><p>Java is not Fortran or C; there is no need for the argument <code>int numberOfContacts</code>, so you can just call <code>contacts.length</code> to get the size of an array. If you use an <code>ArrayList</code>, it is <code>contacts.size()</code> instead.</p></li>\n<li><p>When you print out the results, there is no need for <code>if (found &gt; 0)</code> since the <code>for</code>-loop will not be executed a single time if there is nothing to execute.</p>\n\n<p>Other than that the algorithm looks fine; I don't see much to optimize.<br>\nOptional suggestions:</p></li>\n<li><p>Instead of using an <code>if</code>-statement to check the <code>type</code>, you can look into the Java <code>switch</code>-statement. That would be useful especially if you many types: \"name\", \"phone\", \"address\", \"age\", etc.</p></li>\n<li><p>Instead of using hardcoded strings for the type, look into the <code>enum</code>:</p>\n\n<pre><code>public enum ContactField {\n NAME, PHONE;\n}\n</code></pre>\n\n<p>and instead of passing an argument of type <code>String</code>, use the type <code>ContactField</code>. The <code>switch</code>-statement works with <code>String</code> and <code>enum</code>.</p></li>\n</ol>\n\n<p><strong>SOME EDITS ONE YEAR LATER:</strong></p>\n\n<ol start=\"6\">\n<li><p>In the <code>for</code>-loop, use <code>int i</code> instead of <code>int x</code>. It is just a convention, but everyone uses it.</p></li>\n<li><p>\"Separation of concern\": have your <code>search</code> method only return the list of matches. If you want to print them, print the returned list elsewhere. You want to break your code in small methods so that each one can be reused. For example, you might use your <code>search</code> method in a web server framework and you would need to send the matches over to the user's web page instead of printing them to the console.</p></li>\n</ol>\n\n<p>Since Java 8 came out, you could instead use:</p>\n\n<pre><code>public Stream&lt;Person&gt; searchByName(String name) {\n return Arrays.stream(persons).filter(person -&gt; person.getName().contains(targetName));\n}\n\npublic Stream&lt;Person&gt; searchByPhone(String phone) {\n Arrays.stream(persons).filter(person -&gt; person.getPhone().contains(targetPhone));\n}\n</code></pre>\n\n<p>and then you can whatever you want with that stream. For example,</p>\n\n<pre><code>personsStream.forEach(System.out::println);\n</code></pre>\n\n<p>However, since your instructor asked you to use arrays, it will probably take another 15 years before he/she switches over to the Java 8.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T15:10:18.793", "Id": "31276", "ParentId": "31270", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T03:01:00.023", "Id": "31270", "Score": "4", "Tags": [ "java", "optimization", "homework", "search" ], "Title": "Searching through a contact list for given criteria" }
31270
<p>I managed to create my first wordpress plugin template page collecting various code snippets to make the page function.</p> <p>Everything works fine, but I need hear comments from PHP &amp; wordpress experts to see if it's well-coded.</p> <p>Here's the code.</p> <pre><code>&lt;?php /* Plugin Name: name Plugin URI: http://www.example.com Description: desc Version: 1 Author: someone Author URI: http://www.example */ ?&gt; &lt;?php function my_first_plugin_init(){ register_setting( 'my_first_plugin_grp', 'my_first_plugin' ); } add_action( 'admin_init', 'my_first_plugin_init' ); function my_first_plugin_add_page() { add_menu_page('plugin title', 'plugin title', 'manage_options', 'my_first_plugin', 'my_first_plugin_do_page' ); } add_action( 'admin_menu', 'my_first_plugin_add_page' ); function my_first_plugin_scripts() { wp_enqueue_script('media-upload'); wp_enqueue_script('thickbox'); wp_enqueue_script('my-upload', plugin_dir_url( __FILE__ ).'/upload-func.js'); } add_action('admin_print_scripts', 'my_first_plugin_scripts'); function my_first_plugin_styles() { wp_enqueue_style('ads-stls', plugin_dir_url( __FILE__ ).'/ads-options.css'); wp_enqueue_style('thickbox'); } add_action('admin_print_styles', 'my_first_plugin_styles'); function my_first_plugin_do_page() { global $select_options, $radio_options; if ( ! isset( $_REQUEST['settings-updated'] ) ) $_REQUEST['settings-updated'] = false; ?&gt; &lt;div class="wrap"&gt; &lt;h2&gt;&lt;?php echo $plgnme; ?&gt;&lt;/h2&gt; &lt;?php if ( false !== $_REQUEST['settings-updated'] ) : ?&gt; &lt;div class="updated fade"&gt;&lt;p&gt;&lt;strong&gt;Options saved.&lt;/strong&gt;&lt;/p&gt;&lt;/div&gt; &lt;?php endif; ?&gt; &lt;form method="post" action="options.php"&gt; &lt;?php settings_fields( 'my_first_plugin_grp' ); ?&gt; &lt;?php $options = get_option( 'my_first_plugin' ); ?&gt; &lt;!-- content start --&gt; &lt;!-- ///////////////////////////////////////////////////////////////////////////////////////////////////// --&gt; Sample text input: &lt;input id="my_first_plugin[lpgrdneurl]" class="regular-text" type="text" name="my_first_plugin[lpgrdneurl]" value="&lt;?php esc_attr_e( $options[$lpgrdneurl] ); ?&gt;" placeholder="http://" /&gt; &lt;!-- ///////////////////////////////////////////////////////////////////////////////////////////////////// --&gt; &lt;!-- content end --&gt; &lt;?php submit_button(); ?&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;?php } ?&gt; </code></pre>
[]
[ { "body": "<p>Welcome to the site!</p>\n\n<p>The most difficult part you done; that's to create something. I know a lot of people with tons of ideas, but none of them come to reality. So, well done for your first step. </p>\n\n<p>About your plugin, it's a very simple one. I believe everyone here would do in a different way. The best practices you will get them during your learning journey and time. However, I would suggest you to use (and learn from it) a plugin boilerplate as base. There are several out there, but the follow one is quite popular. <a href=\"https://github.com/tommcfarlin/WordPress-Plugin-Boilerplate\" rel=\"nofollow noreferrer\">https://github.com/tommcfarlin/WordPress-Plugin-Boilerplate</a></p>\n\n<p>I would say study that plugin and <em>port</em> yours to it. It's a nice way to learn new things. And if you don't know OOP, don't worry. Just because you see some code using class, it doesn't mean that they are <em>real</em> OOP. But learning the basic of PHP OOP is a great thing.</p>\n\n<p><strong>Reviewing the code</strong></p>\n\n<p>Two small things:</p>\n\n<ul>\n<li>To enqueue scripts AND styles use <code>wp_enqueue_scripts</code> for the front-end. And <code>admin_enqueue_scripts</code> for the back-end. <a href=\"http://make.wordpress.org/core/2011/12/12/use-wp_enqueue_scripts-not-wp_print_styles-to-enqueue-scripts-and-styles-for-the-frontend/\" rel=\"nofollow noreferrer\">http://make.wordpress.org/core/2011/12/12/use-wp_enqueue_scripts-not-wp_print_styles-to-enqueue-scripts-and-styles-for-the-frontend/</a></li>\n<li>Do not use the close <code>?&gt;</code>php tag in the end of the file. <a href=\"https://stackoverflow.com/questions/4410704/why-would-one-omit-the-close-tag\">https://stackoverflow.com/questions/4410704/why-would-one-omit-the-close-tag</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T13:27:57.307", "Id": "49844", "Score": "0", "body": "Thanks for the tips, I forgot to mention that i'm not a php coder. So I just collected some code snippets to make a basic reliable plugin with just simple form options." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T15:36:56.027", "Id": "49846", "Score": "0", "body": "One more reason for you to use a plugin starter/boilerplate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T14:36:19.623", "Id": "49932", "Score": "0", "body": "you didn't really review the code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T03:02:50.563", "Id": "50012", "Score": "0", "body": "Update my answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T14:57:02.027", "Id": "31275", "ParentId": "31273", "Score": "0" } }, { "body": "<p>First of all, your plugin is not translation ready, see <a href=\"http://codex.wordpress.org/I18n_for_WordPress_Developers\" rel=\"nofollow noreferrer\"><code>l18n</code></a>. In the plugin header, you should add</p>\n\n<pre><code>* Text Domain: your-textdomain\n* Domain Path: /languages\n</code></pre>\n\n<p>Create the language files in <code>wp-content/plugins/your-plugin/languages</code> with <a href=\"http://www.poedit.net/\" rel=\"nofollow noreferrer\">PoEdit</a>. And make all relevant strings translatable with:</p>\n\n<pre><code>add_menu_page( __('Plugin title','your-textdomain'), ...\n// and\n&lt;?php _e('Options saved','your-textdomain'); ?&gt;\n</code></pre>\n\n<hr>\n\n<p>There's a big issue: you're printing your styles and scripts all over the admin area. <strong>It's essential</strong> that you always target the correct page.</p>\n\n<pre><code>add_action( 'admin_menu', 'my_first_plugin_add_page' );\nfunction my_first_plugin_add_page() \n{\n $hook = add_menu_page(\n 'plugin title', \n 'plugin title', \n 'manage_options', \n 'my_first_plugin', \n 'my_first_plugin_do_page'\n );\n add_action( \"admin_print_scripts-$hook\", 'my_first_plugin_scripts' ); \n}\n</code></pre>\n\n<hr>\n\n<p>You don't need to close and open PHP tags if you're not swapping between PHP and HTML:</p>\n\n<pre><code>*/\n?&gt;\n&lt;?php\nfunction my_first_plugin_init(){\n</code></pre>\n\n<p>Get rid of the very last <code>?&gt;</code> too.<br>\nSee <a href=\"https://stackoverflow.com/q/3219383/1287812\">Why do some scripts omit the closing php tag <code>?&gt;</code></a>.</p>\n\n<hr>\n\n<p>It's easier to have a general picture if you declare first the hooks and then the callbacks.</p>\n\n<pre><code>add_action('first_hook', 'prefix_first_callback');\nadd_action('second_hook', 'prefix_second_callback');\nadd_filter('third_hook', 'prefix_third_callback');\nfunction prefix_first_callback() {}\nfunction prefix_second_callback() {}\nfunction prefix_third_callback() {}\n</code></pre>\n\n<hr>\n\n<p>It's important to prefix everything, function names, meta data and <code>$_POST</code>ed data. But for function names this quickly turns into hard to read code. Encapsulating everything in a class avoids this. And also allows us to start-up our plugin in a safe point: <code>plugins_loaded</code>, see <a href=\"https://wordpress.stackexchange.com/q/70055/12615\">Best way to initiate a class in a WP plugin?</a>.</p>\n\n<p>The following is a clean version of <a href=\"https://gist.github.com/toscho/3804204\" rel=\"nofollow noreferrer\">Plugin Class Demo</a>, by <a href=\"https://wordpress.stackexchange.com/users/73/toscho\">toscho◆</a>. Please, go to the source for the full documented class.</p>\n\n<pre><code>add_action(\n 'plugins_loaded',\n array ( PREFIX_My_Plugin::get_instance(), 'plugin_setup' )\n);\n\nclass PREFIX_My_Plugin\n{\n protected static $instance = NULL;\n public $plugin_url = '';\n public $plugin_path = '';\n\n public static function get_instance()\n {\n NULL === self::$instance and self::$instance = new self;\n return self::$instance;\n }\n\n public function plugin_setup()\n {\n $this-&gt;plugin_url = plugins_url( '/', __FILE__ );\n $this-&gt;plugin_path = plugin_dir_path( __FILE__ );\n $this-&gt;load_language( 'plugin_unique_name' );\n // Your stuff: register actions and filters\n add_action( 'admin_init', array( $this, '_admin_init' ) );\n }\n\n public function _admin_init()\n {\n // your_stuff();\n }\n\n public function __construct() {}\n\n public function load_language( $domain )\n {\n load_plugin_textdomain(\n $domain,\n FALSE,\n $this-&gt;plugin_path . 'languages'\n );\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-02T23:00:49.697", "Id": "32159", "ParentId": "31273", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T05:12:13.413", "Id": "31273", "Score": "2", "Tags": [ "php" ], "Title": "Created my first wordpress plugin template page, need comments" }
31273
<p>I was writing a program and I needed a function that could ordinate the <code>argv</code> according to my preferences. That way, <code>getopt</code> would parse the options as needed. I couldn't find any, so I wrote one. I would be very thankful if you guys could have a look and say what you think about it. I'm a C beginner, so don't save comments; I really want to learn!</p> <p>usage: include the header and use the function like this:</p> <p>...</p> <pre><code>/* before the getopt function */ ordering(l:ds:k:w); /* so l will be parsed first, d second, s third...*/ </code></pre> <p>...</p> <p><a href="https://github.com/paolocarrara/getopt_ordering" rel="nofollow">git repo to the function</a></p> <p>Two files(_getopt.h and ordering.c):</p> <p>The first one:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; char **ordering (int *, char **, char *); </code></pre> <p>And, the second one:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define TRUE 1 #define FALSE 0 /* returns the size of a given line */ int get_line_size (char *line) { return strlen (line); } /* returns TRUE if argv[0] is an option, else, returns FALSE */ int verify_if_is_option (char *argv) { if (argv != NULL) { if (argv[0] == '-') { return TRUE; } else { return FALSE; } } else { return FALSE; } } /* counts the number of progem in the given argv * problem def.: a problem is when a we have option and * its argument together, like this: -vbike * this kind of problem need to be treated, to the rest of * the functions work properly * */ int problem_counter (int argc, char **argv) { int i; int number_of_problens; for (i = 1, number_of_problens = 0; i &lt; argc; i++) { if (verify_if_is_option (argv[i]) == TRUE) { if (get_line_size (argv[i]) &gt; 2) { number_of_problens++; } } } return number_of_problens; } /* the orignal argv coudn't be modified, it's reallocced * notice: the functions doesn't really reallocs the the argv, * it just creates another matrix with more size - for the additional * lines - and copy everithing from the original one. * */ char **malloc_argv (int argc, char **argv, int t_problens) { char **new; int i; new = malloc ((argc+t_problens)*sizeof(char*)); for (i = 0; i &lt; argc; i++) { new[i] = argv[i]; } for (; i &lt; argc + t_problens; i++) { new[i] = NULL; } return new; } /* find and return a problematic line * problematic line def.: a problematic lines is a line whose * its option and argument are together in the same vector of the * matrix * */ char *get_problematic_line (int argc, char **argv) { int i; char *line; line = NULL; for (i = 1; i &lt; argc; i++) { if (verify_if_is_option (argv[i]) == TRUE) { if (get_line_size (argv[i]) &gt; 2) { line = argv[i]; } } } return line; } /* get and return the argument of a given line */ char *get_argument (char *line) { char *argument; int i; argument = malloc ((strlen(line)-1)*sizeof(char)); for (i = 2; i &lt; strlen(line); i++) { argument[i-2] = line[i]; } argument[i-2] = '\0'; return argument; } /* push down all the lines from the i element to the bottom */ char **push_down (int argc, char **argv, int i) { for (; argc &gt; i+1; argc--) { argv[argc-1] = argv[argc-2]; } return argv; } /* just do what it name says */ char **push_one_line_down_from_here (char *line, int argc, char **argv) { int i; for (i = 1; i &lt; argc; i++) { if (argv[i] == line) { argv = push_down (argc, argv, i); i = argc; } } return argv; } /* just do what it name says */ char **insert_argument_below_this_line (char *line, char *argument, char **argv) { int i; for (i = 1; line != argv[i]; i++); argv[i+1] = argument; return argv; } /* to remove the argument from a problematic line * this function puts a '\0' at where the option should end * */ void remove_argument_from_problematic_line (char *line) { line[2] = '\0'; } /* realloc the argv matrix and identify and separate problematic lines * obs.: problematic lines are defined in the get_problematic_line function * */ char **malloc_and_divide (int *argc, char **argv) { int t_problens; char *line; char *argument; t_problens = problem_counter (*argc, argv); argv = malloc_argv (*argc, argv, t_problens); (*argc) +=t_problens; for (;t_problens &gt; 0; t_problens--) { line = get_problematic_line (*argc, argv); argument = get_argument (line); argv = push_one_line_down_from_here (line, *argc, argv); argv = insert_argument_below_this_line (line, argument, argv); remove_argument_from_problematic_line(line); } return argv; } /**** THIS PIECE OF CODE IS FOR THE SECOND PART OF THE FUCNTION ****/ /* 'transform' a litteral string in a mallocced string */ char *litteral_to_dinamic (char *literal) { int i; char *dinamic = malloc ((strlen(literal)+1)*sizeof(char)); for (i = 0; i &lt; strlen(literal); i++) { dinamic[i] = literal[i]; } dinamic[i] = '\0'; return dinamic; } /* returns the next option in optstring */ char get_desired_option (char *optstring) { /*char option = optstring[0]; return option; */ return optstring[0]; } /* remove an already used option in optstring */ void remove_option_used (char *optstring) { int i; for (i = 1; i &lt;= strlen(optstring); i++) { optstring[i-1] = optstring[i]; } if (optstring[0] == ':') { remove_option_used (optstring); } } /* returns true if the desired option is in argv, if it is, this * option will be replaced in the right place, else, nothing will * be done * */ int is_in_argv (int argc, char **argv, char option) { int i; for (i = 1; i &lt; argc; i++) { if (argv[i][0] == '-' &amp;&amp; argv[i][1] == option) { return TRUE; } } return FALSE; } /* returns true if both the option that need to be replaced and the * option that is in the 'wrong' place have an argument * */ int both_have_argument (int argc, char **argv, int position, int i) { if(i &lt; argc-1) { if((argv[position+1][0] != '-') &amp;&amp; (argv[i+1][0] != '-')) { return TRUE; } else { return FALSE; } } else { return FALSE; } } /* just do what it name says */ void change_both_arguments (int argc, char **argv, int position, int i) { char *aux; aux = argv[position+1]; argv[position+1] = argv[i+1]; argv[i+1] = aux; } /* return true if only the first option have an argument * the first option is the not desired option * */ int first_have_argument (int argc, char **argv, int position) { if (position &lt; argc-1) { if (argv[position+1][0] != '-') { return TRUE; } } return FALSE; } /* just do what it name says */ void change_first_argument (int argc, char **argv, int position, int i) { char *aux; aux = argv[position+1]; for (position++; position &lt; i; position++) { argv[position] = argv[position+1]; } argv[i] = aux; } /* return true if only the second option have an argument * the second option the desired option * */ int second_have_argument (int argc, char **argv, int i) { if (i &lt; argc-1) { if (argv[i+1][0] != '-') { return TRUE; } } return FALSE; } /* just do what it name says */ void change_second_argument (int argc, char **argv, int position, int i) { char *aux; int j; aux = argv[i+1]; for (j = i+1; j &gt; position; j--) { argv[j] = argv[j-1]; } argv[position+1] = aux; } /* returns the next position that a desired option will fit */ int verify_arguments (int argc, char **argv, int position, int i) { if (both_have_argument (argc, argv, position, i) == TRUE) { change_both_arguments (argc, argv, position, i); return position+2; } else if (first_have_argument (argc, argv, position) == TRUE) { change_first_argument (argc, argv, position, i); return position+1; } else if (second_have_argument (argc, argv, i) == TRUE) { change_second_argument (argc, argv, position, i); return position+2; } else return position+1; } /* changes the option position that is in optstring and was found in the argv */ int change_option_position (int argc, char **argv, char option, int position) { int i; char *aux; for (i = 1; i &lt; argc; i++) { if (argv[i][0] == '-' &amp;&amp; argv[i][1] == option) { aux = argv[position]; argv[position] = argv[i]; argv[i] = aux; position = verify_arguments (argc, argv, position, i); } } return position; } /* organizes the argv according to the optstring requirents */ char **organize (int argc, char **argv, char *optstring) { int position; char option; position = 1; optstring = litteral_to_dinamic (optstring); while (optstring[0] != '\0') { option = get_desired_option (optstring); remove_option_used (optstring); if ((is_in_argv(argc, argv, option)) == TRUE) { position = change_option_position (argc, argv, option, position); } } return argv; } /**** THE MAIN CALLER ****/ /* the main function */ char **ordering (int *argc, char **argv, char *optstring) { argv = malloc_and_divide (argc, argv); argv = organize (*argc, argv, optstring); return argv; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T20:57:21.267", "Id": "49877", "Score": "0", "body": "I have a feeling you have written some stuff that solves a non-existent problem. As far as I know, other people manage fine with `getopt` etc, so what is it about your eventual program that needs this arg-list reordering? Can you explain a bit more what you need to achieve and why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T22:32:52.313", "Id": "49883", "Score": "0", "body": "I'm writing a program that needed the -l option to be parsed before the -c option. -l says the says the size of the password, the -c says what type of character use to create the password: something like this: ./plist -l5 -c[alpha] if the -c option was parsed first so when it expand the length of the password it will have portions of it that wasn't initialized." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T22:49:36.300", "Id": "49885", "Score": "0", "body": "If you want to see the program that I'm writing, just look in the plist repo. The code IS NOT done!! So, errors can happen, and if you want to advice me about anything, please say! I will be very glad!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T05:47:22.587", "Id": "49897", "Score": "0", "body": "So is \"alpha\" the password in this example? Why would you need to announce how long it is when it it there in the string? And if that really is not enough, why can't you just set some flags as you parse the arg list and then do the processing when you know what you have? Maybe I'll look at your program as you suggest..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T13:16:24.340", "Id": "49924", "Score": "0", "body": "The password is a not fixed string. It will be generated by the program. I need to say what is the length of the passwords that will be generate using the char set specified. example: ./plist -l3 -c[digit] will output: 000 001 002 003...997 998 999. So, if the -c options comes first, the *password pointer will have no length at all, because wasn't had any malloc(l*sizeof(char)), got it? About the flags, how this works? I mean, I think that I know what is a flag, but how to use it in this case. If you could take a look at plist would be great! \\o/" } ]
[ { "body": "<p>Rather than continue in the comments, I talk here. This isn't a review of the code...</p>\n\n<p>As I wrote above, I think you have written some stuff that solves a non-existent problem. As far as I know, other people manage fine with getopt etc.</p>\n\n<p>As far as I can see, the following code extracted from your project and altered, does what you need without reordering the argument list:</p>\n\n<pre><code>void get_opt (int argc, char **argv, passSettings *pass)\n{\n int option;\n int length = 0;\n char *cset = NULL;\n char *pos = NULL;\n char *output = NULL;\n\n while ((option = getopt(argc, argv, \"l:o:k:c:hv\")) != -1)\n switch (option) {\n case 'l': length = strtol(optarg, 0, 0); break;\n case 'o': output = optarg; break;\n case 'c': cset = optarg; break;\n case 'k': pos = optarg; break;\n case 'v': version (); break;\n case 'h':\n default: help (); break;\n }\n setPasswordsLength(length, pass);\n setOutput(output, pass);\n setCharacterSet(cset, pass);\n setCharsPositions(pos, pass);\n if (getfp (pass) != NULL) printPasswordSetConfiguration (pass);\n}\n</code></pre>\n\n<p>Clearly you might need some error handling in there or in the called functions, but I've shown the basic idea. Of course I might have a completely wrong understanding of what you want... </p>\n\n<hr>\n\n<p><strong>EDIT</strong> : as requested as few comments. These are comments on the code, concentrating on the style and some details and ignoring the logic.</p>\n\n<ul>\n<li><p><code>get_line_size</code> is redundant - just use <code>strlen</code></p></li>\n<li><p><code>verify_if_is_option</code> is verbose. The following does the same. Note also\nthe use of <code>const</code> on the pointer parameter because the data pointed to is not\nchanged by the function.</p>\n\n<pre><code>int verify_if_is_option (const char *argv)\n{\n return (argv &amp;&amp; (argv[0] == '-'));\n}\n</code></pre>\n\n<p>I have not used TRUE/FALSE as these are not really necessary in C. The\nfunction returns the result of the expression: 1 if it is true, 0\notherwise. When you call the function you would do:</p>\n\n<pre><code>if (verify_if_is_option (argv[i])) {\n</code></pre>\n\n<p>This would read better if the function were named just <code>is_option</code></p></li>\n<li><p>The control variable in <code>for</code> loops can often be defined within the loop:</p>\n\n<pre><code>for (int i = 1; i &lt; argc; i++) {\n</code></pre>\n\n<p>Note that the scope of <code>i</code> above is only the loop, so if you want to use\nthe resulting value on termination of the loop, you must define the\nvariable outside the loop.</p></li>\n<li><p>It is generally better to define and initialise a variable at the point of\nfirst use, for example in <code>malloc_argv</code>:</p>\n\n<pre><code>char **new = malloc(argc + t_problens);\n</code></pre>\n\n<p>Note that I didn't use <code>sizeof(char)</code> because that is 1 by definition.\nAlso note the spacing. It is generally best to check <code>malloc</code> (etc)\nfor failure. Often the only thing that can be done is to print an\nerror and exit, but that is better than seg-faulting on the NULL\npointer returned by a failed <code>malloc</code> call.</p></li>\n<li><p><code>get_argument</code> (and <code>litteral_to_dinamic</code>) is verbose. You can just use\n<code>strdup</code> if you have it or write your own:</p>\n\n<pre><code>char* strdup(const char *s)\n{\n size_t len = strlen(s);\n char *t = malloc(len + 1);\n if (t != NULL) {\n memcpy(t, s, len + 1);\n }\n return t;\n}\n</code></pre>\n\n<p>Note <code>s</code> is <code>const</code>, the length is taken once and then used in the\nmalloc and <code>memcpy</code> calls (you already have the length so you can use\nthe more efficient <code>memcpy</code> instead of <code>strcpy</code>). To duplicate just\npart of the string, pass the relevant offset, eg:</p>\n\n<pre><code>char *copy = strdup(line + 2);\n</code></pre></li>\n<li><p>Empty loops are better made explicit - it is easy to miss a semicolon at\nthe end of the <code>for</code> statement:</p>\n\n<pre><code>for (i = 1; line != argv[i]; i++) { /*nothing*/ }\n</code></pre></li>\n<li><p>Putting a call to <code>strlen</code> inside a loop where the argument does not\nchange, as in</p>\n\n<pre><code>for (i = 1; i &lt;= strlen(optstring); i++) {\n</code></pre>\n\n<p>is arguably lazy/wrong. If compiler optimizations are enabled, the\ncompiler will probably remove the <code>strlen</code> call from the loop. All the\nsame, I prefer to see it explicit:</p>\n\n<pre><code>const size_t len = strlen(optstring);\n\nfor (size_t i = 1; i &lt;= len; i++) {\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T13:00:44.767", "Id": "50163", "Score": "0", "body": "You just made me sad... Yes! The flags! How could I be so... Well, even though the flags can solve my problem they introduce new variables that I will have to be worry, I know! this is nothing compared to the job in writing a function to handle it. But, I'm really thankful for your help. Any other observation will be very appreciated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T17:38:19.823", "Id": "50221", "Score": "0", "body": "The variables are local to the get_opt function aren't they? In that case they are not a cause of worry." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T16:43:05.040", "Id": "50304", "Score": "0", "body": "Thanks for your comments, I'm going to review my code to make it more inteligent. Again, thanks a lot for your observations and corrections." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T17:23:04.313", "Id": "31373", "ParentId": "31279", "Score": "1" } } ]
{ "AcceptedAnswerId": "31373", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T18:20:11.693", "Id": "31279", "Score": "3", "Tags": [ "c", "beginner" ], "Title": "getopt ordering function in C" }
31279
<pre><code>x = int(input("Choose the number of times you want to spam. ")) y = input("What message do you want to spam? ") w = x + 1 for i in range(1,w): print(y) </code></pre> <p>Any way to make this program better? I'm currently learning Python.</p>
[]
[ { "body": "<ol>\n<li>Use descriptive variable names</li>\n<li>No need to add one to x and then use <code>range(1, w)</code> - get used to using <a href=\"http://en.wikipedia.org/wiki/Zero-based_numbering\">zero-based numbering</a></li>\n<li>By convention in Python you can use <code>_</code> as the name for a loop variable when you won't actually be referring to that variable anywhere. </li>\n<li>As you develop this into a full programme, structure code under functions.</li>\n<li>use blank lines <a href=\"http://www.python.org/dev/peps/pep-0008/#blank-lines\">sparingly</a></li>\n</ol>\n\n<p>So:</p>\n\n<pre><code>def main():\n number_of_times = int(input(\"Choose the number of times you want to spam. \"))\n message = input(\"What message do you want to spam? \")\n for _ in range(number_of_times):\n print(message)\n</code></pre>\n\n<p>Alternatively:</p>\n\n<pre><code>print((message + '\\n') * number_of_times)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T20:54:18.157", "Id": "31283", "ParentId": "31282", "Score": "8" } } ]
{ "AcceptedAnswerId": "31283", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T20:38:43.007", "Id": "31282", "Score": "1", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Super simple spam program" }
31282
<p>I am calling <code>defvar</code> in the middle of a function definition. And so far I've always seen its use, with <code>defparameter</code> for global variable. Like <code>*error-output*</code> or <code>*standard-output*</code>.</p> <pre><code>(defun consume-socket-reply (socket end-test-form) (do* ((line "" (read-line (usocket:socket-stream socket) nil)) (text "" (concatenate 'string text line))) ((funcall end-test-form) text))) (defun read-http-content (socket) (defvar line) (consume-socket-reply socket (lambda () (not line)))) </code></pre> <p>Is there a better way to write what I am trying to do? That is: being able to pass the end-test-form to the final inner loop.</p>
[]
[ { "body": "<p>Ok I've modified my code that way, and removed the call to <code>defvar</code>:</p>\n\n<pre><code>(defun consume-socket-reply (socket end-test-form)\n (do* ((line (read-line (usocket:socket-stream socket) nil)\n (read-line (usocket:socket-stream socket) nil))\n (text line (concatenate 'string text line)))\n ((funcall end-test-form line) text)))\n\n(defun read-http-header (socket)\n (consume-socket-reply socket (lambda (line) (equal line \"\"))))\n\n(defun read-http-content (socket)\n (consume-socket-reply socket (lambda (line) (not line))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T10:42:18.373", "Id": "31309", "ParentId": "31284", "Score": "1" } }, { "body": "<p><code>Defvar</code> always creates a globally special variable (unless it already exists, of course). It does not matter where you call it.</p>\n\n<p>It is usually used as a toplevel form or directly inside of an <code>eval-when</code>. The only reason to put it anywhere else that I can think of is the use of closures.</p>\n\n<p>In all other cases, I would strongly suspect that the code does not mean what the author thinks it does.</p>\n\n<p>Here, the globally special variable <code>line</code> is created on the first call of <code>read-http-content</code>. This may lead to surprising effects if you use the name <code>line</code> in other places. Don't do that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-05T20:40:00.980", "Id": "36728", "ParentId": "31284", "Score": "2" } } ]
{ "AcceptedAnswerId": "31309", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T22:22:56.983", "Id": "31284", "Score": "1", "Tags": [ "lisp", "common-lisp" ], "Title": "Is using defvar for a non-global variable ok?" }
31284
<p>I'm beginning to learn Haskell. I've implemented the <a href="http://en.wikipedia.org/wiki/Graham_scan">Graham Scan</a> algorithm for detection of convex hull following the Real World Haskell book.</p> <p>I'm looking for general advice regarding the style and convention of my code, as well as best practices and ways to refactor several ugly places:</p> <ol> <li><code>Vector2D</code> and its accessors. It's structurally equivalent to <code>Point2D</code> but I want to typecheck its usage. Hence I use <code>newtype</code> and not <code>type</code>, but it makes me implement custom accessors to unwrap the underlying <code>Point2D</code>. The nesting looks redundant.</li> <li><p>Point-free usage (or possibility of it) in following places:</p> <pre><code>sqrt . fromIntegral $ (vectorX v) ^ 2 + (vectorY v) ^ 2 </code></pre> <p></p> <pre><code>sortBy (\ (_,b1) (_,b2) -&gt; (b1 :: Double) ``compare`` (b2 :: Double)) (zip l (angleWithXByPoint2DList p l)) </code></pre></li> <li><p>Graham Scan implementation as two-level function — interface one and internal one. Maybe there's a way to merge them?</p></li> </ol> <p></p> <pre><code>import Prelude hiding (Left, Right) import Data.List import Test.Framework (defaultMain, testGroup) import Test.Framework.Providers.HUnit import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.QuickCheck import Test.HUnit data Direction = Left | Right | Straight deriving (Show, Eq) data Point2D = Point2D { x :: Integer , y :: Integer } deriving (Show, Eq, Ord) direction :: Point2D -&gt; Point2D -&gt; Point2D -&gt; Direction direction a b c = let x1 = x a x2 = x b x3 = x c y1 = y a y2 = y b y3 = y c s = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1) in case compare s 0 of GT -&gt; Left LT -&gt; Right EQ -&gt; Straight comparePoints :: Point2D -&gt; Point2D -&gt; Ordering comparePoints a b | y1 &lt; y2 = LT | y1 == y2 &amp;&amp; x1 &lt; x2 = LT | y1 == y2 &amp;&amp; x1 == x2 = EQ | y1 == y2 &amp;&amp; x1 &gt; x2 = GT | y1 &gt; y2 = GT where x1 = x a x2 = x b y1 = y a y2 = y b sortPoints :: [Point2D] -&gt; [Point2D] sortPoints l = sortBy comparePoints l newtype Vector2D = Vector2D Point2D deriving (Show, Eq, Ord) vectorBy2Points :: Point2D -&gt; Point2D -&gt; Vector2D vectorBy2Points a b = let dx = x b - x a dy = y b - y a in Vector2D $ Point2D {x=dx, y=dy} vectorX (Vector2D (Point2D {x=x, y=_})) = x vectorY (Vector2D (Point2D {x=_, y=y})) = y dotProduct2D :: Vector2D -&gt; Vector2D -&gt; Integer dotProduct2D a b = vectorX a * vectorX b + vectorY a * vectorY b euclideanNorm2D :: Vector2D -&gt; Double euclideanNorm2D v = sqrt . fromIntegral $ (vectorX v) ^ 2 + (vectorY v) ^ 2 angleBy3Points2D :: Point2D -&gt; Point2D -&gt; Point2D -&gt; Double angleBy3Points2D a b c = let ba = vectorBy2Points b a bc = vectorBy2Points b c dp = dotProduct2D ba bc n1 = euclideanNorm2D ba n2 = euclideanNorm2D bc in acos( (fromIntegral dp) / (n1 * n2) ) angleWithXBy2Points2D :: Point2D -&gt; Point2D -&gt; Double angleWithXBy2Points2D p@(Point2D {x=x1, y=y1}) a = let b = Point2D {x=x1+1, y=y1} in angleBy3Points2D a p b angleWithXByPoint2DList :: Point2D -&gt; [Point2D] -&gt; [Double] angleWithXByPoint2DList p (a:[]) = [angleWithXBy2Points2D p a] angleWithXByPoint2DList p (a:l) = [angleWithXBy2Points2D p a] ++ angleWithXByPoint2DList p l sortedPointsByAngleWithPX :: Point2D -&gt; [Point2D] -&gt; [(Point2D,Double)] sortedPointsByAngleWithPX p l = sortBy (\ (_,b1) (_,b2) -&gt; (b1 :: Double) `compare` (b2 :: Double)) (zip l (angleWithXByPoint2DList p l)) grahamScanInternal :: [Point2D] -&gt; [Point2D] -&gt; [Point2D] grahamScanInternal acc [] = acc grahamScanInternal acc l = let b = last acc a = last (init acc) c = head l in if (direction a b c) /= Right then grahamScanInternal (acc ++ [c]) (tail l) else grahamScanInternal (init acc ++ [c]) (tail l) grahamScan :: [Point2D] -&gt; [Point2D] grahamScan l = let sp = sortPoints l p = head sp spa = sortedPointsByAngleWithPX p l bp = head spa tspa = tail spa cp = head tspa tsp' = [i | (i,j) &lt;- tspa] b = fst bp c = fst cp li = [p, b] in grahamScanInternal li tsp' class FPEq a where (=~) :: a -&gt; a -&gt; Bool instance FPEq Double where x =~ y = abs ( x - y ) &lt; (1.0e-8 :: Double) (@?=~) :: (Show a, FPEq a) =&gt; a -&gt; a -&gt; Test.HUnit.Assertion (@?=~) actual expected = actual =~ expected @? assertionMsg where assertionMsg = "Expected : " ++ show expected ++ "\nActual : " ++ show actual test_Left = direction (Point2D {x=0, y=0}) (Point2D {x=1, y=1}) (Point2D {x=2, y=3}) @?= Left test_Straight = direction (Point2D {x=0, y=0}) (Point2D {x=1, y=1}) (Point2D {x=2, y=2}) @?= Straight test_Right = direction (Point2D {x=0, y=0}) (Point2D {x=1, y=1}) (Point2D {x=2, y=1}) @?= Right test_SortPoints = sortPoints [ Point2D {x=1, y=3}, Point2D {x=0, y=0}, Point2D {x=5, y=4}, Point2D {x=3, y=1}, Point2D {x=2, y=2}, Point2D {x=4, y=5} ] @?= [ Point2D {x=0, y=0}, Point2D {x=3, y=1}, Point2D {x=2, y=2}, Point2D {x=1, y=3}, Point2D {x=5, y=4}, Point2D {x=4, y=5} ] test_SortPointsCoincident = sortPoints [ Point2D {x=1, y=1}, Point2D {x=0, y=0}, Point2D {x=5, y=4}, Point2D {x=3, y=1}, Point2D {x=2, y=1}, Point2D {x=4, y=4} ] @?= [ Point2D {x=0, y=0}, Point2D {x=1, y=1}, Point2D {x=2, y=1}, Point2D {x=3, y=1}, Point2D {x=4, y=4}, Point2D {x=5, y=4} ] test_VectorBy2Points1 = vectorBy2Points Point2D {x=0,y=1} Point2D {x=1,y=0} @?= Vector2D (Point2D {x=1,y=(-1)}) test_VectorBy2Points2 = vectorBy2Points Point2D {x=2,y=3} Point2D {x=4,y=5} @?= Vector2D (Point2D {x=2,y=2}) test_DotProduct2D1 = dotProduct2D (Vector2D (Point2D {x=1,y=(-1)})) (Vector2D (Point2D {x=2,y=2})) @?= 0 test_DotProduct2D2 = dotProduct2D (Vector2D (Point2D {x=3,y=(-2)})) (Vector2D (Point2D {x=4,y=1})) @?= 10 test_RightAngleBy3Points = angleBy3Points2D Point2D {x=0,y=1} Point2D {x=0,y=0} Point2D {x=1,y=0} @?=~ (pi / 2) test_AngleBy3Points1 = angleBy3Points2D Point2D {x=1,y=1} Point2D {x=0,y=0} Point2D {x=1,y=0} @?=~ (pi / 4) test_GrahamScan1 = grahamScan [ Point2D {x=0 , y=0} -- P , Point2D {x=5 , y=2} -- A , Point2D {x=4 , y=4} -- B , Point2D {x=1 , y=2} -- C , Point2D {x=(-1), y=3} -- D ] @?= [ Point2D {x=0 , y=0} -- P , Point2D {x=5 , y=2} -- A , Point2D {x=4 , y=4} -- B , Point2D {x=(-1), y=3} -- D , Point2D {x=0 , y=0} -- P ] main = defaultMain tests tests = [ testGroup "Direction" [ testCase "Direction for left turn" test_Left, testCase "Direction for straight line" test_Straight, testCase "Direction for right turn" test_Right ], testGroup "Sort List of Points" [ testCase "Sort Points works for all points with different y coordinates" test_SortPoints, testCase "Sort Points works for points with coincident y coordinates" test_SortPointsCoincident ], testGroup "Vector By 2 Points" [ testCase "Vector By 2 Points case 1" test_VectorBy2Points1, testCase "Vector By 2 Points case 2" test_VectorBy2Points2 ], testGroup "Dot Product 2D" [ testCase "Dot Product 2D case 1" test_DotProduct2D1, testCase "Dot Product 2D case 2" test_DotProduct2D2 ], testGroup "Calculate Angle by 3 points" [ testCase "Angle calculation for right angle" test_RightAngleBy3Points, testCase "Angle calculation for Pi/4 angle" test_AngleBy3Points1 ], testGroup "Graham Scan" [ testCase "Graham scan for simple hull of 5 points" test_GrahamScan1 ] ] </code></pre>
[]
[ { "body": "<p>Some ideas:</p>\n\n<ul>\n<li><p>When comparing points, you can use the fact that <code>(,)</code> is lexicographically ordered:</p>\n\n<pre><code>comparePoints :: Point2D -&gt; Point2D -&gt; Ordering\ncomparePoints a b = compare (y a, x a) (y b, x b)\n</code></pre></li>\n<li><blockquote>\n <p><code>Vector2D</code> and it's accessors. It's structurally equivalent to <code>Point2D</code> but I want to typecheck its usage. Hence I use <code>newtype</code> and not type, but it makes me implement custom accessors to unwrap the underlying <code>Point2D</code>. The nesting looks redundant.</p>\n</blockquote>\n\n<p>I strongly encourage to keep this separation. The (un)wrapping can be somewhat avoided by defining all required operations and then use only those, hiding the internal representation. Actually, I'd make them completely distinct (saves one constructor) and instead define their mathematical relationship. The <a href=\"http://www.haskell.org/haskellwiki/Vector-space\" rel=\"nofollow\">vector-space</a> library provides the proper type classes:</p>\n\n<pre><code>{-# LANGUAGE TypeFamilies #-}\nimport Data.AffineSpace\nimport Data.VectorSpace\n\ndata Vector2D = Vector2D { x :: Integer\n , y :: Integer\n } deriving (Show, Eq, Ord)\n\ninstance AdditiveGroup Vector2D where\n zeroV = Vector2D 0 0\n (Vector2D x1 y1) ^+^ (Vector2D x2 y2)\n = Vector2D (x1+x2) (y1+y2)\n negateV (Vector2D x1 y1)\n = Vector2D (-x1) (-y1)\ninstance VectorSpace Vector2D where\n type Scalar Vector2D = Integer\n k *^ (Vector2D x1 y1)\n = Vector2D (k*x1) (k*y1)\ninstance InnerSpace Vector2D where\n (Vector2D x1 y1) &lt;.&gt; (Vector2D x2 y2) = x1*x2 + y1*y2\n\neuclideanNorm2D :: Vector2D -&gt; Double\neuclideanNorm2D = sqrt . fromIntegral . magnitudeSq\n\n\ndata Point2D = Point2D { xv :: Integer\n , yv :: Integer\n } deriving (Show, Eq, Ord)\n\ninstance AffineSpace Point2D where\n type Diff Point2D = Vector2D\n (Point2D x1 y1) .-. (Point2D x2 y2)\n = Vector2D (x2 - x1) (y2 - y1)\n (Point2D x1 y1) .+^ (Vector2D x y)\n = Point2D (x1 + x) (y1 + y)\n</code></pre></li>\n<li><blockquote>\n <p>Point-free usage (or possibility of it) in following places:</p>\n</blockquote>\n\n<p>It's possible to convert any term into the point-free notation, but in some cases it makes things actually worse. Like in those where a variable is repeated: Surely <code>\\x -&gt; x * x</code> is more readable than <code>((*) &lt;*&gt; id)</code>. Anyway, using <code>magnitudeSq</code> from <em>vector-space</em> we can make <code>euclideanNorm2D</code> point-free (see above).</p>\n\n<p>Function <code>sortedPointsByAngleWithPX</code> can be simplified using <code>on</code> from <code>Data.Function</code>:</p>\n\n<pre><code>sortedPointsByAngleWithPX p l =\n sortBy (on compare snd) (zip l (angleWithXByPoint2DList p l))\n</code></pre></li>\n<li><p>It seems to me that <code>angleWithXByPoint2DList</code> can be simplified as</p>\n\n<pre><code>angleWithXByPoint2DList :: Point2D -&gt; [Point2D] -&gt; [Double]\nangleWithXByPoint2DList p = map (angleWithXBy2Points2D p)\n</code></pre>\n\n<p>using that we can make <code>sortedPointsByAngleWithPX</code> partially point-free using <code>(&amp;&amp;&amp;)</code> from <code>Control.Arrow</code>, but I have doubts if it's really useful (for me readability is more important):</p>\n\n<pre><code>sortedPointsByAngleWithPX p =\n sortBy (on compare snd) . map (id &amp;&amp;&amp; angleWithXBy2Points2D p)\n</code></pre></li>\n<li><blockquote>\n <p>Graham Scan implementation as two-level function — interface one and internal one. Maybe there's a way to merge them?</p>\n</blockquote>\n\n<p>On the contrary, I'd recommend keeping them split. Splitting code into more smaller functions is usually better than having one big complex one.</p></li>\n<li><p>Instead of having</p>\n\n<pre><code>grahamScanInternal acc l =\n let ...\n c = head l\n ...\n ... (tail l)\n</code></pre>\n\n<p>I'd strongly suggest using</p>\n\n<pre><code>grahamScanInternal acc (c:cs) =\n let ...\n ...\n ... cs\n</code></pre>\n\n<p>Both <code>head</code> and <code>tail</code> are partial functions and can be source of exceptions when used accidentally on the empty list. Pattern matching instead makes it clear that it can't happen.</p>\n\n<p>Moreover, <code>grahamScanInternal</code> can be rewritten as a fold, which makes its design slightly more clear:</p>\n\n<pre><code>grahamScanInternal :: [Point2D] -&gt; [Point2D] -&gt; [Point2D]\ngrahamScanInternal = foldl f\n where\n f acc c | (direction a b c) == Right = init acc ++ [c]\n | otherwise = acc ++ [c]\n where\n b = last acc\n a = last (init acc)\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T11:45:53.720", "Id": "31312", "ParentId": "31285", "Score": "8" } }, { "body": "<p>Please note that this program is buggy :</p>\n\n<pre><code>&gt; grahamScan [Point2D {x = -4, y = -1},Point2D {x = -5, y = -4},Point2D {x = -4, y = 1},Point2D {x = -5, y = 0},Point2D {x = 5, y = -5}]\n[Point2D {x = 5, y = -5},Point2D {x = 5, y = -5},Point2D {x = -4, y = 1},Point2D {x = -5, y = 0},Point2D {x = -5, y = -4}]\n&gt; grahamScan (grahamScan [Point2D {x = -4, y = -1},Point2D {x = -5, y = -4},Point2D {x = -4, y = 1},Point2D {x = -5, y = 0},Point2D {x = 5, y = -5}])\n[Point2D {x = 5, y = -5},Point2D {x = -4, y = 1},Point2D {x = -5, y = 0},Point2D {x = -5, y = -4},Point2D {x = 5, y = -5},Point2D {x = 5, y = -5}]\n</code></pre>\n\n<p>Even without the strange duplications, the algorithm gives a wrong answer for :</p>\n\n<pre><code>[Point2D {x = -1, y = 8},Point2D {x = 8, y = 4},Point2D {x = -9, y = 6},Point2D {x = 3, y = 7},Point2D {x = 5, y = 7},Point2D {x = -4, y = -6},Point2D {x = -7, y = 6},Point2D {x = 5, y = -1},Point2D {x = -2, y = -2}]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-11T09:34:54.277", "Id": "82084", "Score": "0", "body": "Thank you for noticing. I don't think this qualifies for answer to this question, however." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-11T10:26:30.667", "Id": "82090", "Score": "0", "body": "You are right, this should have been a comment, but it wouldn't fit ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-11T10:35:44.387", "Id": "82092", "Score": "1", "body": "@constantius - This is a great review. Identifying bugs is a very valuable component in a review. This review may not address your request for *style and convention*, etc., but as per the [help/on-topic] it is implied that you: *... want feedback about any or all facets of the code*. This is good feedback on some facets of your code. bartavelle, feel free to review like this again (and again), but also feel free to review other items, and, if it makes sense, feel free to add multiple answers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-11T10:49:29.590", "Id": "82093", "Score": "0", "body": "@bartavelle Welcome to Code Review, and thank you for your contribution! [Any remark that points out a deficiency in the code is a good answer](http://meta.codereview.stackexchange.com/a/1479/9357) — it deserves reputation points, and is too valuable to be merely a comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-11T11:57:00.497", "Id": "82099", "Score": "0", "body": "I just wanted to point out that review done on style/convention provides not bare claims of deficiencies, but means to do better. I don't, however, say, that the reviewer should tell how to fix the bug in this particular case. This difference struck me at first." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-11T09:30:21.907", "Id": "46895", "ParentId": "31285", "Score": "6" } } ]
{ "AcceptedAnswerId": "31312", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T22:49:48.803", "Id": "31285", "Score": "8", "Tags": [ "beginner", "haskell", "computational-geometry" ], "Title": "Graham Scan convex hull algorithm" }
31285
<p>Are there any ways to make this calculator script for Python better or simpler?</p> <pre><code>thelist = ["Add", "add", "Multiply", "multiply", "Divide", "divide","Subtract", "subtract"] def Multiply(x,y): z = x * y print(z) def Divide(x,y): x = float(x) y = float(y) z = x / y print(z) def Add(x,y): z = x + y print(z) def Subtract(x,y): z = x - y print(z) while True: operation = input("What would you like to do? Multiply/Divide/Add/Subtract ") if operation in thelist: break else: print("That was not an option..") if operation == "Multiply" or operation == "multiply": while True: try: x = int(input("First number: ")) break except ValueError: print("Make sure to enter a number.") while True: try: y = int(input("Second number: ")) break except ValueError: print("Make sure to enter a number...") Multiply(x,y) elif operation == "subtract" or operation == "Subtract": while True: try: x = int(input("First number: ")) break except ValueError: print("Make sure to enter a number.") while True: try: y = int(input("Second number: ")) break except ValueError: print("Make sure to enter a number.") Subtract(x,y) elif operation == "Add" or operation == "add": while True: try: x = int(input("First number: ")) break except ValueError: print("Make sure to enter a number..") while True: try: y = int(input("Second number: ")) break except ValueError: print("Make sure to enter a number.") Add(x,y) elif operation == "Divide" or operation == "divide": while True: try: x = int(input("First number: ")) break except ValueError: print("Make sure to enter a number.") while True: try: y = int(input("Second number: ")) break except ValueError: print("Make sure to enter a number.") Divide(x,y) else: pass </code></pre>
[]
[ { "body": "<p>A thorough review would very much depend on what you're trying to achieve.</p>\n\n<p>For example, it seams mighty clumsy to have to type <code>multiply</code> instead of just <code>*</code>. Also, a case-insensitive match would be much better. For that, you might want to check <a href=\"https://stackoverflow.com/questions/6797984/how-to-convert-string-to-lowercase-in-python\">method <code>lower</code></a> or <a href=\"http://docs.python.org/2/library/re.html\" rel=\"nofollow noreferrer\">how to use regular expressions in Python</a>.</p>\n\n<p>Judging from your use of <code>print</code>, you're aiming at Python 3. If this is the case, then - unlike in Python 2 - you don't need </p>\n\n<pre><code>x = float(x)\ny = float(y)\n</code></pre>\n\n<p>in function <code>Divide</code>. Of course, if you want your code to work in both Python 2 &amp; 3, it's O.K. to keep that code. However, even in that case, converting only one of these two variables to float is enough.</p>\n\n<p>Like most (all?) interpreted and pseudocompiled languages, Python has <code>eval</code> function. So, you can basically do <code>result = eval(expression)</code>, where <code>expression</code> is a string with any Python code. For example, if you have a string <code>\"1+2*3\"</code>, and send it to <code>eval</code>, you'll get <code>7</code> (unless my math is off :-)). This might help you significantly, but be careful to not pass on just any (potentially junky) user's input.</p>\n\n<p>One thing seems strange to me. You do</p>\n\n<pre><code>if operation == \"Multiply\" or operation == \"multiply\":\n 12 lines to input x and y\n Multiply(x,y)\nelif operation == \"subtract\" or operation == \"Subtract\":\n THE SAME 12 lines to input x and y\n Subtract(x,y)\n...\n</code></pre>\n\n<p>Why don't you first input <code>x</code> and <code>y</code>, and then do <code>if-elif</code> block for the actual computation, or, at least, make a function to input <code>x</code> and <code>y</code> and return them (functions in Python can return multiple values)? You have functions for simple expressions which are called only once (multiplication, subtraction, etc), which seem completely unnecessary, but you don't make one for 12 lines of code which are invoked 4 times in your code.</p>\n\n<p>Regarding your naming of functions, <a href=\"http://www.python.org/dev/peps/pep-0008/#function-names\" rel=\"nofollow noreferrer\"><em>function names should be lowercase, with words separated by underscores as necessary to improve readability</em></a>, i.e., you shouldn't capitalize the names of your functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T00:40:13.903", "Id": "49810", "Score": "0", "body": "`z` isn't global." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T00:41:35.273", "Id": "49811", "Score": "0", "body": "You're right. Sorry for that, I'll remove it. I had a different agenda in my head (computing in functions and printing outside of them, just like you suggested in your answer). Thank you." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T00:34:00.007", "Id": "31290", "ParentId": "31286", "Score": "4" } }, { "body": "<p>I like how you put <code>divide</code>, <code>multiply</code>, <code>add</code> and <code>subtract</code> each into their own function, but it would be even better if the function returned the result instead of printing it. That way, you can do something else with the result instead of printing it if you want to, and still use the same function.</p>\n\n<pre><code>def multiply(x, y):\n return x * y\n</code></pre>\n\n<p>Then, further down, you need to write <code>print(multiply(x, y))</code>.</p>\n\n<p>The <code>while</code> loops you use to get input look good.</p>\n\n<p>One thing that bothers me is that you have the same 12 lines of code 4 times. You should reuse the same lines as much as possible, so that if you want to change something, you only have to change it in one place. This code should appear only once:</p>\n\n<pre><code>while True:\n try:\n x = int(input(\"First number: \"))\n break\n except ValueError:\n print(\"Make sure to enter a number.\")\nwhile True:\n try:\n y = int(input(\"Second number: \"))\n break\n except ValueError:\n print(\"Make sure to enter a number...\")\n</code></pre>\n\n<p>In this case, it's easy to fix. Put it right before the line:</p>\n\n<pre><code>if operation == \"Multiply\" or operation == \"multiply\":\n</code></pre>\n\n<p>Now it will be run no matter what the operation is and you can delete the repetitions.</p>\n\n<p>But that piece of code above still repeats twice what is essentially the same thing. We should also do something about that. I would use a function (I'd put the function next to the other functions at the top.):</p>\n\n<pre><code>def get_int_input(prompt):\n while True:\n try:\n return int(input(prompt))\n except ValueError:\n print(\"Make sure to enter a number...\")\n\nx = get_int_input(\"First number: \")\ny = get_int_input(\"Second number: \")\n</code></pre>\n\n<p>This will do the same thing as the old code.</p>\n\n<p>Next let's do something about the fact that we're writing every operation's name twice:</p>\n\n<pre><code>if operation == \"Multiply\" or operation == \"multiply\":\n</code></pre>\n\n<p>I would change that by making the content of <code>operation</code> lowercase as soon as possible:</p>\n\n<pre><code>thelist = [\"Add\", \"add\", \"Multiply\", \"multiply\", \"Divide\", \"divide\",\"Subtract\", \"subtract\"]\n</code></pre>\n\n<p>Now you don't need to care about case anymore. Note that this isn't exactly the same, though: it will also allow input such as <code>MULtiplY</code>.</p>\n\n<p>Now we can change the first line to:</p>\n\n<pre><code>operations = [\"add\", \"multiply\", \"divide\", \"subtract\"]\n</code></pre>\n\n<p>(I think <code>operations</code> is a better name than <code>thelist</code>.) And we can change our two checks for each operation to:</p>\n\n<pre><code>if operation == \"multiply\":\n print(multiply(x, y))\nelif operation == \"subtract\":\n ...\n</code></pre>\n\n<p>You can remove <code>else: pass</code>.</p>\n\n<p>This post is already quite long, but one more thing: you should change your code to use 4 spaces per indent. This is because tabs can be displayed in different ways, for example, they break the indentation on here stackexchange if you're not careful. Most editors have a setting so that when you hit the <kbd>tab</kbd> key, 4 spaces appear. To change the code you've already written, use the editor's replace option to replace each <code>tab</code> character with 4 spaces.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T00:35:24.667", "Id": "31291", "ParentId": "31286", "Score": "3" } }, { "body": "<p>There are several concerns with your code.</p>\n\n<ul>\n<li>You cast your numeric inputs as <code>int</code>. Subsequent casting to <code>float</code> won't recover the lost precision.</li>\n<li>It's very repetitive. There is a lot of copy-and-pasted code, which makes the program hard to maintain.</li>\n<li>Your top-level \"function\" is very long. In particular, nesting <code>if</code>-<code>while</code>-<code>try</code> blocks makes the flow of control hard to follow. Ideally, anything longer than a dozen lines should be broken up into simpler functions.</li>\n<li>It takes a lot of work to define a new operation. For example, to support Addition, you have to\n<ul>\n<li>Add two entries to <code>thelist</code></li>\n<li>Define the <code>Add()</code> function</li>\n<li>Change the prompt for the operation</li>\n<li>Add a conditional to check if the operation name matches <code>\"Add\"</code> or <code>\"add\"</code>, and call <code>Add()</code> if it does</li>\n</ul></li>\n</ul>\n\n<p>A key concept for consolidating all that functionality is to define a <code>BinaryOperation</code> class. Then, instead of writing out the instructions explicitly, let the data drive the logic.</p>\n\n<pre><code>from collections import OrderedDict\n\nclass BinaryOperation:\n def __init__(self, op):\n self.op = op\n\n def go(self):\n x = self._prompt(\"First number: \")\n y = self._prompt(\"Second number: \")\n print(self.op(x, y))\n\n def _prompt(self, prompt):\n while True:\n try:\n return float(input(prompt))\n except ValueError:\n print(\"Make sure to enter a number...\")\n\ndef get_operation(operations):\n while True:\n op_name = input(\"What would you like to do? \" +\n '/'.join(operations.keys()) + ' ').title()\n try:\n return operations[op_name]\n except KeyError:\n print(\"That was not an option.\")\n\noperations = OrderedDict([\n ('Multiply', BinaryOperation(lambda x, y: x * y)),\n ('Divide', BinaryOperation(lambda x, y: x / y)),\n ('Add', BinaryOperation(lambda x, y: x + y)),\n ('Subtract', BinaryOperation(lambda x, y: x - y)),\n])\nget_operation(operations).go()\n</code></pre>\n\n<p><strong>Edit:</strong> The OP would like an explanation of the code, so I'll give it a shot.</p>\n\n<p><code>lambda</code> is a way to define a very simple unnamed function. That function can then be assigned and passed around, just like any other value in Python. For example, instead of saying</p>\n\n<pre><code>def square(number):\n return number * number\n</code></pre>\n\n<p>you could say</p>\n\n<pre><code>square = lambda number: number * number\n</code></pre>\n\n<p>In Python, <code>lambda</code>s are limited to just one expression, to prevent programmers from trying to squeeze too much complex code inside. But that's just perfect for our simple calculator. We pass the lambda as a parameter to the <code>BinaryOperation</code> constructor, where it gets stored as the <code>BinaryOperation</code> object's <code>op</code> variable. Later, the <code>go()</code> method can call <code>self.op(x, y)</code> to perform the calculation.</p>\n\n<p>If you're uncomfortable with passing functions around, you could do something with inheritance instead. It's more verbose, though, to have to define so many subclasses.</p>\n\n<pre><code>class BinaryOperation:\n def go(self):\n x = self._prompt(\"First number: \")\n y = self._prompt(\"Second number: \")\n print(self.op(x, y))\n\n def _prompt(self, prompt):\n while True:\n try:\n return float(input(prompt))\n except ValueError:\n print(\"Make sure to enter a number...\")\n\nclass Multiplication(BinaryOperation):\n @staticmethod\n def op(x, y):\n return x * y\n\n# etc.\n\noperations = OrderedDict([\n ('Multiply', Multiplication()),\n ('Divide', Division()),\n ('Add', Addition()),\n ('Subtract', Subtraction()),\n])\nget_operation(operations).go()\n</code></pre>\n\n<p><strong>Edit 2</strong>: I've just learned from @Stuart about the <code>operator</code> module, which already defines the lambdas we want. Therefore, we could equivalently write</p>\n\n<pre><code>import operator\noperations = OrderedDict([\n ('Multiply', BinaryOperation(operator.mul)),\n ('Divide', BinaryOperation(operator.truediv)),\n ('Add', BinaryOperation(operator.add)),\n ('Subtract', BinaryOperation(operator.sub)),\n])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T04:36:47.477", "Id": "49819", "Score": "0", "body": "I wish I was that good at writing code, but I'm still learning basic things. I have no clue what some of those words in this code are. For example, \"self.op\" and \"lambda\". I just mainly know how to do the really basic things in Python. Thanks for the feedback though, I will definitely try learning some of these things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T05:14:59.137", "Id": "49822", "Score": "0", "body": "`int` has unlimited precision. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T05:22:03.997", "Id": "49823", "Score": "0", "body": "Thanks @200_success I appreciate you explaining this more to me. What is the best way to learn Python by myself? It feels like I can't get past the basics, and I'm practically teaching myself. Any suggestions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T05:38:45.507", "Id": "49824", "Score": "0", "body": "@flornquake Yes, but 1.5 + 1.5 = 2 would be lossier than the calculator in MS Windows. =) The [`decimal`](http://docs.python.org/3.1/library/decimal.html) module would be ideal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T05:49:45.990", "Id": "49825", "Score": "0", "body": "@TheSuds13 You're already on the right track! Learning to program is like learning any foreign language — the most effective way is immersion. Practice. Learn from your bugs. Study others' code. Ask for code reviews. Follow the official Python tutorial and documentation; skip the parts you don't understand, and come back to them years later, after dabbling in other languages. This was probably not the advice you were looking for, but it's the truth!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T05:57:44.070", "Id": "49829", "Score": "0", "body": "@200_success Alright thanks! I've only spent about 3 weeks learning this language so far. I can't wait to learn more and more!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T03:10:50.723", "Id": "31298", "ParentId": "31286", "Score": "3" } } ]
{ "AcceptedAnswerId": "31290", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T22:57:02.730", "Id": "31286", "Score": "3", "Tags": [ "python", "python-3.x", "calculator" ], "Title": "Python calculator script" }
31286
<p>This is a simple mixed drink calculator written in Haskell. </p> <p>There are two input files. The <code>drinks</code> file contains a list of simply formatted recipes for mixed drinks:</p> <pre><code>screwdriver:vodka,orange juice white russian:vodka,coffee liqueur,cream greyhound:gin,grapefruit juice ... </code></pre> <p>The <code>ingredients</code> file contains a line-separated list of presently available ingredients:</p> <pre><code>vodka gin rum orange juice cranberry juice grapefruit juice ... </code></pre> <p>The calculator parses the drinks file and the ingredients file, determines which mixed drinks can be created with the available ingredients, and pretty-prints the results to screen:</p> <pre class="lang-none prettyprint-override"><code>Screwdriver: Vodka, Orange juice Greyhound: Gin, Grapefruit juice ... </code></pre> <p>It's a simple program, but I want to improve my code style and make my Haskell more idiomatic.</p> <pre class="lang-hs prettyprint-override"><code>import Text.ParserCombinators.Parsec import Data.Char import Data.List type Drink = (DrinkName, [Ingredient]) type DrinkName = String type Ingredient = String -- parsing the file of drink recipes drinksFile ∷ GenParser Char st [Drink] drinksFile = endBy drink (char '\n') -- parsing each drink recipe drink ∷ GenParser Char st Drink drink = do first ← drinkName next ← recipe return (first, next) -- parsing the drink name drinkName ∷ GenParser Char st DrinkName drinkName = do name ← many (noneOf ":") sep ← many (char ':') return name -- parsing the recipe into a list of ingredients recipe ∷ GenParser Char st [Ingredient] recipe = sepBy (many (noneOf ",\n")) (char ',') -- returns true iff the drink can be made with the given ingredients canMake ∷ [Ingredient] → Drink → Bool canMake ingredients drink = all (flip elem ingredients) recipe where recipe = snd drink -- returns the drinks that can be made with the given ingredients filterByIngredients ∷ [Drink] → [Ingredient] → [Drink] filterByIngredients drinks ingredients = filter (canMake ingredients) drinks -- pretty prints a drink with its recipe printDrink ∷ Drink → String printDrink (drinkName, recipe) = intercalate " " (map capitalize (words drinkName)) ++ ": " ++ intercalate ", " (map capitalize recipe) where capitalize (x : xs) = toUpper x : xs main = do drinks ← readFile "drinks" ingredients ← readFile "ingredients" case parse drinksFile "drinksFile" drinks of Left error → do putStrLn "Error parsing drinks file." Right parsedDrinks → mapM_ (putStrLn ∘ printDrink) (filterByIngredients parsedDrinks (lines ingredients)) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-16T17:11:27.373", "Id": "52403", "Score": "0", "body": "Can you either remove unicode syntax or upload the file to hpaste or other place where I can easily get bit-exact downloads from? Somehow I get parse errors." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-27T20:47:16.357", "Id": "84878", "Score": "1", "body": "+1 Yes, making ***many*** mixed drinks is very idiomatic for Haskell. Now we just need a comprehensive `drinks.txt` file..." } ]
[ { "body": "<h2>Good News:</h2>\n\n<p>Architecturally, your code looks very well designed. I can't think of any language features that would significantly improve your code's architecture. That leaves only function semantics and readability.</p>\n\n<h2>Advise:</h2>\n\n<p>This advise isn't specific to idiomatic Haskell but rather general code readability.</p>\n\n<p>Your current main method does a little too much. the contents of main should have a high level of abstraction. Consider abstracting the work done at the end of your main function:</p>\n\n<pre><code>main = do drinks &lt;- readFile \"drinks\"\n ingredients &lt;- readFile \"ingredients\"\n putStrLn $ \n case parse drinksFile \"drinksFile\" drinks of\n Left error -&gt; \"Error parsing drinks file.\"\n Right parsedDrinks -&gt; showPossibleDrinks parsedDrinks (lines ingredients)\n\nshowPossibleDrinks :: [Drink] -&gt; [Ingredient] -&gt; String\nshowPossibleDrinks drinks ingredients = showDrinks $ filterByIngredients drinks ingredients\n\nshowDrinks :: [Drink] -&gt; String\nshowDrinks = unlines . map printDrink\n</code></pre>\n\n<p>Here we have abstracted the process of printing the possible drinks into two sub methods. This provides greater readability and also allows us to change the return type of <code>case</code> from <code>IO</code> to <code>String</code>. Hence the <code>putStrLn</code> outside the <code>case</code> statement.</p>\n\n<hr>\n\n<p>By changing the argument order of a few functions, we can move the functions towards <a href=\"http://www.haskell.org/haskellwiki/Pointfree\" rel=\"nofollow\"><em>pointfree</em></a> form:</p>\n\n<pre><code>canMake :: [Ingredient] -&gt; Drink -&gt; Bool\ncanMake ingredients = all (flip elem ingredients) . snd\n\nfilterByIngredients :: [Ingredient] -&gt; [Drink] -&gt; [Drink]\nfilterByIngredients ingredients = filter (canMake ingredients)\n\nmain = do drinks &lt;- readFile \"drinks\"\n ingredients &lt;- readFile \"ingredients\"\n putStrLn $\n case parse drinksFile \"drinksFile\" drinks of\n Left error -&gt; \"Error parsing drinks file.\"\n Right parsedDrinks -&gt; showPossibleDrinks (lines ingredients) parsedDrinks\n\nshowPossibleDrinks :: [Ingredient] -&gt; [Drink] -&gt; String\nshowPossibleDrinks = showDrinks . (filterByIngredients ingredients)\n</code></pre>\n\n<p>Given the succinctness of your methods, moving towards <a href=\"http://www.haskell.org/haskellwiki/Pointfree\" rel=\"nofollow\"><em>pointfree</em></a> form is quite readable and more idiomatic.</p>\n\n<hr>\n\n<p>If we import the <a href=\"http://www.haskell.org/ghc/docs/7.6.2/html/libraries/base/Control-Applicative.html#v%3a-60--36--62-\" rel=\"nofollow\"><strong><code>&lt;$&gt;</code></strong></a> operator from <a href=\"http://www.haskell.org/ghc/docs/7.6.2/html/libraries/base/Control-Applicative.html\" rel=\"nofollow\"><strong><code>Control.Applicative</code></strong></a> after transposing the function's arguments we can make <code>filterByIngredients</code> completely <a href=\"http://www.haskell.org/haskellwiki/Pointfree\" rel=\"nofollow\"><em>pointfree</em></a>:</p>\n\n<pre><code>filterByIngredients :: [Ingredient] -&gt; [Drink] -&gt; [Drink]\nfilterByIngredients = filter &lt;$&gt; canMake\n</code></pre>\n\n<hr>\n\n<p>You can make the following equivalence substitutions:</p>\n\n<pre><code>(flip elem ingredients) ==&gt; (`elem` ingredients)\nintercalate \" \" ==&gt; unwords\n</code></pre>\n\n<p>Giving you:</p>\n\n<pre><code>canMake :: [Ingredient] -&gt; Drink -&gt; Bool\ncanMake ingredients = all (`elem` ingredients) . snd\n\nprintDrink :: Drink -&gt; String\nprintDrink (drinkName, recipe) = unwords (map capitalize (words drinkName)) ++\n \": \" ++\n intercalate \", \" (map capitalize recipe)\n where capitalize (x : xs) = toUpper x : xs\n</code></pre>\n\n<hr>\n\n<p><strong>All together we have:</strong></p>\n\n<pre><code>import Control.Applicative ((&lt;$&gt;))\nimport Data.Char\nimport Data.List\nimport Text.ParserCombinators.Parsec\n\ntype Drink = (DrinkName, [Ingredient])\ntype DrinkName = String\ntype Ingredient = String\n\n-- parsing the file of drink recipes\ndrinksFile :: GenParser Char st [Drink]\ndrinksFile = endBy drink (char '\\n')\n\n-- parsing each drink recipe\ndrink :: GenParser Char st Drink\ndrink = do first &lt;- drinkName\n next &lt;- recipe\n return (first, next)\n\n-- parsing the drink name\ndrinkName :: GenParser Char st DrinkName\ndrinkName = do name &lt;- many (noneOf \":\")\n sep &lt;- many (char ':')\n return name\n\n-- parsing the recipe into a list of ingredients\nrecipe :: GenParser Char st [Ingredient]\nrecipe = sepBy (many (noneOf \",\\n\")) (char ',')\n\ncanMake :: [Ingredient] -&gt; Drink -&gt; Bool\ncanMake ingredients = all (`elem` ingredients) . snd\n\nfilterbyIngredients :: [Ingredient] -&gt; [Drink] -&gt; [Drink]\nfilterbyIngredients = filter &lt;$&gt; canMake\n\n-- pretty prints a drink with its recipe\nprintDrink :: Drink -&gt; String\nprintDrink (drinkName, recipe) = unwords (map capitalize (words drinkName)) ++\n \": \" ++\n intercalate \", \" (map capitalize recipe)\n where capitalize (x : xs) = toUpper x : xs\n\nshowPossibleDrinks :: [Ingredient] -&gt; [Drink] -&gt; String\nshowPossibleDrinks ingredients = showDrinks . filterbyIngredients ingredients\n\nshowDrinks :: [Drink] -&gt; String\nshowDrinks = unlines . map printDrink\n\nmain = do drinks &lt;- readFile \"drinks\"\n ingredients &lt;- readFile \"ingredients\"\n putStrLn $ \n case parse drinksFile \"drinksFile\" drinks of\n Left error -&gt; \"Error parsing drinks file.\"\n Right parsedDrinks -&gt; showPossibleDrinks (lines ingredients) parsedDrinks\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-27T22:16:21.653", "Id": "48369", "ParentId": "31288", "Score": "2" } } ]
{ "AcceptedAnswerId": "48369", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-14T23:52:01.093", "Id": "31288", "Score": "8", "Tags": [ "haskell" ], "Title": "Mixed Drink Calculator in Haskell" }
31288
<p>Currently I have a game that does this and then checks for victory conditions in <code>victoryTable</code></p> <pre><code>victoryTable[0] = rows[0][0] + rows[0][1] + rows[0][2]; victoryTable[1] = rows[1][0] + rows[1][1] + rows[1][2]; victoryTable[2] = rows[2][0] + rows[2][1] + rows[2][2]; victoryTable[3] = rows[0][0] + rows[1][0] + rows[2][0]; victoryTable[4] = rows[0][1] + rows[1][1] + rows[2][1]; victoryTable[5] = rows[0][2] + rows[1][2] + rows[2][2]; victoryTable[6] = rows[0][0] + rows[1][1] + rows[2][2]; victoryTable[7] = rows[0][2] + rows[1][1] + rows[2][0]; </code></pre> <p>But I am considering changing it to read this way:</p> <pre><code>for (int i = 0; i &lt; 8; i++ ) { for (int n = 0; n &lt; 3; n++) { for (int t = 0; t &lt; 3; t++) { victoryTable[i] = rows[n][t] + // based on some combination of n,t and // if statement to filter out garbage/duplicates, // the more I think about this implementation the // more complicated it seems. } } } </code></pre> <p>Would this be a step in the wrong direction? It seems like I should put the things that change in a method or loop or something, but it also looks like this will make it harder to read what the code does, and have more potential for bugs (undesired conditions, etc) but also more expandability (if game board became larger in future version, for instance.</p> <p>The larger context is this: This is part of a method that determines the victory state of a Tic Tac Toe game. In a 3x3 <code>int[][]</code>, player X is represented by a <code>3</code>, player O by a <code>30</code>. The code in this post adds each column, row, and diagonal, and stores them in an array. Another method loops through that array and if any element equals <code>90</code>, O wins, if it equals <code>9</code>, X wins, otherwise nobody wins (yet).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T07:46:43.190", "Id": "49831", "Score": "0", "body": "You can look into [magic-square number](http://mathworld.wolfram.com/MagicSquare.html)." } ]
[ { "body": "<p>This is not a direct answer to your question.</p>\n\n<p>You should probably rethink your design. I guess the different elements of <code>rows[][]</code> have some meaning, so you should define a class with the appropriate member variables which have explicit names.</p>\n\n<p>We don't have much information to go on to tell you how to do this. Also, maybe you should rethink <code>victoryTable[]</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T01:18:17.530", "Id": "31294", "ParentId": "31292", "Score": "0" } }, { "body": "<p>Without an advanced math degree, I think this is a perfectly reasonable solution. Here's a sample implementation. It's not that complicated. Basically, for every <code>WIN_CONDITION</code> that exists (each of which is a set of coordinates on the board), we check that sequence and see if the <code>Mark</code>s are all the same. If so, that player has won.</p>\n\n<p>I don't think that's a step in the wrong direction. It's perfectly logical and functional.</p>\n\n<p>Now if it was a more vast game like Connect Four... looping through each variation might be a better option that explicitly listing each win condition, obviously. But since Tic-Tac-Toe has such a small set, this is fine and makes the code pretty readable.</p>\n\n<pre><code>private static Mark[][] board = new Mark[3][3];\n\nprivate static final int[][][] WIN_CONDITIONS = {\n //Rows\n {{ 0, 0 }, { 0, 1 }, { 0, 2 }},\n {{ 1, 0 }, { 1, 1 }, { 1, 2 }},\n {{ 2, 0 }, { 2, 1 }, { 2, 2 }},\n\n //Columns\n {{ 0, 0 }, { 1, 0 }, { 2, 0 }},\n {{ 0, 1 }, { 1, 1 }, { 2, 1 }},\n {{ 0, 2 }, { 1, 2 }, { 2, 2 }},\n\n //Diagonals\n {{ 0, 0 }, { 1, 1 }, { 2, 2 }},\n {{ 2, 0 }, { 1, 1 }, { 0, 2 }}\n};\n\n// other stuff, like an enum for Mark (Mark.X and Mark.O) and the GameState\n\nprivate GameState checkWinConditions() {\n\n GameState won = null;\n\n for(int[][] condition : WIN_CONDITIONS) {\n Mark comparator = board[condition[0][0]][condition[0][1]];\n if(comparator == null) continue;\n\n won = comparator.getWinState();\n for(int[] coordinate : condition) {\n if(board[coordinate[0]][coordinate[1]] != comparator) {\n won = null;\n break;\n }\n }\n if(won != null) break;\n }\n return won;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-04T18:46:27.457", "Id": "32258", "ParentId": "31292", "Score": "3" } }, { "body": "<p>You could store the total of each row, column and the diagonals and check against it at each move. See below:</p>\n\n<pre><code>private class Referee {\n private static final int NO_OF_DIAGONALS = 2;\n private static final int MINOR = 1;\n private static final int PRINCIPAL = 0;\n private final int gridSize;\n private final int[] rowTotal;\n private final int[] colTotal;\n private final int[] diagonalTotal;\n\n private Referee(int size) {\n gridSize = size;\n rowTotal = new int[size];\n colTotal = new int[size];\n diagonalTotal = new int[NO_OF_DIAGONALS];\n }\n\n private String isGameOver(int x, int y, char symbol, int moveCount) {\n if (isWinningMove(x, y, symbol))\n return symbol + \" won the game!\";\n if (isBoardCompletelyFilled(moveCount))\n return \"Its a Draw!\";\n return \"continue\";\n }\n\n private boolean isBoardCompletelyFilled(int moveCount) {\n return moveCount == gridSize * gridSize;\n }\n\n private boolean isWinningMove(int x, int y, char symbol) {\n if (isPrincipalDiagonal(x, y) &amp;&amp; allSymbolsMatch(symbol, diagonalTotal, PRINCIPAL))\n return true;\n if (isMinorDiagonal(x, y) &amp;&amp; allSymbolsMatch(symbol, diagonalTotal, MINOR))\n return true;\n return allSymbolsMatch(symbol, rowTotal, x) || allSymbolsMatch(symbol, colTotal, y);\n }\n\n private boolean allSymbolsMatch(char symbol, int[] total, int index) {\n total[index] += symbol;\n return total[index] / gridSize == symbol;\n }\n\n private boolean isPrincipalDiagonal(int x, int y) {\n return x == y;\n }\n\n private boolean isMinorDiagonal(int x, int y) {\n return x + y == gridSize - 1;\n }\n}\n</code></pre>\n\n<p>Full source available at: <a href=\"https://github.com/nashjain/tictactoe/tree/master/java\" rel=\"nofollow\">https://github.com/nashjain/tictactoe/tree/master/java</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T13:19:40.760", "Id": "52465", "Score": "3", "body": "When you throw an Exception for control flow, it makes me cringe. `throw new GameOverException()` in order to end the game is really poor design. The rest of your code is quite nice though, odd method names and implicit `public`s withstanding." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-18T04:19:33.013", "Id": "52546", "Score": "1", "body": "I've fixed the exception bit!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T12:19:23.587", "Id": "32812", "ParentId": "31292", "Score": "1" } }, { "body": "<p>I would split the <code>for</code> loop into four pieces: one <code>for</code> loop for the rows, one <code>for</code> loop for the columns, and two single statements for the NE-SW and NW-SE diagonals. I think that still saves some typing, without making the calculations too complicated.</p>\n\n<p>Imagine trying to make a three-dimensional tictactoe: then you would need 3 <code>for</code> loops (in the x/y/z directions), and 4 diagonals. Still pretty reasonable, and readable, in my opinion. Only at four-dimensional tictactoe would I start doing fancy stuff :-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T12:39:52.330", "Id": "32813", "ParentId": "31292", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T00:38:10.783", "Id": "31292", "Score": "3", "Tags": [ "java" ], "Title": "Detecting Tic-Tac-Toe win: Enumerate all possibilities or use nested loops?" }
31292
<p>I am trying to write code to convert properties of an Entity Framework entity to strings and back.</p> <p>Here is the code so far that converts back from strings to the object properties.</p> <p>I am stuck trying to figure out how to handle datetime. I am also wondering if there is a better approach.</p> <pre><code>private static FormatterConverter formatConverter; public static FormatterConverter FormatConverter { get { if (formatConverter == null) { formatConverter = new FormatterConverter(); } return formatConverter; } } // ChangeValue is an entity framework entity. static void DoSetValue(ChangeValue cv , PropertyInfo pi, object obj ) { try { switch (pi.PropertyType.ToString()) { case "System.TimeSpan": case "System.Nullable`1[System.TimeSpan]": var s = cv.Value; if (s == "") s = "0"; var ticks = Convert.ToInt64(s); var ts = new TimeSpan(ticks); obj = ts; break; case "": case "System.Nullable`1[System.DateTime]": // code needed here break; case "System.Guid": obj = new Guid(cv.Value); break; default: pi.SetValue(obj, FormatConverter.Convert(cv.Value, pi.PropertyType), null); break; } } catch (Exception ex) { ex.Data.Add("", string.Format( "Error converting type for {0} {1} ",pi.Name ,pi.PropertyType.ToString())); throw ex; } } </code></pre>
[]
[ { "body": "<p>If you are trying to convert the string to DateTime format that might be used in the EF object, you may try:</p>\n\n<pre><code>Convert.ToDateTime(\"2013-09-10 12:12:12\",System.Globalization.CultureInfo.InvariantCulture)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-13T18:28:00.610", "Id": "32649", "ParentId": "31293", "Score": "1" } } ]
{ "AcceptedAnswerId": "32649", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T01:17:00.497", "Id": "31293", "Score": "1", "Tags": [ "c#", "entity-framework", "serialization" ], "Title": "Serialize the properties of an entity framework entity to data fields and back" }
31293
<p>I'm new to Java and Android. While I've created a project that seems to work, I'd like some opinions on how to make it better. </p> <p>The app is going to be used as an interval workout timer/music player for Android devices. I know there's a ton of these already, but I thought it'd be a good way to learn the language, and it's useful for me. I haven't gotten the music player piece working yet. I was thinking of letting you select between selecting a playlist to play or using the 8tracks.com API to play streaming music. Comments are welcome, too.</p> <p>The code can be seen in full <a href="https://github.com/iyeager2004/WorkoutStopwatch" rel="nofollow" title="in this Github">in this Github</a>.</p> <p>Here's the main package:</p> <pre><code>package com.blueflamesys.workoutstopwatch; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.CountDownTimer; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class WorkoutStopwatch extends Activity implements OnClickListener { private static final String TAG = "WorkoutMain"; private static final String API_KEY = "30eee341eb88a9647b40d187faf508b50ca318d9"; private boolean timerRunning, isPaused = false; private long millisLeft = 0; private WorkoutTimer workoutTimer; private enum CounterState { UNKNOWN(0), WORKOUT(1), REST(2); private int stateValue; CounterState(int state) { this.stateValue = state; } public int getStateValue() { return stateValue; } public void setStateValue(int state) { this.stateValue = state; } } CounterState state = CounterState.WORKOUT; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.workout_stopwatch); // Set up OnClickListeners ((Button) findViewById(R.id.start_button)).setOnClickListener(this); ((Button) findViewById(R.id.pause_button)).setOnClickListener(this); ((Button) findViewById(R.id.reset_button)).setOnClickListener(this); } @Override public void onClick(View v) { switch(v.getId()) { case R.id.start_button: Log.d(TAG, "clicked on Start Button"); if (!isPaused &amp;&amp; !timerRunning) { Log.d(TAG, "Wasn't paused and wasn't running..."); timerRunning = true; // If the state is unknown, set it to Workout first int State = state.getStateValue(); if (State == 0) { state.setStateValue(1); } workoutTimer = new WorkoutTimer(50); workoutTimer.start(); } if (isPaused) { timerRunning = true; this.resumeTimer(); Log.d(TAG, "Was paused resumed timer..."); } break; case R.id.pause_button: Log.d(TAG, "clicked on Pause Button"); if (timerRunning) { timerRunning = false; this.pauseTimer(); Log.d(TAG, "Paused timer..."); } break; case R.id.reset_button: Log.d(TAG, "clicked on Reset Button"); if (!timerRunning) { Log.d(TAG, "Wasn't running..."); isPaused = false; TextView digital_display = (TextView) findViewById(R.id.digital_display); digital_display.setText("00:00.0"); } break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.stopwatch_settings, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.settings: startActivity(new Intent(this, Prefs.class)); return true; case R.id.about: Intent i = new Intent(this, About.class); startActivity(i); break; } return false; } public void pauseTimer() { isPaused = true; SharedPreferences workoutTimerDB = getSharedPreferences("workoutTimerDB", MODE_PRIVATE); SharedPreferences.Editor edit = workoutTimerDB.edit(); edit.putLong("millisLeft", (Long)this.millisLeft); edit.commit(); workoutTimer.cancel(); } public void resumeTimer() { if (isPaused) { isPaused = false; SharedPreferences workoutTimerDB = getSharedPreferences("workoutTimerDB", MODE_PRIVATE); millisLeft = workoutTimerDB.getLong("millisLeft", 0); workoutTimer = new WorkoutTimer(millisLeft, 50); workoutTimer.start(); } } private class WorkoutTimer extends CountDownTimer{ public WorkoutTimer(long interval) { super(getThisTime(), interval); Log.d(TAG, "WorkoutTimer Constructed with interval only..."); } public WorkoutTimer(long millis, long interval) { super(millis, interval); Log.d(TAG, "WorkoutTimer Constructed with both..."); } public void onFinish() { int State = state.getStateValue(); int roundsLeft = 0; if (State == 1) { state.setStateValue(2); } else { state.setStateValue(1); decrementRounds(); } Log.d(TAG, "WorkoutState = " + state.getStateValue()); try { TextView numOfRounds = (TextView) findViewById(R.id.number_of_rounds); roundsLeft = Integer.parseInt(numOfRounds.getText().toString()); } catch(NumberFormatException nfe) { roundsLeft = 999; } if (roundsLeft &gt; 0) { // If there's still rounds, start the timer. workoutTimer = new WorkoutTimer(100); workoutTimer.start(); } else { // Stop the timer and reset the display workoutTimer.cancel(); TextView digital_display = (TextView) findViewById(R.id.digital_display); digital_display.setText("00:00.0"); } } public void onTick(long millisUntilFinished) { final long minutes_left = ((millisUntilFinished / 1000) / 60); final long seconds_left = (millisUntilFinished / 1000) - (minutes_left * 60); final long millis = millisUntilFinished % 100; final String time_left = String.format("%02d:%02d.%01d", minutes_left, seconds_left, millis/10); TextView digital_display = (TextView) findViewById(R.id.digital_display); digital_display.setText(time_left); millisLeft = millisUntilFinished; } @Override protected void finalize() throws Throwable { super.finalize(); Log.d(TAG, "Object destroyed"); } } private long getThisTime() { long time = 0; TextView workout_time = (TextView) findViewById(R.id.workout_time); TextView rest_time = (TextView) findViewById(R.id.rest_time); switch(state.getStateValue()) { case 1: try { time = Integer.parseInt(workout_time.getText().toString()); } catch(NumberFormatException nfe) { time = 999; } Log.d(TAG, "Workout time = " + time); break; case 2: try { time = Integer.parseInt(rest_time.getText().toString()); } catch(NumberFormatException nfe) { time = 999; } Log.d(TAG, "Rest time = " + time); break; case 0: time = 0; break; } return time * 1000; } private void decrementRounds() { int roundsLeft = 2; TextView numOfRounds = (TextView) findViewById(R.id.number_of_rounds); try { roundsLeft = Integer.parseInt(numOfRounds.getText().toString()); } catch(NumberFormatException nfe) { roundsLeft = 999; } roundsLeft -= 1; numOfRounds.setText(String.valueOf(roundsLeft)); Log.d(TAG, "set rounds to = " + roundsLeft); } } </code></pre> <p>Don't hold back, and feel free to ask any questions or give any criticisms.</p>
[]
[ { "body": "<p>from the little I saw I have just a few comments (the code looks fairly fine)</p>\n\n<ol>\n<li><p>if all you do with the buttons is set the <code>onClickListener</code> there is no reason not to use the built in xml attribute <code>onClick</code> when designing the buttons.</p></li>\n<li><p>when editing or reading from <code>SharedPrefrences</code> you should probably synchronize it like this:</p>\n\n<pre><code>public static final String WORKOUT_SHARED_PREFS = \"workoutTimerDB\";\npublic void pauseTimer() {\nisPaused = true;\nsynchronized(WORKOUT_SHARED_PREFS) {\n SharedPreferences workoutTimerDB = getSharedPreferences(WORKOUT_SHARED_PREFS, MODE_PRIVATE);\n SharedPreferences.Editor edit = workoutTimerDB.edit();\n edit.putLong(\"millisLeft\", (Long)this.millisLeft);\n edit.commit();\n WORKOUT_SHARED_PREFS.notifyAll();\n }\n workoutTimer.cancel();\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T14:59:58.540", "Id": "57646", "Score": "1", "body": "I agree about defining `onClick` within the XML, but I don't see any need to synchronize editing or reading from `SharedPreferences`. AFAIK, Android is capable of doing that itself." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T14:11:08.667", "Id": "31482", "ParentId": "31295", "Score": "1" } }, { "body": "<p><strong>Your usage of enums</strong></p>\n\n<p>You are misusing your enums. I would get rid of the <code>getStateValue</code> and <code>setStateValue</code> methods. <strong>The enum itself is a state.</strong></p>\n\n<p>I would change code that looks like this:</p>\n\n<pre><code> int State = state.getStateValue();\n if (State == 0) {\n state.setStateValue(1);\n }\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code> if (state == UNKNOWN) {\n state.setStateValue(WORKOUT);\n }\n</code></pre>\n\n<p>What your original code here actually does is that it's taking the <code>state</code> value, which you initialize to <code>CounterState.WORKOUT</code> and then it's changing the <strong>internal integer value</strong> stored in the enum. You never change your <code>state</code> variable from <code>WORKOUT</code>, but instead you change the integer value of the <code>WORKOUT</code>-state. That's definitely not how enums should be used.</p>\n\n<p>(You're also using the variable name <code>State</code> which defies Java coding conventions that variable names should start with a lower case letter)</p>\n\n<p>So, by changing the code snippet in the way I suggested above you will get rid of a lot of the \"magic numbers\" 0, 1 and 2 by using your enums properly. You will also improve readability. You won't have to remember \"Which state is 2\" anymore.</p>\n\n<p>I would also mark the enum type itself with <code>static</code> like this: <code>private static enum CounterState {</code> because the <code>CounterState</code> is not dependent on anything in your outer class). I would also mark its constructor with <code>private</code> - or rather, I would <strong>get rid of the constructor entirely.</strong> There is no use for it when you remove the <code>getStateValue</code> and <code>setStateValue</code> methods. You can use <code>state.ordinal()</code> if you really want to access its int value (which you should generally try to avoid but is useful for things like serialization). The <code>ordinal()</code> method returns the index of the enum.</p>\n\n<p><strong>Other variables</strong></p>\n\n<p>I would rename your <code>isPaused</code> to simply <code>paused</code>. <code>isPaused</code> is a naming convention for a method that returns your internal <code>paused</code> boolean value. You also have one boolean for if the timer is running (<code>timerRunning</code>) and one for if the timer is paused. This confuses me a lot. If the timer isn't running, then it's paused isn't it? Or should the possible options be <code>STOPPED</code>, <code>PAUSED</code>, <code>RUNNING</code>? In that case make it an <code>enum</code> (without any getters and setters!).</p>\n\n<p><strong>On click</strong></p>\n\n<p>I also agree with @thepoosh about defining <code>onClick</code> for your buttons in the XML, unless you're targeting Android API &lt; 4 (which no-one really uses anymore). For information about using <code>onClick</code> in your XML, <a href=\"http://developer.android.com/reference/android/widget/Button.html\" rel=\"nofollow\">see the Android documentation</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T14:47:48.563", "Id": "35535", "ParentId": "31295", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T02:24:09.490", "Id": "31295", "Score": "4", "Tags": [ "java", "android", "beginner" ], "Title": "Review Request - Android CountDownTimer activity" }
31295
<p>I made a Java program that asks for a word, then a screen width, then whether you want it to go fast or slow. Then it outputs that word and bounces it across the screen. Is this code efficient for what it does? Is there a better way to do it (without a pre-defined method/class)? And does it look professional and easy to read?</p> <pre><code>/* This program was designed for use with command prompt on an ASCII character set. Output is run through CMD. This was designed for CMD with only an 80 ASCII character width. str1 is the string containing the spaces. str2 is the string containing the input word. */ import java.util.Scanner; class Wave6 { //Causes the output to lag for a set amount. public static void xwait(long L) { for(long c=0; c&lt;L; c++); } //Asks for a string to "bounce" across the screen. public static String input_string(char chr, String str2) throws java.io.IOException { do { System.out.print("\n" + "What word do you what to input? \n" + "Must be less than 81 characters: "); /* Reads a list of characters and inputs it into a string (to allow for spaces and other non-letter chars). */ do { chr = (char) System.in.read(); if(chr != '\n') str2 += chr; } while(chr != '\n'); //Checks if the string is in the acceptable range. } while((str2.length() &lt; 1) | (str2.length() &gt; 80)); return str2; } //Asks for a screen width (this is arbitrary). public static int input_width(int width, String str2){ Scanner input = new Scanner(System.in); do { System.out.print("\n" + "What is the width of the screen? \n" + "Must be less than 81, and more than " + str2.length() + " characters: "); width = input.nextInt(); } while((width &lt;= str2.length() ) | (width &gt;= 81)); return width; } //Asks if the user wants the program to run //at full speed, or slower. public static long input_speed(char ch, char ign, long L) throws java.io.IOException { do { System.out.print("\n + "Do you want it slow or fast? \n" + "S or F: "); ch = (char) System.in.read(); //Gets rid of unwanted chars in //the char buffer. do { ign = (char) System.in.read(); } while(ign != '\n'); //checks if ch == F or S } while( !(ch == ('F')) ^ (ch == ('S')) ); //Returns a large or small number //to slow down the program, or not. L = 0; if(ch == 'S') L = 25550000L; else if(ch == 'F') L = 0; return L; } public static void main(String args[]) throws java.io.IOException { String str1 = "", str2 = ""; int width = 0, i; char ch = '\0', chr = '\0', ign = '\0'; long L = 0L; str2 = input_string(chr, str2); width = input_width(width, str2); L = input_speed(ch, ign, L); /* Part of the program that actually makes the word bounce around. */ for(;;) { for(;;) { //Right bound /* If the two strings added length is equal to the Input width +1, do not output a character return. This is the end of the right bound, break out of the infinite loop. Based on the code, between the conversion from right bound to left bound, str1 has to equal width. Otherwise the word only goes to the width -1 space. So str1 + str2 must equal width +1 */ if( width + 1 == (str1.length() + str2.length()) ) { System.out.print(str1 + str2); xwait(L); break; } else { System.out.println(str1 + str2); xwait(L); } //If the two strings are not equal to width +1 //add one space to str1 if(width + 1 != ( str1.length() + str2.length()) ) str1 += " "; } for(;;) { //Left bound /* Right bound handles the code when str1 and str2 are equal to width +1, so left bound doesn't have to. Similarly Right bound handles the output for when str1 equals 0, but left bound makes it equal to 0. */ if( width + 1 != (str1.length() + str2.length()) ) { System.out.println(str1 + str2); xwait(L); } //Take a space off of str1. str1 = str1.substring(0, str1.lastIndexOf(" ")); if(str1.length() == 0) break; } } } } </code></pre> <p>Also, I use n++, and I have my tab set to two ASCII character widths, so when I copied and pasted all of it was set to four spaces, is there an easy way to copy it without having to go back and delete all of the tabs and replace them with spaces? It takes forever. (this isn't important to me, but it is a hassle when trying to ask questions about code on here)</p> <p>This happened when I did this in Basic on my Ti 84, but what if I had made an <code>output_leftBound()</code> and <code>output_rightBound()</code> method, used main to call <code>rightBound()</code>, then had <code>rightBound()</code> and <code>leftBound()</code> call each other? Would that be efficient or would it cause the memory to build up? On the calculator, if you <code>goto</code> out of loops, the calculator builds up memory because it reserved it to look for an END command to signal the end of a loop, but it never finds one.</p> <p>Someone mentioned that:</p> <pre><code>public static void main(String args[]) throws java.io.IOExeption { </code></pre> <p>was a code smell. How (in an inquisitive tone)? The book I am using uses it whenever it uses <code>System.in.read()</code>. Though I did notice that when I didn't include it my other methods that use <code>System.in.read()</code>, the compiler reported an error stating:</p> <blockquote> <p>Unreported exception IOExeption; must be caught or declared to be thrown</p> </blockquote> <p>Is this a problem?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T04:32:26.530", "Id": "49818", "Score": "1", "body": "when it is about clean code, make sure that you get rid of unnecessary spaces." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T02:19:21.203", "Id": "50124", "Score": "0", "body": "Give some better names to variables/methods. You have some comments but I really prefer to see good names without comments (as Uncle Bob used to say)" } ]
[ { "body": "<p>One suggestion that I would make is to use better names for your variables. Typically your variable name should be long enough to describe what the variable represents (and not it's type). Short variable names work ok for loop indexes or in a very small scope (say a lambda expression) but generally you want the reader to be able to understand what the variable is without having to read the context. For example, in your code you might want to name <code>str2</code> as <code>userInput</code>.</p>\n\n<p>Another suggestion would be, perhaps, to use a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html\" rel=\"nofollow\">BufferedReader</a> to read the input line.\nFor numeric input, where you want to handle incorrect input nicely, you might want to use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29\" rel=\"nofollow\">Integer.parseInt</a> and catch NumberFormatException.</p>\n\n<p>For what it's worth, I'd typically prefer a <code>do-while(true)</code> loop over an infinite <code>for</code> loop, but that's my personal preference.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T04:15:27.237", "Id": "49817", "Score": "0", "body": "Thanks, I'll look into BfferedReader and Integer parseint. When I was writing this (if you noticed that it is called Wave6, it has four other versions; #4 I intended to use after working on #3, but that developed into #5), I used a string based code from my previous version and didn't think about changing the string variables to proper names. Thanks for the tip though." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T03:28:12.123", "Id": "31300", "ParentId": "31297", "Score": "1" } }, { "body": "<h1>Major issues</h1>\n\n<p>This feels like C code more than Java. Part of the reason is the code structure — you're using class methods everywhere instead of instance methods. The bigger problem is your <strong>parameter passing</strong>. For example, in <code>input_string(char chr, String str2)</code>, you are using <code>chr</code> and <code>str2</code> as nothing more than local variables — you completely disregard their input values. Why not just take zero parameters and return a String?</p>\n\n<p>Your <strong>input routines</strong> are unnecessarily complicated. You shouldn't have to read one character at a time. Just read a line at a time using <code>BufferedReader.readLine()</code>.</p>\n\n<p>Your <code>xwait()</code> function relies on <strong>busy-waiting</strong>, which you should never ever do. The first problem with busy-waiting is that it chews up CPU cycles which could be yielded to other processes running on the machine. Laptop users will hate you for wasting battery power warming up the CPU and spinning the fan. These days, you might even be running on a virtual machine on a multi-tenant host, which will cause other customers to complain! The other problem with busy-waiting is that the delay depends on the CPU's speed, which will differ wildly on various machines. Assumptions about the CPU speed are what forced early PCs to have a \"Turbo\" button — to slow down the CPU so that poorly written games could run at their intended speed. If you want to introduce a delay, call <code>Thread.sleep()</code>.</p>\n\n<p>Your right-bound and left-bound <strong>loops are excessively complex</strong>. The way you use an infinite <code>for(;;)</code> loop and break out of them is unconventional. Why not use the for-loops the way they are intended to be used? Then every programmer can tell at a glance what the structure of your loops are — what is being tested and what changes between iterations.</p>\n\n<h1>Nitpicks</h1>\n\n<p>Comments on your classes and functions might as well be <strong>JavaDoc</strong> comments. All you have to do is follow the JavaDoc formatting conventions.</p>\n\n<p><strong>Indentation</strong> should be at least four spaces. Two spaces is too narrow to read reliably, and it also encourages excessively deep nesting, which is a symptom of poorly organized code.</p>\n\n<p><strong>Method names</strong> in Java should <code>lookLikeThis()</code>.</p>\n\n<p>Your <strong>variables</strong> <code>str1</code>, <code>str2</code>, <code>L</code>, <code>ch</code>, <code>chr</code>, <code>ign</code> are all poorly named. None of them is self-descriptive. For the first three, I suggest <code>lead</code>, <code>word</code>, and <code>delay</code> instead. Avoid declaring all your variables at the beginning of the function. For tightest scoping and least mental workload, you should declare variables as close as possible to where they are used. Also, <strong>don't initialize</strong> all your variables to 0 or <code>\\0</code> frivolously — let the Java compiler tell you when you have failed to assign them meaningful values before usage.</p>\n\n<p>You should use a <strong>boolean-or</strong> rather than a bitwise-or in <code>while((str2.length() &lt; 1) | (str2.length() &gt; 80))</code> and similar expressions.</p>\n\n<p>When <strong>shrinking <code>str1</code></strong>, just call <code>str1.substring(1)</code>. Chopping off the first character is much easier than finding the last one and removing it. Also, test <code>.isEmpty()</code> rather than <code>.length() == 0</code>.</p>\n\n<h1>Proposed Solution</h1>\n\n<pre><code>import java.io.*;\n\n/**\n * This program was designed for use with command prompt on an ASCII\n * character set. Output is run through CMD.\n * This was designed for CMD with only an 80 ASCII character width.\n */\nclass Wave6 {\n /**\n * Asks for a string to \"bounce\" across the screen.\n */\n public static String inputString(BufferedReader in)\n throws IOException {\n String input;\n do {\n System.out.print(\"\\n\"\n + \"What word do you want to input? \\n\"\n + \"Must be less than 81 characters: \");\n input = in.readLine();\n if (null == input) throw new EOFException();\n //Checks if the string is in the acceptable range.\n } while (input.length() &lt; 1 || input.length() &gt; 80);\n return input;\n }\n\n\n /**\n * Asks for a screen width (this is arbitrary).\n */\n public static int inputWidth(BufferedReader in, String word)\n throws IOException {\n int width;\n do {\n System.out.print(\"\\n\"\n + \"What is the width of the screen? \\n\"\n + \"Must be less than 81, and more than \"\n + word.length() + \" characters: \");\n String input = in.readLine();\n if (null == input) throw new EOFException();\n width = Integer.parseInt(input);\n } while ((width &lt;= word.length() ) | (width &gt;= 81));\n return width;\n }\n\n\n /**\n * Asks if the user wants the program to run at full speed, or slower.\n * @return The number of milliseconds of delay per output line\n */\n public static long inputDelay(BufferedReader in)\n throws IOException {\n while (true) {\n System.out.print(\"\\n\"\n + \"Do you want it slow or fast? \\n\"\n + \"S or F: \");\n switch (in.read()) {\n case -1: throw new EOFException();\n case 'S': return 100;\n case 'F': return 0;\n }\n // Swallow the rest of the line and the end-of-line terminator\n in.readLine();\n }\n }\n\n public static void bounce(String word, int width, long delay)\n throws InterruptedException {\n // lead is the string containing the leading spaces.\n String lead = \"\";\n\n while (true) {\n\n // Right-bound loop\n for(; lead.length() + word.length() &lt;= width; lead += \" \") {\n System.out.print(lead);\n System.out.println(word);\n Thread.sleep(delay);\n }\n\n // Take two spaces off of lead: one because a space was added\n // when leaving the loop above, and another because we want to\n // start moving left.\n lead = lead.substring(2);\n\n // Left-bound loop\n for(; !lead.isEmpty(); lead = lead.substring(1)) {\n System.out.print(lead);\n System.out.println(word);\n Thread.sleep(delay);\n }\n }\n }\n\n public static void main(String args[])\n throws IOException {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\n String word = inputString(br);\n int width = inputWidth(br, word);\n long delay = inputDelay(br);\n\n // Part of the program that actually makes the word bounce around.\n try {\n bounce(word, width, delay);\n } catch (InterruptedException timeToQuit) {\n // Sleep interrupted? Time to quit.\n }\n }\n}\n</code></pre>\n\n<h1>Optional Suggestion</h1>\n\n<p>Consider <strong>pre-allocating</strong> an array of 80 (or however many) <code>lead</code> strings instead of creating and tossing one for each line.</p>\n\n<pre><code> private static String[] leads;\n public static void bounce(String word, int width, long delay)\n throws InterruptedException {\n // Pre-allocate all the leading space strings, such that\n // leads[i] is a string containing i spaces\n if (null == leads || leads.length &lt; width - word.length()) {\n leads = new String[width - word.length() + 1];\n StringBuffer sb = new StringBuffer(leads.length);\n for (int i = 0; i &lt; leads.length; i++) {\n leads[i] = sb.toString();\n sb.append(' ');\n }\n }\n\n while (true) {\n // Right-bound loop\n for(int i = 0; i &lt; width - word.length(); i++) {\n System.out.print(leads[i]);\n System.out.println(word);\n Thread.sleep(delay);\n }\n\n // Left-bound loop\n for(int i = width - word.length(); i &gt;= 1; i--) {\n System.out.print(leads[i]);\n System.out.println(word);\n Thread.sleep(delay);\n }\n }\n }\n</code></pre>\n\n<h1>Addendum: Suggestion to use <code>printf()</code></h1>\n\n<p>Another way to print a string with leading spaces is to use <code>System.out.printf()</code>.</p>\n\n<pre><code>public static void bounce(String word, int width, long delay)\n throws InterruptedException {\n while (true) {\n for (int w = word.length(); w &lt; width; w++) {\n System.out.printf(\"%\" + w + \"s\\n\", word);\n Thread.sleep(delay);\n }\n for (int w = width; w &gt; word.length(); w--) {\n System.out.printf(\"%\" + w + \"s\\n\", word);\n Thread.sleep(delay);\n }\n }\n}\n</code></pre>\n\n<p>It's less efficient, but I think that the resulting simplicity in your own code is worth it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T16:09:11.603", "Id": "49851", "Score": "0", "body": "Thankyou, since I am reading from the book, it is difficult to know what is a good idea or not in my own programs. When I didn't initialize a variable, but I initialized it through if statements (in another pogram), the compiler had problems, so I think that's why I did that. Thanks on mentioning 0 parameters, I didn't think about returning to another variable. I did use buisy-waiting because I didn't know of a built in java method to do it; thanks for mentioning one. I did use the for loops with an iteration once before, but that felt like it added complexity to my code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T16:23:45.313", "Id": "49853", "Score": "0", "body": "You're right, my advice about variable initialization was very poorly worded. I've corrected it in [Revision 3](http://codereview.stackexchange.com/revisions/31306/3). I've also corrected some input-handling issues in [Revision 2](http://codereview.stackexchange.com/revisions/31306/2)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T16:28:39.537", "Id": "49855", "Score": "0", "body": "Though the way you implemented the for loops was a ton better than what I did. What does `str1.substring(1)` do exactly? One thing I noticed was many people commented that I should use boolean instead of bitewise operators, but in this book, bitewise operators are the same as logical operators (i.e. the symbols used to call them), so what is the difference between the two? I am using them as conditionals to break out of a do loop, not to change the bits of their values. And how do I implement a pre-allocating array? Thanks for your reply, I needed it (as you can see)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T16:44:38.830", "Id": "49857", "Score": "0", "body": "@Lightfire [EDIT] I looked up substring in the java documentation, so i know what it does now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T17:11:02.870", "Id": "49858", "Score": "0", "body": "See [bitwise vs. logical operators](http://stackoverflow.com/questions/1724205). Also, I've added a pre-allocation implementation to the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T21:21:51.753", "Id": "409973", "Score": "0", "body": "Now having been through college and now having a programming job, this makes me cringe so hard.\n\nSorry for subjecting you all to the \"Not a clue what he's doing\" kid" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T08:10:07.753", "Id": "31306", "ParentId": "31297", "Score": "8" } } ]
{ "AcceptedAnswerId": "31306", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T03:05:00.297", "Id": "31297", "Score": "7", "Tags": [ "java", "console", "formatting" ], "Title": "Bouncing a word left-right on screen" }
31297
<p>I am not sure if I am correctly handling <code>$_POST</code> data in MVC pattern:</p> <p><strong>Dummy <code>$_POST</code> data</strong></p> <pre><code>$_POST = array( "menu" =&gt; array( "key_name" =&gt; '', "pub_name" =&gt; '' ) ); </code></pre> <p><strong>View</strong></p> <pre><code>$connection = null; $entry = new menuPostController($connection); echo $entry-&gt;renderXML(); </code></pre> <p>I will get this result when there the input field is empty:</p> <pre><code>&lt;xml&gt; &lt;response&gt; &lt;error elementid="key_name" message="Key name - You must not leave this field empty!" /&gt; &lt;error elementid="pub_name" message="Public name - You must not leave this field empty!" /&gt; &lt;/response&gt; &lt;/xml&gt; </code></pre> <p>Then if all fields are filled in, I will get this result:</p> <pre><code>&lt;xml&gt; &lt;response&gt; &lt;success message="well done!" path="test.php?id=2" action="add" /&gt; &lt;/response&gt; &lt;/xml&gt; </code></pre> <p><strong>Controller</strong></p> <pre><code>class menuPostController { private $connection = null; public $data = array(); public function __construct($connection) { $this-&gt;connection = $connection; } public function getData(){ if(isset($_POST['menu'])){ $menu = new menuSanitizor($this-&gt;connection); $this-&gt;data = $menu-&gt;getData($_POST['menu']); return $this-&gt;data; } } public function renderXML(){ $data = self::getData(); if(isset($data)) { $xml = new xmlHelper(); echo $xml-&gt;getXML($data); } } } </code></pre> <p><strong>Model</strong></p> <pre><code>class menuSanitizor { private $connection = null; public $error = array(); public $key_name = null; public $pub_name = null; public $post = null; public function __construct($connection) { $this-&gt;post = new post(); $this-&gt;connection = $connection; } public function getData($params = array()) { $this-&gt;key_name = self::setKeyName($params['key_name']); $this-&gt;pub_name = self::setPubName($params['pub_name']); if($this-&gt;error) { return array("error" =&gt; array_merge( is_array($this-&gt;key_name)? $this-&gt;key_name : array(), is_array($this-&gt;pub_name)? $this-&gt;pub_name : array() )); } else { // inject into the database $inject = self::inject(); if($inject === true) { return array("success" =&gt; array( "message" =&gt; "well done!", "path" =&gt; "test.php?id=2", "action" =&gt; "add" )); } } } public function inject(){ /* $sql = " INSERT INTO menu ( key_name, pub_name, created_on )VALUES( ?, ?, NOW() )"; $result = $this-&gt;connection-&gt;executeSQL($sql,array( $this-&gt;key_name, $this-&gt;pub_name )); return $result; * * */ return true; } // only the setter sanitizes the data. public function setKeyName($key_name = null) { // Get the value first. $key_name = $this-&gt;post-&gt;get('key_name', $key_name); //print_r($key_name); if($key_name === null) { $this-&gt;error = array("key_name" =&gt; "Key name - You must not leave this field empty!"); return $this-&gt;error; } else { // Set the value. $this-&gt;key_name = $key_name; return $this-&gt;key_name; } } public function setPubName($pub_name = null) { // Get the value first. $key_name = $this-&gt;post-&gt;get('pub_name', $pub_name); if($key_name === null) { $this-&gt;error = array("pub_name" =&gt; "Public name - You must not leave this field empty!"); return $this-&gt;error; } else { // Set the value. $this-&gt;pub_name = $pub_name; return $this-&gt;pub_name; } } } </code></pre> <p><strong>Global getter helper</strong></p> <pre><code>class post { public $data = array(); // check a series of parameters that may or may not be set, and sanitize them one by one.. public function get($param, $default = null) { // silently convert empty strings to NULLs if ($default === '') { $default = null; } if (!isset($this-&gt;data[$param])) {//not set, return default return $default; } return $this-&gt;data[$param]; } } </code></pre> <p><strong>Global XML helper</strong></p> <pre><code>class xmlHelper { public $xml = null; public function getXML($data = array()) { $this-&gt;xml = new SimpleXMLElement('&lt;xml/&gt;'); $response = $this-&gt;xml-&gt;addChild('response'); if(isset($data['error']) &amp;&amp; count($data['error']) &gt; 0){ foreach($data['error'] as $key =&gt; $value) { $error = $response-&gt;addChild('error'); $error-&gt;addAttribute('elementid', $key); $error-&gt;addAttribute('message', $value); } } else if(isset($data['success'])){ $success = $response-&gt;addChild('success'); foreach($data['success'] as $key =&gt; $value) { $success-&gt;addAttribute($key, $value); } } Header('Content-type: text/xml'); return $this-&gt;xml-&gt;asXML(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T13:03:52.890", "Id": "49921", "Score": "0", "body": "What is the `$connection` argument that will be passed to the controller? I take it it's a DB connection, in which case: _it has no business being in a controller, DB is part of the Model-layer_. Likewise for the `$_POST`: It's still being processed by the Model-layer, as [I explained in my answer to your previous question](http://codereview.stackexchange.com/questions/31035/how-to-put-xml-results-in-the-mvc-pattern/31085#31085), the model-layer should not process the request..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T13:43:37.843", "Id": "49926", "Score": "0", "body": "Yes you are right. `$connection` is a DB connection. It pass the DB connection from the controller to models." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T13:48:58.453", "Id": "49928", "Score": "1", "body": "Well, don't. Honestly, the best way to go about this is to create a Service layer. The controller can interact with this service layer, and it's this service layer that creates the DB connections, and decides what methods are to be called. [Read about this approach here](http://zf-boilerplate.com/documentation/service-orientation/), to see a simple graph [click here](http://leahayes.files.wordpress.com/2011/04/service-mvc-001.png), that should clarify what I'm on about" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T13:51:50.560", "Id": "49929", "Score": "1", "body": "[Also check this](http://bpesquet.developpez.com/tutoriels/php/evoluer-architecture-mvc/images/3.png). As you can see, the DB is not part of the controller's responsability. That's dealt with in the Model _LAYER_. I can't stress this enough the `Model` part of MVC isn't an object, it's a _LAYER_. It can (and IMHO should) consist of various object, each with their own, distinct tasks. No need to try and cram it all into a single object..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T14:44:00.033", "Id": "49935", "Score": "0", "body": "it seems that I must pass the DB connection as a singleton approach? For instance `DB::fetchRows($sql);` otherwise - how can I pass the DB connection into models because controller is always the first class to be called isn't?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T14:48:49.437", "Id": "49936", "Score": "1", "body": "Singletons have no point in PHP... but that's another story. You just need a config object, and pass that to a DB class constructor. That class can then use the config to connect to the DB. The config object can be passed to the service in the controller, hell: the config can even be _global_. But connections to DB's is something that is not done in a controller. A controller is something that should contain as little code as possible! (google dependency injection and singletons are evil, to learn why you shouldn't use them)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T14:51:19.433", "Id": "49937", "Score": "0", "body": "I don't use singletons :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T14:57:17.130", "Id": "49939", "Score": "0", "body": "`You just need a config object, and pass that to a DB class constructor. That class can then use the config to connect to the DB. The config object can be passed to the service in the controller` - I still don't quite get it. Do you have any example codes that I can look into? thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T06:30:04.050", "Id": "50021", "Score": "1", "body": "On the config: A config file (ini, xml, yml... doesn't matter) should be parsed at the very beginning. This config can contain all sorts of information (like where the autoloader is, what routing plugins you're using and _the DB connection info_). This can be passed around freely, but you only connect to the DB once you _know_ for a fact that you're going to query for data. It's how most MVC frameworks work: Zend, Symfony... they all do this. Just check their source code for examples... the config is the first thing they load..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T07:22:22.127", "Id": "50023", "Score": "0", "body": "thanks. what about the answer from this question - http://programmers.stackexchange.com/questions/178831/using-pdo-with-mvc the db connection is initialised in a controller... `It's perfectly fine to inject the data access into a controller or instantiate it directly in there. If data access logic is complicated, encapsulate it in its own class` - is it incorrect then?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T07:23:36.130", "Id": "50024", "Score": "0", "body": "`$this->repository = new Repository();` from that answer is a db connection class I assume..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T08:27:02.807", "Id": "50031", "Score": "0", "body": "yes and no, though it sounds/looks as though creating DB connections in the controller is the way to go about your business, look closely: the `Respoitory` class's constructor is where the connection is actually being made. The controller merely calls a method, which returns a datamodel. Hence, `Respoitory` acts more like a service, not a DB class. Ideally, `Repository` should create an instance of PDO or MySQLi in its constructor (or lazy-load it), and each method should then use that connection to query & fetch into a model, which it then returns" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T08:30:48.133", "Id": "50032", "Score": "1", "body": "The `Respository` class, in the given example, then contains the _logic_. The DB connection can be handled by another abstraction layer (for example Doctrine). Creating the `Repository` instance could look like this: `$inst = new Repository($configObject);` and its constructor: `__construct(Config $conf){ $this->connection = new DBWrapper($config->databaseConfig);}`... that's what I mean by passing around the config, but keeping actual DB work to the model layer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T08:48:41.397", "Id": "50033", "Score": "0", "body": "Now I understand. thanks for the help! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T09:34:20.647", "Id": "50037", "Score": "1", "body": "Well, I've poured these many comments into a single answer. I hope it clears a couple of things up for you. I must say: the difference between your first code example, and the one you posted here now is night and day (in a good way)! Keep at it, you're almost there. PS: would you mind accepting either my answer here and/or to your other question? Unless you want to wait and see if a better answer might be added?" } ]
[ { "body": "<p>Since I've explained a lot in the comments, I thought I might distill those comments into an answer, so here goes:</p>\n\n<p>You're definitely improving, <a href=\"https://codereview.stackexchange.com/questions/31035/how-to-put-xml-results-in-the-mvc-pattern/31085#31085\">considering your previous question</a>. Well, to be honest: I must say the difference between your first code example, and the one you posted here now is night and day (in a good way)! The main problem with your code, at this point is that you're still connecting to the DB in the controller. Don't. DB work/logic resides in the model <em>Layer</em>.<br/>\nThe best way to structure more complex applications (within the confines of the MVC pattern) is by implementing a service layer. Read about it <a href=\"http://zf-boilerplate.com/documentation/service-orientation/\" rel=\"nofollow noreferrer\">here</a>. Use this graph to guide you along:</p>\n\n<p><img src=\"https://i.stack.imgur.com/hlhOw.png\" alt=\"Schematic Service\"></p>\n\n<p>Your DB-related objects are still having to sanitize the request data, which they really shouldn't. Processing the request should've been done way before they even come into play. The last point where you can still work on the request is the controller, as shown in this graph:</p>\n\n<p><img src=\"https://i.stack.imgur.com/toFYm.png\" alt=\"MVC with responsibilities\"></p>\n\n<p>It's important to note that the DB is not part of the controller's responsibility. That's dealt with in the Model LAYER. I can't stress this enough the Model part of MVC isn't an object, it's a LAYER. It can (and IMHO should) consist of various object, each with their own, distinct tasks. No need to try and cram it all into a single object...<br/>\nThere is, however, one object that can be passed to all other objects in the MVC pattern (save for data models), and that is the object representing the app's configuration. You pass that object around freely: to a DB class constructor, via the service's constructor, or through setters. Each class can then use the <code>Config</code> object to extract whatever data it needs from the instance for it to do its job. Hell: the config can even be global. But connections to DB's is something that is not done in a controller. A controller is something that should contain as little code as possible.</p>\n\n<p><em>On the config:</em><br/>\nThis can be any old file (ini, xml, yml... doesn't matter), but should be parsed at the very beginning. This config can contain all sorts of information (like where the autoloader is, what routing plugins you're using and the DB connection info). This can be passed around freely, but you only connect to the DB once you know for a fact that you're going to query for data. It's how most MVC frameworks work: Zend, Symfony... they all do this. Just check their source code for examples...</p>\n\n<p>You refer to <a href=\"https://softwareengineering.stackexchange.com/questions/178831/using-pdo-with-mvc\">this answer</a>, because it'd seem to create a DB connection in the controller. Well, in effect, it creates a <em>service</em> instance in the controller, and it's that service's job to connect to the DB, and query it, based on the methods that are called in the controller. These methods then return Data models, back to the controller, where they're passed on to the view. That's standard, by-the-book, MVC. Though the snippet doesn't make mention of any config object, it's quite easy to implement it:</p>\n\n<pre><code>//controller:\npublic function someAction(Config $conf)\n{\n $service = new Repository($conf);\n $model = $service-&gt;getDataForUser(\n $this-&gt;request-&gt;get('User', 'guest')//get User param, or guest if User param not found\n );\n if ($model === null)\n {\n return $this-&gt;redirect('user_invalid_page');\n }\n $this-&gt;view-&gt;user = $model;\n}\n//Repository class (=== service)\nclass Repository\n{\n private $config = null;\n private $conn = null;\n public function __construct(Config $conf)\n {\n $this-&gt;config = $conf;\n }\n public function getDataForUser($userName)\n {//LOGIC HERE!\n $db = $this-&gt;getDb();//Lazy-loader!\n $query = $db-&gt;buildQuery(\n array(\n 'table' =&gt; 'users',\n 'where' =&gt; array(\n 'usrName' =&gt; $userName\n )\n )\n );\n $data = $db-&gt;execute($query);\n if (!$data)\n {\n return null;\n }\n $model = new UserModel;\n foreach($data as $field =&gt; $val)\n {//check my other answers on why I use setters here...\n $model-&gt;{'set'.$field}($val);\n }\n return $model;\n }\n private function getDb()\n {\n if ($this-&gt;conn === null)\n {\n $db = new DBWrapper($this-&gt;config-&gt;database);//pass DB connection config to class\n $this-&gt;setDb($db);\n }\n return $this-&gt;conn;\n }\n public function setDb(DBWrapper $db)\n {//injection =&gt; public\n if ($this-&gt;conn instanceof DBWrapper)\n {//close current connection\n $this-&gt;conn-&gt;close();\n }\n $this-&gt;conn = $db;\n return $this;\n }\n}\n</code></pre>\n\n<p>This is a (somewhat) crude example of how to implement MVC can be implemented correctly. The DB connection is handled by a DB object. The instance of <code>DBWrapper</code> is created by the service, which also creates the data-models, based on the return values from the DB class. The controller calls upon the service to attempt to retrieve the desired data. What the service needs to do to get to that data is non of the controller's business. Nor does the controller need to know/care what type of DB is being used. That's up to the <code>DBWrapper</code> class.<br/>\nPlease note how little code the controller actually contains, and how much of the <em>\"heavy lifting\"</em> is done in the <em>service</em> and the classes this service actually creates. While writing code that goes into the controller, make sure you're not writing your application logic, save it for the service.</p>\n\n<p>The service only cares if the requested data was found, and how it should be poured into objects. If no data was returned, it'll return <code>null</code> to the controller. If data <em>was</em> found, the service will try its very best to return a nice model to the controller. In short: to each class its own tasks/concerns. If you need to add logic, you open and edit the service class, if you need to add a user action, add an action method in the controller, if you want to change/add support for another type of DB, you turn to the <code>DBWrapper</code> class. Easy!</p>\n\n<p><em>Please note, <code>DBWrapper</code> isn't a terrible good name, it suggests it's just a wrapper class for <code>PDO</code> or <code>Mysqli</code>, and <a href=\"https://codereview.stackexchange.com/questions/29362/very-simple-php-pdo-class/29394#29394\">I'm not a fan of such classes</a></em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-09-17T09:32:16.233", "Id": "31415", "ParentId": "31301", "Score": "3" } } ]
{ "AcceptedAnswerId": "31415", "CommentCount": "15", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T04:41:39.053", "Id": "31301", "Score": "1", "Tags": [ "php", "mvc", "controller", "helper" ], "Title": "Doing $_POST the right way" }
31301
<p>I am toying around and playing a lot with defining a function. I'm trying to get extremely comfortable with it. The code I have wrote works fairly well, but definitely is not perfect. Also, the function I made called <code>playagain</code> is having some errors. When I type in "Yes" for the input I'm getting a strange TypeError. If you can fix that, please explain to me how, in the simplest way possible.</p> <pre><code>import sys OPTIONS = ["Divide", "divide", "Multiply", "multiply", "Add", "add", "Subtract", "subtract"] def userinput(): while True: try: number = int(input("Number: ")) break except ValueError: print("NOPE...") return number def operation(): while True: operation = input("Multiply/Divide/Add: ") if operation in OPTIONS: break else: print("Not an option.") return operation def playagain(): while True: again = input("Again? Yes/No: ") if again == "Yes" or again == "yes": break elif again == "No" or again == "no": sys.exit(0) else: print("Nope..") def multiply(x,y): z = x * y print(z) def divide(x,y): z = x / y print(z) def add(x,y): z = x + y print(z) def subtract(x,y): z = x - y print(z) while True: operation = operation() x = userinput() y = userinput() if operation == "add" or operation == "Add": add(x,y) elif operation == "divide" or operation == "Divide": divide(x,y) elif operation == "multiply" or operation == "Multiply": multiply(x,y) elif operation == "subtract" or operation == "Subtract": subtract(x,y) playagain() </code></pre> <p>I tried defining as much functions as possible to make it simpler and easier to fix and debug. Please let me know what you think. </p> <p>NOTE: I am not making this program to actually be a beneficial program. I am simply using it to help myself with the defining a function portion of Python.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T08:13:27.940", "Id": "49832", "Score": "0", "body": "possible duplicate of [Python Calculator](http://codereview.stackexchange.com/questions/31286/python-calculator)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T08:42:38.817", "Id": "49834", "Score": "0", "body": "@200_success It's not a duplicate, but a follow-up question. The code is not the same, but an already much improved version of the code in the previous question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T08:49:47.907", "Id": "49835", "Score": "1", "body": "@tobias_k I recognize and applaud the improvements, but it's still fundamentally the same question, and any answers to this question will be very similar to those of the predecessor. There are also plenty of suggestions in previous answers that have not been incorporated yet." } ]
[ { "body": "<p>Of the feedback on your earlier version of this programme, the most obvious thing that you haven't done yet is to use <code>lower()</code> on text inputs so that you only have to compare against lower case options. e.g.</p>\n\n<pre><code> again = input(\"Again? Yes/No: \").lower()\n if again == \"yes\":\n break\n elif again == \"no\":\n sys.exit(0)\n</code></pre>\n\n<p>It might be useful to know that the operations you define already exist as methods of numeric variables in Python, called <code>__mul__</code>, <code>__add__</code>, etc., and are also available within the <code>operator</code> module. e.g. <code>operator.add(3, 4)</code> is equivalent to <code>3 + 4</code>. So you could, for example, do this</p>\n\n<pre><code>import operator\n\nOPTIONS = {\n 'divide': operator.truediv,\n 'multiply': operator.mul,\n 'add': operator.add,\n 'subtract': operator.sub\n}\n\ndef user_input():\n while True:\n try:\n return int(input(\"Number: \"))\n except ValueError:\n print(\"NOPE...\")\n\ndef get_operation():\n while True:\n operation = input(\"Multiply/Divide/Add/Subtract: \").lower()\n try:\n return OPTIONS[operation]\n except KeyError:\n print(\"Not an option.\")\n\ndef play_again():\n while True:\n again = input(\"Again? Yes/No: \").lower()\n if again == \"yes\":\n return True\n elif again == \"no\":\n return False\n else:\n print(\"Nope..\")\n\nwhile True:\n operation = get_operation()\n x = user_input()\n y = user_input()\n print(operation(x, y))\n if not play_again():\n break\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T11:15:03.013", "Id": "49839", "Score": "0", "body": "Your code didn't work for me, but it's still a very nice answer. I have provided corrections in a separate answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T11:31:54.583", "Id": "49840", "Score": "0", "body": "Thanks, I was mixing up Python 2 and 3. I corrected it above to Python 3 as that is what the question uses." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T18:10:28.840", "Id": "49864", "Score": "0", "body": "Thanks @Stuart I appreciate your answer! I will definitely start using the .lower() , I never really knew about it or knew what it did. I will study your code and make some changes." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T10:41:20.563", "Id": "31308", "ParentId": "31304", "Score": "4" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/31308/26493\">Stuart's code</a> is very nicely written, and provides much to a learner, but it didn't work for me. Fixed versions are too long for just a comment, so here they are.</p>\n\n<h2>Python 2</h2>\n\n<p>The exact version I use: 2.7.3</p>\n\n<pre><code>import operator\n\nOPTIONS = {\n 'divide': operator.div,\n 'multiply': operator.mul,\n 'add': operator.add,\n 'subtract': operator.sub\n}\n\ndef user_input():\n while True:\n try:\n return input(\"Number: \")\n except ValueError:\n print(\"NOPE...\")\n\ndef get_operation():\n while True:\n operation = raw_input(\"Multiply/Divide/Add/Subtract: \").lower()\n try:\n return OPTIONS[operation]\n except KeyError:\n print(\"Not an option.\")\n\ndef play_again():\n while True:\n again = raw_input(\"Again? Yes/No: \").lower()\n if again == \"yes\":\n return True\n elif again == \"no\":\n return False\n else:\n print(\"Nope..\")\n\nwhile True:\n operation = get_operation()\n x = user_input()\n y = user_input()\n print operation(x, y)\n if not play_again():\n break\n</code></pre>\n\n<p>In Python 2, <code>input</code> returns an integer, so <code>int(input(...))</code> is redundant, and inputting string (for operation and going again) fails. The later is fixed by using <code>raw_input</code>.</p>\n\n<h2>Python 3</h2>\n\n<p>The exact version I use: 3.2.3</p>\n\n<pre><code>import operator\n\nOPTIONS = {\n 'divide': operator.truediv,\n 'multiply': operator.mul,\n 'add': operator.add,\n 'subtract': operator.sub\n}\n\ndef user_input():\n while True:\n try:\n return int(input(\"Number: \"))\n except ValueError:\n print(\"NOPE...\")\n\ndef get_operation():\n while True:\n operation = input(\"Multiply/Divide/Add/Subtract: \").lower()\n try:\n return OPTIONS[operation]\n except KeyError:\n print(\"Not an option.\")\n\ndef play_again():\n while True:\n again = input(\"Again? Yes/No: \").lower()\n if again == \"yes\":\n return True\n elif again == \"no\":\n return False\n else:\n print(\"Nope..\")\n\nwhile True:\n operation = get_operation()\n x = user_input()\n y = user_input()\n print(operation(x, y))\n if not play_again():\n break\n</code></pre>\n\n<p>The obvious error here was the last <code>print</code> statement: it's a function in Python 3, so <code>print operation(x, y)</code> had to be replaced with <code>print(operation(x, y))</code>.</p>\n\n<p>The less obvious one is <code>operator.div</code> which doesn't exist in Python 3, but was instead replaced by <code>operator.truediv</code> and <code>operator.floordiv</code>. In the spirit of this program, I assumed that the former is what was intended.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T11:13:48.227", "Id": "31310", "ParentId": "31304", "Score": "1" } }, { "body": "<p>[Warning, Ugly Code Ahead...]</p>\n\n<p>I do not quite understand the question, however, I am assuming that you would like to build a calculator application. I have quickly \"whipped up\" this code. It is compatible with python3, and comes with a graphical user interphase.</p>\n\n<p>Instead of creating that huge function to determine the operator, just use the <code>eval()</code> function instead in a GUI.</p>\n\n<p>As seen in the function <code>Calculate()</code>, I am actually getting the text input from the display screen and just evaluating it. I also error check using a <code>try</code> and <code>except</code> statement.</p>\n\n<p>Calculator with a GUI:</p>\n\n<pre><code>from tkinter import *\nfrom tkinter import ttk\nimport time\nimport random\n\ntk = Tk()\ncanvas = Canvas(tk, height=400, width=300, bg = 'white')\ncanvas.pack()\ntk.title('Calculator')\ntk.resizable(False, False)\n\nclass Calculator:\n def Title(self):\n title = Label(tk, text = 'Calculator', font='Times, 20')\n title.place(x = 0, y = 10)\n def EntryBar(self):\n self.CalculationBox = Text(tk, height=2, width=27, font='Times, 15', bg = 'gray60')\n self.CalculationBox.place(x = 0, y = 60)\n self.counter = 1\n\n def DisplayCal(self, num):\n self.CalculationBox.insert(END, num)\n\n def Calculate(self):\n try:\n answer = eval(self.CalculationBox.get('1.0', END))\n self.CalculationBox.delete(\"1.0\", END)\n #print(answer) #For debugging\n self.CalculationBox.insert(END, answer)\n except Exception:\n self.CalculationBox.delete(\"1.0\", END)\n self.CalculationBox.insert(END, \"Error\")\n\nc = Calculator()\n\nclass Buttons: \n def Buttons(self):\n self.ZeroBtn = Button(tk, text = '0', height=2, width=8, bg = 'gray60', fg = 'white', command = lambda: c.DisplayCal(num=0))\n self.ZeroBtn.place(x = 120, y = 360)\n self.OneBtn = Button(tk, text = '1', height=2, width=8, bg = 'gray60', fg = 'white', command = lambda: c.DisplayCal(num=1))\n self.OneBtn.place(x = 53, y = 320)\n self.TwoBtn = Button(tk, text = '2', height=2, width=8, bg = 'gray60', fg = 'white', command = lambda: c.DisplayCal(num=2))\n self.TwoBtn.place(x = 120, y = 320)\n self.ThreeBtn = Button(tk, text = '3', height=2, width=8, bg = 'gray60', fg = 'white', command = lambda: c.DisplayCal(num=3))\n self.ThreeBtn.place(x = 187, y = 320)\n self.FourBtn = Button(tk, text = '4', height=2, width=8, bg = 'gray60', fg = 'white', command = lambda: c.DisplayCal(num=4))\n self.FourBtn.place(x = 53, y = 280)\n self.FiveBtn = Button(tk, text = '5', height=2, width=8, bg = 'gray60', fg = 'white', command = lambda: c.DisplayCal(num=5))\n self.FiveBtn.place(x = 120, y = 280)\n self.SixBtn = Button(tk, text = '6', height=2, width=8, bg = 'gray60', fg = 'white', command = lambda: c.DisplayCal(num=6))\n self.SixBtn.place(x = 187, y = 280)\n self.SevenBtn = Button(tk, text = '7', height=2, width=8, bg = 'gray60', fg = 'white', command = lambda: c.DisplayCal(num=7))\n self.SevenBtn.place(x = 53, y = 240)\n self.EightBtn = Button(tk, text = '8', height=2, width=8, bg = 'gray60', fg = 'white', command = lambda: c.DisplayCal(num=8))\n self.EightBtn.place(x = 120, y = 240)\n self.NineBtn = Button(tk, text = '9', height=2, width=8, bg = 'gray60', fg = 'white', command = lambda: c.DisplayCal(num=9))\n self.NineBtn.place(x = 187, y = 240)\n self.AddBtn = Button(tk, text = '+', height=2, width=8, bg = 'gray60', fg = 'white', command = lambda: c.DisplayCal(num='+'))\n self.AddBtn.place(x = 53, y = 200)\n self.MultBtn = Button(tk, text = 'x', height=2, width=8, bg = 'gray60', fg = 'white', command = lambda: c.DisplayCal(num='*'))\n self.MultBtn.place(x = 120, y = 200)\n self.DivBtn = Button(tk, text = '÷', height=2, width=8, bg = 'gray60', fg = 'white', command = lambda: c.DisplayCal(num='/'))\n self.DivBtn.place(x = 187, y = 200)\n self.SubBtn = Button(tk, text = '-', height=2, width=8, bg = 'gray60', fg = 'white', command = lambda: c.DisplayCal(num='-'))\n self.SubBtn.place(x = 53, y = 160)\n self.EquBtn = Button(tk, text = '=', height=2, width=8, bg = 'gray60', fg = 'white', command = c.Calculate)\n self.EquBtn.place(x = 187, y = 160)\n self.ClsBtn = Button(tk, text='Clear', height=2, width=8, bg = 'gray60', fg = 'white', command = lambda: c.CalculationBox.delete('1.0',END))\n self.ClsBtn.place(x = 120, y = 160)\nb = Buttons()\ndef main():\n c.Title()\n c.EntryBar()\n b.Buttons()\n\nmain()\n\ntk.mainloop()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-24T18:53:24.270", "Id": "183564", "ParentId": "31304", "Score": "1" } } ]
{ "AcceptedAnswerId": "31308", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T07:49:39.073", "Id": "31304", "Score": "1", "Tags": [ "python", "calculator" ], "Title": "Simple calculator (going H.A.M with defining functions)" }
31304
<p>I have the code below to get an infinite generator of the products of an iterable (e.g. for the iterable "ABC" it should return</p> <p>A, B, C, AA, AB, AC, BA, BB, BC, CA, CB, CC, AAA, AAB, AAC etc.</p> <pre><code>for product in (itertools.product("ABC", repeat=i) for i in itertools.count(0)): for each_tuple in product: print(each_tuple) </code></pre> <p>How would I remove the nested for loop, or is there a better approach?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T20:05:09.893", "Id": "49875", "Score": "1", "body": "you can write `itertools.count()` instead of `.count(0)`. :)" } ]
[ { "body": "<p>Well, you effectively have 3 nested loops including the generator comprehension, which you can reduce to two just by simplifying:</p>\n\n<pre><code>def get_products(string):\n for i in itertools.count(0):\n for product in itertools.product(string, repeat=i):\n yield product\n</code></pre>\n\n<p>Or if you are intent on putting it in a single line, use <code>chain</code>:</p>\n\n<pre><code>products_generator = itertools.chain.from_iterable(itertools.product(\"ABC\", repeat=i)\n for i in itertools.count(0))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T13:11:41.357", "Id": "31315", "ParentId": "31313", "Score": "4" } } ]
{ "AcceptedAnswerId": "31315", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T12:22:07.123", "Id": "31313", "Score": "3", "Tags": [ "python", "combinatorics", "python-3.x" ], "Title": "Python infinite product generator" }
31313
<p>For a code challenge, I'm trying to write a comprehensive URI parser in Python that handles both URIs with <code>authority</code> paths (ex: URLs such as <code>http://user:login@site.com/page?key=value#fragment</code>) and other URI schemes (ex: <code>mailto:mail@domain.com?subject=Blah</code>).</p> <p>Here's my current code:</p> <pre><code>import json import re class Uri(object): """ Utility class to handle URIs """ ESCAPE_CODES = {' ' : '%20', '&lt;' : '%3C', '&gt;' : '%3E', '#' : '%23', '%' : '%25', '{' : '%7B', '}' : '%7D', '|' : '%7C', '\\' : '%5C', '^' : '%5E', '~' : '%7E', '[' : '%5B', ']' : '%5D', '`' : '%60', ';' : '%3B', '/' : '%2F', '?' : '%3F', ':' : '%3A', '@' : '%40', '=' : '%3D', '&amp;' : '%26', '$' : '%24'} @staticmethod def encode(string): """ "Percent-encodes" the given string """ return ''.join(c if not c in Uri.ESCAPE_CODES else Uri.ESCAPE_CODES[c] for c in string) # We could parse (most of) the URI using this regex given on the RFC 3986: # http://tools.ietf.org/html/rfc3986#appendix-B # We won't do it though because it spoils all the fun! \o/ # We're only going to use it detect broken URIs URI_REGEX = "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?" def __init__(self, uri): """ Parses the given URI """ uri = uri.strip() if not re.match(Uri.URI_REGEX, uri): raise ValueError("The given URI isn't valid") # URI scheme is case-insensitive self.scheme = uri.split(':')[0].lower() self.path = uri[len(self.scheme) + 1:] # URI fragments self.fragment = None if '#' in self.path: self.path, self.fragment = self.path.split('#') # Query parameters (for instance: http://mysite.com/page?key=value&amp;other_key=value2) self.parameters = dict() if '?' in self.path: separator = '&amp;' if '&amp;' in self.path else ';' query_params = self.path.split('?')[-1].split(separator) query_params = map(lambda p : p.split('='), query_params) self.parameters = {key : value for key, value in query_params} self.path = self.path.split('?')[0] # For URIs that have a path starting with '//', we try to fetch additional info: self.authority = None if self.path.startswith('//'): self.path = self.path.lstrip('//') uri_tokens = self.path.split('/') self.authority = uri_tokens[0] self.hostname = self.authority self.path = self.path[len(self.authority):] # Fetching authentication data. For instance: "http://login:password@site.com" self.authenticated = '@' in self.authority if self.authenticated: self.user_information, self.hostname = self.authority.split('@', 1) # Fetching port self.port = None if ':' in self.hostname: self.hostname, self.port = self.hostname.split(':') self.port = int(self.port) # Hostnames are case-insensitive self.hostname = self.hostname.lower() def serialize_parameters(self): """ Returns a serialied representation of the query parameters. """ return '&amp;'.join('{}={}'.format(key, value) for key, value in sorted(self.parameters.iteritems())) def __str__(self): """ Outputs the URI as a string """ uri = '{}:'.format(Uri.encode(self.scheme)) if self.authority: uri += '//' if self.authenticated: uri += Uri.encode(self.user_information) + '@' uri += self.hostname if self.port: uri += ':{}'.format(self.port) uri += self.path if self.parameters: uri += '?' + self.serialize_parameters() if self.fragment: uri += '#' + Uri.encode(self.fragment) return uri def json(self): """ JSON serialization of the URI object """ return json.dumps(self.__dict__, sort_keys=True, indent=2) def summary(self): """ Summary of the URI object. Mostly for debug. """ uri_repr = '{}\n'.format(self) uri_repr += '\n' uri_repr += "* Schema name: '{}'\n".format(self.scheme) if self.authority: uri_repr += "* Authority path: '{}'\n".format(self.authority) uri_repr += " . Hostname: '{}'\n".format(self.hostname) if self.authenticated: uri_repr += " . User information = '{}'\n".format(self.user_information) if self.port: uri_repr += " . Port = '{}'\n".format(self.port) uri_repr += "* Path: '{}'\n".format(self.path) if self.parameters: uri_repr += "* Query parameters: '{}'\n".format(self.parameters) if self.fragment: uri_repr += "* Fragment: '{}'\n".format(self.fragment) return uri_repr </code></pre> <p>Also <a href="https://github.com/halflings/uriparser" rel="nofollow">hosted on github</a>.</p> <p>All feedback, including failure to respect PEP8 or existence of more "pythonic" methods, is welcome!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T09:18:57.663", "Id": "62810", "Score": "0", "body": "There is no better place to look at than the python standard library:\nhttp://hg.python.org/cpython/file/2.7/Lib/urlparse.py" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T23:33:41.357", "Id": "62811", "Score": "0", "body": "It might seem arrogant, but I don't think urlparse's implementation isn't the most elegant one. (other Python Standard Libraries are also horrible, like the ones handling ZIP and TAR files)" } ]
[ { "body": "<p>You referenced <a href=\"https://www.rfc-editor.org/rfc/rfc3986\" rel=\"nofollow noreferrer\">RFC 3986</a>, but I don't think you've tried to follow it.</p>\n<p>In your constructor, you immediately lower-case everything. That is obviously wrong. <a href=\"https://www.rfc-editor.org/rfc/rfc3986#section-6.2.2.1\" rel=\"nofollow noreferrer\">RFC 3986 Sec. 6.2.2.1</a> says that only the scheme and host portions of URIs are case-insensitive.</p>\n<p>You have an <code>escape()</code> function, but oddly no <code>unescape()</code> function, which I expect would be needed for parsing URIs. Please be aware when implementing <code>unescape()</code> that query strings have special unescaping rules. The RFC uses the term &quot;percent-encoding&quot;, so perhaps you should call it &quot;encode&quot; rather than &quot;escape&quot;.</p>\n<p>Your <code>escape()</code> function only encodes specific characters, which is dangerous, considering that more characters exist that require encoding than that can be passed through.</p>\n<p>Be careful when calling <code>split()</code> where you expect at most one separator. You should use <code>split(':', 1)</code>, <code>split('@', 1)</code> and <code>split('#', 1)</code> instead.</p>\n<p>Better yet, don't try to split at all. Instead, consistently use regular expression capturing for identifying <em>all</em> parts of the URI. You should be able to make one huge regular expression. All complex regular expressions, including the one you are using now, should have embedded <a href=\"http://docs.python.org/2/library/re.html#re.VERBOSE\" rel=\"nofollow noreferrer\">comments</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T20:43:24.987", "Id": "49876", "Score": "0", "body": "I quickly skimmed over RFC 3986 and have, as you proved it, missed many things. I'm gonna try to fix those asap!\n\nI tried to avoid using one big pile of regex (event commented) because I think the goal of this programming exercise was to parse string in various ways and show a good coding style. Using one big regex wouldn't be relevant IMHO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T20:57:56.910", "Id": "49878", "Score": "0", "body": "Regarding the \"percent-encoding\", from what I've understood only reserved characters must be percented-encoded in the URI. And I think I already got all of those covered." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T00:18:48.367", "Id": "49892", "Score": "0", "body": "[Sec 2.1](http://tools.ietf.org/html/rfc3986#section-2.1): \"A percent-encoding mechanism is used to represent a data octet in a component when that octet's corresponding character is outside the allowed set or is being used as a delimiter of, or within, the component.\" The reserved set contains a list of common delimiters. There are also plenty of characters outside the allowed set. [Appendix A](http://tools.ietf.org/html/rfc3986#appendix-A) suggests that anything outside the nonreserved set should be percent-encoded if it's not being used for a syntactically significant role in the URL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T01:07:33.787", "Id": "49893", "Score": "0", "body": "OK! Forgot about non ASCII letters and other exotic characters." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T18:38:27.977", "Id": "31324", "ParentId": "31317", "Score": "5" } } ]
{ "AcceptedAnswerId": "31324", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T16:43:27.130", "Id": "31317", "Score": "1", "Tags": [ "python", "parsing", "url" ], "Title": "A (comprehensive) URI parser for Python" }
31317
<p>Here's a trick for preallocating some memory for some type <code>T</code>. Do there exist similar tricks? Improvements?</p> <pre><code>#include &lt;cassert&gt; #include &lt;cstdlib&gt; #include &lt;atomic&gt; #include &lt;limits&gt; #include &lt;new&gt; #include &lt;thread&gt; #include &lt;utility&gt; namespace { template &lt;typename T, typename A = unsigned&gt; struct static_store { static constexpr auto const max_instances = ::std::numeric_limits&lt;unsigned char&gt;::digits * sizeof(A); static void cleanup() { delete [] store_; } #ifdef __GNUC__ template &lt;typename U&gt; static int ffz(U const v) { return __builtin_ctzll(~v); } #elif _MSC_VER &amp;&amp; !__INTEL_COMPILER template &lt;typename U&gt; static int ffz(U const v) { return ::std::numeric_limits&lt;unsigned char&gt;::digits * sizeof(v) - __lzcnt64(v &amp; -v); } #elif __INTEL_COMPILER template &lt;typename U&gt; static int ffz(U const v) { return _bit_scan_forward(~v); } #else template &lt;typename U&gt; static int ffz(U v) { decltype(ffz()) b{}; for (; (v &amp; 1); ++b) { v &gt;&gt;= 1; } return b; } #endif static ::std::atomic_flag lock_; static A memory_map_; static typename ::std::aligned_storage&lt;sizeof(T), alignof(T)&gt;::type* store_; }; template &lt;typename T, typename A&gt; ::std::atomic_flag static_store&lt;T, A&gt;::lock_; template &lt;typename T, typename A&gt; A static_store&lt;T, A&gt;::memory_map_; template &lt;typename T, typename A&gt; typename ::std::aligned_storage&lt;sizeof(T), alignof(T)&gt;::type* static_store&lt;T, A&gt;::store_{(::std::atexit(static_store&lt;T, A&gt;::cleanup), new typename ::std::aligned_storage&lt;sizeof(T), alignof(T)&gt;::type[static_store&lt;T, A&gt;::max_instances])}; template &lt;typename T, typename ...A&gt; inline T* static_new(A&amp;&amp; ...args) { using static_store = static_store&lt;T&gt;; while (static_store::lock_.test_and_set(::std::memory_order_acquire)) { ::std::this_thread::yield(); } auto const i(static_store::ffz(static_store::memory_map_)); auto p(new (&amp;static_store::store_[i]) T(::std::forward&lt;A&gt;(args)...)); static_store::memory_map_ |= 1ull &lt;&lt; i; static_store::lock_.clear(::std::memory_order_release); return p; } template &lt;typename T&gt; inline void static_delete(T* const p) { using static_store = static_store&lt;T&gt;; auto const i(p - static_cast&lt;T*&gt;(static_cast&lt;void*&gt;( static_store::store_))); //assert(!as_const(static_store::memory_map_)[i]); while (static_store::lock_.test_and_set(::std::memory_order_acquire)) { ::std::this_thread::yield(); } static_store::memory_map_ &amp;= ~(1ull &lt;&lt; i); static_cast&lt;T*&gt;(static_cast&lt;void*&gt;(&amp;static_store::store_[i]))-&gt;~T(); static_store::lock_.clear(::std::memory_order_release); } } </code></pre> <p>Usage:</p> <pre><code>auto const p(static_new&lt;int&gt;()); *p = 10; static_delete(p); </code></pre> <p>The code uses an integral type (<code>A</code>), as a bit mask, where each cleared bit means, that a corresponding slot in the <code>store_</code> is not occupied, and a set bit means it is occupied. This is done to minimize the storage requirements for the allocation mechanism. To find a free slot, the <code>ffz</code> function (find first zero) is used: it is compiled into a single instruction on many platforms. The same thing could have been done with an array of <code>bool</code>s, but with greatly increased storage requirements.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T17:19:29.127", "Id": "49859", "Score": "0", "body": "Let teh editz commence? ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T17:20:04.437", "Id": "49860", "Score": "1", "body": "@Jamal nay, let the comments begin!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T17:20:46.523", "Id": "49861", "Score": "0", "body": "That, too. But what about the answers?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T17:27:52.950", "Id": "49862", "Score": "0", "body": "@Jamal Hmmm, that too, I hope especially for alternative trickery, that one might use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T22:26:56.270", "Id": "49882", "Score": "1", "body": "If you have tricks. Ask on stackoverflow. There are many more experienced C++ users there that can tell you if it is a good idea or not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T06:13:12.807", "Id": "49898", "Score": "0", "body": "@LokiAstari That's their problem. They are so elite, they tear down every new idea, while my motto is: \"if you like it and it works, then why not use it\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T07:14:23.080", "Id": "49900", "Score": "0", "body": "@user1095108: They will tear it down if it is a bad idea. If you can defend it then they will accept it. But I am unsure why I need it? Why would i use this over normal new? Also I find it hard to follow your code. But just a quick glance reveals problems that I could tear it apart with. But what I really want to know is what is the use case where this is useful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T07:19:09.887", "Id": "49901", "Score": "0", "body": "@LokiAstari When you need memory from the heap, without the overhead of `new` and you don't need lots of it. Making the code bulletproof could also make it slow. By all means, criticize the code, if it is bad." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T07:32:02.310", "Id": "49902", "Score": "0", "body": "@user1095108: Seriously. The standard memory management routines have been optimized for specifically this type of allocation. But they are general purpose allocator so you can not expect optimal in all situations. Have you done any timing to see the performance differences?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T07:33:04.860", "Id": "49903", "Score": "0", "body": "@user1095108: The normal way to do this is to write an allocator (see std::allocator). This will help you do it properly. Then you can do things like a general purpose pool allocator etc.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T07:39:57.117", "Id": "49904", "Score": "0", "body": "@LokiAstari Hmmm, you write an allocator only if you want to expose your allocation mechanism to the `STL` and the like, otherwise you don't need to. And yeah, the code works for me, it's fast, and thread-safe. One could also write a `::std::allocator` adapter class that would call `static_new` and `static_delete`, but I don't really need this functionality." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-16T07:51:48.393", "Id": "49905", "Score": "0", "body": "Still don't understand the code. Comment it a bit more than I will review it." } ]
[ { "body": "<p>I still have trouble understanding how the whole works, but there are still some small things that could be improved:</p>\n\n<ul>\n<li><p>In your comments, you say that <code>A</code> is an integer type used as a bitmask. The safest <a href=\"http://en.cppreference.com/w/cpp/concept/BitmaskType\">bitmask types</a> are <code>unsigned</code> types or <code>std::bitset</code>. You should make this condition clear in your code, write</p>\n\n<pre><code> template &lt;typename T, typename BitmaskType=unsigned&gt;\n struct static_store { /* ... */ };\n</code></pre>\n\n<p>You could even make it an error to use a nonconforming type and create a <code>is_bitmask</code> trait, which would allow you to create a meaningful error message:</p>\n\n<pre><code>static_assert(is_bitmask&lt;BitmaskType&gt;::value,\n \"the BitmaskType requirements are not satisfied\");\n</code></pre></li>\n<li><p>I got confused with these lines:</p>\n\n<pre><code>template &lt;typename T, typename ...A&gt;\ninline T* static_new(A&amp;&amp; ...args)\n</code></pre>\n\n<p>It is once again a naming problem: I had in mind the template parameter <code>A</code> from <code>static_store</code>. Since it represents arguments to be forwarding, you should just use the common convetion and name it <code>Args</code> instead. I don't know whether there are written guidelines to name variadic parameter packs, but <code>Args</code> is probably the name that I saw the most often.</p></li>\n<li><p>You could probably slightly hide details and reduce the visual burden by using a <code>typedef</code> for the type of <code>store_</code>:</p>\n\n<pre><code>using store_type = typename ::std::aligned_storage&lt;sizeof(T), alignof(T)&gt;::type;\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T19:53:18.980", "Id": "84364", "Score": "0", "body": "`new` has to be fast, that's why no `::std::bitset`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T22:04:12.387", "Id": "84385", "Score": "0", "body": "@user1095108 That makes sense :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-02T10:45:28.920", "Id": "46029", "ParentId": "31319", "Score": "8" } } ]
{ "AcceptedAnswerId": "46029", "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T17:12:47.940", "Id": "31319", "Score": "8", "Tags": [ "c++", "c++11" ], "Title": "static_new and static_delete" }
31319
<p>I wrote this block of code as part of a JS utility library I'm working on. I will be thankful if someone could scan through it for eventual bugs or improvements that might be applied to it. </p> <p>The idea is to create a function that will configure an object to manage its own data collection by attaching <code>.data()</code> function to it and plugging in a few utility functions to further control objects data:</p> <pre><code>// // #idb // // enables an object to hold arbitrary data // plugges in 'data' ( fn ) property to passed object // handles adding, removing, modifing, replacing, iterating, checking for data // adds 'idb' identifier to global scope // // .data() // # reads/manipulates objects data: // - if no parameters are passed returns private data store // - if one parameter is passed ( and its primitive ) returns it's coresponding value, // if plain object is provided extends data with it's props // - if two parameters are passed sets data key to coresponding value, // if second parameter is not a primitive value, // tries to extends private data with provided data value( extends plain objs, adds values to arrays ) // // static fns: // // .data.alter() // # replaces data with provided ( plain obj ) parameter // # @param1, object, required // # returns host object // // .data.drop() // # removes data, if parameter is provided deletes it's coresponding data, otherwise empties data store // # @param1, scalar, optional // # retutns host object // // .data.has() // # checks if data value coresponding to provided key exists // # @param1, scalar, required // # returns boolean // // .data.each() // # iterates data store, sequentialy passes data key and it's data value to provided fn, sets fn's context to host obj // # @param1, function, required // # returns host object // // .data.index() // # returns existing data keys as array // # returns array // // use: // // var o = idb({}); // // o.data("prop1", 1); // o.data("prop2", {p:12}); // o.data("prop3", {p1:1, p2:{}, p3:[]}); // o.data() -&gt; Object, ( data object ) // o.data('prop1'); -&gt; 1 // o.data('prop1', []); // o.data('prop1'); -&gt; [] // o.data.has('prop4'); -&gt; false // o.data.alter({p:1,q:2}); // o.data("p"); -&gt; 1 // o.data("prop1"); -&gt; undefined // o.data.each( // function ( k, v ) { // console.log( k, v); // } // ); -&gt; p 1 // q 2 // o.data.drop("q"); // o.data(); -&gt; {p:1} // o.data.drop(); // o.data(); -&gt; {} // ; (function(_host_) { var t = !0, f = !t, nl = null, _dbs = [], _db, un; // #helpers Array.prototype.each = function(fn) { for ( var i = 0, len = this.length; i &lt; len; i++) { if (fn.call(this, i, this[i]) === f) break; } return this; }; Array.prototype.has = function(v) { return this.indexOf(v) !== -1; }; function isobj(o) { return o === Object(o); } function isfn(o) { return typeof o === 'function' &amp;&amp; (Object.prototype.toString.call(o) === '[object Function]'); } function isplainobj(o) { return Object.prototype.toString.call(o) === '[object Object]'; } function isvalid(arg) { return arg !== un &amp;&amp; arg !== nl &amp;&amp; (arg === arg); } function isarray(o) { return isfn(Array.isArray) ? Array.isArray(o) : Object.prototype.toString.call(o) === '[object Array]'; } function slc(a, i1, i2) { return Array.prototype.slice.call(a, i1, i2); } function overload(o, method_v1, method_v2) { var origm = o[method_v1]; return o[method_v1] = function() { var args = slc(arguments); if (method_v2.length === arguments.length) { return method_v2.apply(this, args); } else if (isfn(origm)) { return origm.apply(this, args); } else { return un; } }; } function rig_props(obj, props) { if ( isobj(obj) &amp;&amp; isplainobj(props)) { each( props, function(p, v) { obj[p] = v; }) } return obj; } function owns(obj, prop) { return obj.hasOwnProperty(prop); } function each(obj, fn) { for (var p in obj) { if (owns(obj, p)) { if (fn.call(obj, p, obj[p]) === f) break; } } return obj; } function vacate_obj(obj) { if (isobj(obj)) { for (var p in obj) { try { if (!owns(Object.prototype, p)) { delete obj[p]; } } catch (xc) {} } } return obj; } function extend(hostObj, obj) { each( obj, function(prop) { if (owns(hostObj, prop) &amp;&amp; isobj(hostObj[prop])) { if (isobj(this[prop])) { if (!isarray(this[prop])) { if ( isplainobj(this[prop]) &amp;&amp; isplainobj(hostObj[prop])) { extend(hostObj[prop], this[prop]); } else { hostObj[prop] = this[prop]; } } else if (isarray(this[prop])) { if (isarray(hostObj[prop])) { this[prop].each( function(k, v) { hostObj[prop].has(v) || hostObj[prop].push(v); }); } else { hostObj[prop] = this[prop]; } } else { hostObj[prop] = this[prop]; } } else { hostObj[prop] = this[prop]; } } else { hostObj[prop] = this[prop]; } }); return hostObj; } // // // declare main fn // accepts any object _db = function(obj) { if ( isobj(obj) &amp;&amp; !_dbs.has(obj)) { (function(_d) { var host = this, dtfn = "data"; // if no arguments are provided return private data store // else pass responsibility to overloaded fns this[dtfn] = function() { return (arguments.length === 0) ? _d : host[dtfn](arguments[0], arguments[1]); }; // if one argument is provided deal with reading data value // or if plain object is provided extend data store with provided obj's props overload( this, dtfn, function(dtk) { return isplainobj(dtk) &amp;&amp; (extend(_d, dtk), host) || _d[dtk]; }); // if two arguments are given handle setting a data property // if value to set and current data value are objs extend current data value // else set data value to given parameter overload( this, dtfn, function(dtk, dtv) { isplainobj(dtv) &amp;&amp; ( isplainobj(_d[dtk]) &amp;&amp; (extend(_d[dtk], dtv), t) || (_d[dtk] = dtv), t) || (_d[dtk] = dtv); return host; }); // attach utility fns to data method rig_props( this[dtfn], { alter: function(dt) { return ( isplainobj(dt) &amp;&amp; (_d = dt), host); }, drop: function(dtk) { isvalid(dtk) &amp;&amp; (delete _d[dtk], t) || vacate_obj(_d); return host; }, has: function(dtk) { return isvalid(dtk) ? owns(_d, dtk['valueOf']()) : un; }, each: function(fn) { if (isfn(fn)) { each( _d, function(p, v) { return fn.call(host, p, v); }); } return host; }, index: function() { var k = []; this.each( function(p, v) { k.push(p); }); return k; } }); // remember configured object to avoid configuration rerun _dbs.push(this); }).call(obj, {}); } // end if // return configured object return obj; } // attach 'idb' fn identifier to global scope _host_.idb = _db; })(self); // // </code></pre>
[]
[ { "body": "<p>I am not sure why you would want to do this, what does this add over standard JS objects, all you would need is add <code>Object.prototype.alter</code> and <code>Object.prototype.forEach</code>.</p>\n\n<p>From a once over:</p>\n\n<ul>\n<li>If you are going to have <code>f</code> -> <code>false</code> and <code>t</code> -> <code>true</code>, then you might as well point to them <code>true</code> and <code>false</code> instead of <code>!0</code> and <code>!t</code></li>\n<li>Variables like <code>nl</code> for <code>null</code> are unfortunate, it reduces the quality of your code</li>\n<li>Your prototype <code>each</code> should probably be <code>forEach</code> and only be set if <code>forEach</code> is not already there ( it is there for more most browsers )</li>\n<li>You should use lowerCamelCase: <code>isarray</code> -> <code>isArray</code> etc.</li>\n<li><p>You are overdoing the newlines:</p>\n\n<pre><code>function rig_props( obj, props ) {\n if (\n isobj( obj )\n &amp;&amp; isplainobj( props )\n ) {\n each(\n props,\n function ( p, v ) {\n obj[p] = v;\n }\n )\n }\n return obj;\n}\n</code></pre>\n\n<p>should be </p>\n\n<pre><code>function rigPropertiess( o, properties ) {\n if ( isObject( o ) &amp;&amp; isPlainObject( properties ){\n each( properties, function ( key, value ) {\n o[key] = value;\n });\n }\n return o;\n}\n</code></pre></li>\n<li><code>vacate_obj</code> worries me, why would you need this compare to just assigning a new object ?</li>\n<li><p><code>extend</code> has a severe case of arrow pattern coding:</p>\n\n<pre><code> } else {\n hostObj[prop] = this[prop];\n }\n } else {\n hostObj[prop] = this[prop];\n }\n } else {\n hostObj[prop] = this[prop];\n }\n } else {\n hostObj[prop] = this[prop];\n }\n }\n );\n return hostObj;\n}\n</code></pre>\n\n<p>I am sure that with some deep thoughts you can do this better</p></li>\n</ul>\n\n<p>Again, I think you are re-inventing the wheel, unless I am missing something.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-19T17:48:09.723", "Id": "83541", "Score": "0", "body": "useful hints. I guess abandoning bad habits is pretty tough stuff. +" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-14T19:09:37.950", "Id": "47173", "ParentId": "31326", "Score": "2" } } ]
{ "AcceptedAnswerId": "47173", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T18:45:38.947", "Id": "31326", "Score": "2", "Tags": [ "javascript", "library" ], "Title": "Making an object manage custom data in JavaScript" }
31326
<p>I want you to pick my code apart and give me some feedback on how I could make it better or more simple. In my opinion this is the best code I have written, being that I'm new to programming. The program is a basic "converter" that has the user input his/her age and it tells how many days, hours, and minutes the user has been alive. Let me know what you think!</p> <pre><code>import time import sys def name(): name = input("What is your name? ") while name.isdigit(): print("Make sure to enter an actual name.") name = input("What is your name? ") return name def user_input(): while True: age = input("What is your age? ") try: return int(age) break except ValueError: try: return float(age) break except ValueError: print("Make sure to enter a real age.") def again(): while True: again = input("Play again? Yes/No ").lower() if again == "no": sys.exit(0) elif again == "yes": break else: print("That was not an option.") while True: the_name = name() age = user_input() Days = age * 365 Hours = Days * 24 Minutes = Hours * 60 print("Ok {}, I have your results.".format(the_name)) time.sleep(2) print("If you are {} years of age....".format(age)) time.sleep(2) print("You are {} days old.".format(Days)) time.sleep(2) print("You are {} hours old.".format(Hours)) time.sleep(2) print("You are {} minutes old!".format(Minutes)) again() </code></pre> <p><strong>NOTE:</strong> If you make a change, please explain to me why and how it works in the most simple way you can, so I understand it better.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T23:03:04.893", "Id": "49887", "Score": "0", "body": "Why not ask for a birth date (and time?) so you can calculate the real values?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T23:44:36.317", "Id": "49889", "Score": "0", "body": "Can you create an answer and show me how you would write the code to do that? @GraemeStuart" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-18T21:18:10.830", "Id": "50235", "Score": "0", "body": "OK I have added an answer @TheSuds13." } ]
[ { "body": "<p>This:</p>\n\n<pre><code>def name():\n name = input(\"What is your name? \")\n while name.isdigit():\n print(\"Make sure to enter an actual name.\")\n name = input(\"What is your name? \")\n return name\n</code></pre>\n\n<p>means that \"1\" is not a real name, but \"a\" and \"17xy\" are. I think it might be better to use some kind of a regular expression, or - better - just accept whatever nonempty string the user chooses to give you as his/her name.</p>\n\n<p>In your <code>user_input()</code>, you try to convert the input to <code>int</code>, and - if that fails - to <code>float</code>. Why not straight to <code>float</code>? I don't see how is <code>17</code> better than <code>17.0</code>.</p>\n\n<p>Also, in the same function, your <code>break</code> statements will never execute, as the <code>return</code> statement terminates the function.</p>\n\n<p>I think it'd be a much better program if the input was date of birth. Do you know your current age, as anything more precise than \"between <em>x</em> and <em>x</em>+1 years old\"?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T19:52:50.067", "Id": "31330", "ParentId": "31328", "Score": "6" } }, { "body": "<p>Why not ask for a birth date (and time?) so you can calculate the real values. You will need to import datetime.</p>\n\n<pre><code>import time\nimport sys\nfrom datetime import datetime\n</code></pre>\n\n<p>This function is OK, though I am not sure whether your isdigit test will catch many mistakes</p>\n\n<pre><code>def get_name():\n name = raw_input(\"What is your name? \")\n while name.isdigit():\n print(\"Make sure to enter an actual name.\")\n name = raw_input(\"What is your name? \")\n return name\n</code></pre>\n\n<p>Your function name, user_input() is too vague.\nI have changed it to get_date_of_birth() to make it more obvious what's going on\nYour original may be better named as get_age() for example\nI have also simplified the logic, your return statement is enough, no need to break\nI have also converted the input to a date using datetime.strptime()</p>\n\n<pre><code>def get_date_of_birth():\n date_string = raw_input(\"What's your date of birth? \")\n while True:\n try:\n return datetime.strptime(date_string, '%d/%m/%Y')\n except ValueError:\n date_string = raw_input(\"What's your date of birth? (format: dd/mm/yyyy) \")\n</code></pre>\n\n<p>Your again() function is great. I have simplified by returning a boolean value from the function which allows me to use it differently in the main logic below. I have also added single character options using 'in'</p>\n\n<pre><code>def again():\n while True:\n again = raw_input(\"Play again? (Yes/No) \").lower()\n if again in [\"no\", \"n\"]:\n return False\n elif again in [\"yes\", \"y\"]:\n return True\n else:\n print(\"That was not an option.\")\n</code></pre>\n\n<p>I have moved the main game flow into a function. Here I have changed it to use a datetime as the user's date of birth.</p>\n\n<pre><code>def play():\n name = get_name()\n dob = get_date_of_birth()\n age = datetime.today() - dob\n print(\"Ok {}, I have your results.\".format(name))\n time.sleep(1)\n print(\"You are {} years and {} days old....\".format(age.days // 365, age.days % 365))\n time.sleep(1)\n print(\"You are {} days old.\".format(age.days))\n time.sleep(1)\n print(\"You are {} hours old.\".format(int(age.total_seconds() // (60*60))))\n time.sleep(1)\n print(\"You are {} minutes old!\".format(int(age.total_seconds() // 60)))\n</code></pre>\n\n<p>The main logic is reduced to a simple, obvious loop. Code that executes should be protected behind <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">if <strong>name</strong> == \"<strong>main</strong>\"</a> so it doesn't run on import. </p>\n\n<pre><code>if __name__ == \"__main__\":\n play()\n while again():\n play()\n</code></pre>\n\n<p>I'm using raw_input() rather than input() as my code is python 2.7. I guess you are using python 3.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T21:52:41.073", "Id": "31447", "ParentId": "31328", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T19:13:14.480", "Id": "31328", "Score": "5", "Tags": [ "python", "beginner", "datetime", "python-3.x", "converting" ], "Title": "Simple age converter" }
31328
<p>This code finds a common ancestor. If one of the input does not exist in the tree then throws an exception. This does not use extra storage. It does not even traverse more than what it should be. It would also account for duplicate node values in binary tree.</p> <p>I want you to pick my code apart and give me some feedback on how I could make it better or more simple.</p> <pre><code>public class LeastCommonAncestor { private TreeNode root; private static class TreeNode { TreeNode left; TreeNode right; int item; TreeNode (TreeNode left, TreeNode right, int item) { this.left = left; this.right = right; this.item = item; } } public void createBinaryTree (Integer[] arr) { if (arr == null) { throw new NullPointerException("The input array is null."); } root = new TreeNode(null, null, arr[0]); final Queue&lt;TreeNode&gt; queue = new LinkedList&lt;TreeNode&gt;(); queue.add(root); final int half = arr.length / 2; for (int i = 0; i &lt; half; i++) { if (arr[i] != null) { final TreeNode current = queue.poll(); final int left = 2 * i + 1; final int right = 2 * i + 2; if (arr[left] != null) { current.left = new TreeNode(null, null, arr[left]); queue.add(current.left); } if (right &lt; arr.length &amp;&amp; arr[right] != null) { current.right = new TreeNode(null, null, arr[right]); queue.add(current.right); } } } } private static class LCAData { TreeNode lca; int count; public LCAData(TreeNode parent, int count) { this.lca = parent; this.count = count; } } public int leastCommonAncestor(int n1, int n2) { if (root == null) { throw new NoSuchElementException("The tree is empty."); } LCAData lcaData = new LCAData(null, 0); foundMatchAndDuplicate (root, lcaData, n1, n2, new HashSet&lt;Integer&gt;()); if (lcaData.lca != null) { return lcaData.lca.item; } else { throw new IllegalArgumentException("The tree does not contain either one or more of input data. "); } } private boolean foundMatchAndDuplicate (TreeNode node, LCAData lcaData, int n1, int n2, Set&lt;Integer&gt; set) { if (node == null) { return false; } // when both were found if (lcaData.count == 2) { return false; } // when only one of them is found if ((node.item == n1 || node.item == n2) &amp;&amp; lcaData.count == 1) { if (!set.contains(node.item)) { lcaData.count++; return true; } } boolean foundInCurrent = false; // when nothing was found (count == 0), or a duplicate was found (count == 1) if (node.item == n1 || node.item == n2) { if (!set.contains(node.item)) { set.add(node.item); lcaData.count++; } foundInCurrent = true; } boolean foundInLeft = foundMatchAndDuplicate(node.left, lcaData, n1, n2, set); boolean foundInRight = foundMatchAndDuplicate(node.right, lcaData, n1, n2, set); if (((foundInLeft &amp;&amp; foundInRight) || (foundInCurrent &amp;&amp; foundInRight) || (foundInCurrent &amp;&amp; foundInLeft)) &amp;&amp; lcaData.lca == null) { lcaData.lca = node; return true; } return foundInCurrent || (foundInLeft || foundInRight); } } </code></pre>
[]
[ { "body": "<p>There are a number of issues in your code that I can see:</p>\n\n<ul>\n<li><p>Input validation.</p>\n\n<blockquote>\n<pre><code>public void createBinaryTree (Integer[] arr) {\n if (arr == null) {\n throw new NullPointerException(\"The input array is null.\");\n }\n\n root = new TreeNode(null, null, arr[0]);\n</code></pre>\n</blockquote>\n\n<p>You check the <code>arr</code> is not null, but you do not check that its <code>arr.length</code> > 0. An empty array will cause an ArrayIndexOutOfBounds exception.</p></li>\n<li><p>AutoBoxing</p>\n\n<p>You have the method:</p>\n\n<blockquote>\n<pre><code>public void createBinaryTree (Integer[] arr) { ... }\n</code></pre>\n</blockquote>\n\n<p>which takes an array of <code>Integer[]</code>, which you then have to check for nulls in, and then you store the values away as:</p>\n\n<blockquote>\n<pre><code>current.left = new TreeNode(null, null, arr[left]);\n</code></pre>\n</blockquote>\n\n<p>where the constructor for TreeNode is an <code>int</code> value.</p>\n\n<p>Why do you take an <code>Integer[]</code> array at all? it should all be <code>int[]</code>...</p>\n\n<p>As a consequence, you have null-value issues in your code which make your code harder to read.</p></li>\n<li><p>The inner iteration of your code is unnecessarily complicated. This code here:</p>\n\n<blockquote>\n<pre><code> for (int i = 0; i &lt; half; i++) {\n if (arr[i] != null) {\n final TreeNode current = queue.poll();\n final int left = 2 * i + 1;\n final int right = 2 * i + 2;\n</code></pre>\n</blockquote>\n\n<p>should not start with <code>i = 0</code> because <code>arr[0]</code> was already included as the root. This is not obvious. You should have code that looks more like (note the <code>+ 1</code> and <code>+ 2</code> have been changed to <code></code> and <code>+ 1</code> respectively):</p>\n\n<pre><code> // start at 1 because arr[0] is already processed.\n for (int i = 1; i &lt; half; i++) {\n if (arr[i] != null) {\n final TreeNode current = queue.poll();\n final int left = 2 * i;\n final int right = 2 * i + 1;\n</code></pre></li>\n<li><p>In your recursion method, <code>set</code> is a really, really bad variable name, it should be <code>dupcheck</code> or something.</p></li>\n<li><p><strong>BUG</strong> your code does not find the least common ancestor (for whatever definition of Least you choose). This code here:</p>\n\n<blockquote>\n<pre><code>boolean foundInLeft = foundMatchAndDuplicate(node.left, lcaData, n1, n2, set);\nboolean foundInRight = foundMatchAndDuplicate(node.right, lcaData, n1, n2, set);\n</code></pre>\n</blockquote>\n\n<p>means that if there is a (duplicate) match in both the left, and the right, that whatever happened in the 'left' side is kept, and whatever happens in the right side is 'forgotten' (because you later have the check <code>&amp;&amp; lcaData.lca == null</code> ). As a result, you only identify the 'left-most' common ancestor.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T20:52:15.227", "Id": "42808", "ParentId": "31331", "Score": "6" } }, { "body": "<ol>\n<li><p>With better API design you could avoid this condition completely:</p>\n\n<pre><code>public int leastCommonAncestor(int n1, int n2) {\n if (root == null) {\n throw new NoSuchElementException(\"The tree is empty.\");\n }\n ...\n}\n</code></pre>\n\n<p>I'd create a <code>BinaryTree</code> class which gets the input array in the constructor:</p>\n\n<pre><code>public class BinaryTree {\n\n public BinaryTree(int[] input) {\n ...\n }\n\n public int getLeastCommonAncestor(int n1, int n2) {\n ...\n }\n}\n</code></pre>\n\n<p>If a client haven't constructed the object they are unable to call <code>getLeastCommonAncestor()</code> method.</p>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G31: Hidden Temporal Couplings</em>, p302) </p></li>\n<li><pre><code>TreeNode(TreeNode left, TreeNode right, int item) {\n ...\n}\n</code></pre>\n\n<p>The first two parameters are unnecessary, the code always call the constructor with <code>null</code> values.</p></li>\n<li><p>The same issue here with the first parameer:</p>\n\n<pre><code>public LCAData(TreeNode parent, int count) {\n ...\n}\n</code></pre></li>\n<li><p>If the input array contains a <code>null</code> it skips that branch. I'd throw an exception instead. I guess it's rather a bug on the side of the caller and there is not point to continue the calculation with wrong input. (<em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>.)</p></li>\n<li><p>It's not clear what are <code>n1</code> and <code>n2</code> here:</p>\n\n<pre><code>public int leastCommonAncestor(int n1, int n2) {\n ...\n}\n</code></pre>\n\n<p>Are they values (<code>TreeNode.item</code>)? Are they indexes? Give them a more descriptive name.</p></li>\n<li><pre><code>private boolean foundMatchAndDuplicate (TreeNode node, \n LCAData lcaData, int n1, int n2, Set&lt;Integer&gt; set) {\n ...\n}\n</code></pre>\n\n<p>What's the purpose of the <code>set</code> here? A better name would help readers a lot.</p></li>\n<li><pre><code>if (lcaData.lca != null) {\n return lcaData.lca.item;\n} else {\n throw new IllegalArgumentException(\"The tree does not contain either one or more of input data. \");\n}\n</code></pre>\n\n<p>I'd invert this condition and remove the else block, it's easier to read:</p>\n\n<pre><code>if (lcaData.lca == null) {\n throw new IllegalArgumentException(\"The tree does not contain either one or more of input data. \");\n}\nreturn lcaData.lca.item;\n</code></pre></li>\n<li><pre><code>throw new IllegalArgumentException(\"The tree does not contain either one or more of input data. \");\n</code></pre>\n\n<p>It would help debugging if exception message contains the input values.</p></li>\n<li><p>I agree with <em>@rolfl</em> that you shouldn't use <code>Integer[]</code>. ;) Instead of it use generics and your call could be used with any type of objects! Here is almost the same code (mostly without the suggestions above) but with generics:</p>\n\n<pre><code>public class LeastCommonAncestor&lt;T&gt; {\n private TreeNode&lt;T&gt; root;\n\n private static class TreeNode&lt;T&gt; {\n TreeNode&lt;T&gt; left;\n TreeNode&lt;T&gt; right;\n T item;\n\n TreeNode(T item) {\n this.item = item;\n }\n }\n\n public void createBinaryTree(T[] arr) {\n ...\n root = new TreeNode&lt;T&gt;(arr[0]);\n\n Queue&lt;TreeNode&lt;T&gt;&gt; queue =\n new LinkedList&lt;TreeNode&lt;T&gt;&gt;();\n ...\n for (int i = 0; i &lt; half; i++) {\n if (arr[i] != null) {\n TreeNode&lt;T&gt; current = queue.poll();\n ...\n if (arr[left] != null) {\n current.left = new TreeNode&lt;T&gt;(arr[left]);\n queue.add(current.left);\n }\n ...\n }\n }\n }\n\n private static class LCAData&lt;T&gt; {\n TreeNode&lt;T&gt; lca;\n ...\n }\n\n public T leastCommonAncestor(T n1, T n2) {\n LCAData&lt;T&gt; lcaData = new LCAData&lt;T&gt;(0);\n\n foundMatchAndDuplicate(root, lcaData, n1, n2, \n new HashSet&lt;T&gt;());\n ...\n }\n\n private boolean foundMatchAndDuplicate(TreeNode&lt;T&gt; node, \n LCAData&lt;T&gt; lcaData, T n1, T n2, Set&lt;T&gt; set) {\n ...\n }\n}\n</code></pre>\n\n<p>(Effective Java 2nd Edition, <em>Item 26: Favor generic types</em> and <em>Item 27: Favor generic methods</em>)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T23:27:29.200", "Id": "42824", "ParentId": "31331", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T22:28:22.160", "Id": "31331", "Score": "3", "Tags": [ "java", "algorithm", "tree" ], "Title": "Least common ancestor in binary tree" }
31331