body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have been attempting to write a code that converts Prefix expressions to Postfix expressions.</p> <p>So far here's what I have made (note that I am new and hence it may not be efficient!) </p> <pre><code>/*************************************************** NOTE: This code fails to realise the precedence of parentheses and $ (exponential) expressions ****************************************************/ import java.util.Scanner; class Stack{ //Private Declarations private int top; private String a[] = new String [100]; //Public Declarations public Stack(){ top = -1; a[0] = "\0"; } public void push(String x){ if (top != 99){ a[++top] = x; } else{ System.out.println("Stack overflow"); } }; public String pop(){ if (top == -1){ System.out.println("\nStack empty!"); return "\n"; } else{ return a[top--]; } }; public int ret_top(){ return top; }; } public class Prefix2Postfix { public static void main(String[] args) { //Declaration Scanner in = new Scanner (System.in); Stack op = new Stack (); Stack sym = new Stack (); char ch; int i; String exp, str, str1, str2, str3; //Taking input from the user System.out.println("Enter the prefix expression : "); exp = in.next(); for (i=0; i&lt;exp.length(); i++){ ch = exp.charAt(i); if((ch == '+') ||(ch == '-') ||(ch == '*') ||(ch == '/') ||(ch == '$')){ str = Character.toString(ch); op.push(str); } else{ str = Character.toString(ch); sym.push(str); if (sym.ret_top() == 1){ str1 = sym.pop(); str2 = sym.pop(); str3 = op.pop(); str1 = str2.concat(str1); str1 = str1.concat(str3); sym.push(str1); } } } //Output str = sym.pop(); System.out.println("After conversion to postfix" + ": " + str); in.close(); } } </code></pre> <p>As I have already commented in the code, my code fails to realize the precedence in the case of prefix expressions.</p> <p>For example:</p> <blockquote> <p>Infix : a + (b*c)</p> <p>Prefix : +a*bc</p> <p>Postfix : abc*+ //Expected output</p> <p>Output I get : ab*c+</p> </blockquote> <p>Is something wrong with the logic I am using, or is there something I need to add? Can you please suggest some method by means of which my code can work properly? If anybody can help I will be grateful.</p> <p>NB: Our professor has advised us to write our own stack class and code. Please also note that this is kind of a homework assignment.</p> <p><strong>Edit:</strong> To make sure my Stack class works fine I have written this piece of code:</p> <pre><code>import java.util.Scanner; class STACK { //Private Declarations private int top; private int elem[] = new int [100]; //Public Declarations public STACK (){ top = -1; elem[0] = 0; } public void push(int x){ if (top != 99){ elem[++top] = x; } else{ System.out.println("Stack overflow"); } }; public int pop(){ if (top == -1){ System.out.println("Stack empty!"); return 0; } else{ return elem[top--]; } }; } public class StackPushPop { public static void main(String[] args) { STACK s = new STACK(); Scanner in = new Scanner (System.in); int choice, x; do{ System.out.println("Menu Options :"); System.out.println("1 -&gt; Push an element"); System.out.println("2 -&gt; Pop an element"); System.out.println("3 -&gt; Empty complete stack"); System.out.println("Any other input for exit"); System.out.println("Your choice : "); choice = in.nextInt(); switch(choice){ case 1: System.out.println("\nEnter element : "); x = in.nextInt(); s.push(x); break; case 2: System.out.print("\nPopping element : "); x = s.pop(); if (x != 0){ System.out.println(x); } break; case 3: System.out.println("\nEmptying stack!"); x = 1; while (x!= 0){ x = s.pop(); if(x != 0){ System.out.print(x + " "); } } break; default: choice = 0; } }while (choice != 0); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T11:05:52.080", "Id": "48378", "Score": "0", "body": "May be here is bug: `a[++top] = x;` You will write first value at index 1, not 0." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T11:13:39.497", "Id": "48380", "Score": "0", "body": "@k06a : Please check the code properly. In my constructor I have assigned top to -1. Hence a[++top] = x; will first increase top to 0 and then store value at a[0]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T12:02:30.620", "Id": "48384", "Score": "0", "body": "This is Java code. Why is there a C++ tag?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T12:03:23.003", "Id": "48385", "Score": "0", "body": "I am so sorry. I must have put it there by mistake. Thanks for pointing that out, I will remove it right away." } ]
[ { "body": "<p>You are talking about Polish notation (PN) and reverse Polish notation (RPN):</p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Polish_notation\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Polish_notation</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Reverse_Polish_notation\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Reverse_Polish_notation</a></li>\n</ul>\n\n<p>Looks like you need to write some tests for your <strong>stack</strong> and <strong>function</strong> to make sure all works fine.</p>\n\n<p>And IMHO it will be more clear to rewrite your <code>if</code> with <code>switch</code>:</p>\n\n<pre><code>switch (ch)\n{\n case '+':\n case '-':\n case '*':\n case '/':\n case '$':\n // ...\n\n default:\n // ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T10:54:49.193", "Id": "48373", "Score": "0", "body": "My stack works fine but the fact that precedence in my Polish notation is ignored is whats bugging me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T10:58:11.190", "Id": "48374", "Score": "0", "body": "@iluvthee07 only tests can prove yourcode works fine. Your comments can't :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T11:01:57.190", "Id": "48375", "Score": "0", "body": "@iluvthee07 please post test, witch your code fails .." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T11:03:58.377", "Id": "48377", "Score": "0", "body": "I have given the test for which my code fails in the question, please see it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T15:28:28.530", "Id": "48395", "Score": "0", "body": "@iluvthee07: When people talk about tests, they mean code that calls a certain function with a set of inputs and verify that the output or state change is what is expected. Try looking into unit tests. What you posted allows you to manually test `Stack`. Every time you make a change, you have to repeat the same process. Additionally, it is not testing is the parsing logic in `main()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T15:49:21.623", "Id": "48397", "Score": "0", "body": "@unholysampler : Can you provide me with examples or links to examples of what you just said so that I can try it out?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T16:41:18.763", "Id": "48400", "Score": "1", "body": "@iluvthee07: JUnit is a popular unit test framework. [Tutorial on JUnit](http://www.vogella.com/articles/JUnit/article.html) Even if you don't end up using JUnit, the core concepts should carry over." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T10:52:54.527", "Id": "30429", "ParentId": "30426", "Score": "0" } }, { "body": "<p>You should define a constant that represents the size of your array. If tomorrow you want the array to be 200 elements and just change</p>\n\n<pre><code>private String a[] = new String [200];\n</code></pre>\n\n<p>your code will break.</p>\n\n<p>However if you class looked like the following, changing the size of the stack is simple and easy.</p>\n\n<pre><code>class Stack{\n private static final int STACK_SIZE = 100;\n private String a[] = new String [STACK_SIZE];\n //...\n public void push(String x){\n if (top &lt;= STACK_SIZE-1){\n a[++top] = x;\n }\n else{\n System.out.println(\"Stack overflow\");\n }\n };\n}\n</code></pre>\n\n<p>Also, if you accidentally increment <code>top</code> by more than one, <code>top != STACK_SIZE-1</code> can fail and cause an indexing error. Checking for less than or equal is what you want to do conceptually, so have the code actually do that.</p>\n\n<hr>\n\n<pre><code>public int ret_top(){\n return top;\n};\n</code></pre>\n\n<p>The convention is to name this type of method <code>getTop()</code> (note both the name and casing).</p>\n\n<hr>\n\n<p>You don't need to define all of you variables at the start of <code>main()</code>. Try to keep a variable as tightly scoped as you can. This will improve memory usage because instances you no longer need can be garbage collected. But more importantly, it will prevent you from accidentally using a value from a previous usage that you did not intend to use.</p>\n\n<p>Additionally, names like <code>str2</code> are not good variable names. The type system tells me that the variable is a <code>String</code>, so you shouldn't need to put the type in the name. Your variable names should describe what the value is conceptually.\nWhat makes a value popped from <code>op</code> different from a value popped from <code>sym</code>?</p>\n\n<p>On more thing, you don't need to keep variable names to less than 5 characters. I can guess what <code>sym</code> and <code>op</code> stand for, but it would be better if the code just told me. You shouldn't jump to 50 character names, but actual words are generally better than abbreviations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T14:03:45.577", "Id": "48392", "Score": "0", "body": "Thanks a lot! I am a beginner and am learning to code. I find your answer really useful in the long run. But it still does not answer my question and hence I can't accept it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T15:22:34.567", "Id": "48394", "Score": "0", "body": "@iluvthee07: Code Review is designed for getting comments on code quality. Think \"Is this code good? Could it be better?\" For \"Why doesn't this work?\" StackOverflow is best." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T15:50:20.800", "Id": "48398", "Score": "0", "body": "I accept the point you brought to my notice. Thanks a lot!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T13:15:48.937", "Id": "30437", "ParentId": "30426", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T10:35:40.640", "Id": "30426", "Score": "2", "Tags": [ "java", "algorithm", "homework", "converting" ], "Title": "Conversion of expression from Prefix to Postfix notation (Problem with precedence)" }
30426
<p>The problem is <a href="http://www.haskell.org/haskellwiki/99_questions/11_to_20" rel="nofollow">here</a>, the solutions are <a href="http://www.haskell.org/haskellwiki/99_questions/Solutions/18" rel="nofollow">here</a>. I don't see a solution like mine (maybe the 4th), it seems to work though.</p> <pre><code>-- --------------------------- -- 18 (**) Extract a slice from a list (idx start from 1) slice _ _ 0 = [] slice (x:xs) 1 k = x : slice xs 1 (k-1) slice (x:xs) i k = slice xs (i-1) (k-1) </code></pre> <p>I tried testing it with QuickCheck against the drop/take solution, but it gives up because of the very restrictive conditions (1 &lt;= i &lt;= k &lt;= len xs) and I don't want to get deeper in testing right now.</p> <p>Is this good Haskell code? Am I forgetting any edge case? (...should I suggest it on the solutions wiki?)</p>
[]
[ { "body": "<p>Yes you forgot to cover some cases.</p>\n\n<p>Your compiler should be able to detect one of them. Here is what <code>ghc -Wall</code> says:</p>\n\n<pre><code>slice.hs:2:1: Warning:\n Pattern match(es) are non-exhaustive\n In an equation for `slice':\n Patterns not matched: [] _ (GHC.Types.I# #x) with #x `notElem` [0#]\n\nslice.hs:4:8: Warning: Defined but not used: `x'\n</code></pre>\n\n<p>This version fixes those two warnings:</p>\n\n<pre><code>slice [] _ _ = []\nslice _ _ 0 = []\nslice (x:xs) 1 k = x : slice xs 1 (k-1)\nslice (_:xs) i k = slice xs (i-1) (k-1)\n</code></pre>\n\n<p>But it is still incorrect, because there is another case that the compiler doesn't warn you about: a negative <code>k</code> value. Your code will return the entire list instead of an empty list.</p>\n\n<p>Consequently, if you use a negative <code>k</code> on an infinite list you get an infinite loop:</p>\n\n<pre><code>&gt; print $ slice [1..] 1 (-1)\n[1,2,3,4,5,6,7,8,9,...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T15:33:41.643", "Id": "48396", "Score": "0", "body": "Very exhaustive (negative `i` too is a problem). Indeed, I supposed strictly valid input. +1 also for the `-Wall` suggestion (which told me about other bad habits I was developing)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T11:59:10.857", "Id": "30434", "ParentId": "30431", "Score": "3" } } ]
{ "AcceptedAnswerId": "30434", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T11:12:19.297", "Id": "30431", "Score": "1", "Tags": [ "haskell" ], "Title": "99 Haskell problems, problem 18" }
30431
<p>Here is my solution <a href="https://stackoverflow.com/questions/18326787/display-message-if-close-window-in-asp-net-but-not-on-postback">for this stackoverflow question.</a></p> <p>It is designed to return an <code>onbeforeunload</code> message when the user leaves the page (excluding postbacks). It does this by logging a timestamp each time a .NET control causes a postback (either full or partial using update panels). When this happens, if <code>allowedWaitTime</code> has elapsed, amessage will be returned.</p> <p>Are there any best or better practices missing from this code and does anyone have an opinion on my style (albeit a small sample)?</p> <pre><code>(function ($) { if (typeof $ !== 'function') { throw new Error('jQuery required'); } /* The time in milliseconds to allow between a function call and showing the onbeforeunload message. */ var allowedWaitTime = 100, timeStamp = new Date().getTime(), // Each function to override baseFuncs = { __doPostBack: this.__doPostBack, WebForm_DoPostBackWithOptions: this.WebForm_DoPostBackWithOptions }; // Set timeStamp when each baseFunc is called for (var baseFunc in baseFuncs) { (function (func) { this[func] = function () { var baseFunc = baseFuncs[func]; timeStamp = new Date().getTime(); if (typeof baseFunc === 'function') { baseFunc.apply(arguments.callee, arguments); } } })(baseFunc); } /* Form submit buttons don't call __doPostBack so we'll set timeStamp manually on click. */ $('input[type="submit"]').click(function () { timeStamp = new Date().getTime(); }); $(this).on('beforeunload', function (e) { // Only return string if allowedWaitTime has elapsed if (e.timeStamp - timeStamp &gt; allowedWaitTime) { return 'message'; } }); }).call(window, jQuery); </code></pre>
[]
[ { "body": "<p>Interesting question,</p>\n\n<p>I think the biggest thing is that <code>callee</code> is <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments/callee\" rel=\"nofollow\">going the way of the Dodo bird</a>.</p>\n\n<p>JsHint does not like your code because you are using <code>for( .. in .. )</code> without filtering properties, which is fine since you create the object with Object Notation, and I assume you did not modify the <code>Object</code> prototype. You are also creating functions/closures in a loop. Are you sure you need those closures there?</p>\n\n<p>Other than well commented, and easy to follow, something that I would not mind using in one of my projects.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-18T13:56:26.967", "Id": "60376", "ParentId": "30435", "Score": "2" } } ]
{ "AcceptedAnswerId": "60376", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T12:17:41.763", "Id": "30435", "Score": "1", "Tags": [ "javascript", "jquery", "asp.net" ], "Title": "Wrapping postback functions to call custom code at execution" }
30435
<p>Which is the best practice in getting data from repository? passing just by object or by Id?</p> <pre><code>public IQueryable&lt;Attendance&gt; GetByPersonId(int id) { return DbSet.Where(ps =&gt; ps.PersonId == id); } </code></pre> <p>or </p> <pre><code>public IQueryable&lt;Attendance&gt; GetByPerson(Person person) { return DbSet.Where(ps =&gt; ps.Person == person); } </code></pre> <p>Are there any performance implication? Or is it a case to case basis? If so what are the cases that you might want to pass by object and not by Id?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-29T07:59:51.603", "Id": "51064", "Score": "2", "body": "I personally would probably just pass the Id as then the caller does not have to assume knowledge of the method. Otherwise they have to pass an entire person object because who knows what the method might want to use..." } ]
[ { "body": "<p>I think you may pass complete entity because you already have it, this allow you do another condition type if you need.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T06:24:56.687", "Id": "30488", "ParentId": "30436", "Score": "0" } }, { "body": "<p>If the return type is <code>IQueryable&lt;Attendance&gt;</code> then use a <code>Person</code> object because it implies that the method could use any of the passed <code>Person</code> object's properties to query other persons or other related objects.</p>\n\n<p>If you want to find one person with <code>Id</code>, change the method's signature to tomething like this:</p>\n\n<pre><code>public Attendance GetByPersonById(int id)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-29T17:12:36.150", "Id": "51084", "Score": "0", "body": "»it implies that the method could use any of the passed Person object's properties to query other persons or other related objects.« Yes - but is that likely to happen? I do not know the framework enough, but I would guess the framework just uses the id. That is what ids are for: to clearly identify one object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-30T10:00:51.677", "Id": "51138", "Score": "0", "body": "It is not depending on the framework rather then the developer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-29T17:01:14.800", "Id": "31987", "ParentId": "30436", "Score": "1" } }, { "body": "<p>Think of the simple case:</p>\n\n<p>Is it likely, that the caller of your method has the <em>ID</em> of a person or the complete <code>Person</code>? Most of the times, I suppose is the former the case. Then you have to build a <code>Person</code>-Dummy only with the <em>ID</em> to use your method, which makes no sense. On the other hand, you could if you really really can't decide, which one is better simply use method overloading and offering both. But that would perhaps clutter your API. It's up to you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-29T17:20:50.187", "Id": "31988", "ParentId": "30436", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T13:09:45.650", "Id": "30436", "Score": "3", "Tags": [ "c#", "entity-framework" ], "Title": "Pass by Entity or EntityId in repositories?" }
30436
<p>I'd like to improve my code, but I'm not sure where to start. Everything works as I want it to; I just think it's ugly. </p> <p>I'll split this into two parts:</p> <ol> <li><p>I have two drop-downs that I'll explain later. In these drop-downs, I have options to set currency and language. I use a hidden form to set the current values with PHP, and extract the current value from these field. I then compare if the selected value matches the initial one. </p></li> <li><p>Within my two drop-downs, clicking on one or the other closes the other one, and open itself if it's not open. Upon closing the drop-down, I check if I should submit the form (<code>reloadPage()</code>).</p></li> </ol> <p>I think this should be split into separate functions, but I don't really know how to merge all of this together. I'm not asking for a full recode of my stuff, but I'd appreciate how to make this less ugly.</p> <p><strong>Part 1</strong></p> <pre><code>$(function() { hasChanged = false; var $options = $('#options'); var $currencycode = $options.find('#currency_code'); var $languagecode = $options.find('#language_code'); var $initCurrencycode = $currencycode.val(); console.log($initCurrencycode); $('.monnaie').find('a').click(function() { $this = $(this); if(!$this.hasClass('selected')) { $this.parent().siblings().find('a').removeClass('selected'); $myCurrencycode = $this.attr('class'); $currencycode.val($myCurrencycode); $this.addClass('selected'); if($myCurrencycode == $initCurrencycode) { hasChanged = false; console.log(hasChanged); } else { hasChanged = true; console.log(hasChanged); } } }); }); </code></pre> <p><strong>Part 2</strong></p> <pre><code>$optionsdropdown = $('#mobile-options'); $menudropdown = $('#mobile-menu'); function reloadPage() { if(hasChanged) { alert('reload now'); } else { console.log('nope'); } } $('.options-toggler').click( function() { if(!$optionsdropdown.hasClass('hide')) { $optionsdropdown.addClass('hide'); } else { $optionsdropdown.removeClass('hide'); } if(!$menudropdown.hasClass('hide')) { $menudropdown.addClass('hide'); } }); $('.menu-toggler').click( function() { if(!$menudropdown.hasClass('hide')) { $menudropdown.addClass('hide'); } else { $menudropdown.removeClass('hide'); } if(!$optionsdropdown.hasClass('hide')) { $optionsdropdown.addClass('hide'); } }); $('html').click(function() { if(!$optionsdropdown.hasClass('hide')) { $optionsdropdown.addClass('hide'); } if(!$menudropdown.hasClass('hide')) { $menudropdown.addClass('hide'); reloadPage(); } }); $('#mobile-menu, .menu-toggler').click(function(event){ event.stopPropagation(); }); $('#mobile-options, .options-toggler').click(function(event){ event.stopPropagation(); }); </code></pre>
[]
[ { "body": "<p>My 2 cents:</p>\n\n<ul>\n<li>Use jQuery toggleClass : <a href=\"http://api.jquery.com/toggleClass/\" rel=\"nofollow\">http://api.jquery.com/toggleClass/</a></li>\n<li>Use camelCase : currencycode -> currencyCode etc.</li>\n<li>Use English everywhere : 'monnaie' should not be there</li>\n<li>Booleans are awesome</li>\n</ul>\n\n<blockquote>\n<pre><code> if($myCurrencycode == $initCurrencycode) {\n hasChanged = false;\n console.log(hasChanged);\n } else {\n hasChanged = true;\n console.log(hasChanged);\n }\n</code></pre>\n \n <p>should be</p>\n\n<pre><code> hasChanged = ($myCurrencycode != $initCurrencycode)\n console.log( hasChanged );\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Finally, </li>\n</ul>\n\n<blockquote>\n<pre><code>if(!$menuDropdown.hasClass('hide')) {\n $menuDropdown.addClass('hide');\n}\n</code></pre>\n \n <p>can be replaced with <code>$menuDropdown.addClass('hide');</code>\n it will not add the class multiple times.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T16:43:57.030", "Id": "48401", "Score": "0", "body": "OP isn't even using `hasChanged`, so he could also go a step further and use `console.log($myCurrencycode != $initCurrencycode);`. Though that's starting to approach the edge between brevity and readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T18:03:57.393", "Id": "48406", "Score": "1", "body": "I actually wrote exactly that and then removed it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T18:47:03.900", "Id": "48409", "Score": "0", "body": "Thank you, I've applied your suggestions to my code (I've edited my original post)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T19:59:34.693", "Id": "48415", "Score": "0", "body": "@tomdemuyt: \"results indicate a significant improvement in time and lower visual effort with the underscore style\" ~ http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T20:21:57.527", "Id": "48417", "Score": "0", "body": "@DaveJarvis Sure, but for JavaScript the standard is camelCase, when in Rome.." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T15:33:04.973", "Id": "30443", "ParentId": "30441", "Score": "7" } }, { "body": "<p><code>.addClass()</code> won't add a class multiple times, so this:</p>\n\n<pre><code>if(!$optionsDropdown.hasClass('hide')) {\n $optionsDropdown.addClass('hide');\n}\n</code></pre>\n\n<p>can be rewritten as:</p>\n\n<pre><code>$optionsDropdown.addClass('hide');\n</code></pre>\n\n<p>But why even use a <code>hide</code> class at all ? jQuery has <a href=\"http://api.jquery.com/hide/\" rel=\"nofollow\">.hide()</a> and <a href=\"http://api.jquery.com/show/\" rel=\"nofollow\">.show()</a> helper functions, so you can just write:</p>\n\n<pre><code>$optionsDropdown.hide();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T13:58:24.350", "Id": "48529", "Score": "0", "body": "Because I'm applying the class in the source, I find it more semantic to hide a dropdown menu with a class than with hide(). I might be wrong, but I don't know. I will update my code to use addClass once, thanks :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T19:09:27.633", "Id": "30450", "ParentId": "30441", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T14:06:22.013", "Id": "30441", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Setting currency and language values" }
30441
<p>So far I've implemented a way to add to my <code>RedBlackTree</code> (will be used with A* pathfinding - hence the F value). I'm not entirely sure how to improve it further.</p> <p>I want to add a remove function to this tree, but can't find anything online that suits my style of tree. Any help? I only need to delete the first node. Also, what could I improve in my current code?</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RedBlackTree { //From Wiki: //The performance of an AA tree is equivalent to the performance of a red-black tree. //While an AA tree makes more rotations than a red-black tree, the simpler algorithms tend to be faster, and all of this balances out to result in similar performance. //A red-black tree is more consistent in its performance than an AA tree, but an AA tree tends to be flatter, which results in slightly faster search times. class RedBlackTree { private const bool red = false; private const bool black = true; private rbtNode root; private int _count = 0; public int count { get { return _count; } } //public bool Contains(PNode Key) //{ // Node current = root; // while (current != null) // { // if (current.Key == Key) // { // return true; // } // else if (value &lt; current.value) // { // current = current.left; // } // else // { // current = current.right; // } // } // return false; //} #region Insert Methods public void Insert(Node value) { rbtNode n = new rbtNode(value); if (root == null) { root = n; } else { rbtNode current = root; while (true) { if (current.F == value.F) { return; } else if (value.F &lt; current.F) { if (n.left == null) { current.left = n; break; } else { current = current.left; } } else if (value.F &gt; current.F) { if (current.right == null) { current.right = n; break; } else { current = current.right; } } } n.parent = current; } _count++; InsertCase1(n); } //Root node test, make it black private void InsertCase1(rbtNode n) { if (n.parent == null) { n.colour = black; } else { InsertCase2(n); } } //Node has black parent == No problems! private void InsertCase2(rbtNode n) { if (n.parent.colour == black) { return; } else { InsertCase3(n); } } // If Uncle is red, there is a certain error since we are red and parent is red // Make g red, and u and p black. No more error. Red grandparent needs to be checked though // If uncle isn't red and parent IS red then the fix is different, and we move to case 4 private void InsertCase3(rbtNode n) { if (Uncle(n).colour == red) { n.parent.colour = black; Uncle(n).colour = black; Grandparent(n).colour = red; InsertCase1(Grandparent(n)); } else { InsertCase4(n); } } // This case tests if the tree is in one of 2 forms which // need to be converted to other forms before they can be // fixed in case 5 (conversion is by rotation, left or right) // These are: // n = left child of right child // n = right child of left child // Any forms not covered in case 4 are already fine for processing by case 5. // e.g. // n = left child of left child // n = right child of right child private void InsertCase4(rbtNode n) { if (n == n.parent.right &amp;&amp; n.parent == Grandparent(n).left) { RotateLeft(n.parent); n = n.left; } else if (n == n.parent.left &amp;&amp; n.parent == Grandparent(n).right) { RotateRight(n.parent); n = n.right; } InsertCase5(n); } private void InsertCase5(rbtNode n) { n.parent.colour = black; Grandparent(n).colour = red; if (n == n.parent.left &amp;&amp; n.parent == Grandparent(n).left) { RotateRight(Grandparent(n)); } else if (n == n.parent.right &amp;&amp; n.parent == Grandparent(n).right) { RotateLeft(Grandparent(n)); } } #endregion private void RotateRight(rbtNode n) { rbtNode temp = n.left; ReplaceNode(n, temp); n.left = temp.right; if (temp.right != null) { temp.right.parent = n; } temp.right = n; n.parent = temp; } private void RotateLeft(rbtNode n) { rbtNode temp = n.right; ReplaceNode(n, temp); n.right = temp.left; if (temp.left != null) { temp.left.parent = n; } temp.left = n; n.parent = temp; } private void ReplaceNode(rbtNode oldn, rbtNode newn) { //This function does a lot of the hard work when swapping nodes. Reassigns parents and children. if (oldn.parent == null) { root = newn; } else { if (oldn == oldn.parent.left) { oldn.parent.left = newn; } else { oldn.parent.right = newn; } } if (newn != null) { newn.parent = oldn.parent; } } private rbtNode Uncle(rbtNode n) { if (n.parent != null) { return Sibling(n.parent); } else { return null; } } private rbtNode Sibling(rbtNode n) { if (n.parent != null) { if (n == n.parent.left) { return n.parent.left; } else { return n.parent.right; } } else { return null; } } private rbtNode Grandparent(rbtNode n) { if (n != null &amp;&amp; n.parent != null) return n.parent.parent; return null; } class rbtNode { public int Key; public int F; internal bool colour = false; //true = black, false = red internal rbtNode parent; internal rbtNode left; internal rbtNode right; internal rbtNode(Node Value) { this.Key = Value.Key; this.F = Value.F; left = null; right = null; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T16:35:17.333", "Id": "48399", "Score": "4", "body": "Asking how to add something to your code is off topic for this site. Though asking how to improve it in general isn't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-04T16:11:17.970", "Id": "463888", "Score": "0", "body": "I was about to suggest adding unit tests - still, in `void Insert()`, checking the node `n` just created `if (n.left == null)` looks *wrong*: improve them." } ]
[ { "body": "<h2>Edit / Update:</h2>\n\n<p>I noticed that you have a misplaced curly bracket (<code>}</code>) that makes it so that your last class is inside of your first class, <strong>meaning that this code shouldn't compile</strong>. </p>\n\n<hr>\n\n<p>For some reason I don't like <code>Else if</code> at the end of an <code>if..then..else</code> block, that might just be personal style/opinion but I figured that I would throw that out there. </p>\n\n<p>I also noticed that there were a couple of <code>If...then...else</code> blocks that end with an <code>Else if</code> like this one</p>\n\n<pre><code>if (current.F == value.F)\n{\n return;\n}\nelse if (value.F &lt; current.F)\n{\n if (n.left == null)\n {\n current.left = n;\n break;\n }\n else\n {\n current = current.left;\n }\n}\nelse if (value.F &gt; current.F)\n{\n if (current.right == null)\n {\n current.right = n;\n break;\n }\n else\n {\n current = current.right;\n }\n}\n</code></pre>\n\n<p>I would probably rewrite it like</p>\n\n<pre><code>if (current.F == value.F)\n{\n return;\n}\nelse if (value.F &lt; current.F)\n{\n if (n.left == null)\n {\n current.left = n;\n break;\n }\n else\n {\n current = current.left;\n }\n}\nelse \n{\n if (current.right == null)\n {\n current.right = n;\n break;\n }\n else\n {\n current = current.right;\n }\n}\n</code></pre>\n\n<p>Notice that I changed <code>else if (value.F &gt; current.F)</code> to <code>else</code>, I didn't see how there could be another case after that, so showing that anything other then the first two cases would fall into this category.</p>\n\n<p>your <code>if...then...else</code> blocks can really screw with an application, you can have all the right code in them but have them in totally the wrong order, I would be specific in the way that you form them and have a set pattern that you use, so that when you look back at it you can tell what is priority one, because the first one it hits is the only one it hits and then it ducks out of the <code>if</code> statement.</p>\n\n<p>As far as the <code>Delete()</code> Method, add it and see if it works the way you intend it to.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T20:27:08.653", "Id": "30453", "ParentId": "30442", "Score": "3" } }, { "body": "<p>I've made the classes more idiomatic for C# by using properties, recommended capitalization and an <code>enum</code> (as opposed to a <code>bool</code> for red-ness and black-ness). It also allowed for removal of extraneous code such as <code>else</code>-blocks that follow <code>break</code>s or <code>return</code>s and simplification of to the ternary operator. </p>\n\n<pre><code>namespace RedBlackTree\n{\n internal enum RedBlackIndicator\n {\n Red,\n\n Black\n }\n\n // From Wiki:\n // The performance of an AA tree is equivalent to the performance of a red-black tree.\n // While an AA tree makes more rotations than a red-black tree, the simpler algorithms tend to be faster, and all of this balances out to result in similar performance.\n // A red-black tree is more consistent in its performance than an AA tree, but an AA tree tends to be flatter, which results in slightly faster search times.\n internal class RedBlackTree\n {\n private rbtNode root;\n\n public int Count { get; private set; }\n\n ////public bool Contains(PNode Key)\n ////{\n //// Node current = root;\n //// while (current != null)\n //// {\n //// if (current.Key == Key)\n //// {\n //// return true;\n //// }\n //// else if (value &lt; current.value)\n //// {\n //// current = current.left;\n //// }\n //// else\n //// {\n //// current = current.right;\n //// }\n //// }\n //// return false;\n ////}\n\n #region Insert Methods\n\n public void Insert(Node value)\n {\n var n = new rbtNode(value);\n\n if (this.root == null)\n {\n this.root = n;\n }\n else\n {\n var current = this.root;\n\n while (true)\n {\n if (current.F == value.F)\n {\n return;\n }\n\n if (value.F &lt; current.F)\n {\n if (n.Left == null)\n {\n current.Left = n;\n break;\n }\n\n current = current.Left;\n }\n else if (value.F &gt; current.F)\n {\n if (current.Right == null)\n {\n current.Right = n;\n break;\n }\n\n current = current.Right;\n }\n }\n\n n.Parent = current;\n }\n\n this.Count++;\n this.InsertCase1(n);\n }\n\n private static rbtNode Uncle(rbtNode node)\n {\n return node.Parent == null ? null : Sibling(node.Parent);\n }\n\n private static rbtNode Sibling(rbtNode node)\n {\n return node.Parent == null ? null : (node == node.Parent.Left ? node.Parent.Left : node.Parent.Right);\n }\n\n private static rbtNode Grandparent(rbtNode n)\n {\n return n == null || n.Parent == null ? null : n.Parent.Parent;\n }\n\n // Root node test, make it black\n private void InsertCase1(rbtNode node)\n {\n if (node.Parent == null)\n {\n node.Colour = RedBlackIndicator.Black;\n }\n else\n {\n this.InsertCase2(node);\n }\n }\n\n // Node has black parent == No problems!\n private void InsertCase2(rbtNode node)\n {\n if (node.Parent.Colour != RedBlackIndicator.Red)\n {\n this.InsertCase3(node);\n }\n }\n\n // If Uncle is red, there is a certain error since we are red and parent is red\n // Make g red, and u and p black. No more error. Red grandparent needs to be checked though\n // If uncle isn't red and parent IS red then the fix is different, and we move to case 4\n private void InsertCase3(rbtNode node)\n {\n if (Uncle(node).Colour == RedBlackIndicator.Red)\n {\n node.Parent.Colour = RedBlackIndicator.Black;\n Uncle(node).Colour = RedBlackIndicator.Black;\n Grandparent(node).Colour = RedBlackIndicator.Red;\n this.InsertCase1(Grandparent(node));\n }\n else\n {\n this.InsertCase4(node);\n }\n }\n\n // This case tests if the tree is in one of 2 forms which\n // need to be converted to other forms before they can be\n // fixed in case 5 (conversion is by rotation, left or right)\n // These are: \n // n = left child of right child\n // n = right child of left child\n // Any forms not covered in case 4 are already fine for processing by case 5.\n // e.g.\n // n = left child of left child\n // n = right child of right child\n private void InsertCase4(rbtNode node)\n {\n if (node == node.Parent.Right &amp;&amp; node.Parent == Grandparent(node).Left)\n {\n this.RotateLeft(node.Parent);\n node = node.Left;\n }\n else if (node == node.Parent.Left &amp;&amp; node.Parent == Grandparent(node).Right)\n {\n this.RotateRight(node.Parent);\n node = node.Right;\n }\n\n this.InsertCase5(node);\n }\n\n private void InsertCase5(rbtNode node)\n {\n node.Parent.Colour = RedBlackIndicator.Black;\n Grandparent(node).Colour = RedBlackIndicator.Red;\n if (node == node.Parent.Left &amp;&amp; node.Parent == Grandparent(node).Left)\n {\n this.RotateRight(Grandparent(node));\n }\n else if (node == node.Parent.Right &amp;&amp; node.Parent == Grandparent(node).Right)\n {\n this.RotateLeft(Grandparent(node));\n }\n }\n\n #endregion\n\n private void RotateRight(rbtNode node)\n {\n var temp = node.Left;\n\n this.ReplaceNode(node, temp);\n node.Left = temp.Right;\n if (temp.Right != null)\n {\n temp.Right.Parent = node;\n }\n\n temp.Right = node;\n node.Parent = temp;\n }\n\n private void RotateLeft(rbtNode node)\n {\n var temp = node.Right;\n\n this.ReplaceNode(node, temp);\n node.Right = temp.Left;\n if (temp.Left != null)\n {\n temp.Left.Parent = node;\n }\n\n temp.Left = node;\n node.Parent = temp;\n }\n\n private void ReplaceNode(rbtNode oldNode, rbtNode newNode)\n {\n // This function does a lot of the hard work when swapping nodes. Reassigns parents and children.\n if (oldNode.Parent == null)\n {\n this.root = newNode;\n }\n else\n {\n if (oldNode == oldNode.Parent.Left)\n {\n oldNode.Parent.Left = newNode;\n }\n else\n {\n oldNode.Parent.Right = newNode;\n }\n }\n\n if (newNode != null)\n {\n newNode.Parent = oldNode.Parent;\n }\n }\n\n private sealed class rbtNode\n {\n private readonly int key;\n\n private readonly int f;\n\n internal rbtNode(Node node)\n {\n this.key = node.Key;\n this.f = node.F;\n this.Colour = RedBlackIndicator.Red;\n }\n\n public int Key\n {\n get\n {\n return this.key;\n }\n }\n\n public int F\n {\n get\n {\n return this.f;\n }\n }\n\n internal RedBlackIndicator Colour { get; set; }\n\n internal rbtNode Parent { get; set; }\n\n internal rbtNode Left { get; set; }\n\n internal rbtNode Right { get; set; }\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T17:48:55.713", "Id": "30521", "ParentId": "30442", "Score": "3" } }, { "body": "<p>I see code I can't quite believe true.<br>\n<code>rbtNode Uncle(rbtNode n)</code> has been <a href=\"https://codereview.stackexchange.com/a/30521/93149\">competently condensed by Jesse C. Slicer</a>, but</p>\n\n<pre><code>private static rbtNode Sibling(rbtNode node) {\n return node.Parent == null ? null\n : (node == node.Parent.Left ? node.Parent.Left : node.Parent.Right);\n}\n</code></pre>\n\n<p>seems to just return <code>node</code> instead of its sibling just as the original.<br>\nIn <code>Insert(Node value)</code>, an <code>rbtNode</code> is instantiated unconditionally, to immediately fall into oblivion when \"the F value\" is found.<br>\nNothing (much) wrong with that, but if <code>n</code> had not been defined beforehand,</p>\n\n<pre><code>if (value.F &lt; current.F) {\n if (n.left == null) {\n current.left = n;\n break;\n }\n current = current.left;\n} else if (value.F &gt; current.F) {\n if (current.right == null) {\n current.right = n;\n break;\n }\n current = current.right;\n}\n</code></pre>\n\n<p>would have been more eye-catching. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-04T17:57:59.007", "Id": "463911", "Score": "0", "body": "Where is that code in the question? It looks like you're reviewing one of the answers..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-04T18:03:20.173", "Id": "463914", "Score": "0", "body": "@TobySpeight hardly. I did take the liberty to reformat. (As stated: *In `Insert(Node value)`*.)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-04T17:12:18.523", "Id": "236658", "ParentId": "30442", "Score": "0" } } ]
{ "AcceptedAnswerId": "30521", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T14:26:13.993", "Id": "30442", "Score": "6", "Tags": [ "c#", "algorithm", "tree", "pathfinding" ], "Title": "A* path finding algorithm for a red-black tree" }
30442
<p>I'd like this code reviewed.</p> <pre><code>import java.util.NoSuchElementException; public class MergeSort { private Node first; private Node last; private static class Node { int element; Node next; Node(int element, Node node) { this.element = element; this.next = node; } } public void displayList() { Node tempFirst = first; while (tempFirst != null) { System.out.print(tempFirst.element + " "); tempFirst = tempFirst.next; } } public void add (int val) { final Node l = last; final Node newNode = new Node(val, null); last = newNode; if (first == null) { first = newNode; } else { l.next = newNode; } } public void sort() { /** * QQ: should there be an exception check for last == null also ? */ if (first == null) { throw new NoSuchElementException("The linkedlist doesnot contain any node."); } first = divide(first, last); } private Node getMidPoint(Node node) { assert node != null; Node fast = node.next; Node slow = node; while (fast != null &amp;&amp; fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; } private Node divide(Node node1, Node node2) { if (node1 == node2) return node1; Node midPoint = getMidPoint(node1); Node midpointNext = midPoint.next; midPoint.next = null; Node n1 = divide(node1, midPoint); Node n2 = divide(midpointNext, node2); return mergeLinkedList(n1, n2); } private Node mergeLinkedList(Node node1, Node node2) { assert node1 != null; assert node2 != null; Node current = null; Node currentHead = null; while (node1 != null &amp;&amp; node2 != null) { if (node1.element &lt; node2.element) { if (current == null) { currentHead = node1; current = node1; } else { current.next = node1; current = current.next; } node1 = node1.next; } else { if (current == null) { currentHead = node2; current = node2; } else { current.next = node2; current = current.next; } node2 = node2.next; } } current.next = node1 != null ? node1 : node2; return currentHead; } public static void main(String args[]) { // odd size list MergeSort ms1 = new MergeSort(); int[] a1 = {5, 4, 3, 2, 1}; for (int i : a1) { ms1.add(i); } ms1.sort(); ms1.displayList(); System.out.println(); // even size list. MergeSort ms2 = new MergeSort(); int[] a2 = {5, 4, 3, 2}; for (int i : a2) { ms2.add(i); } ms2.sort(); ms2.displayList(); System.out.println(); // list of size 1 MergeSort ms3 = new MergeSort(); int[] a3 = {1}; for (int i : a3) { ms3.add(i); } ms3.sort(); ms3.displayList(); System.out.println(); // list of size 2 MergeSort ms4 = new MergeSort(); int[] a4 = {2, 1}; for (int i : a4) { ms4.add(i); } ms4.sort(); ms4.displayList(); System.out.println(); } } </code></pre>
[]
[ { "body": "<p>Starting with some Java API documentation:</p>\n\n<blockquote>\n <p>public class NoSuchElementException\n extends RuntimeException</p>\n \n <p>Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.</p>\n</blockquote>\n\n<p>This is not an Enumeration and you have not called nextElement(). This is not an appropriate exception</p>\n\n<p><strong>sort()</strong> should really take a list as a parameter and return a sorted list. Give it a list as a parameter; if a null is passed, Java will do you a nice NullPointerException, free of charge. If the given list is simply empty, return an empty list. Being asked to sort an empty list is not an exceptional error situation. It's no more an error than being asked to sort a list with 1 element, which you do show you can do.</p>\n\n<p>Which brings me to the more important stuff...</p>\n\n<h1>Method and object conflated and confused.</h1>\n\n<p>You've combined a sorting algorithm with the (hand-rolled) list to be sorted. It would be better to have a properly usable list class and either a mergeSort method on that class or a static helper class with a MergeSort method that can act on any list object. Then you could create a list, examine it to show that it was a well-functioning and populated list, create a mergeSort()-ed version, check that this was a valid list, that it still had all the right elements (none missing, none added or substituted) and that they were in the desired order. You'd have something useful you could do more with.</p>\n\n<h1>List object cannot be tested/examined.</h1>\n\n<p>This is part of the problem created by the previous issue. There's no way to get at the list data. You print it out on the screen, but it's inaccessible to the rest of your code. What use was the sort? Did it even work? How is this validated except by the naked eye? Since you don't print the unsorted version out on the screen, how does the viewer know you did anything?</p>\n\n<p>Make the list fully usable. Provide a way to traverse and inspect it. Then your <em>code</em> can verify the sort (and do something useful with the sorted data afterwards, if you like).</p>\n\n<h1>Printing directly from within the merge class.</h1>\n\n<p>Don't do this. Have your class methods return useful values which can be inspected and tested. Print out the results in your main method if you want, but don't litter your classes with println statements.</p>\n\n<h1>Final, what?</h1>\n\n<p>What do you think you are gaining with those final keywords? Those local variables are going to evaporate when that tiny method returns, so what have you achieved?</p>\n\n<p>I should go on to examine the actual sorting algorithm but I think I'll leave that to somebody else - it's late and I'm tired.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T00:22:51.293", "Id": "30470", "ParentId": "30445", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T18:08:47.857", "Id": "30445", "Score": "1", "Tags": [ "java", "sorting", "linked-list", "mergesort" ], "Title": "Merge sort with a linked list" }
30445
<p>I have a jQuery "checkbox checked/unchecked" function that works well. This is a checkbox for turning a particular URL parameter on or off. But I believe this code could be written a lot tighter. Does anyone have any suggestions?</p> <pre><code>$('#mapControl').live('click', function(){ var thisUrl = $(location).attr('href'); if($(this).is(':checked')) { var lastFour = thisUrl.substr(thisUrl.length - 4); var param; if (lastFour == 'com/') {param='?mapControl=true'} else {param='&amp;mapControl=true'} thisUrl=thisUrl+param; } else { $('#urlParam').val(thisUrl); if (thisUrl.indexOf('?mapControl=true') &gt;= 0){ thisUrl=thisUrl.replace('?mapControl=true',''); } else if (thisUrl.indexOf('&amp;mapControl=true') &gt;= 0){ thisUrl=thisUrl.replace('&amp;mapControl=true',''); } } $('#urlParam').val(thisUrl); }); </code></pre> <p>I was given some suggestions (because i erroneously posted on StackOverflow) and was asked to post my question here. So with the feedback I got - I ended up with this code.</p> <pre><code> function getParam() { var n; var myUrl = window.location.href; var lastFour = myUrl.substr(myUrl.length - 4); if (lastFour == 'com/') {n='?'} else {n='&amp;'} return n; } $('#mapControl').on('click', function(){ var thisUrl = window.location.href; var urlParamObj = $('#urlParam'); if(this.checked === true) { var lastFour = thisUrl.substr(thisUrl.length - 4); var param = getParam(); thisUrl=thisUrl+param+'mapControl=true'; } else { urlParamObj.val(thisUrl); thisUrl=thisUrl.replace('?mapControl=true','').replace('&amp;mapControl=true',''); } urlParamObj.val(thisUrl); }); </code></pre> <p>I think this is the tightest it could be and I can use the <code>getParam</code> function for other checkboxes.</p>
[]
[ { "body": "<p>This is tighter I think:</p>\n\n<pre><code>function addParameter( url , name , value )\n{\n var justHostname = ( location.href == ( location.protocol + \"//\" + location.host + \"/\" ),\n separator = justHostname?\"?\":\"&amp;\"\n return url + separator + encodeURIComponent(name) + \"=\" + encodeURIComponent(value);\n}\n\n\n$('#mapControl').on('click', function(){ \n var url = window.location.href,\n urlParamObj = $('#urlParam');\n if(this.checked) \n {\n url = addParameter( url , 'mapControl' , 'true' )\n } else {\n url = url.replace('?mapControl=true&amp;','?')\n .replace('?mapControl=true','')\n .replace('&amp;mapControl=true',''); \n }\n urlParamObj.val(thisUrl);\n});\n</code></pre>\n\n<p>I did not test this, but you should catch the drift.</p>\n\n<p>If it were me though, I would not re-invent the wheel and use the code from the answer here : \n<a href=\"https://stackoverflow.com/questions/6953944/how-to-add-parameters-to-a-url-that-already-contains-other-parameters-and-maybe\">https://stackoverflow.com/questions/6953944/how-to-add-parameters-to-a-url-that-already-contains-other-parameters-and-maybe</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T18:57:11.063", "Id": "30449", "ParentId": "30446", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T18:16:54.780", "Id": "30446", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Determine whether a checkbox is checked or unchecked" }
30446
<p>So, I'm diving into C and decided to create cons cells. I'd like some thoughts on style and correctness. There are no warnings with <code>-Wall -g</code> and Valgrind doesn't complain about anything.</p> <p>I'm really not sure what to do when the list is <code>NULL</code> in the <code>first</code> function.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; struct Cell { int val; struct Cell *next; }; struct Cell *cons(int val, struct Cell *rest) { struct Cell *cell = malloc(sizeof(struct Cell)); cell-&gt;val = val; cell-&gt;next = rest; return cell; } int first(struct Cell *list) { if (list) { return list-&gt;val; } return 0; } struct Cell *rest(struct Cell *list) { return list-&gt;next; } int length(struct Cell *list) { if (list) { return 1 + length(rest(list)); } return 0; } void destroy(struct Cell *list) { if (list) { destroy(rest(list)); free(list); } } void print(struct Cell *list) { if (list) { printf("%d\n", first(list)); print(rest(list)); } } </code></pre> <p>The main function.</p> <pre><code>int main(int argc, char *argv[]) { struct Cell *list = NULL; int i; for (i = 1; i &lt; argc; ++i) { list = cons(atoi(argv[i]), list); } puts("Entire list:"); print(list); puts("First:"); printf("%d\n", first(list)); puts("Rest:"); print(rest(list)); puts("Length:"); printf("%d\n", length(list)); destroy(list); return 0; } </code></pre> <p>Running it.</p> <pre><code>./cons 1 2 3 4 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T01:56:31.633", "Id": "48449", "Score": "0", "body": "I like it! Apart from the in-band error return in `first` I think it is very good C." } ]
[ { "body": "<p>A few comments:</p>\n\n<p><code>typedef</code> your <code>struct</code>s:</p>\n\n<pre><code>typedef struct Cell\n{\n int val;\n struct Cell *next;\n} Cell;\n</code></pre>\n\n<p><code>typedef</code> means you no longer have to write <code>struct</code> all over the place:</p>\n\n<pre><code>Cell *cons(int val, Cell *rest)\n{\n Cell *cell = malloc(sizeof(Cell));\n cell-&gt;val = val;\n cell-&gt;next = rest;\n return cell;\n}\n</code></pre>\n\n<p>That not only saves keystrokes, it also can make the code cleaner since it provides a bit more abstraction.</p>\n\n<hr>\n\n<p>I would check if the pointer is <code>NULL</code> rather than if it isn't (<a href=\"https://codereview.stackexchange.com/questions/11544/is-it-better-practice-to-return-if-false-or-execute-an-if-statement-if-true\">related question</a>):</p>\n\n<pre><code>int length(struct Cell *list)\n{\n if (!list) return NULL; // or something else like -1\n return 1 + length(rest(list));\n}\n</code></pre>\n\n<hr>\n\n<p>Set the pointer to <code>NULL</code> after freeing it.</p>\n\n<pre><code>void destroy(struct Cell *list)\n{\n if (list)\n {\n destroy(rest(list));\n free(list);\n list = NULL;\n }\n}\n</code></pre>\n\n<p>Re-using a freed pointer can be a subtle error. Your code keeps right on working, and then crashes for no clear reason because some seemingly unrelated code wrote in the memory that the re-used pointer happens to be pointing at. This is to prevent that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T20:29:12.620", "Id": "48418", "Score": "0", "body": "Thanks for your feedback! I changed the code to use a typedef for the struct, but now I have a bunch of \"incompatible pointer type\" warnings. I'll have to invesitage that more. As for the length function, I understand the point of returning early, but aren't I already doing that? Also, I think a NULL (empty) list should return 0, and never NULL a negative integer. You're suggesting I NULL out the pointer because it's an argument and could be used elsewhere?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T20:34:42.387", "Id": "48420", "Score": "0", "body": "You are checking if a function is true and then exiting if it is false rather than checking if false and returning right away. `NULL` is defined as `(void*) 0`, not a negative number. And yes, you should always set the pointer to `NULL` when you are done using it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T20:40:20.117", "Id": "48421", "Score": "0", "body": "What's with returning `NULL` as an int? In the best case, it's the same as returning 0. In the worst case, it blows up in your face." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T20:57:20.070", "Id": "48423", "Score": "0", "body": "@syb0rg I meant to say \"or a negative number\" per your inline comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T01:47:55.407", "Id": "48447", "Score": "0", "body": "I see no point in setting `list` to NULL here. If you were going to do it, you'd want to do so within the `if (list) {...}` block, not outside it. But what you really want is to set the caller's list pointer (if it is a pointer) to null and you can do that as it stands." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T01:53:56.293", "Id": "48448", "Score": "0", "body": "Jeremy, your compile error after changing comes from the missing `Cell` in the above: it should read `typdef struct Cell {... } Cell;` - the first `Cell` is missing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T04:13:49.153", "Id": "48457", "Score": "0", "body": "@WilliamMorris I changed setting the list to NULL inside the blocks. I \"fixed\" the above compiler error even though I didn't get the error with only one `Cell`." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T19:57:36.363", "Id": "30452", "ParentId": "30447", "Score": "3" } }, { "body": "<p>In my opinion, this is pretty good C! Just a few nitpicks:</p>\n\n<ul>\n<li><strong>Function interface design</strong>: There's not much you can do if <code>list</code> is <code>NULL</code> in <code>first</code>, since C offers nothing like exceptions and your list contains an <code>int</code>, so you can't return an out-of-range value to indicate error, as is the convention sometimes. If signalling an error is crucial, I'd change the function interface to take a pointer to an int, where it would store the value, and return an error/success code. Generally it's easier (and acceptable) to rely on client code not to pass <code>NULL</code>, but this should be <em>well</em> documented in real-life code.</li>\n<li><strong>Recursion</strong>: I'd advise against the use of recursion when an iterative solution would work just as well. This is because stack space is ultimately limited and nothing guarantees the compiler would eliminate tail recursion even if you wrote your recursion that way.</li>\n<li><strong>Freeing pointed-to memory</strong>: Set the pointers that point to just-freed memory to NULL to avoid dereferencing them down the road. (This relies on a nullity check when appropriate, of course)</li>\n<li><strong>Typedefs</strong>: I'd actually advise <em>against</em> typedefing structs if you're accessing their members directly. Typedefs should represent either types that might change (like platform-specific ones) or opaque types you need to use accessor functions to read or mutate. Either way, if while coding you make no assumptions about the internal structure of the type, typedef it. Otherwise, you'd be better off letting client code (or other maintainer or even you a few weeks from now) know it's a struct. The same goes for pointer types.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T21:24:41.797", "Id": "48426", "Score": "0", "body": "Thanks! 1) In lisp fashion, calling `first` on an null or empty list just returns null. Would it be out of place to have it return `int *`, and have Cell use a `int *` for val? 2) I agree about not using recursion here. 3) Is this more-or-less a defensive action? It should be fine if there is no intention to ever use the pointer again, correct? I'm just diving deeper because Valgrind doesn't complain about it. 4) In this case, I think the Cell type is inconsequential since all operations on it can be done using `cons`, `first`, and `rest`. Even then you'd still suggest not using typedef?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T22:02:30.563", "Id": "48432", "Score": "0", "body": "Yes, your code is very lispy indeed. 1) I wouldn't store a `int*` in the list node. That serves no real purpose. Also, returning an `int*` from `first` would force the caller to dereference the return value to get to the actual content of the list node. This isn't really natural for a C programmer IMO. If you want to return \"multiple values\", pass pointers to the function. This way you can return an error code as well as \"return\" the content of the list node." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T22:14:47.197", "Id": "48433", "Score": "0", "body": "3) Valgrind would only generally complain about accessing memory you shouldn't (like a freed pointer) or not deallocating all dynamically allocated memory. Since you've done neither, Valgrind is happy. But you run the risk of not being able to tell the pointers are invalid in the future, because they point to seemingly valid, but undesireable addresses." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T05:36:42.303", "Id": "48465", "Score": "0", "body": "Thanks. I suppose my next exercise should be more C oriented." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T20:39:22.347", "Id": "30454", "ParentId": "30447", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T18:18:19.867", "Id": "30447", "Score": "1", "Tags": [ "c" ], "Title": "Basic cons cells in C" }
30447
<p>I wrote this little program, but I'm not sure if it's properly written. Actually, it can't handle leap years (every year is 365 days long) and you have to write the earlier date before. It seems to be working correctly.</p> <p>Can you tell me if it's okay or not, and what should I change in it to make it good?</p> <pre><code>#include &lt;iostream&gt; using namespace std; int first_date_month; int first_date_days; int first_date_year; int second_date_month; int second_date_days; int second_date_year; int days; int month_days[] = {31,28,31,30,31,30,31,31,30,31,30,31}; int main() { cout &lt;&lt; "Enter first date: "; cin &gt;&gt; first_date_year &gt;&gt; first_date_month &gt;&gt; first_date_days; cout &lt;&lt; "Enter second date: "; cin &gt;&gt; second_date_year &gt;&gt; second_date_month &gt;&gt; second_date_days; if(first_date_year == second_date_year) { if(first_date_month == second_date_month) days = second_date_days - first_date_days; else { for(int i = first_date_month; i &lt; second_date_month-1;i++) days += month_days[i]; days += month_days[first_date_month-1] - first_date_days + second_date_days; } } else { for(int i = 0; i &lt; second_date_month-1; i++) days += month_days[i]; for(int i = first_date_month; i &lt; 12; i++) days += month_days[i]; if(second_date_year - first_date_year &gt;= 0) days += (second_date_year - first_date_year - 1)*365 + month_days[first_date_month-1] - first_date_days + second_date_days; } cout &lt;&lt; "Days between the two dates: " &lt;&lt; days; return(0); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T20:17:35.370", "Id": "48416", "Score": "2", "body": "You are doing it the hard way. Convert your dates into unix time stamps (or similar single value ratio). Do a single subtraction then divide by (24*60*60)." } ]
[ { "body": "<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Do not use <code>using namespace std</code> in global scope</a>.</p></li>\n<li><p><em>Never use global variables</em>. Right away, this will introduce all sorts of problems, including maintainability and bugs. There are different alternatives to this, one being a <code>struct</code>:</p>\n\n<p>Such a structure just needs the month, day, and year:</p>\n\n<pre><code>struct Date\n{\n int month;\n int day;\n int year;\n};\n</code></pre>\n\n<p>Initialize the two <code>Date</code> instances:</p>\n\n<pre><code>// same order as appears in struct\nDate date1 = {1, 2, 2000};\nDate date2 = {4, 5, 2001};\n</code></pre>\n\n<p>Access the structures and set the data members (with your code):</p>\n\n<pre><code>std::cout &lt;&lt; \"Enter first date: \";\nstd::cin &gt;&gt; date1.year &gt;&gt; date1.month &gt;&gt; date1.day;\nstd::cout &lt;&lt; \"Enter second date: \";\nstd::cin &gt;&gt; date2.year &gt;&gt; date2.month &gt;&gt; date2.day;\n</code></pre>\n\n<p>If you want to get into encapsulation/information-hiding, I'd recommend a <code>class</code> instead. If you want to keep this simpler than a <code>struct</code>, just move the globals into <code>main()</code> (but use the variables from my example). You could also create more specialized functions, thereby not just working in <code>main()</code>. Modularity will help keep your code more organized and maintainable.</p></li>\n<li><p>I don't like <code>int</code> for these values (dates cannot be negative). I'd go with <code>std::size_t</code> instead (include <code>&lt;cstddef&gt;</code> to use it).</p></li>\n<li><p><code>month_days[]</code> should be a <code>const</code> while in global scope. As a constant, it <em>can</em> remain there because it cannot be changed by anything else. However, this will prevent you from accounting for leap-years. Speaking of which...</p></li>\n<li><p>To account for leap-years, I'd either:</p>\n\n<ol>\n<li>leave out February's value from the array (it's the only value that could change)</li>\n<li>not make the array a constant (the program will handle the values during runtime)</li>\n</ol>\n\n<p>With that, you can allow the program to adjust February's value if a leap-year.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T19:22:40.393", "Id": "48410", "Score": "0", "body": "thanks :)\nso you mean instead of using the namespaces I should use this (std::cout) form? Is it true for every namespace?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T19:27:27.380", "Id": "48411", "Score": "0", "body": "Yes. Generally, `using` is not good *in global scope* because it can cause name-clashes. For instance, let's say you've created your own `pow()`, but have also included `<cmath>`. What happens if you're using `using namespace std`? The compiler will not be able to tell them apart, causing errors. Plus, *you* may also not know which is which. Get the idea? :-) That said, you're welcome to put the `using` in `main()` because then it *won't* be in global scope." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T19:30:17.347", "Id": "48412", "Score": "0", "body": "i see :) thank you :D\nanother question:\nwhat if I used a struct like this:\nstruct Date\n{\nmonth;\nday;\nyear;\n}\n\nand then I create two instances of them (one for first_date, and an other for second_date)? Which solution is better?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T19:31:15.210", "Id": "48413", "Score": "0", "body": "Yes, a `struct` is okay for a starter. I'm already working on an edit regarding that." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T19:15:22.580", "Id": "30451", "ParentId": "30448", "Score": "8" } }, { "body": "<pre><code>#include &lt;iostream&gt;\n#include &lt;cmath&gt;\n\nint days;\n\n\nstruct Day\n{\n int count;\n friend std::istream&amp; operator&gt;&gt;(std::istream&amp; s, Day&amp; d)\n {\n int day_year;\n int day_month;\n int day_days;\n\n s &gt;&gt; day_year &gt;&gt; day_month &gt;&gt; day_days;\n\n // calculate number of leap years.\n int leapyears = day_year / 4;\n if (day_year % 4 == 0 &amp;&amp; day_month &lt; 3)\n {\n // If this is a leap year\n // And we have not passed Feburary then it does\n // not count.....\n leapyears --;\n }\n // convert year/month/day into a day count\n d.count = day_year * 365 + month_days[day_month-1] + day_days + leapyears;\n\n // return stream for chaining\n return s;\n }\n friend int operator-(Day const&amp; lhs, Day const&amp; rhs)\n {\n // subtraction gives you the difference between two Days objects.\n return lhs.count - rhs.count;\n }\n static int month_days[];\n};\n\nint Day::month_days[] = {0,31,59,90,120,151,181,212,243,273,304,334};\n</code></pre>\n\n<p>Main is now simple to write:</p>\n\n<pre><code>int main()\n{\n\n // Declare variables as close to the point of first use as you can.\n Day first;\n std::cout &lt;&lt; \"Enter first date: \";\n std::cin &gt;&gt; first;\n\n Day second;\n std::cout &lt;&lt; \"Enter second date: \";\n std::cin &gt;&gt; second;\n\n std::cout &lt;&lt; \"Days between the two dates: \" &lt;&lt; std::abs(first - second) &lt;&lt; \"\\n\";\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T21:22:32.257", "Id": "48425", "Score": "0", "body": "thanks :) but it's a bit complicated to me :D I've just started learning c++." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T21:40:00.290", "Id": "48429", "Score": "0", "body": "@mitya221: He essentially takes my basic `struct` suggestion and completes the implementation of the program (using the calculations and such). Of course, feel free to ask specific questions about what you don't understand here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T10:31:56.740", "Id": "48507", "Score": "0", "body": "well.. I understand it but I couldn't write such a program yet :) but thank you very much :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-31T09:53:56.797", "Id": "398598", "Score": "0", "body": "I hate to downvote this, because it's pretty good pedagogic code (apart from failing to check inputs, and getting some leap years wrong). But it's really not a _review_." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T20:42:05.903", "Id": "30455", "ParentId": "30448", "Score": "3" } }, { "body": "<p>When reading from a stream, one should always check that the read was successful:</p>\n\n<pre><code>std::cout &lt;&lt; \"Enter first date: \";\nstd::cin &gt;&gt; first_date_year &gt;&gt; first_date_month &gt;&gt; first_date_days;\nif (!std::cin) {\n std::cerr &lt;&lt; \"Date format error\" &lt;&lt; std::endl;\n return 1;\n}\n</code></pre>\n\n<p>(You could be much more helpful with the error message, of course).</p>\n\n<p>It's probably also a good idea to flush the output stream before reading input:</p>\n\n<pre><code>std::cout &lt;&lt; \"Enter first date: \" &lt;&lt; std::flush;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-31T09:35:13.377", "Id": "206642", "ParentId": "30448", "Score": "1" } } ]
{ "AcceptedAnswerId": "30451", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T18:42:13.923", "Id": "30448", "Score": "7", "Tags": [ "c++", "algorithm", "datetime", "reinventing-the-wheel" ], "Title": "Day counter between two dates" }
30448
<p>In the effort to improve my C knowledge, I tried creating a wildcard search function:</p> <pre><code>bool wildcard(char *value, char *wcard) { size_t vsize = strlen(value); size_t wsize = strlen(wcard); bool no_match = false; if (wsize &gt; vsize) { return false; } for (int w = 0, v = 0; w &lt; wsize; w++, v++) { switch (wcard[w]) { case MULTICHAR: if (w == wsize) { goto match; } else { w++; while (v &lt; vsize) { if (wcard[w] == value[v++]) { v--; break; } } if (no_match) { goto no_match; } } break; case ONECHAR: break; default: if (wcard[w] != value[v]) { goto no_match; } } } match: return true; no_match: return false; } </code></pre> <p>I have tested this by doing:</p> <pre><code>printf("Result: %d &lt;- Should be true\n",wildcard("Hello World","Hello*")); printf("Result: %d &lt;- Should be true\n",wildcard("Hello World","*Hello*")); printf("Result: %d &lt;- Should be true\n",wildcard("Hello World","He?lo*")); </code></pre> <p>All return 1.</p> <p>You can see the project <a href="https://github.com/AntonioCS/tests/blob/master/wildcards.c" rel="nofollow">here</a>.</p> <p>Any tips or improvements are welcome.</p> <h2>Note</h2> <p>I've already found a bug. If the wcard in present in the string, it will return <code>true</code> even if there is more data there.</p> <p>Example:</p> <pre><code>wildcard("Hello World","Hello") </code></pre> <p>This will return <code>true</code> when it shouldn't.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T10:12:01.667", "Id": "49297", "Score": "0", "body": "By the way, when you're not coding for recreational/educational purposes, just use the POSIX `fnmatch()` function." } ]
[ { "body": "<p>There's no need for the <code>goto</code>s whatsoever. Just use the appropriate <code>bool</code>s. You also complicate the logic by giving a variable and a <code>goto</code> the same name.</p>\n\n<p>I'd put <code>MULTICHAR</code>'s work in a function for clarity.</p>\n\n<p>Personally, I prefer <code>isMatch</code> over <code>no_match</code>. It's up to you.</p>\n\n<p>Since the function returns a <code>bool</code>, just have the <code>switch</code> update <code>isMatch</code> and return it at the end.</p>\n\n<pre><code>bool wildcard(char *value, char *wcard) {\n size_t vsize = strlen(value);\n size_t wsize = strlen(wcard);\n\n bool isMatch = false;\n\n if (wsize &gt; vsize) {\n return isMatch;\n }\n\n for (int w = 0, v = 0; w &lt; wsize; w++, v++) { \n switch (wcard[w]) {\n case MULTICHAR: \n isMatch = doSomethingWithBool();\n break;\n case ONECHAR:\n break;\n default:\n isMatch = (wcard[w] == value[v]);\n break;\n }\n }\n\n return isMatch;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T08:48:28.330", "Id": "48491", "Score": "0", "body": "Sorry. Multichar is just *. I will have to restructure the logic due to the bug I found. I should be checking the string against the pattern and not the pattern against the string." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T22:47:16.293", "Id": "30463", "ParentId": "30456", "Score": "2" } }, { "body": "<p>You should the parameters for null values. <code>strlen()</code> does not tolerate nulls passed to it as parameters.</p>\n\n<p>I'm not a complete zealot when it comes to the use of goto, but I'm not sure what benefit it gives in this code. Replacing the gotos with <code>return true</code> or <code>return false</code> would make the code a little simpler and more readable.</p>\n\n<pre><code> if (no_match) {\n goto no_match;\n }\n</code></pre>\n\n<p>compared to this for example: </p>\n\n<pre><code> if (no_match)\n return false;\n</code></pre>\n\n<p>For the bug you mentioned you will need to compare the lengths of the first and second wildcard parameters IF there is no special character in the second parameter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T08:46:58.197", "Id": "48489", "Score": "0", "body": "I was just trying to avoid multiple exit points, so in case of a clean up I know where the code will always go." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T20:01:09.327", "Id": "48556", "Score": "0", "body": "A worthy aim. You do have two return points in the code BTW." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T22:50:18.003", "Id": "30465", "ParentId": "30456", "Score": "3" } }, { "body": "<p>Your program returns 1 all the time (for your examples) because you never set <code>no_match</code> apart from at initialisation. Note also that the if <code>(w == wsize)</code> condition is never true because the loop condition is <code>w &lt; size</code>. </p>\n\n<p>I'm also not entirely sure what the function should do in all conditions, but maybe I'm being slow. </p>\n\n<p>Note also that you include four standard library headers in your public header. These includes belong in the C file, not the H file. </p>\n\n<p>Note further that your loop variables should be <code>size_t</code> not <code>int</code> to avoid sign conversion warnings.</p>\n\n<p><strong>EDIT:</strong> Exporting unnecessary headers like this is bad practice as they become part of the public interface and any program using your header becomes dependent upon those headers; the compiler must read them in each time it compiles their code. Most of the time this doesn't matter. But I have worked on embedded systems where this sort of thing is a real nuisance. As you are achieving nothing extra by placing the headers in the H file here - they are not providing any declarations needed <strong>by the header</strong> - put them in the C file. Some projects outlaw nested includes completely, but in general people put them in where the <strong>user</strong> of the header (not the implementation of what the header exports) needs them to compile correctly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T08:45:35.803", "Id": "48488", "Score": "0", "body": "Well I did find a bug but no, it doesn't return always true. If I do wildcard(\"Hello World\",\"sdffdsdsfdsfadsfsdf?lo*\"). This returns false. What is the problem with the headers?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T12:26:40.230", "Id": "48520", "Score": "1", "body": "Yes you are right - I was looking at your examples, not all possibilities. I will add a note on headers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T14:07:59.507", "Id": "48530", "Score": "0", "body": "Thanks for the quick reply. I will update the code. So in my .h file I should just have the function prototype and any define I have, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T19:05:02.617", "Id": "48552", "Score": "0", "body": "Yes, that is right." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T02:23:28.620", "Id": "30476", "ParentId": "30456", "Score": "2" } }, { "body": "<p>First, let's clear up some <strong>terminology</strong>. To me, a wildcard is a special character such as <code>*</code> and <code>?</code> in shell, or <code>%</code> and <code>_</code> in SQL. Your <code>wcard</code> parameter is a wildcard <em>expression</em>. Unix users might call it a <em>glob</em>, though Windows users rarely do. I think that <em>pattern</em> would be the most appropriate term, so let's go with that.</p>\n\n<p>(I would also prefer the term <em>subject</em> to <em>value</em>. Also, strictly speaking, this is a wildcard <em>matching</em> function, not a <em>searching</em> function. But those aren't really much of an issue in your code.)</p>\n\n<p>Also on the subject of naming, the <strong>inverted logic</strong> of <code>bool no_match</code> is unnecessarily confusing. Fortunately, that turns out to be irrelevant since you <strong>never actually use the <code>no_match</code> variable</strong>!</p>\n\n<p>It's not valid to say that <code>wsize &gt; vsize</code> means the match fails. A long subject (e.g. <code>abc</code>) can match a short pattern (<code>a*</code>). A short subject (<code>a</code>) can match a long pattern (<code>a*</code>). Therefore, <code>if (wsize &gt; vsize) return false</code> is a <strong>bug</strong>.</p>\n\n<p>The <strong>goto</strong> feature should be used judiciously, and here its use is inappropriate. This function has no side effects, and you haven't allocated anything other than some local stack variables. There is nothing to clean up, and therefore no reason to restrict your function's exit points. Just return true or false as soon as you know the answer — the code will be more readable.</p>\n\n<p>I think <strong>incrementing <code>v</code> in the <code>for</code> loop</strong> is a bad idea. Since a <code>MULTICHAR</code> wildcard can match zero characters, it's not certain that <code>v</code> will advance by one character every loop iteration. We do know that <code>w</code> will advance by one character each loop iteration, so the <code>for</code> loop should only be about <code>w</code>.</p>\n\n<p>Instead of counting <code>v</code> and <code>w</code>, then <strong>calculating <code>value[v]</code> and <code>wcard[w]</code> all the time</strong>, I would just use pointers that crawl along the subject and pattern. Using crawling pointers has the additional advantage of <strong>avoiding <code>strlen()</code></strong> — you just look for the null terminator as you go.</p>\n\n<p>Your <code>ONECHAR</code> and <code>default</code> cases need to verify that you have not <strong>run past the end</strong> of the <code>value</code> string.</p>\n\n<p>In your <code>MULTICHAR</code> case, <code>if (w == wsize) goto match</code> is <strong>unreachable code</strong> that indicates a logic bug. That condition can never be met since you just checked for <code>w &lt; wsize</code> as a condition in the <code>for</code> loop.</p>\n\n<p>The biggest problem with your <code>MULTICHAR</code> handling is that it only does the <strong>non-greediest match possible</strong>, which is not expected behaviour. I would expect <code>wildcard(\"Hello world\", \"H*orld\")</code> to be true, but the <code>o</code> following <code>*</code> would only match the <code>o</code> of <code>Hello</code>, ignoring the other possibility. The simplest way to test all possibilities for the <code>MULTICHAR</code> wildcard is to use recursion.</p>\n\n<p>In summary, here's how I would do it…</p>\n\n<pre><code>bool wildcard(char *subject, char *pattern) {\n for (; *pattern; pattern++) {\n switch (*pattern) {\n case MULTICHAR:\n if (*(pattern + 1) == '\\0') {\n /* This wildcard appears at the end of the pattern.\n If we made it this far already, the match succeeds\n regardless of what the rest of the subject looks like. */\n return true;\n }\n for (char *s = subject; *s; s++) {\n if (wildcard(s, pattern + 1)) {\n return true;\n }\n }\n return false;\n\n case ONECHAR:\n if (*(subject++) == '\\0') {\n return false;\n }\n break;\n\n default:\n if (*subject == '\\0' || *pattern != *(subject++)) {\n return false;\n }\n }\n }\n\n /* End of pattern reached. If this also the end of the subject, then\n match succeeds. */\n return *subject == '\\0';\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T13:20:42.423", "Id": "30985", "ParentId": "30456", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T21:26:25.180", "Id": "30456", "Score": "4", "Tags": [ "c", "strings", "search" ], "Title": "Wildcard search in C" }
30456
<p>I have implemented the following code:</p> <pre><code>class A { abstract void f1(Object obj, Object data); } class A1:A { void f1(Object obj, Object data) { m1(obj,data); } void m1(Object obj, Object data) { } } class A2:A { void f1(Object obj, Object data) { m2(obj, data); } void m2(Object obj, Object data) { } } static class Factory { public static A GetInstance(int i) { if (i == 1) return new A1(); else if (i == 2) return new A2(); else return null; } } </code></pre> <p>Methods are being called from some other part of the application, as following:</p> <pre><code>var a = Factory.GetInstance(1); a.f1(obj, data); </code></pre> <p>In the above code, the abstract method <code>f1()</code> has two parameters <code>obj</code> and <code>data</code>. While I reviewed the code, I found the parameter <code>data</code> can be determined from the first parameter <code>obj</code> itself. The area of the application from where the method <code>f1()</code> is being called, there the Libraries for getting data are not available. So I refactored the code further as following in order to send one parameter <code>obj</code>. Following is the implementation:</p> <pre><code>class A { public Object data { get; set; } abstract void f1(Object obj); } class A1:A { void f1(Object obj) { m1(obj,data); } void m1(Object obj, Object data) { } } class A2:A { void f1(Object obj) { m2(obj, data); } void m2(Object obj, Object data) { } } static class Factory { public static A GetInstance(int i) { if (i == 1) return new A1(); else if (i == 2) return new A2(); else return null; } } </code></pre> <p>Now, I am calling the method as following:</p> <pre><code>var a = Factory.GetInstance(1); a.data = GetData(); a.f1(obj); </code></pre> <p>Please let me know whether or not the refactoring is correct. Also, please suggest some ways for better refactoring.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T06:37:25.693", "Id": "48427", "Score": "0", "body": "Your code is strange why you do that :\n obj.f1(obj);\n\nfor me is not necessary to pass obj at f1 because is \"this\" in the body methode." } ]
[ { "body": "<p>The code still looks a bit strange to me.</p>\n\n<pre><code>obj.f1(obj);\n</code></pre>\n\n<p>Why are you passing the object as a parameter when the method already is a member? Skip the parameter and use <code>this</code> instead.</p>\n\n<p>You should also try to minimize the number of method the user needs to call to perform one thing. Requiring <code>obj.data</code> to be set before calling <code>obj.f1</code> is error prone. It would be better to let the <code>obj</code> constructor call <code>GetData</code> to extract the <code>data</code> from the obj.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T06:56:18.130", "Id": "48428", "Score": "0", "body": "Sorry for the mistake. The pass parameter in f1() is some other object.Lets make it obj.f1(obj) . I can not let the obj constructor call GetData to extract the data from the obj, as the lilbraries which are required to get the \"data\" , are not available in calle's place." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T06:31:33.277", "Id": "30459", "ParentId": "30458", "Score": "1" } }, { "body": "<p>In order to do a proper refactoring, you should move your classes somewhere, where you can calculate data. If you cannot do so, then you'll be better off with your original version. The second version is completely counterintuitive. Without digging into implementation details it is impossible to guess, that you need to set <code>data</code> property for <code>f1</code> method to work.</p>\n\n<p>Also returning <code>null</code> from factory (unless it is a valid value) is bad code style. You should throw <code>NotSupportedException</code> instead</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T04:52:16.293", "Id": "30484", "ParentId": "30458", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T06:25:28.837", "Id": "30458", "Score": "1", "Tags": [ "c#", "design-patterns" ], "Title": "Refactoring implementation in.NET" }
30458
<p>Are there any issues in this code?</p> <pre><code>/// &lt;summary&gt; /// This function gets the unique identifier of a member by the given /// login user name of that member on our web site. /// &lt;/summary&gt; /// &lt;param name="userName"&gt;The username&lt;/param&gt; public static string GetMemberNumberByUserId(string userName, string connectionString) { try { SqlConnection database = new SqlConnection(connectionString); SqlCommand command = new SqlCommand("GetMemberInfoByUserID", database); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@userID", userName); database.Open(); SqlDataReader reader = command.ExecuteReader(); reader.Read(); string memberNumber = reader.GetString(reader.GetOrdinal("memberNumber")); // Make sure the member number is a 11 or 12 digit number if (Regex.IsMatch(memberNumber, @"^(000|100)\d{6,7}(?!00)\d{2}$")) { return memberNumber; } else { return ""; } } catch(Exception) { return null; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T21:50:42.200", "Id": "48431", "Score": "0", "body": "As mentioned below, not closing the connection. Also I would consider not handling the exception and letting it bubble up instead" } ]
[ { "body": "<p>One thing is that you never close the SQL connection. I would change that structure a bit and put things inside a <code>using</code> block:</p>\n\n<pre><code>using (SqlConnection database = new SqlConnection(connectionString))\n{\n try\n {\n //other code\n }\n catch(Exception)\n {\n //exception code\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T14:10:53.580", "Id": "49032", "Score": "0", "body": "one common 'pattern' is to put `Close()` in a `finally{}` block." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T21:46:45.273", "Id": "30461", "ParentId": "30460", "Score": "1" } }, { "body": "<p>As well as what squillman suggested I might look at passing in SQLConnection rather than the connection string. This way the connection could be re-used as it is fairly expensive to create SQLConnections all the time.</p>\n\n<p>Something like:</p>\n\n<pre><code>// Or even better I might consider making this a resource string or injecting it int\n// the method as a parameter\nstatic string string MemberNumberFormat = @\"^(000|100)\\d{6,7}(?!00)\\d{2}$\";\n\npublic static string GetMemberNumberByUserId(SqlConnection connection, string userID)\n{\n var command = new SqlCommand(\"GetMemberInfoByUserID\", connection)\n {\n CommandType = CommandType.StoredProcedure\n };\n\n command.Parameters.AddWithValue(\"@userID\", userID);\n\n using (SqlDataReader reader = command.ExecuteReader())\n {\n reader.Read();\n\n string memberNumber = reader.GetString(reader.GetOrdinal(\"memberNumber\"));\n\n return Regex.IsMatch(memberNumber, MemberNumberFormat)\n ? memberNumber\n : string.Empty;\n } \n}\n</code></pre>\n\n<p>Then a wrapper class that would be responsible for creating the connection or managinging it's existence. That method for example might look like:</p>\n\n<pre><code>public string GetMemberNumberByUserId(string userID)\n{\n var connectionString = string.Empty;\n\n using (var database = new SqlConnection(connectionString))\n {\n database.Open();\n return GetMemberNumberByUserId(database, userID);\n } \n}\n</code></pre>\n\n<p>No exception handling is required. The only reason I could see from the code for an exception occurring would be for a major failure. At which point I think you might want to capture that at another level anyway.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T02:28:36.390", "Id": "48454", "Score": "0", "body": "could u explain what the difference between passing a sql connection and using connection string is?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T07:38:53.317", "Id": "48710", "Score": "0", "body": "You have the chance to re-use the sqlconnection in other parts of the code without needing to recreate it as it was created elsewhere of this method" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T14:16:35.177", "Id": "49034", "Score": "1", "body": "Thumbs up to **reusing the Connection** object. You'd think SQLxxxx objects were immutable, the way coders never reuse these things. Re-instantiating and building up `SQLAdapter`s over and over again makes me cringe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-07T08:26:57.213", "Id": "113244", "Score": "0", "body": "I would go further than this. Don't even pass the connection to methods. Have centralized database object classes that hold the connection as a field rather than having every method accept a connection. On the caller side make sure to only create one such object. Maybe even have that class be responsible for building up the connection to keep the database layer in there." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T22:31:42.763", "Id": "30462", "ParentId": "30460", "Score": "3" } }, { "body": "<pre><code>catch(Exception)\n{\n return null;\n}\n</code></pre>\n\n<p>You should never do this. Exception means that there is some sort of problem. And you shouldn't ignore problems, you should learn about them and do something about them as soon as possible.</p>\n\n<p>What you should do is that at first, don't catch any exceptions. Then, if you find out that some exceptions actually do happen under normal conditions, then handle those, <em>but only those</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T22:49:49.210", "Id": "30464", "ParentId": "30460", "Score": "4" } }, { "body": "<blockquote>\n <p>I need to know if there are any issues in this code</p>\n</blockquote>\n\n<p><code>GetMemberNumberByUserId</code> should not be checking the validity of the returned data. This method should be <em>concerned</em> with only \"getting a member number by the user id\". This is an example of violating the Single Responsibility Principle.</p>\n\n<p><strong>Exceptions</strong> - \"covering\" database calls with <code>try/catch</code> is idiomatic. To put a fine point on, and perhaps contradict, a couple of previous answers:</p>\n\n<ol>\n<li>limit the body of <code>try</code> to the code that you <em>really</em> need to cover. This also means you get specific about the exceptions caught there. </li>\n<li>catch exceptions as close as practical to the likely source; and database calls is a likely source. Then you can capture lots of good information about your <code>connection</code>, <code>command</code>, etc. objects, parameters passed, etc. and put that stuff in the <code>Exception.Data</code> property.</li>\n<li>1 &amp; 2 go hand-in-hand</li>\n<li>still have an exception catch higher up as suggested by svik.</li>\n</ol>\n\n<p>To illustrate #1 above: do you really want to throw an exception if there is no regex match? Then do not put that in the <code>try</code> block. And it should not be in that method in the first place.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T21:00:37.037", "Id": "30793", "ParentId": "30460", "Score": "1" } }, { "body": "<p>I think there are several issues with this code. In no particular order...</p>\n\n<ol>\n<li><p>Why is this a static method? While the sql connection string is generally either going to be injected or a dependency, the user name seems likely to be a property of the object. Not a big issue, and in context it could be the right thing.</p></li>\n<li><p>Disposable objects should generally be wrapped in a using block -- unless there is a need for the object to be used after the function is done, which doesn't seem to be the case here.</p></li>\n<li><p>Why are you doing validation in a method called Get...? That should either be done in the database, or after this method.</p></li>\n<li><p>You return an empty string in the case of validation error and null on an exception. You do nothing with your exception handling except return an error -- no logging, no report to the user.</p></li>\n<li><p>You catch an exception at the first point you know what to do to recover from the error -- since this function doesn't do anything with the string it retrieves, how does return null; recover from the error?</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T21:42:50.847", "Id": "30795", "ParentId": "30460", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T21:34:49.810", "Id": "30460", "Score": "3", "Tags": [ "c#", "database" ], "Title": "Getting the unique identifier from a given login username" }
30460
<p>I want to get the filename and last 23 characters when I drag into a textbox.</p> <p>I have it working, but I would like to just have one line. Currently, I think I am doing a bit of a workaround. As I must use a string array, and I only want one string, so I don't really need an array.</p> <pre><code>private void First_DragDrop(object sender, DragEventArgs e) { string[] fileList = e.Data.GetData(DataFormats.FileDrop) as string[]; string filename = Path.GetFileNameWithoutExtension(fileList[0]); First.Text = filename.Substring(filename.Length - 23, 23); } </code></pre> <p>As you can see, I must do it in 3 steps. First, get the string array. Then, get one string from that array and turn it into a filename. FInally, I need to get the last 23 characters of that string.</p> <p>I think I should be able to just get everything immediately. Though maybe it's not possible? It just seems weird that I must use an array that contains one thing.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T23:30:04.860", "Id": "48442", "Score": "0", "body": "Thanks as always Jamal, much appreciated for the corrections:)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T23:31:37.010", "Id": "48443", "Score": "0", "body": "You're welcome. :-) Just want to help others help you." } ]
[ { "body": "<p>Yes, you can write everything in one line, but you will not be happy with the result. And no, .Net creators did not think of implementing a single call which would return exactly 23 characters of dropped file name. :) Silly them. :) </p>\n\n<p>Meanwhile, your code makes sense. I see only two possible issues:</p>\n\n<ol>\n<li>You do not handle multiple files being dropped (that is why there is an array)</li>\n<li>You do not handle <code>fileList</code> being <code>null</code>.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T08:58:02.650", "Id": "48493", "Score": "0", "body": "Hehe, well to bad;P But the problem is, as you say, i have an array for multiple (i never drop multiple files), and which is why i want to only get the file dropped (if i drop more files, just ignore them or something), cause i am only interested in 1 file, it doesn´t make sense to get that info from many files at the same time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T09:33:06.630", "Id": "48496", "Score": "1", "body": "@Zerowalker, if you develop application for yourself - then its fine, i guess. If not, then you should not assume that user will only drop single file. You should not even assume that he will drop files, and not something else." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T10:31:22.627", "Id": "48506", "Score": "0", "body": "it´s for myself, so it shouldn´t be a problem:)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T07:57:25.107", "Id": "48609", "Score": "0", "body": "But is there a way to simple put it into a single string? or am i forced to use an array?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T05:21:38.617", "Id": "48751", "Score": "0", "body": "@Zerowalker, you have to use an array" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T10:50:44.457", "Id": "48771", "Score": "0", "body": "Ah okay, good to know, have been searching on it. Thanks!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T05:18:03.337", "Id": "30487", "ParentId": "30468", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T23:18:48.327", "Id": "30468", "Score": "1", "Tags": [ "c#" ], "Title": "Drag Drop, get filename and last 23 characters" }
30468
<p>This is an implementation of a trie, that I will be using on a code editor to parse keywords from a given <em>programming</em> language. I decided to use a trie when I asked <a href="https://stackoverflow.com/questions/18347793/optimizing-a-word-parser">this question</a>, and the implementation seems to perform pretty well and without errors from valgrind/memcheck.</p> <p>I want to make sure I'm squeezing every bit of performance out of this thing, though. So I want to know if there's anything more I can do to improve performance (I guess that makes this a performance-related review). Are there any performance tips?</p> <p>While I'm not specifically looking for a review of the coding style, if I'm doing anything weird please point it out. </p> <hr> <p><strong>Implementation:</strong></p> <hr> <p><em>Header:</em></p> <pre><code>// trie.h #include &lt;stdlib.h&gt; #define TRIE_SIZE 256 // would be different for unicode struct trie_node { int class; /* acts as a class or id of the word * and used for checking for a match */ struct trie_node * nodes[TRIE_SIZE]; }; struct trie { struct trie_node head, * current; }; int trie_init (struct trie * t); int trie_adds (struct trie_node * head, char * str, int class); int trie_freenode (struct trie_node * node); int trie_free (struct trie * t); int trie_pass (struct trie * t, unsigned char c); int trie_reset (struct trie * t); </code></pre> <p><em>Implementation:</em></p> <pre><code>#include "trie.h" #include &lt;stdlib.h&gt; int trie_init (struct trie * t){ t-&gt;current = &amp;t-&gt;head; for (int i = 0; i &lt; TRIE_SIZE; i++){ t-&gt;head.nodes[i] = 0; } t-&gt;head.class = 0; return 0; } int trie_adds (struct trie_node * head, char * str, int class){ if (str[0]){ int num = str[0]; if (!head-&gt;nodes[num]){ // create new node head-&gt;nodes[num] = calloc (1, sizeof (struct trie_node)); if (!head-&gt;nodes[num]) return -1; } if (str[1]) return trie_adds (head-&gt;nodes[num], &amp;str[1], class); else head-&gt;nodes[num]-&gt;class = class; } return 0; } // used in trie_free static int trie_freenode (struct trie_node * node){ if (!node || !node-&gt;nodes){ return -1; } for (int i = 0; i &lt; TRIE_SIZE; i++){ if (node-&gt;nodes[i]){ trie_freenode (node-&gt;nodes[i]); free (node-&gt;nodes[i]); } } return 0; } int trie_free (struct trie * t){ for (int i = 0; i &lt; TRIE_SIZE; i++){ if (t-&gt;head.nodes[i]){ trie_freenode (t-&gt;head.nodes[i]); free (t-&gt;head.nodes[i]); t-&gt;head.nodes[i] = 0; } } t-&gt;current = &amp;t-&gt;head; return 0; } int trie_pass (struct trie * t, unsigned char c){ t-&gt;current = t-&gt;current ? t-&gt;current-&gt;nodes[c]) : 0; return t-&gt;current ? t-&gt;current-&gt;state : 0; } int trie_reset (struct trie * t){ t-&gt;current = &amp;t-&gt;head; return 0; } </code></pre> <p><em>Comparative test program (no trie):</em></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; char * gettestfile (char * filename); int strcmp2 (char * str1, char * str2); #define isqualifier(c)\ (((c &gt;= 'a') &amp;&amp; (c &lt;= 'z')) || ((c &gt;= 'A') &amp;&amp; (c &lt;= 'Z'))) int main (int argc, char * argv[]){ if (argc &lt; 3){ printf ("usage %s filename [words]\n", argv[0]); return -1; } char * buffer = gettestfile (argv[1]); if (!buffer){ return -1; } int nmatches = 0; for (int i = 0; buffer[i];){ while (buffer[i] &amp;&amp; !isqualifier (buffer[i])) i++; if (!buffer[i]) break; int i2 = 0; for (int j = 2; j &lt; argc; j++){ i2 = strcmp2 (&amp;buffer[i], argv[j]); if (i2 &gt; 0) break; } if (i2 &gt; 0){ i += i2; nmatches++; } else while (buffer[i] &amp;&amp; isqualifier (buffer[i])) i++; } printf ("found %d matches\n", nmatches); free (buffer); return 0; } int strcmp2 (char * str1, char * str2){ int i = 0; for (; str1[i] &amp;&amp; str2[i]; i++){ if (str1[i] != str2[i]){ break; } } return (str2[i] || isqualifier (str1[i])) ? 0 : i; } char * gettestfile (char * filename){ char * buffer = 0; int len = 0; FILE * file = fopen (filename, "r"); if (!file){ return 0; } fseek(file, 0L, SEEK_END); len = ftell(file); fseek(file, 0L, SEEK_SET); buffer = calloc (len + 1, 1); if (!buffer){ fclose (file); return 0; } fread (buffer, 1, len, file); fclose (file); return buffer; } </code></pre> <p><em>Comparative test program (with trie):</em></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include "trie.h" #define isqualifier(c)\ (((c &gt;= 'a') &amp;&amp; (c &lt;= 'z')) || ((c &gt;= 'A') &amp;&amp; (c &lt;= 'Z'))) char * gettestfile (char *); int main (int argc, char * argv[]){ char * buffer = 0; struct trie t; if (argc &lt; 3){ printf ("usage: %s filename [words]\n", argv[0]); return -1; } trie_init (&amp;t); for (int i = 2; i &lt; argc; i++){ trie_adds (&amp;t.head, argv[i], 1); } buffer = gettestfile (argv[1]); int nmatches = 0; if (buffer){ for (int i = 0; buffer[i]; i++){ char c = buffer[i]; if (isqualifier (c)){ trie_pass (&amp;t, buffer[i]); } else { if (t.current &amp;&amp; t.current-&gt;class){ nmatches++; } trie_reset (&amp;t); } } free (buffer); } printf ("found %d matches\n", nmatches); trie_free (&amp;t); return 0; } char * gettestfile (char * filename){ char * buffer = 0; int len = 0; FILE * file = fopen (filename, "r"); if (!file){ return 0; } fseek(file, 0L, SEEK_END); len = ftell(file); fseek(file, 0L, SEEK_SET); buffer = calloc (len + 1, 1); if (!buffer){ fclose (file); return 0; } fread (buffer, 1, len, file); fclose (file); return buffer; } </code></pre> <p><em>Notes about implementation:</em></p> <p><code>isqualifier</code> is used to check if a character is a qualifying unit of a word. In this case, it is the alphabet (it may also be contain numbers and '_' if it is parsing code). The use of this macro is to eliminate matches like <code>the</code> within the word <code>there</code>. If there is a qualifier before or after a two sequences of characters, it is not considered a match.</p> <hr> <p><strong>Performance testing:</strong></p> <hr> <p>I've already timed both of these with a large text file. Here's some of the results:</p> <p><em>Test 1:</em></p> <pre><code>root@nodeTwo:/usr/local/src/trie# time ./std-test big.txt one found 3091 matches real 0m0.058s user 0m0.052s sys 0m0.004s root@nodeTwo:/usr/local/src/trie# time ./trie-test big.txt one found 3091 matches real 0m0.068s user 0m0.064s sys 0m0.000s </code></pre> <p><em>Test 2:</em></p> <pre><code>root@nodeTwo:/usr/local/src/trie# time ./std-test big.txt one the here that now next hello for while this found 100085 matches real 0m0.137s user 0m0.132s sys 0m0.004s root@nodeTwo:/usr/local/src/trie# time ./trie-test big.txt one the here that now next hello for while this found 100085 matches real 0m0.077s user 0m0.072s sys 0m0.004s </code></pre> <p><em>Test 3:</em></p> <pre><code>root@nodeTwo:/usr/local/src/trie# time ./std-test big.txt one the here that now next hello for while this when do something crazy let me know found 107419 matches real 0m0.188s user 0m0.184s sys 0m0.004s root@nodeTwo:/usr/local/src/trie# time ./trie-test big.txt one the here that now next hello for while this when do something crazy let me know found 107419 matches real 0m0.077s user 0m0.072s sys 0m0.004s </code></pre> <p><em>Notes about testing:</em></p> <p>To perform this test, I downloaded <a href="http://norvig.com/big.txt" rel="nofollow noreferrer">this</a> text file (warning: it's 6.5MB of text) and used it with both programs. If you would like to download the text file and build the source for this review, you can use that link and <a href="https://github.com/taylorholberton/trie" rel="nofollow noreferrer">this</a> link to the GitHub page.</p> <hr> <p><strong>Solutions:</strong></p> <hr> <p>The only way I can think of that <em>may</em> increase performance is by allocating the entire list into continuous virtual memory (would that help get it into CPU Cache?), instead of broken up chunks, and mapping the list to that. I don't know how much to expect this to help, so I'm not sure if I should bother with it or not.</p>
[]
[ { "body": "<p>On the assumption that the list of keywords does not change often, the fastest code will be to precompile your trie into a tree of switch statements like this, where <code>p</code> is the current character pointer, and suppose your keywords are <code>a</code>, <code>aa</code>, <code>ab</code>, <code>b</code>, <code>ba</code> and <code>bb</code>:</p>\n\n<pre><code>switch(p[0]){\nbreak; case 'a': switch(p[1]){\n break; case 'a':{\n if (!alphanumeric(p[2]){/* found aa */}\n }\n break; case 'b':{\n if (!alphanumeric(p[2]){/* found ab */}\n }\n break; default: if (!alphanumeric(p[1])){ /* found a */ } else\n /* no keyword here */\n }\nbreak; case 'b': switch(p[1]){\n break; case 'a':{\n if (!alphanumeric(p[2]){/* found ba */}\n }\n break; case 'b':{\n if (!alphanumeric(p[2]){/* found bb */}\n }\n break; default: if (!alphanumeric(p[1])){ /* found b */ } else\n /* no keyword here */\n }\nbreak; default:\n /* no keyword here */\n}\n</code></pre>\n\n<p>This code is tedious to write (!), but you could write a separate program to input the list of keywords and print out this code, which you could then include in your original program.</p>\n\n<p>Why is it fast? <strong><em>No data structure.</em></strong></p>\n\n<p>When I need speed, I try to use as little data structure as possible, and only to hold information that actually is not known until run time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T03:45:44.043", "Id": "48597", "Score": "0", "body": "I avoided this because I will be using this tree for many coding languages, and writing this kind of code for all of them would take a long time and would be hard to maintain and debug. You're right that it would be faster, but I don't think I can practically use this solution" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T14:22:57.827", "Id": "48622", "Score": "0", "body": "@Taylor: That's up to you of course, but if the little preprocessing program is written, then it only has to be run once for each language, and a separate executable (or dll) compiled for each language. If you want to have a single executable for all languages, then I would do it the way you are, except I would not use a trie, for space reasons. I would just use binary search as a first cut. I would not assume this is a bottleneck until it actually proves to be one, which I detect by random pausing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T22:33:04.760", "Id": "30535", "ParentId": "30469", "Score": "1" } }, { "body": "<p>It's encouraging that your test indicates that the trie execution time is (almost) independent of the number of keywords.</p>\n\n<p>I think you'll find that <code>isqualifier</code> is a significant contributor to the execution time, and gets worse as the complexity of the list of qualifying characters grows. For anything more complicated than [A-Za-z], a look-up table will be just as good. Only 256 bytes are needed; if that bothers you, you can actually make it work (for certain definitions of qualifying sets) with a couple of 64-bit constants and some bit-whacking:</p>\n\n<pre><code>// Matches [0-9A-Za-z_]\nstatic const uint64_t low_64 = 0x03FF000000000000UL;\nstatic const uint64_t high_64 = 0x07FFFFFE87FFFFFEUL;\nstatic inline bool qualifies(uint8_t c) {\n uint8_t bit7 = (c &gt;&gt; 6);\n return ((c &gt;&gt; 7) ^ 1) &amp; (\n ((low_64 &gt;&gt; (c &amp; 0x7F)) &amp; (bit7 ^ 1) |\n ((high_64 &gt;&gt; (c &amp; 0x7F)) &amp; bit7));\n}\n</code></pre>\n\n<p>There are lots of variations on the above theme; you'd need to profile. But I wouldn't actually do that with tries, because you can take advantage of the trie itself to discriminate.</p>\n\n<p>The trie is really a simple state machine. With a small modification, we can actually build the precise state machine. Here it is in a simple version, recognizing <code>a</code>, <code>on</code> and <code>one</code>. Note that all the keywords end with a transition to \"Accept\"; this is really a transition to \"Start\" which also indicates that the keyword was accepted. (Code below.)</p>\n\n<pre><code>Start: a --&gt; State1\n o --&gt; State2\n other qualifying --&gt; Skip\n non_qualifying --&gt; Start\n\n# Come here after matching `a`\nState1: qualifying --&gt; Skip\n non_qualifying --&gt; Accept\n\n# Come here after matching `o`\nState2: n --&gt; State3\n other qualifying --&gt; Skip\n non_qualifying --&gt; Start\n\n# Come here after matching `on`\nState3: e --&gt; State4\n other qualifying --&gt; Skip\n non_qualifying --&gt; Accept\n\n# Come here after matching `one`\nState4: qualifying --&gt; Skip\n non_qualifying --&gt; Accept\n\n# Come here after matching any other word.\nSkip: qualifying --&gt; Skip\n non_qualifying --&gt; Start\n</code></pre>\n\n<p>Building this state machine is almost exactly the same as building the trie. The following is based on your trie code:</p>\n\n<pre><code>struct trie_node {\n int class;\n struct trie_node* nodes[TRIE_SIZE];\n};\n\nstruct trie {\n trie_node skip;\n trie_node start;\n trie_node* current;\n}\n\nint trie_init(struct trie* t) {\n for (int c = 0; c &lt; TRIE_SIZE; ++c) {\n t-&gt;skip[c] = isqualifying(c) ? &amp;t-&gt;skip\n : &amp;t-&gt;start;\n }\n // Initially, no keywords\n t-&gt;start = t-&gt;skip;\n t-&gt;current = &amp;t-&gt;start;\n}\n\nint trie_adds(struct trie* t, const char* s, int class) {\n struct trie_node* current = t-&gt;start;\n for (; *s; ++s) {\n uint8_t ch = *s;\n if (current[ch] == &amp;t-&gt;skip) {\n current[ch] = malloc(sizeof *current[ch]);\n *current[ch] = t-&gt;skip;\n }\n current = current[ch];\n }\n current-&gt;class = class;\n}\n\nstatic inline int trie_step(struct trie* t, int ch) {\n int class = t-&gt;current-&gt;class;\n t-&gt;current = t-&gt;current.nodes[ch];\n return t-&gt;current == &amp;t-&gt;start ? class : 0;\n}\n</code></pre>\n\n<p>(The above code is completely untested. It probably doesn't even compile.)</p>\n\n<p>With the above, you no longer need to call is_qualifying on every character. You just pass each character in turn -- including the terminating NUL -- through trie_step, and any time it returns a non-zero value, you've found a keyword.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-19T17:24:15.100", "Id": "31547", "ParentId": "30469", "Score": "2" } } ]
{ "AcceptedAnswerId": "31547", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T23:33:29.063", "Id": "30469", "Score": "3", "Tags": [ "optimization", "c", "performance", "parsing", "trie" ], "Title": "Improving Trie Implementation" }
30469
<p>I've been told that my code is horribly-written. It works exactly the way I want it to, but I have been told that it needs to be safer and more efficient.</p> <p><a href="https://gist.github.com/Thorbis/b858c303a8e1452f251e" rel="nofollow">Here's the code</a>.</p> <p>Here's the main PHP script:</p> <pre><code>&lt;?php $host = "*******"; // Host firstname $name = "*******"; // Mysql userfirstname $password = "*******!"; // Mysql password $db_name = "*******"; // Database firstname $tbl_name = "users"; // Table firstname // Connect to server and select database. mysql_connect("$host", "$username", "$password") or die("cannot connect"); mysql_select_db("$db_name") or die("cannot select DB"); foreach($_POST as &amp;$v) $v = mysql_real_escape_string($v); // Get values from form $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $email = $_POST['email']; $resumewebsitename = $_POST['resumewebsitename']; $resumewebsitename = substr($resumewebsitename, 0, 20); $website = 'http://www.thorbis.com/onlineresumes/users/' . $resumewebsitename; $cell = $_POST ['cell']; $overview = $_POST ['overview']; $query = mysql_query("SELECT * FROM users WHERE email='$email'"); if(mysql_num_rows($query) != 0) { echo "email already exists"; // redirect back to form and populate with // data that has already been entered by the user } else { $dbunames = mysql_query("SELECT * FROM users WHERE website='$website'"); if (mysql_num_rows($dbunames) &gt; 0) { echo "Sorry That Resume Name Has Been Taken Please Try Again :D"; } //mysql_num_rows($dbunames) &gt; 0 else { // function to recursively copy // a directory and its subdirectories function copyRecursive($source, $destination) { // check if source exists if (!file_exists($source)) { die("'$source' is not valid"); } //!file_exists($source) if (!is_dir($destination)) { mkdir($destination); } //!is_dir($destination) // open directory handle $dh = opendir($source) or die("Cannot open directory '$source'"); // iterate over files in directory while (($file = readdir($dh)) !== false) { // filter out "." and ".." if ($file != "." &amp;&amp; $file != "..") { if (is_dir("$source/$file")) { // if this is a subdirectory // recursively copy it copyRecursive("$source/$file", "$destination/$file"); } //is_dir("$source/$file") else { // if this is a file // copy it copy("$source/$file", "$destination/$file") or die("Cannot copy file '$file'"); } } //$file != "." &amp;&amp; $file != ".." } //($file = readdir($dh)) !== false // close directory closedir($dh); } $source_directory = "Interactive Resume/"; $destination_directory = "users/"; copyRecursive($source_directory, $destination_directory); @rename("users/user", "users/" . $resumewebsitename); $emails = ("$email, bcw1995@gmail.com"); $to = $emails; $subject = 'Thorbis | Submit'; $message = "&lt;h3 style='color: red;'&gt;This is ALL of your Info That You Inputed I will get back to you ASAP and customly make your website for you :D if i dont email me again at &lt;a style='color: darkread;' href='mailto:bcw1995@gmail.com'&gt;bcw1995@gmail.com&lt;/a&gt;&lt;/h3&gt;&lt;br&gt; &lt;a href='https://plus.google.com/113626141520121345204/posts' style='color:blue;'&gt;Follow Me On google Plus&lt;/a&gt;&lt;br&gt; &lt;a href='http://twitter.com/thorbis' style='color:blue;'&gt;Follow Me On Twitter&lt;/a&gt;&lt;br&gt; &lt;a href='http://www.linkedin.com/profile/view?id=226237754&amp;goback=%2Enmp_*1_*1_*1_*1_*1_*1_*1_*1_*1_*1&amp;trk=spm_pic' style='color:blue;'&gt;Find Me on Linked In&lt;/a&gt;&lt;br&gt; &lt;a href='http://facebook.com/thorbisinc' style=' color:blue;'&gt;Follow Me On Facebook&lt;/a&gt;&lt;br&gt; &lt;a href='http://www.youtube.com/user/byronwade10' style=' color:blue;'&gt;Subscrib To Me On YouTube&lt;/a&gt;&lt;br&gt; &lt;a href='https://github.com/Thorbis/Rejoice' style=' color:blue;'&gt;Fork Me On GitHub&lt;/a&gt;&lt;/br&gt;&lt;hr&gt;" . "Name: " . $firstname . "&lt;br&gt;" . "Last: " . $lastname . "&lt;br&gt;" . "Email: " . $email . "&lt;br&gt;" . "cell: " . $cell . "&lt;br&gt;" . "Website: &lt;a href='" . $website . "'&gt;CLIENT WEBSITE&lt;a/&gt;&lt;br&gt;"; $headers = "From: $from\r\n"; $headers .= "Content-type: text/html\r\n"; if (mail($to, $subject, $message, $headers)) { echo ("&lt;p&gt;Since You Have Used My services I will get an email stating that you have filled out this form and i will contact you back within 6 hours of you submiting the form! Also you sill get an adutomated message of exactly what i get!&lt;/p&gt;"); } //mail($to, $subject, $message, $headers) else { echo ("&lt;p&gt;I dident get a message stating that you have filled out the form can you manualy send me your email and info so i can customize your website please my email is bcw1996@gmail.com thank you :D&lt;/p&gt;"); } // Insert data into mysql $sql = "INSERT INTO $tbl_name(firstname, lastname, email, website, cell, overview)VALUES('$firstname', '$lastname', '$email', '$website', '$cell', '$overview')"; $result = mysql_query($sql); // if successfully insert data into database, displays message "Successful". if ($result) { echo "Successful"; echo "&lt;BR&gt;"; echo "This is your new resume site i will edit it with your info ASAP once i have contected you: &lt;a href='" . $website . "'&gt;Your Website&lt;/a&gt;"; echo "&lt;BR&gt;"; echo "&lt;a href='http://www.thorbis.com'&gt;Back to Home Page&lt;/a&gt;"; } //$result } } ?&gt; </code></pre>
[]
[ { "body": "<p>There is quite a lot that can be done</p>\n\n<p>For a start use mysqli_ functions as mysql_ functions are deprecated</p>\n\n<p>on database queries, it is good practice to check for errors (like this)</p>\n\n<pre><code>// $dbunames = mysql_query(\"SELECT * FROM users WHERE website='$website'\");\n$dbunames = mysql_query(\"SELECT * FROM users WHERE website='$website'\") or die(mysql_error());\n</code></pre>\n\n<p>It is not necessary to put quotes around variables unless you are concatenating them. By the way $username is not set in your script.</p>\n\n<pre><code>// mysql_connect(\"$host\", \"$username\", \"$password\") or die(\"cannot connect\");\nmysql_connect($host, $username, $password) or die(\"cannot connect\");\n</code></pre>\n\n<p>This will cause an error notice if firstname is not set, check it exists like this</p>\n\n<pre><code>// $firstname = $_POST['firstname'];\n$firstname = isset($_POST['firstname']) ? $_POST['firstname'] : '';\n</code></pre>\n\n<p>My personal preference is not to nest functions inside if/else statements as you have done with the copyRecursive($source, $destination) function. Put functions at the top level it will make your code easier to read. </p>\n\n<p>For code readability I would also move your email generation code into a separate function </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T08:24:35.660", "Id": "48484", "Score": "2", "body": "+1 to both answers, with the minor comment that you do not necessarily need to switch to `mysqli_*`; you can also consider `PDO`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T04:29:44.673", "Id": "30483", "ParentId": "30472", "Score": "7" } }, { "body": "<p>I agree with most of the points in @bumperbox's answer, except handling errors with <code>... or die</code>. That's not very graceful. It's better to use if-then-else blocks and print informative error messages for the user, and log more details for yourself. Error messages for the user should be human-friendly and without revealing sensitive internal details of your setup.</p>\n\n<p>Move <code>copyRecursive</code> and the email sending part to top-level functions, possible in a reusable utility file that you can include when needed and reuse easily.</p>\n\n<p>I recommend making the most important literal strings constants and define them at the top of the file. I would do the same for SQL statements, making them parameterized using <code>%s</code> and <code>%d</code> as appropriate. That way you can see easily what SQL statements are used by the code, all in one place at the top.</p>\n\n<p>Clean up the indenting. You are using sometimes 4 spaces sometimes 16. I would go with 4 spaces consistently, to make long lines easier to read without scrolling.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T06:35:58.350", "Id": "30490", "ParentId": "30472", "Score": "4" } }, { "body": "<p>In addition to the answers provided above, removing the PHP closing tag is also considered good practice, at least for beginners. Whitespace following the closing tag, whether introduced by the developer, user, or an FTP application, can cause unwanted output, PHP errors, or if the latter are suppressed, blank pages.</p>\n\n<p>Alternatively, you may want to use a comment block to mark the end of your file so you can still identify the file as being complete, and not truncated.</p>\n\n<p>Here's a little something on the topic: <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></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-15T18:42:23.907", "Id": "31325", "ParentId": "30472", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T00:43:27.697", "Id": "30472", "Score": "3", "Tags": [ "php", "recursion" ], "Title": "Recursive Directory Copy" }
30472
<p>I've got a CSV that contains users and permissions in the below format, where users can have as little as one or as many as eight different permissions:</p> <pre class="lang-none prettyprint-override"><code>USER,PERM1,PERM2,PERM3,PERM4,PERM5,PERM6,PERM7,PERM8 jdoe,perm1,perm2 tsmith,perm1,perm2,perm3,perm4,perm5,perm6,perm7,perm8 </code></pre> <p>This is the desired format, with each unique user and permission pair on a new line:</p> <pre class="lang-none prettyprint-override"><code>USER,PERM jdoe,perm1 jdoe,perm2 tsmith,perm1 tsmith,perm2 tsmith,perm3 tsmith,perm4 tsmith,perm5 tsmith,perm6 tsmith,perm7 tsmith,perm8 </code></pre> <p>My script below accomplishes this, but it's ugly, repetitive and I know there's a more Pythonic way to do it. Even worse, I had to bring the output file into Excel afterwards to filter and delete the rows with blank PERM values. Any recommendations to shorten this code and cut down on repetition would be much appreciated.</p> <pre><code>import csv def reformat_ul(original_ul, formated_ul): with open(original_ul) as user_list: dict_reader = csv.DictReader(user_list) ul = [] for row in dict_reader: ul.append(row) with open(formated_ul, 'w') as output2: output2.write('USER,PERM\n') for uperm in ul: p1 = '{},{}\n'.format(uperm['USER'], uperm['PERM1']) p2 = '{},{}\n'.format(uperm['USER'], uperm['PERM2']) p3 = '{},{}\n'.format(uperm['USER'], uperm['PERM3']) p4 = '{},{}\n'.format(uperm['USER'], uperm['PERM4']) p5 = '{},{}\n'.format(uperm['USER'], uperm['PERM5']) p6 = '{},{}\n'.format(uperm['USER'], uperm['PERM6']) p7 = '{},{}\n'.format(uperm['USER'], uperm['PERM7']) p8 = '{},{}\n'.format(uperm['USER'], uperm['PERM8']) output2.write(p1) output2.write(p2) output2.write(p3) output2.write(p4) output2.write(p5) output2.write(p6) output2.write(p7) output2.write(p8) reformat_ul('user_list.csv', 'output.txt') </code></pre>
[]
[ { "body": "<p>This is shorter:</p>\n\n<pre><code>import csv\n\n\ndef reformat_ul(original_ul, formated_ul):\n with open(formated_ul, 'w') as output2:\n output2.write('USER,PERM\\n')\n with open(original_ul) as user_list:\n dict_reader = csv.DictReader(user_list)\n for row in dict_reader:\n user = row['USER']\n for key in sorted(row)[:-1]:\n if row[key]:\n output2.write(\"%s,%s\\n\" % (user, row[key]))\n\nreformat_ul('user_list.csv', 'output.txt')\n</code></pre>\n\n<p>The highlights:</p>\n\n<ul>\n<li>It doesn't waste memory by storing the rows in a temporary list. Using the two nested <code>with</code> there, it outputs while reading the output, piping properly</li>\n<li>In <code>sorted(row)[:-1]</code> I take advantage of the fact that I know the column names, and that <code>USER</code> will come after all the <code>PERM1..PERM8</code>. If you need a more flexible implementation then you can amend the deepest <code>if</code> there, for example <code>if key.startswith('PERM') and row[key]</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T05:08:43.930", "Id": "30485", "ParentId": "30473", "Score": "2" } }, { "body": "<p>With included csvwriter <a href=\"http://docs.python.org/2/library/csv.html#csv.csvwriter.writerow\" rel=\"nofollow\">writerow</a> method.</p>\n\n<pre><code> import csv\n from collections import OrderedDict\n from itertools import ifilter\n\n\n def reformat_ul(original_ul, formated_ul):\n with open(formated_ul, 'w') as output2, open(original_ul) as user_list:\n csv_dictreader = csv.DictReader(user_list)\n field1, field2 = csv_dictreader.fieldnames[0:2]\n field2 = field2[:-1]\n csvwriter = csv.writer(output2)\n csvwriter.writerow([field1, field2])\n for row in csv_dictreader:\n user = row.pop(field1)\n perms = ifilter(lambda k: k,\n OrderedDict(sorted(row.items())).itervalues())\n map(lambda p: csvwriter.writerow([user, p]), perms)\n reformat_ul('user_list.csv', 'output.txt')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T22:59:43.113", "Id": "30538", "ParentId": "30473", "Score": "1" } }, { "body": "<p>A simple csv.reader does the job for me. For each row, I pop off the username and then simply loop over the rest of the data in the row and yield it with the username.</p>\n\n<pre><code>import csv\n\ndef read_original(path):\n with open(path, 'r') as f:\n reader = csv.reader(f)\n reader.next()\n for row in reader:\n user = row.pop(0)\n for perm in row:\n yield user, perm\n\ndef reformat_ul(original_ul, formatted_ul):\n with open(formatted_ul, 'w') as f:\n writer = csv.writer(f)\n writer.writerow(['USER', 'PERM'])\n for row in read_original(original_ul):\n writer.writerow(row)\n\nreformat_ul('user_list.csv', 'output.txt')\n</code></pre>\n\n<p>This allows the read_original iterator to be used independently.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T23:06:41.517", "Id": "30898", "ParentId": "30473", "Score": "0" } }, { "body": "<p>As you don't really care for which permissions are present or not, just to split into those existing I would suggest reading the file using the simpler <code>csv.reader()</code>, skipping the first line, and then output the permissions in the same run.</p>\n\n<p>Here is some code:</p>\n\n<pre><code>import csv\nimport sys\n\nDEFAULT_SOURCEFILE = 'user_list.csv'\nDEFAULT_DESTINATIONFILE = 'output.txt'\n\ndef split_permissions(sourcefile, destinationfile):\n \"\"\"Split permissions from sourcefile into single permission in destinationfile.\"\"\"\n\n # Open both files simultaneously, to make an efficient read and write loop\n with open(sourcefile) as source, open(destinationfile, 'w') as output:\n dict_reader = csv.reader(source)\n next(dict_reader) # Skip header line\n\n output.write('USER,PERM\\n')\n\n # Read each line in source, and split into multiple output lines\n for row in dict_reader:\n print row\n user = row[0]\n for perm in row[1:]:\n output.write('{},{}\\n'.format(user, perm))\n\n\nif __name__ == '__main__':\n\n # Use filenames from command line if present, else use defaults\n if len(sys.argv) == 3:\n sourcefile = sys.argv[1]\n destinationfile = sys.argv[2]\n else:\n sourcefile = DEFAULT_SOURCEFILE\n destinationfile = DEFAULT_DESTINATIONFILE\n\n\n # Split the permissions file into single permissions\n split_permissions(sourcefile, destinationfile)\n</code></pre>\n\n<p>In addition to the new function to actually do the split, I've also added some basic handling to allow for filenames to be defined on the command line. And packed everything in a construct so that the file can be used as a module presenting the <code>split_permissions()</code> function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-26T01:47:36.950", "Id": "111860", "ParentId": "30473", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T01:00:12.460", "Id": "30473", "Score": "4", "Tags": [ "python", "regex", "csv" ], "Title": "Managing a CSV of users and permissions" }
30473
<p>For the following problem statement, I design following classes. Can you please tell me if this is the correct implementation or if there can be a better one?</p> <p>Let's say there is call center with three levels of employees: fresher, technical lead (TL), product manager (PM). There can be multiple employees, but only one TL or PM. An incoming telephone call must be allocated to a fresher who is free. If a fresher can’t handle the call, he or she must escalate the call to technical lead. If the TL is not free or not able to handle it, then the call should be escalated to PM. Design the classes and data structures for this problem.</p> <pre><code>using System; using System.Linq; using System.Collections.Generic; namespace TestNS { public class Employee { public string Name { get; set; } public bool IsFree { get; set; } public Employee Manager { get; set; } } public class Call { public Employee AllocatedTo { get; set; } public bool HandleCall() { AllocatedTo.IsFree = false; bool isHandled = false; // Write custom logic to handle the call &amp; set the value of isHandled if (isHandled) { AllocatedTo.IsFree = true; } return isHandled; } public void Escalate() { AllocatedTo = AllocatedTo.Manager; HandleCall(); } } public class CallManager { List&lt;Employee&gt; fresherList = new List&lt;Employee&gt;(); public void CreateEmployeeList() { Employee PM = new Employee() { Name = "PM1", IsFree = true }; Employee TL = new Employee() { Name = "TL1", IsFree = true }; TL.Manager = PM; fresherList = new List&lt;Employee&gt;(); fresherList.Add(new Employee() { Name = "F1", Manager = TL, IsFree = true }); fresherList.Add(new Employee() { Name = "F2", Manager = TL, IsFree = true }); fresherList.Add(new Employee() { Name = "F3", Manager = TL, IsFree = true }); fresherList.Add(new Employee() { Name = "F4", Manager = TL, IsFree = true }); fresherList.Add(new Employee() { Name = "F5", Manager = TL, IsFree = true }); fresherList.Add(new Employee() { Name = "F6", Manager = TL, IsFree = true }); } private Employee FindFreeEmployee() { Employee e = null; foreach (Employee emp in fresherList) { if (emp.IsFree) { e = emp; break; } } return e; } public void ReceiveAndAllocateCall(Call call1) { call1.AllocatedTo = FindFreeEmployee(); call1.HandleCall(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T10:50:25.897", "Id": "48508", "Score": "0", "body": "I think \"CallManager` is a very bad name, it does not describe what the class does (\"manage\" can mean almost anything). There is a method named \"..AllocateCall\", this is closer to the true purpose of the class. Perhaps `CallAllocator` or `CallRouter` would be better names." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T09:50:54.563", "Id": "73070", "Score": "0", "body": "Your scenario can perfectly take advantage of [Chain Of Responsibility](http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern) Design Pattern. Have a look at it and see if its perfect for you problem. You can find many examples of implementation in .NET." } ]
[ { "body": "<ol>\n<li>I like the <code>Employee</code> class with the built-in <code>Manager</code> chain.</li>\n<li>I think <code>Call</code> class should be \"dumb\" like the <code>Employee</code>. The methods seem like call processing - what the <code>CallManager</code> should be doing.</li>\n<li>Id say part of the \"call handing process\" is in the <code>CallManager</code> and part of it is in <code>Call</code> class. Broken apart like this it's hard to discern/follow the flow of a call-handling.</li>\n<li>Should you implement queues? A queue of <code>Call</code>s to model lots of calls coming in before they can get allocated.</li>\n<li>The code has allocation and \"isFree\" as 2 separate things. This suggests to me that we could have a <code>Employee.CallQueue</code> for allocated calls, then set <code>IsFree = false</code> when he picks up the phone.</li>\n<li>Also an <code>Employee.CallQueue</code> of assigned calls. The code suggests that allocation and handling are 2 separate things</li>\n<li>In <code>ReceiveAndAllocateCall.FindFreeEmployee()</code> could return <code>null</code> so we need code to handle that. Maybe that when the call goes into a waiting queue.</li>\n</ol>\n\n<hr>\n\n<pre><code>public class CallManager {\n . . .\n\n // call processing\n call1.AllocatedTo = FindFreeEmployee();\n\n // what to do if AllocatedTo is null?\n\n call1.AllocatedTo.IsFree = false;\n call1.IsHandled = false; \n\n // I see `IsHandled` as a `Call` property. It will persist if we \n // pass it to the manager. As is, `IsHandled` disappears when `HandleCall()` ends and we don't know if the call is handled anymore.\n\n while (! call1.IsHandled) {\n // Write custom logic to handle the call &amp; set the value of isHandled\n if (! call1.isHandled) {\n if (call1.AllocatedTo.Manager != null) { call1.AllocateTo = AllocateTo.Manager\n }else{ break;}\n }\n } // while\n\n // if IsHandled == false still, what to do? Hang up and send them a lollypop I guess.\n</code></pre>\n\n<ul>\n<li>The 1st line, calling <code>FindFreeEmployee()</code> might best be done outside of, or somewhere else in <code>CallManager</code> Imagine a complex process for deciding how to pair calls to employees. Then pass that pair into <code>CallManager</code>, and all call manager does is process the call. - Separation of Responsibilities.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T04:05:05.307", "Id": "30481", "ParentId": "30474", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T01:05:24.417", "Id": "30474", "Score": "2", "Tags": [ "c#", ".net" ], "Title": "Design class to handle calls for support functions" }
30474
<p>How might I refactor this to get rid of all the if-else?</p> <pre><code> def self.dispatches_for(object) scope = Dispatch.asc(:days) if object.class == Habit scope.where(:habit=&gt;object).map{|d|d} elsif object.class == User scope.where(:coach=&gt;object).map{|d|d} elsif object.class == Content scope.where(:content=&gt;object).map{|d|d} end end </code></pre>
[]
[ { "body": "<pre><code>def self.dispatches_for(object)\n klass = object.class.to_s.downcase.to_sym\n raise \"unacceptable class\" unless klass.in? [:habit, :coach, :content]\n scope = Dispatch.asc(:days)\n scope.where(klass=&gt;object).map{|d|d}\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T16:47:42.697", "Id": "48849", "Score": "0", "body": "Also, if you're using `ActiveRecord` or similar you can do `scope.where(klass=>object).to_a` instead of `map{|d|d}`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T16:50:25.793", "Id": "48850", "Score": "0", "body": "@kardeiz, yes, nice point. I'm not sure what is the usage so I refactored the logic only." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T03:18:59.863", "Id": "30480", "ParentId": "30475", "Score": "2" } } ]
{ "AcceptedAnswerId": "30480", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T01:30:55.930", "Id": "30475", "Score": "0", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Creating a generic function for objects of different classes" }
30475
<p>I am new to C, so I have been trying to get practice doing some coding.</p> <p>Usually I use languages like Java, python, ruby, etc: Garbage collected languages. So manually cleaning up is new to me and I would appreciate any advice on whether there are major flaws in my approach.</p> <p>Also any other comments on the overall idomatic-ness of this code, and things that I need to watch out for as I try to learn more C. (If it matters, I am compiling this to the c99 standards)</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; /* a reference counted BST node... */ typedef struct _node node; struct _node { char *word; unsigned int refs; node *left; node *right; }; /* allocate a node onto the heap. * copy word into a new array so that it can free it when it wants to * later without fear of clobbering another node's string. * * TODO: Maybe implement word counting so that if someone else adds a * word that's already in the tree, I don't need to store two * instances. */ node* node_new(char *word) { node *n = malloc(sizeof(node)); char *nword = malloc(strlen(word) + 1); memcpy(nword, word, sizeof(nword)); n-&gt;word = nword; n-&gt;refs = 0; n-&gt;left = NULL; n-&gt;right = NULL; return n; } /* Decrement the references and if it is determined that no one holds * a ref to this object, then free it and check its children. * * Return the number of nodes freed in this manner. If this node has * referents, then return 0 since no nodes were freed. */ int node_del(node *n) { n-&gt;refs -= 1; if (n-&gt;refs &gt; 0) return 0; int removed = 1; if (n-&gt;left != NULL) removed += node_del(n-&gt;left); if (n-&gt;right != NULL) removed += node_del(n-&gt;right); free(n-&gt;word); free(n); return removed; } /* replace link with n. * Cleans up link if needed. */ void node_setlink(node **link, node *n) { if (*link != NULL) { node_del(*link); } n-&gt;refs += 1; *link = n; } /* Add a node to the BST. */ void node_additem(node *root, node *n) { int comp = strcmp(root-&gt;word, n-&gt;word); node **target = (comp &gt; 0) ? &amp;(root-&gt;left) : &amp;(root-&gt;right); if (*target == NULL) node_setlink(target, n); else node_additem(*target, n); } /* Traverse the BST in order, dumping the words to standard out. * No side effects. */ void node_traverse(node *root) { if (root-&gt;left != NULL) node_traverse(root-&gt;left); printf("%s\n", root-&gt;word); if (root-&gt;right != NULL) node_traverse(root-&gt;right); } /* Go through each argument, adding it to the tree. Then traverse the tree. Then * free the tree. */ int main(int argc, char **argv) { if (argc &lt; 3) { printf("Please give me two arguments, or there won't be anything to sort!"); return 1; } node *n; node_setlink(&amp;n, node_new(argv[1])); for (int i = 2; i &lt; argc; i++) { node_additem(n, node_new(argv[i])); } node_traverse(n); printf("n is %s %d\n", n-&gt;word, n-&gt;refs); printf("%d removed when n freed.\n", node_del(n)); return 0; } </code></pre>
[]
[ { "body": "<p>The code looks nice. Just a few comments: </p>\n\n<p>In <code>new_node</code>, your word-copying is wrong as you use <code>sizeof(nword)</code> where\n<code>nword</code> is a pointer. Using <code>sizeof</code> on a pointer gives only the size of the\npointer itself, not the size of what it points to. try it with some long\nwords. Your word copying could either use <code>strdup</code> or if you don't have that,\nwrite your own.</p>\n\n<p>In <code>main</code>, set <code>n</code> to NULL before using it.</p>\n\n<p>There are no checks for malloc failure. It is good practice to check, but the\nonly thing one can do is often to exit.</p>\n\n<p>It is best to avoid leading underscore on identifiers (they are reserved). And it is generally better to use explicit braces around statements even when strictly unnecessary. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T05:01:39.020", "Id": "48600", "Score": "0", "body": "Okay. I was under the impression that sizeof(some_array) gave the size in bytes of that array. After reading up on it, i learned that that only works on arrays that you declare with `type thing[size]`. And using strdup is great, saves a lot of hassle. But... Why should I set n to null if I am going to assign a value to it immediately? Is it just good practice? And how SHOULD i do that typedef? I don't feel right about doing `typedef struct somestruct somestruct;`, it feels like I'm clobbering a value( which I am in a manner of speaking). It feels wierd to have two things with the same name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T18:05:19.177", "Id": "48647", "Score": "1", "body": "Your call to `node_setlink` tests the content of its first parameter, which in this case was `n` in `main`. So you should make sure that `n` is set to zero. Also, the namespace used for structs is different from that used for typedefs. So `typedef struct somestruct somestruct;` is correct and indeed normal." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T20:46:25.713", "Id": "30530", "ParentId": "30486", "Score": "2" } } ]
{ "AcceptedAnswerId": "30530", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T05:14:29.857", "Id": "30486", "Score": "3", "Tags": [ "c", "memory-management" ], "Title": "Does this C binary search tree have memory leaks?" }
30486
<p>I have implemented a recursive <code>O(n log n)</code> algorithm for solving the maximum sub-array problem. I would like a general review for it.</p> <p>Here the <code>max_subarray</code> is the main function, and the <code>static</code> one is the auxillary function for it.</p> <pre><code>#include&lt;stdio.h&gt; int max_subarray(int array[], int *low, int *high); static int max_crossing_subarray(int array[], int *low, int mid, int *high); int main() { //The maximum subarray-sum is 43 for the following int array[16] = {13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7}; int low = 0; int high = 15; printf("%d", max_subarray(array, &amp;low, &amp;high)); printf("\n%d %d", low, high); return 0; } int max_subarray(int array[], int *low, int *high) { if (*low == *high) { return array[*low]; } else { //Don't change avoids overflow int mid = *low + (*high - *low)/2; int left_low = *low; int left_high = mid; int left_sum = max_subarray(array, &amp;left_low, &amp;left_high); int right_low = mid + 1; int right_high = *high; int right_sum = max_subarray(array, &amp;right_low, &amp;right_high); int cross_low = *low; int cross_high = *high; int cross_sum = max_crossing_subarray(array, &amp;cross_low, mid, &amp;cross_high); if (left_sum &gt;= right_sum &amp;&amp; left_sum &gt;= cross_sum) { *low = left_low; *high = left_high; return left_sum; } else if (right_sum &gt;= left_sum &amp;&amp; right_sum &gt;= cross_sum) { *low = right_low; *high = right_high; return right_sum; } else { *low = cross_low; *high = cross_high; return cross_sum; } } } static int max_crossing_subarray(int array[], int *low, int mid, int *high) { int left_sum = 0; int max_left = mid; for (int i = mid, sum = 0; i &gt;= *low; i--) { sum += array[i]; if (sum &gt; left_sum) { left_sum = sum; max_left = i; } } int right_sum = 0; int max_right = mid; for (int i = mid + 1, sum = 0; i &lt;= *high; i++) { sum += array[i]; if (sum &gt; right_sum) { right_sum = sum; max_right = i; } } *low = max_left; *high = max_right; return left_sum + right_sum; } </code></pre>
[]
[ { "body": "<p>Your program fails when all of the members of an array are negative, it simply returns <code>0</code> instead of the maximum negative number. </p>\n\n<hr>\n\n<p>Recursion here is slowing you down. Using <a href=\"https://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane.27s_algorithm\" rel=\"nofollow noreferrer\">Kadane's algorithm</a>, we can make the time complexity linear, or O(n) .</p>\n\n<pre><code>#include&lt;stdio.h&gt;\n\n#define max(a, b) (((a) &gt; (b)) ? (a) : (b))\n\nint maxSubArraySum(int array[], int size)\n{\n int maxSoFar = array[0];\n int currentMax = array[0];\n\n for (int i = 1; i &lt; size; i++)\n {\n currentMax = max(array[i], currentMax + array[i]);\n maxSoFar = max(maxSoFar, currentMax);\n }\n return maxSoFar;\n}\n\nint main()\n{\n int array[] = {-2, -3, 4, -1, -2, 1, 5, -3};\n int len = sizeof(array) / sizeof(array[0]);\n int maxSum = maxSubArraySum(array, len);\n printf(\"Maximum contiguous sum is %d\\n\", maxSum);\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-05T09:38:21.283", "Id": "64418", "Score": "2", "body": "Returning 0 is not unreasonable, if you consider an empty subarray to be a valid solution." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-05T02:59:13.787", "Id": "38603", "ParentId": "30489", "Score": "9" } } ]
{ "AcceptedAnswerId": "38603", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T06:34:06.747", "Id": "30489", "Score": "7", "Tags": [ "c", "recursion" ], "Title": "Maximum Subarray Problem - Recursive O(n log n) algorithm" }
30489
<p>I implemented an iterative \$O(n)\$ algorithm for solving the maximum sub-array problem. I would like a general review for it.</p> <p>Here the <code>max_subarray</code> is the main function and the ones which are <code>static</code> are auxiliary functions for it.</p> <pre><code>#include&lt;stdio.h&gt; int max_subarray(int array[], int *low, int *high); static void initialize(int *sum, int *low, int *high); static void update_var(int increase, int *sum, int *low, int *high, int i); int main() { //The maximum subarray-sum is 43 for the following int array[16] = {13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7}; int low = 0; int high = 15; printf("%d", max_subarray(array, &amp;low, &amp;high)); printf("\n%d %d", low, high); return 0; } int max_subarray(int array[], int *low, int *high) { int max_sum, max_low, max_high; int bet_sum, bet_low, bet_high; int inc_sum, inc_low, inc_high; initialize(&amp;max_sum, &amp;max_low, &amp;max_high); initialize(&amp;bet_sum, &amp;bet_low, &amp;bet_high); initialize(&amp;inc_sum, &amp;inc_low, &amp;inc_high); for (int i = *low; i &lt;= *high; i++) { if (max_sum + bet_sum + array[i] &gt; max_sum) { update_var(bet_sum + array[i], &amp;max_sum, &amp;max_low, &amp;max_high, i); initialize(&amp;bet_sum, &amp;bet_low, &amp;bet_high); initialize(&amp;inc_sum, &amp;inc_low, &amp;inc_high); } else { update_var(array[i], &amp;bet_sum, &amp;bet_low, &amp;bet_high, i); if (inc_sum + array[i] &gt; inc_sum) { update_var(array[i], &amp;inc_sum, &amp;inc_low, &amp;inc_high, i); if (inc_sum &gt; max_sum) { max_sum = inc_sum; max_low = inc_low; max_high = inc_high; initialize(&amp;bet_sum, &amp;bet_low, &amp;bet_high); initialize(&amp;inc_sum, &amp;inc_low, &amp;inc_high); } } } } *low = max_low; *high = max_high; return max_sum; } static void update_var(int increase, int *sum, int *low, int *high, int i) { *sum += increase; *high = i; if (*low == -1) { *low = i; } } static void initialize(int *sum, int *low, int *high) { *sum = 0; *low = -1; *high = -1; } </code></pre>
[]
[ { "body": "<h3>Subarray representation</h3>\n\n<ul>\n<li><strong>Name of <code>low</code> and <code>high</code>:</strong> I prefer <code>lower</code> and <code>upper</code> because they contain the same number of characters, so that code lines up nicely. ☺︎</li>\n<li><p><strong>Inclusive-inclusive intervals:</strong> Your <code>low</code> and <code>high</code> variables form an inclusive-inclusive interval. Usually, you would be better off with an inclusive-exclusive interval, especially in a language with zero-based arrays. Consider examples</p>\n\n<ul>\n<li><a href=\"http://www.cplusplus.com/reference/vector/vector/end/\" rel=\"nofollow\"><code>std::vector::end</code></a> in C++</li>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring%28int,%20int%29\" rel=\"nofollow\"><code>String.substring(beginIndex, endIndex)</code></a> in Java</li>\n<li><a href=\"http://docs.python.org/2/library/functions.html#range\" rel=\"nofollow\"><code>range(start, stop)</code></a> in Python</li>\n</ul>\n\n<p>The generic benefit of having <code>high</code> being one greater than the last element is that <code>high - low</code> is the number of elements. This is nicer — you don't have to hard-code 16 or 15 anywhere:</p>\n\n<pre><code>int array[] = { 13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7 };\nint lower = 0, upper = sizeof(array) / sizeof(array[0]);\n</code></pre>\n\n<p>A specific benefit for this problem is that any interval with <code>lower == upper</code> represents an empty interval. You don't have to use -1 for that.</p></li>\n<li><strong>Type of <code>low</code> and <code>high</code>:</strong> Array indices should be <code>size_t</code> rather than <code>int</code>. Especially since your array consists of <code>int</code>s, there could be confusion as to whether <code>int *lower</code> should be a pointer to the first data element (i.e., <code>&amp;array[0]</code>) or a pointer to the index of the first element. Not having to support -1 lets you use <code>size_t</code> instead, which clarifies your intentions.</li>\n<li><p><strong>Clusters of variables:</strong> Variables <code>blah_sum</code>, <code>blah_low</code>, and <code>blah_high</code> are always initialized and updated together. There should be a struct representing subarrays, with operations \"init\" and \"extend\".</p>\n\n<pre><code>typedef struct {\n int sum;\n size_t lower;\n size_t upper;\n} subarray;\n\nstatic void init_subarray(subarray *sa, size_t i) {\n sa-&gt;sum = 0;\n sa-&gt;lower = sa-&gt;upper = i;\n}\n\nstatic void extend_subarray(subarray *sa, size_t i, int increase) {\n sa-&gt;sum += increase;\n sa-&gt;upper = i + 1;\n}\n</code></pre></li>\n</ul>\n\n<h3>Nitpicks</h3>\n\n<ul>\n<li><strong>Const-correctness:</strong> <code>max_subarray()</code> should take a <code>const int array[]</code>.</li>\n<li><strong>Brace style:</strong> Pick a brace style and stick with it.</li>\n</ul>\n\n<h3>Algorithm</h3>\n\n<p>Your code is wrong. For an input array <code>{ -1, 5 }</code>, it prints 4 instead of 5 as the maximum sum.</p>\n\n<p>As @cat_baxter points out, <a href=\"http://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane.27s_algorithm\" rel=\"nofollow\">Kadane's algorithm</a> is simpler.</p>\n\n<pre><code>/**\n * Finds the earliest consecutive block of array elements with the maximum sum.\n *\n * Parameters:\n * lower IN: a pointer to an integer that is the array index of the first\n * element to consider (normally 0).\n * OUT: a pointer to an integer that is the array index of the first\n * element of the maximum subarray.\n *\n * upper IN: a pointer to an integer that is one greater than the array index\n * of the last element to consider (normally sizeof(array) /\n * sizeof(int)).\n * OUT: a pointer to an integer that is one greater than the array index\n * of the last element of the maximum subarray.\n *\n * Returns: the sum of the maximum subarray\n */\nint max_subarray(const int array[], size_t *lower, size_t *upper) {\n subarray max, tmp;\n init_subarray(&amp;max, *lower);\n init_subarray(&amp;tmp, *lower);\n\n for (int i = *lower; i &lt; *upper; i++) {\n if (tmp.sum &lt; 0) {\n init_subarray(&amp;tmp, i);\n }\n extend_subarray(&amp;tmp, i, array[i]);\n\n if (tmp.sum &gt; max.sum) {\n max = tmp;\n }\n }\n *lower = max.lower;\n *upper = max.upper;\n return max.sum;\n}\n\nint main() {\n //The maximum subarray-sum is 43 for the following\n int array[] = { 13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7 };\n size_t lower = 0, upper = sizeof(array) / sizeof(array[0]);\n\n printf(\"%d\\n\", max_subarray(array, &amp;lower, &amp;upper));\n printf(\"%zu %zu\\n\", lower, upper);\n\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T21:56:26.587", "Id": "36538", "ParentId": "30491", "Score": "3" } } ]
{ "AcceptedAnswerId": "36538", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T06:36:20.337", "Id": "30491", "Score": "4", "Tags": [ "c", "array" ], "Title": "Maximum Subarray Problem - Iterative O(n) algorithm" }
30491
<p>I have an accordion that checks if there is data to be displayed and if so, the accordion show the data from the specific month.</p> <p>Is there a way to simplify the code below?</p> <pre><code>&lt;?php $conn = mysql_connect("localhost","user","pass"); mysql_select_db("lista_de_analize"); mysql_set_charset("UTF8", $conn); ?&gt; &lt;script&gt; $(function() { var icons = { header: "ui-icon-circle-arrow-e", activeHeader: "ui-icon-circle-arrow-s" }; $( "#dam" ).accordion({ icons: icons, heightStyle: "content", collapsible: false }); $( "#antrecut" ).accordion({ icons: icons, heightStyle: "content", collapsible: true }); }); &lt;/script&gt; &lt;?php $construct ="SELECT * FROM Anunturi, TabelAnunturi"; $constructian ="SELECT * from Anunturi WHERE MONTH(DataIntroducere) = 1 AND YEAR(DataIntroducere) = YEAR(CURDATE())"; $constructfeb ="SELECT * from Anunturi WHERE MONTH(DataIntroducere) = 2 AND YEAR(DataIntroducere) = YEAR(CURDATE())"; $constructmar ="SELECT * from Anunturi WHERE MONTH(DataIntroducere) = 3 AND YEAR(DataIntroducere) = YEAR(CURDATE())"; $constructapr ="SELECT * from Anunturi WHERE MONTH(DataIntroducere) = 4 AND YEAR(DataIntroducere) = YEAR(CURDATE())"; $constructmai ="SELECT * from Anunturi WHERE MONTH(DataIntroducere) = 5 AND YEAR(DataIntroducere) = YEAR(CURDATE())"; $constructiun ="SELECT * from Anunturi WHERE MONTH(DataIntroducere) = 6 AND YEAR(DataIntroducere) = YEAR(CURDATE())"; $constructiul ="SELECT * from Anunturi WHERE MONTH(DataIntroducere) = 7 AND YEAR(DataIntroducere) = YEAR(CURDATE())"; $constructaug ="SELECT * from Anunturi WHERE MONTH(DataIntroducere) = 8 AND YEAR(DataIntroducere) = YEAR(CURDATE())"; $constructsep ="SELECT * from Anunturi WHERE MONTH(DataIntroducere) = 9 AND YEAR(DataIntroducere) = YEAR(CURDATE())"; $constructoct ="SELECT * from Anunturi WHERE MONTH(DataIntroducere) = 10 AND YEAR(DataIntroducere) = YEAR(CURDATE())"; $constructnov ="SELECT * from Anunturi WHERE MONTH(DataIntroducere) = 11 AND YEAR(DataIntroducere) = YEAR(CURDATE())"; $constructdec ="SELECT * from Anunturi WHERE MONTH(DataIntroducere) = 12 AND YEAR(DataIntroducere) = YEAR(CURDATE())"; $run = mysql_query($construct) or die(mysql_error()); $runian = mysql_query($constructian) or die(mysql_error()); $runfeb = mysql_query($constructfeb) or die(mysql_error()); $runmar = mysql_query($constructmar) or die(mysql_error()); $runapr = mysql_query($constructapr) or die(mysql_error()); $runmai = mysql_query($constructmai) or die(mysql_error()); $runiun = mysql_query($constructiun) or die(mysql_error()); $runiul = mysql_query($constructiul) or die(mysql_error()); $runaug = mysql_query($constructaug) or die(mysql_error()); $runsep = mysql_query($constructsep) or die(mysql_error()); $runoct = mysql_query($constructoct) or die(mysql_error()); $runnov = mysql_query($constructnov) or die(mysql_error()); $rundec = mysql_query($constructdec) or die(mysql_error()); $foundnum = mysql_num_rows($run); $foundnumian = mysql_num_rows($runian); $foundnumfeb = mysql_num_rows($runfeb); $foundnummar = mysql_num_rows($runmar); $foundnumapr = mysql_num_rows($runapr); $foundnummai = mysql_num_rows($runmai); $foundnumiun = mysql_num_rows($runiun); $foundnumiul = mysql_num_rows($runiul); $foundnumaug = mysql_num_rows($runaug); $foundnumsep = mysql_num_rows($runsep); $foundnumoct = mysql_num_rows($runoct); $foundnumnov = mysql_num_rows($runnov); $foundnumdec = mysql_num_rows($rundec); if ($foundnum==0) { echo "Nu avem noutăți!"; } else { echo" &lt;div id='dam'&gt;"; if(mysql_num_rows($rundec) &gt; 0 ) { echo" &lt;h3&gt;Decembrie 2013&lt;/h3&gt; &lt;div&gt;&lt;br&gt;"; while($runrows = mysql_fetch_assoc($rundec)) { $Luna = $runrows ['Luna']; $Ziua = $runrows ['Ziua']; $Mesaj = $runrows ['Mesaj']; $Anul = $runrows ['Anul']; echo " &lt;table class='noutatitabel'&gt; &lt;tr&gt; &lt;td class='faramargini'&gt; &lt;div class='data'&gt; &lt;div class='luna'&gt;$Luna $Anul&lt;/div&gt; &lt;div class='ziua'&gt;$Ziua&lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;td class='albastru'&gt;$Mesaj &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;br&gt;"; } echo" &lt;br&gt;&lt;hr&gt;&lt;br&gt;&lt;/div&gt;"; } if(mysql_num_rows($runnov) &gt; 0 ) { echo" &lt;h3&gt;Noiembrie 2013&lt;/h3&gt; &lt;div&gt;&lt;br&gt;"; while($runrows = mysql_fetch_assoc($runnov)) { $Luna = $runrows ['Luna']; $Ziua = $runrows ['Ziua']; $Mesaj = $runrows ['Mesaj']; $Anul = $runrows ['Anul']; echo " &lt;table class='noutatitabel'&gt; &lt;tr&gt; &lt;td class='faramargini'&gt; &lt;div class='data'&gt; &lt;div class='luna'&gt;$Luna $Anul&lt;/div&gt; &lt;div class='ziua'&gt;$Ziua&lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;td class='albastru'&gt;$Mesaj &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;br&gt;"; } echo" &lt;br&gt;&lt;hr&gt;&lt;br&gt;&lt;/div&gt;"; } if(mysql_num_rows($runoct) &gt; 0 ) { echo" &lt;h3&gt;Octombrie 2013&lt;/h3&gt; &lt;div&gt;&lt;br&gt;"; while($runrows = mysql_fetch_assoc($runoct)) { $Luna = $runrows ['Luna']; $Ziua = $runrows ['Ziua']; $Mesaj = $runrows ['Mesaj']; $Anul = $runrows ['Anul']; echo " &lt;table class='noutatitabel'&gt; &lt;tr&gt; &lt;td class='faramargini'&gt; &lt;div class='data'&gt; &lt;div class='luna'&gt;$Luna $Anul&lt;/div&gt; &lt;div class='ziua'&gt;$Ziua&lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;td class='albastru'&gt;$Mesaj &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;br&gt;"; } echo" &lt;br&gt;&lt;hr&gt;&lt;br&gt;&lt;/div&gt;"; } if(mysql_num_rows($runsep) &gt; 0 ) { echo" &lt;h3&gt;Septembrie 2013&lt;/h3&gt; &lt;div&gt;&lt;br&gt;"; while($runrows = mysql_fetch_assoc($runsep)) { $Luna = $runrows ['Luna']; $Ziua = $runrows ['Ziua']; $Mesaj = $runrows ['Mesaj']; $Anul = $runrows ['Anul']; echo " &lt;table class='noutatitabel'&gt; &lt;tr&gt; &lt;td class='faramargini'&gt; &lt;div class='data'&gt; &lt;div class='luna'&gt;$Luna $Anul&lt;/div&gt; &lt;div class='ziua'&gt;$Ziua&lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;td class='albastru'&gt;$Mesaj &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;br&gt;"; } echo" &lt;br&gt;&lt;hr&gt;&lt;br&gt;&lt;/div&gt;"; } if(mysql_num_rows($runaug) &gt; 0 ) { echo" &lt;h3&gt;August 2013&lt;/h3&gt; &lt;div&gt;&lt;br&gt;"; while($runrows = mysql_fetch_assoc($runaug)) { $Luna = $runrows ['Luna']; $Ziua = $runrows ['Ziua']; $Mesaj = $runrows ['Mesaj']; $Anul = $runrows ['Anul']; echo " &lt;table class='noutatitabel'&gt; &lt;tr&gt; &lt;td class='faramargini'&gt; &lt;div class='data'&gt; &lt;div class='luna'&gt;$Luna $Anul&lt;/div&gt; &lt;div class='ziua'&gt;$Ziua&lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;td class='albastru'&gt;$Mesaj &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;br&gt;"; } echo" &lt;br&gt;&lt;hr&gt;&lt;br&gt;&lt;/div&gt;"; } if(mysql_num_rows($runiul) &gt; 0 ) { echo" &lt;h3&gt;Iulie 2013&lt;/h3&gt; &lt;div&gt;&lt;br&gt;"; while($runrows = mysql_fetch_assoc($runiul)) { $Luna = $runrows ['Luna']; $Ziua = $runrows ['Ziua']; $Mesaj = $runrows ['Mesaj']; $Anul = $runrows ['Anul']; echo " &lt;table class='noutatitabel'&gt; &lt;tr&gt; &lt;td class='faramargini'&gt; &lt;div class='data'&gt; &lt;div class='luna'&gt;$Luna $Anul&lt;/div&gt; &lt;div class='ziua'&gt;$Ziua&lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;td class='albastru'&gt;$Mesaj &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;br&gt;"; } echo" &lt;br&gt;&lt;hr&gt;&lt;br&gt;&lt;/div&gt;"; } if(mysql_num_rows($runiun) &gt; 0 ) { echo" &lt;h3&gt;Iunie 2013&lt;/h3&gt; &lt;div&gt;&lt;br&gt;"; while($runrows = mysql_fetch_assoc($runiun)) { $Luna = $runrows ['Luna']; $Ziua = $runrows ['Ziua']; $Mesaj = $runrows ['Mesaj']; $Anul = $runrows ['Anul']; echo " &lt;table class='noutatitabel'&gt; &lt;tr&gt; &lt;td class='faramargini'&gt; &lt;div class='data'&gt; &lt;div class='luna'&gt;$Luna $Anul&lt;/div&gt; &lt;div class='ziua'&gt;$Ziua&lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;td class='albastru'&gt;$Mesaj &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;br&gt;"; } echo" &lt;br&gt;&lt;hr&gt;&lt;br&gt;&lt;/div&gt;"; } if(mysql_num_rows($runmai) &gt; 0 ) { echo" &lt;h3&gt;Mai 2013&lt;/h3&gt; &lt;div&gt;&lt;br&gt;"; while($runrows = mysql_fetch_assoc($runmai)) { $Luna = $runrows ['Luna']; $Ziua = $runrows ['Ziua']; $Mesaj = $runrows ['Mesaj']; $Anul = $runrows ['Anul']; echo " &lt;table class='noutatitabel'&gt; &lt;tr&gt; &lt;td class='faramargini'&gt; &lt;div class='data'&gt; &lt;div class='luna'&gt;$Luna $Anul&lt;/div&gt; &lt;div class='ziua'&gt;$Ziua&lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;td class='albastru'&gt;$Mesaj &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;br&gt;"; } echo" &lt;br&gt;&lt;hr&gt;&lt;br&gt;&lt;/div&gt;"; } if(mysql_num_rows($runapr) &gt; 0 ) { echo" &lt;h3&gt;Aprilie 2013&lt;/h3&gt; &lt;div&gt;&lt;br&gt;"; while($runrows = mysql_fetch_assoc($runapr)) { $Luna = $runrows ['Luna']; $Ziua = $runrows ['Ziua']; $Mesaj = $runrows ['Mesaj']; $Anul = $runrows ['Anul']; echo " &lt;table class='noutatitabel'&gt; &lt;tr&gt; &lt;td class='faramargini'&gt; &lt;div class='data'&gt; &lt;div class='luna'&gt;$Luna $Anul&lt;/div&gt; &lt;div class='ziua'&gt;$Ziua&lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;td class='albastru'&gt;$Mesaj &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;br&gt;"; } echo" &lt;br&gt;&lt;hr&gt;&lt;br&gt;&lt;/div&gt;"; } if(mysql_num_rows($runmar) &gt; 0 ) { echo" &lt;h3&gt;Martie 2013&lt;/h3&gt; &lt;div&gt;&lt;br&gt;"; while($runrows = mysql_fetch_assoc($runmar)) { $Luna = $runrows ['Luna']; $Ziua = $runrows ['Ziua']; $Mesaj = $runrows ['Mesaj']; $Anul = $runrows ['Anul']; echo " &lt;table class='noutatitabel'&gt; &lt;tr&gt; &lt;td class='faramargini'&gt; &lt;div class='data'&gt; &lt;div class='luna'&gt;$Luna $Anul&lt;/div&gt; &lt;div class='ziua'&gt;$Ziua&lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;td class='albastru'&gt;$Mesaj &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;br&gt;"; } echo" &lt;br&gt;&lt;hr&gt;&lt;br&gt;&lt;/div&gt;"; } if(mysql_num_rows($runfeb) &gt; 0 ) { echo" &lt;h3&gt;Februarie 2013&lt;/h3&gt; &lt;div&gt;&lt;br&gt;"; while($runrows = mysql_fetch_assoc($runfeb)) { $Luna = $runrows ['Luna']; $Ziua = $runrows ['Ziua']; $Mesaj = $runrows ['Mesaj']; $Anul = $runrows ['Anul']; echo " &lt;table class='noutatitabel'&gt; &lt;tr&gt; &lt;td class='faramargini'&gt; &lt;div class='data'&gt; &lt;div class='luna'&gt;$Luna $Anul&lt;/div&gt; &lt;div class='ziua'&gt;$Ziua&lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;td class='albastru'&gt;$Mesaj &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;br&gt;"; } echo" &lt;br&gt;&lt;hr&gt;&lt;br&gt;&lt;/div&gt;"; } if(mysql_num_rows($runian) &gt; 0 ) { echo" &lt;h3&gt;Ianuarie 2013&lt;/h3&gt; &lt;div&gt;&lt;br&gt;"; while($runrows = mysql_fetch_assoc($runian)) { $Luna = $runrows ['Luna']; $Ziua = $runrows ['Ziua']; $Mesaj = $runrows ['Mesaj']; $Anul = $runrows ['Anul']; echo " &lt;table class='noutatitabel'&gt; &lt;tr&gt; &lt;td class='faramargini'&gt; &lt;div class='data'&gt; &lt;div class='luna'&gt;$Luna $Anul&lt;/div&gt; &lt;div class='ziua'&gt;$Ziua&lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;td class='albastru'&gt;$Mesaj &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;br&gt;"; } echo" &lt;br&gt;&lt;hr&gt;&lt;br&gt;&lt;/div&gt;"; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T07:14:04.167", "Id": "48466", "Score": "0", "body": "What's the point of filtering by month if you want all of them? Are you looking for counts or averages?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T07:15:39.807", "Id": "48467", "Score": "0", "body": "i have an accordion and the header is shown if there are result in the specific month..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T07:18:36.407", "Id": "48468", "Score": "0", "body": "I don't quite understand that. Could you explain your use case for this in a bit more detail in your question (by [edit]ing it)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T07:36:31.697", "Id": "48474", "Score": "0", "body": "Thanks! Good news: there are ways to make it shorter indeed :-) Can you tell us also approximately how many entries you expect per month? (i.e. just a few, dozens, hundreds, more?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T07:39:43.323", "Id": "48475", "Score": "0", "body": "5 to 10 entries... but not always there will be data in a month..." } ]
[ { "body": "<p>Hopefully you can understand what I have done, I have written comments in English</p>\n\n<pre><code>&lt;?php\n\n// mysql_ is deprecated use mysqli_\n// die on error\n$link = mysqli_connect(\"localhost\",\"user\",\"pass\") or die(mysqli_connect_error());\nmysqli_select_db($link, \"lista_de_analize\");\nmysqli_set_charset($link, \"UTF8\");\n\n// select all data at once\n$constructian =\"SELECT * from Anunturi WHERE YEAR(DataIntroducere) = YEAR(CURDATE()) ORDER BY DataIntroducere DESC\";\n\n$runian = mysqli_query($link, $constructian) or die(mysqli_error($link));\n\n// build multi-dimensional array from data\n$data = array();\n\nwhile($runrows = mysql_fetch_assoc($runian)) {\n $month_year = date('F Y', strtotime($runrows['DataIntroducere']));\n $data[$month_year][] = $runrows;\n}\n\n\n?&gt;\n &lt;script&gt;\n $(function()\n {\n var icons =\n {\n header: \"ui-icon-circle-arrow-e\",\n activeHeader: \"ui-icon-circle-arrow-s\"\n };\n $( \"#dam\" ).accordion({\n icons: icons,\n heightStyle: \"content\",\n collapsible: false\n });\n $( \"#antrecut\" ).accordion({\n icons: icons,\n heightStyle: \"content\",\n collapsible: true\n });\n });\n &lt;/script&gt;\n&lt;?php\n\nif (count($data)==0)\n{\n echo \"Nu avem noutăți!\";\n}\nelse\n{\n echo\"\n &lt;div id='dam'&gt;\";\n\n foreach ($data as $month_year =&gt; $month_year_runrows)\n {\n echo\"\n &lt;h3&gt;$month_year&lt;/h3&gt;\n &lt;div&gt;&lt;br&gt;\";\n\n foreach ($month_year_runrows as $runrows)\n {\n echo \"\n &lt;table class='noutatitabel'&gt;\n &lt;tr&gt;\n &lt;td class='faramargini'&gt;\n &lt;div class='data'&gt;\n &lt;div class='luna'&gt;{$runrows['Luna']} {$runrows['Anul']}&lt;/div&gt;\n &lt;div class='ziua'&gt;{$runrows ['Ziua']}&lt;/div&gt;\n &lt;/div&gt;\n &lt;/td&gt;\n &lt;td class='albastru'&gt;{$runrows ['Mesaj']}\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;&lt;br&gt;\";\n }\n\n echo\"\n &lt;br&gt;&lt;hr&gt;&lt;br&gt;&lt;/div&gt;\";\n }\n}\n\n\n?&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T08:01:00.800", "Id": "48478", "Score": "0", "body": "This is SHORT!!! too bad that i can't check if it works... i have to go... but i'll be back in 2 hours..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T08:42:09.723", "Id": "48487", "Score": "0", "body": "Today everything is short... :) your code, my meeting... Checked your code... you did something there... gorgeous. It doesn't work with mysqli statements... so i reverted to mysql with the proper changes so... it works!!! but the month is not displayed as i wanted (only shows first 3 letters of the month) and something else... in my code, the order of months was from dec to ian (desc) but here is no restriction..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T10:23:19.203", "Id": "48503", "Score": "0", "body": "I have made a couple of small changes. $month_year = date('F Y' Use F Y instead of M Y for full month name, and on $constructian =\"SELECT I have added and ORDER BY clause, so they are in date order you can choose ASC or DESC" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T11:22:21.093", "Id": "48510", "Score": "0", "body": "The part with ASC or DESC i have done it... but thank you again for the F Y... i was searching the net for the answer... If i want to have the name of months in another language must I make an array or is there another easy way of doing this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T16:44:27.133", "Id": "48540", "Score": "0", "body": "You could either use an array, or set your locale http://php.net/manual/en/function.setlocale.php" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T04:53:53.640", "Id": "48599", "Score": "0", "body": "yeah... it doesn't work with locale... but i did str_replace and now everything works as expected. Thank you all for this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T08:14:06.147", "Id": "48610", "Score": "0", "body": "I have found something else... The code you provided (which is excellent) show's even future data in current year... which is not so good. I want the data to be displayed from the past until current date... what must be done?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T19:35:44.030", "Id": "48662", "Score": "0", "body": "SELECT * from Anunturi WHERE YEAR(DataIntroducere) = YEAR(CURDATE()) AND DataIntroducere < NOW() ORDER BY DataIntroducere DESC" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T07:56:42.747", "Id": "30493", "ParentId": "30492", "Score": "5" } }, { "body": "<p>(Note: I don't know HTML or JavaScript enough to comment on the jQuery part or the layout.)</p>\n\n<p>First things first: you really shouldn't be using the <code>mysql_*</code> functions any more. There are better alternatives available, see for instance this question on Stack Overflow: <a href=\"https://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php\">Why shouldn't I use mysql_* functions in PHP?</a></p>\n\n<p>That won't directly help you here though. What you need to do is refactor your code a bit.</p>\n\n<ul>\n<li>All the code blocks that output the individual rows are identical. That's a sure sign you should have created a function to do so. Create a function <code>output_one_row($row)</code> that takes one record and does the same thing as the blocks inside the <code>while(mysql_fetch_assoc())</code> loops.</li>\n<li><p>All the individual selects on <code>Anunturi</code> are identical except for the month queried. You could also create a function that produces the query for a month (given as a parameter) and returns the result set for that month. Using a bind variable would be even better.</p>\n\n<p>Also don't use <code>select *</code>, select only the columns you will need to output. This might not matter for you right now, but if that table gets additional columns in the future, you'll be making your database do unnecessary work to retrieve data you're not using.</p>\n\n<p>An <code>order by</code> for the date column could make sense, if that's relevant for your use case.</p></li>\n<li><p>You're repeating the same code pattern for the twelve distinct months. You should instead have a single function that lays out the table for a given month, and call that function twelve times. The function could take only a month, and do the querying and output based on the two functions above.</p>\n\n<p>Use an associative array to get the month name from the month number. (Or a PHP builtin if one exists that is properly localized for your environment.)</p></li>\n<li>Don't do <code>select * from ...</code> then count in PHP if you only need the count. Rather, you should <code>select count(*) from ...</code>, i.e. let the database do the counting (which it can sometimes optimize from indexes, or actually have buffered already). Don't retrieve the whole dataset just to count it.</li>\n</ul>\n\n<p>If you do that, your code would look like (pseudo-code):</p>\n\n<pre><code>function output_one_row($row) { /* ... */ }\nfunction select_offers($month) {\n // build query for the specified month\n // execute it\n // return result set\n}\nfunction output_month_table($month) {\n // get result set for the month\n // check if there is any data (leave if not, returning 0)\n // output table header\n // output individual rows using output_row\n // output table footer\n // return number of rows printed\n}\n// \"main\"\n$total_rows_output = 0;\nfor ($month in 1 .. 12) {\n $total_rows_output += output_month_table($month);\n}\nif ($total_rows_output == 0) {\n // print \"no data found\"\n}\n</code></pre>\n\n<p>Notice that you don't need the global select count with this, you derive it from the individual months.</p>\n\n<p>You can also avoid the <code>num_rows</code> calls completely by using a bit more state in the <code>output_month_table</code>, something like:</p>\n\n<pre><code> $rows_processed = 0;\n while ($row = mysql_fetch_assoc(...)) {\n if ($rows_processed == 0) {\n // output month header\n }\n // output the table row\n $rows_processed++;\n }\n if ($rows_processed &gt; 0) {\n // output month footer\n }\n return $rows_processed;\n</code></pre>\n\n<p>Now that's still twelve queries, when a single one could be enough. If you want to reduce the number of queries, it's possible too but requires a bit more state. The idea for that would be to select the data for the complete year, sorted by date, and include the <code>month(DataIntroducere)</code> in the selected columns (for convenience, you could derive it in PHP too).</p>\n\n<p>Then, as you traverse the (ordered) result set, you do check if the current row is in the same month as the previous one. If it is, you simply output the row. If it isn't, you close the previous month's table, open the (now current) month's header, and output the row.</p>\n\n<p>In pseudo-code:</p>\n\n<pre><code>$result_set = // select [columns] from your_table where [current year] order by date\n$current_month = -1; // invalid month number\n$total_rows = 0;\nforeach ($row in $result_set) {\n if ($row[\"month\"] != $current_month) {\n if ($total_rows != 0) {\n // output the HTML to close the previously output month table\n }\n $current_month = $row[\"month\"];\n // output current month table header\n }\n // output row\n $total_rows++;\n}\nif ($total_rows &gt; 0) {\n // close last month table\n} else {\n // no data found at all\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T09:36:51.300", "Id": "48497", "Score": "0", "body": "A very good answer... one can learn from that! thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T08:27:39.060", "Id": "30496", "ParentId": "30492", "Score": "1" } } ]
{ "AcceptedAnswerId": "30493", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T07:12:49.967", "Id": "30492", "Score": "2", "Tags": [ "php", "mysql" ], "Title": "Displaying data for a specific month with an accordion" }
30492
<p>I'd like feedback on my callbacks/promises alternative, please.</p> <p><a href="https://github.com/Lcfvs/yld/" rel="nofollow">The yld repository</a></p> <pre><code>var yld; yld = (function () { 'use strict'; var slice, clearer, defer, prepare, yld; slice = Array.prototype.slice; clearer = { yld: { value: undefined }, throw: { value: undefined } }; Object.freeze(clearer); defer = typeof process === 'object' &amp;&amp; typeof process.nextTick === 'function' ? process.nextTick : function nextTick(closure) { setTimeout(closure); }; prepare = function* (parent) { var proto, generator, fnGenerator, response; proto = { yld: function (fn) { var parent; parent = this; return function () { var generator, proto, fnGenerator; generator = prepare(parent); proto = generator.next().value; generator.next(generator); fnGenerator = fn.apply(proto, arguments); generator.next(fnGenerator); return Object.create(proto, clearer); }; }, next: function (value) { defer(function () { generator.next(value); }); }, nextCb: function () { var value; value = slice.call(arguments); defer(function () { generator.next(value); }); }, throw: function(error) { defer(function() { fnGenerator.throw(error); }); } }; if (parent !== undefined) { proto.parent = Object.create(parent, clearer); } generator = yield proto; fnGenerator = yield null; while (true) { response = yield defer(function () { fnGenerator.next(response); }); } }; yld = function (fn) { return function () { var generator, proto, fnGenerator; generator = prepare(); proto = generator.next().value; generator.next(generator); fnGenerator = fn.apply(proto, arguments); generator.next(fnGenerator); return Object.create(proto, clearer); }; }; return yld; }()); if (typeof module === 'object' &amp;&amp; module.exports !== undefined) { module.exports = yld; } </code></pre>
[]
[ { "body": "<p>Interesting question;</p>\n\n<p>I honestly can't follow the code, and I tried a while. I like to think of myself as above average in JavaScript, which means that from a readability/maintainability perspective you have a problem. It might be related to the fact that you have no comments in there ;)</p>\n\n<p>Some minor style tips</p>\n\n<ul>\n<li><p>For easier reading you can merge your <code>var</code> declarations with initial assignments, this</p>\n\n<pre><code>var parent;\n\nparent = this;\n</code></pre>\n\n<p>becomes then</p>\n\n<pre><code>var parent = this;\n</code></pre></li>\n<li><p>You make a shortcut for <code>Array.prototype.slice</code>, but you use it only once, I would throw away the shortcut and simply go for <code>value = Array.prototype.slice.call(arguments);</code>.</p></li>\n<li><p>There is no need to keep creating a function in your loop, just create the function outside of your loop.</p>\n\n<pre><code>while (true) {\n response = yield defer(function () {\n fnGenerator.next(response);\n });\n}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-18T18:28:34.297", "Id": "60407", "ParentId": "30498", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T09:04:30.157", "Id": "30498", "Score": "2", "Tags": [ "javascript", "node.js", "callback", "promise" ], "Title": "My yld NPM - callbacks/promises alternative" }
30498
<p>I've been reading the security issue on logging out from a website system written in PHP, using sessions.</p> <p>My current code is:</p> <pre><code>session_start(); if (isset($_SESSION["logged_in"])) { unset($_SESSION["logged_in"]); unset($_SESSION["ss_fprint"]); unset($_SESSION["alive"]); session_destroy(); session_regenerate_id(true); } // NEW MODIFIED CODE session_start(); if (isset($_SESSION["logged_in"])) { $_SESSION = array(); if (ini_get("session.use_cookies")) { $params = session_get_cookie_params(); setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"] ); } session_destroy(); header("Location: ../index.php"); die(); } else { header("Location: ../online.php"); die(); } </code></pre> <p>I use <a href="http://www.phpclasses.org/browse/file/12194.html" rel="nofollow">this class</a>.</p> <p>The code from the class should ensure and protect against hijacking and capture and fixation.</p> <p>I have generated a session with this code from the above link, and I want to logout properly. </p> <p>I tried <code>print_r()</code> out all <code>$_SESSION data</code>, and it was empty after I ran my logout code.</p> <p>Is my logout secure enough?</p> <p>OBS:: This system I'm making is not for some big company with a huge big mega need for security, but the basics should be implemented.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T10:27:38.383", "Id": "48505", "Score": "1", "body": "die() is usually used to indicate an error, I would use exit; instead." } ]
[ { "body": "<p>looks alright enough. i would change is replace all those unset() lines with just <code>$_SESSION = array();</code></p>\n\n<p>and check the <a href=\"http://sg3.php.net/session_destroy\" rel=\"nofollow\">manual</a>, it has a sample to clear your session cookies if you have them enabled.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T09:45:49.930", "Id": "48498", "Score": "0", "body": "Thanks for your answer. So basicly i can just use the code efrom your link, and if i have session cookies enabled they will get deleted?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T09:48:21.660", "Id": "48499", "Score": "0", "body": "I change my unset() with $_SESSION = array();" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T10:11:39.717", "Id": "48501", "Score": "0", "body": "I modified my code in my original question.. any comments on it?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T09:38:30.947", "Id": "30501", "ParentId": "30500", "Score": "3" } } ]
{ "AcceptedAnswerId": "30501", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T09:33:14.003", "Id": "30500", "Score": "1", "Tags": [ "php", "security", "session" ], "Title": "Secure logout: session termination" }
30500
<p>I've tried implementing priority queue with fixed size in Java using <code>TreeSet</code> and overriding <code>add()</code> method:</p> <pre><code>public class FixedSizePriorityQueue&lt;E&gt; extends TreeSet&lt;E&gt; { private final int capacity; public FixedSizePriorityQueue(final int capacity) { this.capacity = capacity; } public FixedSizePriorityQueue( final int capacity, final Comparator&lt;? super E&gt; comparator) { super(comparator); this.capacity = capacity; } @Override public boolean add(final E e) { // initialized with 0 or less than zero capacity if (capacity &lt;= 0) { return false; } // keep adding until we fill the queue if (size() &lt; capacity) { return super.add(e); } if (comparator() != null &amp;&amp; comparator().compare(this.last(), e) &lt; 0) { pollLast(); return super.add(e); } return false; } } </code></pre> <p>I would really appreciate your thoughts, hints and comments.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T10:10:00.930", "Id": "48500", "Score": "1", "body": "Are you sure you want your `FixedSizePriorityQueue` be a `TreeSet`? Do you want to support all methods of a `TreeSet` ? I would internally use a `TreeSet` but not extend it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T10:11:44.953", "Id": "48502", "Score": "2", "body": "@MrSmith42, good point! I don't need to extend it, I can use it internally. Tnx." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T14:34:45.713", "Id": "48533", "Score": "0", "body": "What's the usage of `pollLast()` method in `add` method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T13:48:30.717", "Id": "48722", "Score": "0", "body": "@tintinmj the idea is to have fixed size priority queue, and with `pollLast()`, I remove the most irrelevant element and add new one, using `super.add()`, leaving super to prioritize." } ]
[ { "body": "<p>Two thoughts:</p>\n\n<ol>\n<li><p>If there is other code and you need all the features of a TreeSet great, otherwise delegate to a TreeSet member variable.</p></li>\n<li><p>Your code <code>if (capacity &lt;= 0)</code> is somewhat superfluous because of the next test <code>if (size() &lt; capacity)</code></p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T10:25:58.200", "Id": "48504", "Score": "0", "body": "thanks for noticing `if (capacity <= 0)`. `size()` will always return 0 or greater than 0 :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T10:16:52.437", "Id": "30505", "ParentId": "30504", "Score": "3" } }, { "body": "<p>I rarely check the return of add methods. I would suggest throwing an exception to indicate the container is full. \nAdd methods that return available space and full state.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T00:56:43.780", "Id": "72415", "Score": "6", "body": "I didn't downvote on this answer, but this is not what I would consider a \"proper\" review. Look at some other answers on this site, get a feel for what they should look like, and then come back with that knowledge and integrate it into your answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-16T08:42:59.057", "Id": "321743", "Score": "0", "body": "@syb0rg How is this not a proper review? (This answer was recently flagged, that's why I'm asking)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-16T17:50:22.890", "Id": "321804", "Score": "0", "body": "@SimonForsberg It seemed better served as a comment, and I still believe it would be. There isn't enough content in my opinion. Why doesn't the OP check the return of add methods, there is no reason given nor a link to point me to evidence? Would one throw a custom exception, or a standard library exception, and why? Where is the benefit in adding functions that return available space and full state, and how would that be used to refine the code in the question? Now for you and I, these questions are well known. But I think newcomers need more explanation than what was supplied here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-17T06:52:47.573", "Id": "321864", "Score": "0", "body": "@syb0rg That arguably makes it a bad answer, not \"not an answer\". Short answers are fine." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T07:16:01.523", "Id": "30549", "ParentId": "30504", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T10:01:05.937", "Id": "30504", "Score": "4", "Tags": [ "java", "queue" ], "Title": "Fixed size priority queue" }
30504
<p>I wrote this little code in c++. It calculates the needed time for a given speed of a medium (for example the speed is 1024 B/s, the file size is 1MB, it'll take 17 minutes and 4 seconds to finish). The code works, but I'm not sure if it's proper. </p> <p>Can you tell me if it's okay or not?</p> <pre><code>#include &lt;iostream&gt; int main() { int transmission_speed; //speed of the transmission in bytes per seconds int file_size_mb; //file's size in MBs std::cout &lt;&lt; "Enter the speed of the transmission in bytes per seconds: "; std::cin &gt;&gt; transmission_speed; std::cout &lt;&lt; "Enter the file's size in megabytes: "; std::cin &gt;&gt; file_size_mb; int file_size_b = file_size_mb *1024*1024; int seconds_needed = file_size_b / transmission_speed; int days_needed = (seconds_needed / 3600) / 24; seconds_needed -= days_needed*86400; int hours_needed = seconds_needed / 3600; seconds_needed -= hours_needed*3600; std::cout &lt;&lt; "Days needed: " &lt;&lt; days_needed &lt;&lt; std::endl; std::cout &lt;&lt; "Hours needed: " &lt;&lt; hours_needed &lt;&lt; std::endl; std::cout &lt;&lt; "Seconds needed: " &lt;&lt; seconds_needed &lt;&lt; std::endl; return(0); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T12:08:10.783", "Id": "48519", "Score": "0", "body": "This code is incredibly clean and easy to read, however, you might want to eliminate the output for `days_needed` when `days_needed` is 0. Think about that. It will make the program output cleaner if the output is not specified like in a contest or homework." } ]
[ { "body": "<p>The code looks good though, did you miss on the <code>minutes needed</code>?</p>\n<p>All the calculations you're doing are on <code>int</code>. You may consider using <code>float</code> at some places.</p>\n<blockquote>\n<p>e.g.:</p>\n<p>file-size-in-MB may be 3.4MB</p>\n<p>transmission-speed-in-bytes may be 5.9B/s</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T11:42:51.657", "Id": "48515", "Score": "0", "body": "thanks :D \nafter I posted the question I noticed the \"missing minutes\", but I thought it's not important :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T11:45:43.720", "Id": "48516", "Score": "0", "body": "Why would floats help here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T11:56:01.027", "Id": "48518", "Score": "0", "body": "@Mat, imagine a user input of float number going to an integer variable. It may change the figures and hence the calculation output." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T11:38:55.843", "Id": "30507", "ParentId": "30506", "Score": "3" } }, { "body": "<p>I see very few things to change, your code is easy to read.</p>\n\n<ul>\n<li><p>You're not validating the input. What if someone enters something that's not a number?</p>\n\n<p>I'd suggest you create a function that takes the prompt string and returns the entered integer. That function can do the validation, which isn't completely trivial.</p>\n\n<p>Two good examples of how to do the validation:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/546470/635608\">What is the best way to do input validation in C++ with cin?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/2075898/good-input-validation-loop-using-cin-c\">Good input validation loop using cin</a></li>\n</ul></li>\n<li><p>(Very minor) You put a comment on the first two variable declarations, but not on the following ones. In my opinion, you chose sufficiently descriptive variable names, the comments aren't necessary. But if you do put a comment on some (or if your local coding style guidelines enforce that), do it consistently.</p></li>\n<li><p>This \"looks\" strange:</p>\n\n<pre><code>int days_needed = (seconds_needed / 3600) / 24;\nseconds_needed -= days_needed*86400;\n</code></pre>\n\n<p>You should be dividing with the same constant(s) that you use in the multiplication (or vice-versa). (These constants are easy to identify, I don't think giving them names is worth the effort. Just be systematic in how you use them.)</p></li>\n<li><p><code>return(0);</code> is unusual, it looks like a function call. <code>return</code> is not a function call, it's a statement. I would prefer <code>return 0;</code> instead.</p></li>\n<li><p>Your code appears to have forgotten about minutes :-)</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T11:44:38.433", "Id": "30508", "ParentId": "30506", "Score": "5" } }, { "body": "<p>It's a very simple little program, however, there's a few comments to make:</p>\n\n<ul>\n<li>All of the code is in <code>main</code>. Of course, for a program of this size, that doesn't really matter too much, however, you should prefer to break things up into self-contained functions where possible. For example, there should be a separate function here to actually do the calculations.</li>\n<li>Use the correct data type for what you need. Can time ever be negative here? The answer is no, so I'd prefer to use <code>unsigned</code> over <code>int</code>. </li>\n<li>You should be somewhat careful about overflow. Any filesize over 2048MB (2GB) will overflow the size of an <code>int</code> (assuming a 4 byte int - in actuality, an <code>int</code> is only technically required to be at least 2 bytes). Using an <code>unsigned</code> will change this to 4GB, however, if you expect any filesizes larger than that, you should look at another datatype (<code>std::uint64_t</code> perhaps).</li>\n<li>Magic numbers. It's not so bad when dealing with time, because it's generally fairly obvious here, but numbers like <code>86400</code> shouldn't be shown as-is. They should be a named constant, such as <code>const unsigned seconds_in_day = 86400</code>. </li>\n</ul>\n\n<p>I'd suggest breaking this up into a <code>main</code> function and a <code>required_time(unsigned transmission_rate, unsigned file_size)</code> function. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T20:02:12.707", "Id": "48557", "Score": "0", "body": "or `unsigned const seconds_in_day = 24*60*60;`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T11:52:05.677", "Id": "30509", "ParentId": "30506", "Score": "11" } }, { "body": "<p>In addition to all the helpful suggestions made by others...</p>\n\n<p>Using a console interactively to get input is so old style!! It's more convenient to have the input data in a file and just read them directly without the lines for the prompt. Just use:</p>\n\n<pre><code>std::cin &gt;&gt; transmission_speed;\nstd::cin &gt;&gt; file_size_mb;\n</code></pre>\n\n<p>Then, you can use:</p>\n\n<pre><code>cat input.txt | ./program\n</code></pre>\n\n<p>This is very small oversight but the number of seconds computed in the line</p>\n\n<pre><code>int seconds_needed = file_size_b / transmission_speed;\n</code></pre>\n\n<p>will be off by 1 second if <code>file_size_b % transmission_speed != 0</code>. You should add </p>\n\n<pre><code>if ( file_size_b % transmission_speed != 0 )\n ++seconds_needed;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-29T03:53:00.923", "Id": "75102", "ParentId": "30506", "Score": "0" } } ]
{ "AcceptedAnswerId": "30509", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T11:25:30.497", "Id": "30506", "Score": "5", "Tags": [ "c++", "algorithm" ], "Title": "Time calculator for a given speed and file size" }
30506
<p>For a project I need to replicate a website and I was wondering if any of you could take a quick look to see if I made any obvious mistakes. Right now it's just the HTML part, but I would like to make sure everything is correct in the HTML part before I move on to the CSS. Picture added below. Thanks in advance!</p> <p><img src="https://i.stack.imgur.com/UGK4A.jpg" alt="This is the site I need to replicate"></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="nl"&gt; &lt;head&gt; &lt;title&gt; IKEA &lt;/title&gt; &lt;meta charset="utf-8" /&gt; &lt;link rel="stylesheet" href="css/reset.css" /&gt; &lt;link rel="stylesheet" href="css/style.css" /&gt; &lt;!--[if lt IE 9]&gt; &lt;script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="wrapper"&gt; &lt;header&gt; &lt;h1&gt;Ikea&lt;/h1&gt; &lt;p&gt;Welkom bij IKEA België! &lt;a href="#"&gt;Log in&lt;/a&gt; of &lt;a href="#"&gt;maak een profiel aan&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="#"&gt;&lt;img src="images/page1/small_anna.gif" alt="Vraag het aan Anna" /&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Vraag het aan Anna&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;NL&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;FR&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Winkel informatie&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;IKEA FAMILY&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Mijn boodschappenlijst&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Startpagina&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Mijn profiel&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Jobs@IKEA&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;nav&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Alle producten&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Nieuw&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Promoties&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Inspiratie&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Plannen&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Praktische info&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;3D Keukenplanner&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Alle afdelingen&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/header&gt; &lt;div id="content"&gt; &lt;div id="reclameImg"&gt; &lt;a href="#"&gt;&lt;img src="images/page1/__ikea_besta_hp_900x518_nl.jpg" alt="BESTÅ opbergsysteem"&gt;&lt;/a&gt; &lt;/div&gt; &lt;aside&gt; &lt;h1&gt;Handige links&lt;/h1&gt; &lt;div id="linksAside"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Bereid je aankoop voor&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Openingstijden&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Voorraadinformatie&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Dienst na verkoop&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;FAQ&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Contacteer ons&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;IKEA restaurant&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Jobs bij ikea&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id="inDeBuurt"&gt; &lt;h1&gt;IKEA bij jou in de buurt&lt;/h1&gt; &lt;p&gt;Kies hieronder een vestiging voor routebeschrijvingen, openingstijden, aanbiedingen en activiteiten.&lt;/p&gt; &lt;/div&gt; &lt;/aside&gt; &lt;div id="midden"&gt; &lt;div id="boodschappenlijst"&gt; &lt;p&gt;Wil je makkelijker winkelen? &lt;a href="#"&gt;Maak dan gebruik van de boodschappenlijst&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Volg ons op: &lt;a href="#"&gt;&lt;img src="images/page1/fb.jpg"&gt;&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;div id="reclameMidden"&gt; &lt;section id="reclame1"&gt; &lt;a href="#"&gt;&lt;img src="images/page1/fr1.jpg"&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;img src="images/page1/w11-13_nl_172x255.jpg"&gt;&lt;/a&gt; &lt;/section&gt; &lt;section id="reclame2"&gt; &lt;a href="#"&gt;&lt;img src="images/page1/fr2.jpg"&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;img src="images/page1/w11-13_nl_172x255.jpg"&gt;&lt;/a&gt; &lt;/section&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;footer&gt; &lt;div id="footerLinks"&gt; &lt;h2&gt;Catalogus en brochures 2012&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Catalogus 2012 bestellen&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Keukenbrochure bestellen&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Catalogus 2012 online&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Keukenbrochure online&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Matrassenbrochure&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Garderobekastenbrochure&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;BESTÅ brochure&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;Informatie over IKEA&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Het IKEA woonwarenhuis&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;IKEA voor kinderen&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Onze verantwoordelijkheid&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;IKEA Social Initiative&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Ons bedrijfsconcept&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Onze geschiedenis&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;Praktische info&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Contacteer ons&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Hulp bij het plannen&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;IKEA cadeaupas&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Dienst naverkoop&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Onze garanties&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;IKEA Home Planner&lt;/h2&gt; &lt;h2&gt;Onze Services&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Leveringsservice&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Installatieservice voor keukens&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Montageservice&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Financieringsservice&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Recyclingservice matrassen&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;Jobs bij IKEA&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Beschikbare jobs&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;IKEA en het milieu&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Mens en milieu&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Het verhaal zonder einde&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Klimaatverandering&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Producten en materialen&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Onze gedragscode&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Voedselveiligheid&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Katoen&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Partnerships&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id="footerCopyright"&gt; &lt;p&gt;© Inter IKEA Systems B.V. 1999-2012 | &lt;a href="#"&gt;Privacy&lt;/a&gt; | &lt;a href="#"&gt;Alg. voorwaarden&lt;/a&gt; | &lt;a href="#"&gt;Sitemap&lt;/a&gt; | &lt;a href="#"&gt;IKEA FAMILY lid worden&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/footer&gt; &lt;/div&gt; </code></pre> <p> </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T12:31:29.477", "Id": "48521", "Score": "0", "body": "Are you asking whether your HTML could be a faithful replica of the site (given the right CSS)? Or are you asking for general review of your code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T12:33:00.717", "Id": "48522", "Score": "1", "body": "Also, be aware that replicating an existing site exactly is most likely illegal and it makes me wonder whether you're creating a scam site." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T12:54:39.350", "Id": "48525", "Score": "0", "body": "@svick This is actually a project for a class I'm taking to learn html and css. This is an old version of what the IKEA website used to look like and literally just a random site taken from the web. I guess I'm asking if it could be a faithful replica of the site given the right css. I'm really not that good with the whole html css thing yet so I'm wondering if i'm using the correct attributes etc. Thanks for your response! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T13:56:21.293", "Id": "48528", "Score": "0", "body": "If you are on a unix/linux system, use wget here a link: [Create a mirror of a website with Wget](http://fosswire.com/post/2008/04/create-a-mirror-of-a-website-with-wget/)" } ]
[ { "body": "<p>Not important in this case, but it’s a good practice in general:<code>meta</code>-<code>charset</code> should be the first element in <code>head</code>.</p>\n\n<p>You shouldn’t duplicate the information \"Vraag het aan Anna\" in the <code>alt</code> attribute. But anyway, to me this image doesn’t look like content, it’s probably more decoration resp. a navigational hint. If this is true (to check, you could ask yourself: Would the page convey the same meaning without this image?), you could use CSS to include this image instead.</p>\n\n<p>\"Vraag het aan Anna\" should probably be part of the link.</p>\n\n<p>You could use the <code>abbr</code> element for \"NL\" and \"FR\".</p>\n\n<p>Use <code>rel</code>-<code>alternate</code> + <code>hreflang</code> for the language switching links.</p>\n\n<p>In the <code>aside</code> I’d use <code>section</code> elements explicitly.</p>\n\n<p><code>&lt;img src=\"images/page1/fb.jpg\"&gt;</code> is missing an <code>alt</code> attribute. It should describe the target of the link (i.e. \"Facebook\"), not the graphic itself.</p>\n\n<p>The images in <code>.reclameMidden</code> are missing <code>alt</code> attributes.</p>\n\n<p>Use <code>small</code> for \"© Inter IKEA Systems B.V. 1999-2012\". You could also use <code>time</code> for \"1999-2012\",</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T17:51:44.390", "Id": "48959", "Score": "0", "body": "images need those `alt` attributes. depending on who you are writing the page for it could be a really, really big deal if you don't have them. just get into the habit of always putting the `alt` attribute in with something very meaningful. it helps with screen readers for people with disabilities. good catch unor." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T22:59:39.530", "Id": "30537", "ParentId": "30510", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T12:03:07.020", "Id": "30510", "Score": "2", "Tags": [ "html" ], "Title": "replica site checkup" }
30510
<p>I've written a GM script to filter some results from Experteer.com results: specifically, many of the rows are "only for Premium members" and don't allow you to click through or see details, so I've written the script to hide those results from cluttering the display. </p> <p>I'm very much a newbie to JavaScript and cobbled together this script after a lot of googling, so it's quite possibly horrific in several ways, please show me better ways in those cases.</p> <p>The code follows with some notes on my reasoning: </p> <pre><code>// ==UserScript== // @name ExperteerNoPremium // @namespace abiteasier.in // @description Removes the annoying "only for Premium members" rows from Experteer results // @include https://eu.experteer.com/goal/position/* // @include https://eu.experteer.com/search/jobs // @version 0.3 // @grant none // ==/UserScript== var remove_premium_rows = function () { var result_rows = document.body.querySelectorAll('.search-result-body'); for (var i = 0; i &lt; result_rows.length; i++) { var row = result_rows[i]; </code></pre> <p>The two different pages included in <code>@include</code> above have the "only for premium" text in different columns, but they both have a <code>td</code> with <code>class="search-result-job-action"</code> which is in both cases two columns before the one we need, hence the selection and double <code>nextElementSibling</code> calls: </p> <pre><code> var company_cell = row.querySelector('.search-result-job-action').nextElementSibling.nextElementSibling; var premium_only_re = /only\s+for\s+Premium\s+Members/i; if (premium_only_re.test(company_cell.textContent)) { row.style.display = 'none'; } } }; remove_premium_rows(); </code></pre> <p>The results page also has a few Ajax controls which update the results table and I would like the pruning to happen on these new results as well. Since <a href="https://developer.mozilla.org/en-US/docs/XUL/Events#Mutation_DOM_events" rel="nofollow">Mutation events</a> seem to be discouraged by everyone, I went with a very hacky way of monkeypatching the function that does the Ajax updates itself, adding the <code>remove_premium_rows</code> as a callback:</p> <pre><code>unsafeWindow.ajaxUpdater = function () { new Ajax.Updater('result', '/desire/refine_matches', {asynchronous:true, evalScripts:true, method: 'get', parameters:Form.serialize($('matches')), onComplete: remove_premium_rows}); } </code></pre> <p>That's it, the code as above works for my purposes, but I would like to know in what it can be improved to adhere with standard practices.</p>
[]
[ { "body": "<p>If you want to maximize the speed, to iterate big arrays, use</p>\n\n<pre><code>for (var i = 0, l = array.length; i &lt; l; i++)\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>for (var i = 0; i &lt; array.length; i++)\n</code></pre>\n\n<p>Moreover, if you want to get the elements of a class, there's no need to use <code>querySelectorAll</code>, you can use the faster <code>getElementsByClassName</code> (see <a href=\"http://jsperf.com/getelementbyid-vs-queryselector/70\" rel=\"nofollow\">benchmark</a>)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T03:23:48.377", "Id": "40018", "ParentId": "30511", "Score": "2" } }, { "body": "<p>It's a minor thing, and it won't make a noticeable difference,\nbut as a matter of principle, you should move this line out of the <code>for</code> loop:</p>\n\n<blockquote>\n<pre><code> var premium_only_re = /only\\s+for\\s+Premium\\s+Members/i;\n</code></pre>\n</blockquote>\n\n<p>As the value never changes, simply there's no point having it inside the loop.</p>\n\n<p>This statement is hard to read, because multiple attributes are on the same line:</p>\n\n<blockquote>\n<pre><code>new Ajax.Updater('result', '/desire/refine_matches',\n {asynchronous:true, evalScripts:true, method: 'get',\n parameters:Form.serialize($('matches')), \n onComplete: remove_premium_rows});\n</code></pre>\n</blockquote>\n\n<p>It would be more readable to have one attribute per line, and a space after each <code>:</code>, like this:</p>\n\n<pre><code>new Ajax.Updater('result', '/desire/refine_matches', {\n asynchronous: true, \n evalScripts: true,\n method: 'get',\n parameters: Form.serialize($('matches')),\n onComplete: remove_premium_rows\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-23T18:41:57.527", "Id": "114904", "ParentId": "30511", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T12:13:59.790", "Id": "30511", "Score": "1", "Tags": [ "javascript", "beginner", "web-scraping", "userscript" ], "Title": "Greasemonkey script for filtering out results from experteer.com" }
30511
<p>I have 2 nested resources in one of my Rails apps and the way the index is handled by the inner resources bothers me somewhat:</p> <pre><code>def index @program = Program.approved.find(params[:program_id]) if params[:program_id] if params[:tags] tags = params[:tags].split(" ") if @program @sites = Site.where(:program_id =&gt; @program.id).tagged_with(tags).page(params[:page]) else @sites = Site.joins(:program =&gt; :user).tagged_with(tags).page(params[:page]) end else if @program @sites = Site.where(:program_id =&gt; @program.id).page(params[:page]) else @sites = Site.joins(:program =&gt; :user).page(params[:page]) end end respond_to do |format| format.html # index.html.erb format.json { render json: @sites } end end </code></pre> <p>The complexity is caused because I want my <code>Site</code> resource to be accessible both through it's <code>Program</code> or directly. The results are also optionally filtered based on tags if they are included in the <code>params</code>.</p> <p>The joins are required because if a site belongs to a user then I display <code>Edit/Delete</code> options.</p> <p>It just doesn't feel like good Ruby code. So any refactoring tips would be helpful.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T13:57:00.373", "Id": "48723", "Score": "0", "body": "What the url to #index will look like with tags?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T14:27:26.350", "Id": "48725", "Score": "0", "body": "Like so - /sites?tags=football+hockey" } ]
[ { "body": "<p>You could get rid of the code duplication by making use of the fact, that arel expressions are lazily evaluated:</p>\n\n<pre><code>def index\n @program = Program.approved.find(params[:program_id]) if params[:program_id]\n\n sites =\n if @program\n Site.where(program_id: @program)\n else\n Site.joins(program: :user)\n end\n if params[:tags]\n tags = params[:tags].split(\" \")\n sites = sites.tagged_with(tags)\n end\n @sites = sites.page(params[:page])\n\n respond_to do |format|\n format.html\n format.json { render json: @sites }\n end\nend\n</code></pre>\n\n<p>Because you're using ruby 1.9 hash syntax in the render expression I also adapted the other hashes. That seems more consistent for me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T21:31:38.397", "Id": "30534", "ParentId": "30512", "Score": "1" } }, { "body": "<p>A better place for such logic is the model, to make things simpler and cleaner.</p>\n\n<pre><code>#SitesController\ndef index\n @sites = Site.scope_filtered(params)\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @sites }\n end\nend\n\n#Site model\ndef self.scope_filtered(args)\n result = args[:program_id] ? where(program_id: args[:program_id]) : joins(program: :user)\n result = result.tagged_with(args[:tags].split(' ')) if args[:tags]\n result = result.page(args[:page]) if args[:page]\nend\n</code></pre>\n\n<p><em>Side note: I'm not very sure what <code>:user</code> is in <code>joins(:program =&gt;:user)</code>. I assume it will work according to original code.</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T15:30:36.663", "Id": "30619", "ParentId": "30512", "Score": "0" } } ]
{ "AcceptedAnswerId": "30534", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T12:46:32.517", "Id": "30512", "Score": "1", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Rails 3 nested controller method" }
30512
<p>This is my implementation based on <code>Map&lt;K,V&gt;</code> interface. The BST is a linked binary tree with root reference, both internal and external nodes (<code>MyBSNode</code>) contains <strong>(key, value)</strong> entries</p> <p>What do you think? There's something to improve?</p> <pre><code>public BSPosition&lt;E&gt; insert(int k, E e) { if(isEmpty()){ /* Sets root */ BSPosition&lt;E&gt; r = new MyBSNode&lt;E&gt;(null); r.setElement(k, e); setRoot(r); size++; return r; } BSPosition&lt;E&gt; n = treeInsert(k, root); //k-key node or last node visited if(k == n.getKey()){ //tree has already a k-key node n.setElement(k, e); //only modifies e return n; } /* n is a external (last visited) node with different key */ size++; if(k &lt; n.getKey()) return n.setLeftChild(k, e); else return n.setRightChild(k, e); } private BSPosition&lt;E&gt; treeInsert(int k, BSPosition&lt;E&gt; v){ if(isLeaf(v)) return v; if(k &lt; v.getKey()){ if(v.getLeftChild() == null) return v; return treeInsert(k, v.getLeftChild()); } else if(k == v.getKey()) return v; else{ if(v.getRightChild() == null) return v; return treeInsert(k, v.getRightChild()); } } </code></pre>
[]
[ { "body": "<p>The algorithm looks fine. Some other notes:</p>\n\n<ol>\n<li><p>I would use longer variable names than <code>r</code>, <code>k</code>, <code>e</code> etc. Longer names would make the code more readable since readers/maintainers don't have to decode or memorize the abbreviations.</p></li>\n<li>\n\n<pre><code>new MyBSNode&lt;E&gt;(null)\n</code></pre>\n\n<p>Consider creating a default contructor, a named factory method or an explanatory local variable for <code>null</code>. Currently readers have to check the <code>MyBSNode</code> constructor to figure out what's that null supposed to mean.</p></li>\n<li><p><code>MyBSNode</code> does not seem to have a good name. Try to find something more descriptive.</p></li>\n<li><pre><code>n.setElement(k, e); // only modifies e\n</code></pre>\n\n<p>Creating a <code>setValue(E value)</code> method would make the comment unnecessary and would be cleaner.</p></li>\n<li><p>I'd consider moving <code>isLeaf</code> to <code>BSPosition</code> since it seems <a href=\"http://c2.com/cgi/wiki?DataEnvy\" rel=\"nofollow\">data envy</a>. I guess its only task is to check that both left and right children are <code>null</code>s.</p></li>\n<li><p><code>treeInsert</code> does not do any insertion, its name is a little bit misleading, it just searches the parent of the new node or a node with the same key. I'd call it according to that. (<code>searchInsertionPoint</code> for example.)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-22T13:35:06.063", "Id": "42501", "ParentId": "30519", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T15:41:08.943", "Id": "30519", "Score": "3", "Tags": [ "java", "binary-search", "tree" ], "Title": "Binary Search Tree insert method (map interface)" }
30519
<p>I wrote this converter code. It can convert a number from 1-100 into words. It works perfectly, but it seems to be too complicated to me. </p> <p>Can you tell me whether it's okay or not? </p> <pre><code>#include &lt;iostream&gt; int main() { int number; int first_digit; int second_digit; std::cout &lt;&lt; "Enter the number: "; std::cin &gt;&gt; number; first_digit = number/10; second_digit = number%10; if(number &gt;= 11 &amp;&amp; number &lt;= 20) { switch(number) { case 11: std::cout&lt;&lt;"eleven"; break; case 12: std::cout&lt;&lt;"twelve"; break; case 13: std::cout&lt;&lt;"thirteen"; break; case 14: std::cout&lt;&lt;"fourteen"; break; case 15: std::cout&lt;&lt;"fifteen"; break; case 16: std::cout&lt;&lt;"sixteen"; break; case 17: std::cout&lt;&lt;"seventeen"; break; case 18: std::cout&lt;&lt;"eighteen"; break; case 19: std::cout&lt;&lt;"nineteen"; break; } } else { switch(first_digit) { case 1: if(second_digit == 0) std::cout&lt;&lt;"ten"; break; case 2: std::cout&lt;&lt;"twenty"; break; case 3: std::cout&lt;&lt; "thirty"; break; case 4: std::cout&lt;&lt;"fourty"; break; case 5: std::cout&lt;&lt;"fifty"; break; case 6: std::cout&lt;&lt;"sixty"; break; case 7: std::cout&lt;&lt;"seventy"; break; case 8: std::cout &lt;&lt;"eighty"; break; case 9: std::cout &lt;&lt;"ninety"; break; case 10: std::cout &lt;&lt;"one hundred"; break; } if(first_digit &gt; 1 &amp;&amp; number != 100) std::cout&lt;&lt;"-"; switch(second_digit) { case 1: std::cout&lt;&lt;"one"; break; case 2: std::cout&lt;&lt;"two"; break; case 3: std::cout&lt;&lt;"three"; break; case 4: std::cout&lt;&lt;"four"; break; case 5: std::cout&lt;&lt;"five"; break; case 6: std::cout&lt;&lt;"six"; break; case 7: std::cout&lt;&lt;"seven"; break; case 8: std::cout&lt;&lt;"eight"; break; case 9: std::cout&lt;&lt;"nine"; break; default: break; } } return 0; } </code></pre>
[]
[ { "body": "<p>Code will break on <code>20</code></p>\n\n<pre><code>if(number &gt;= 11 &amp;&amp; number &lt;= 20)\n{\n switch(number)\n {\n ......\n case 19:\n std::cout&lt;&lt;\"nineteen\";\n break;\n /// No Twenty here.\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T20:08:44.967", "Id": "30526", "ParentId": "30525", "Score": "2" } }, { "body": "<p>I've never tackled such a problem before, so I'll proceed with this cautiously.</p>\n\n<ul>\n<li><p>You don't need to declare those three variables and then assign to them. Instead, initialize them right away where they're first used.</p>\n\n<p>You can also move <code>number</code> right above the <code>cin</code> for slightly closer scope.</p>\n\n<pre><code>std::cout &lt;&lt; \"Enter the number: \";\nint number;\nstd::cin &gt;&gt; number;\nint first_digit = number/10;\nint second_digit = number%10;\n</code></pre></li>\n<li><p>I suppose <code>switch</code> is an okay choice for this program. Either way, the <code>switch</code> can still be condensed while making the program more modular (with functions).</p>\n\n<p>Here's what 11-20 could look like within its own function:</p>\n\n<pre><code>std::string elevenThroughTwenty(unsigned int number)\n{\n switch (number)\n {\n case 11: return \"eleven\";\n // ...\n case 20: return \"twenty\"; // you forgot the 20 in your code\n\n // throw an exception if number not in the switch\n // include &lt;stdexcept&gt; to use this\n default: throw std::logic_error(\"Not 11 through 20\");\n }\n}\n</code></pre>\n\n<p>Separating them as such helps with readability, organization, and conciseness. You will also need proper <code>default</code>s so that invalid numbers don't cause crippling errors.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T20:19:17.853", "Id": "48559", "Score": "0", "body": "Thank you :) but I have a question: what does O(1) mean?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T20:32:30.990", "Id": "48563", "Score": "0", "body": "@mitya221: Constant time. Meaning, one pass no matter what. Example: `arr[7] = 25`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T20:38:01.107", "Id": "48564", "Score": "1", "body": "@Jamal I don't think switches are \"constant time\" in the way that you mean. A switch with N different cases will (I'm pretty sure) generate N different branch statements that the program would proceed through sequentially." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T20:46:43.590", "Id": "48565", "Score": "0", "body": "@alecbenzer: Noted. The OP didn't know what O(1) meant anyway, so I've explained that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T21:15:21.320", "Id": "48566", "Score": "1", "body": "@mitya221: As already brought to my attention, O(1) is not guaranteed here (but my comment still stands). Also, most of the examples I've found on this use arrays. I suppose it doesn't make a huge difference (although still different times), but it's up to you. As for `switch`es in general, I'd at least make them as condensed (but readable) as possible. They can take up much physical space." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-22T21:37:09.750", "Id": "129036", "Score": "0", "body": "Negative values being illegal is not considered a good enough reason to use `unsigned`. See discussion in comments [here](http://codereview.stackexchange.com/questions/70027/given-n-numbers-find-out-the-least-k-numbers-from-them/70031#70031)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-22T21:42:02.373", "Id": "129037", "Score": "0", "body": "@nwp: Fair enough, also given that my `default` would handle incorrect numbers. And this is an older answer, so I was less aware. I'll update." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T20:09:54.407", "Id": "30527", "ParentId": "30525", "Score": "5" } }, { "body": "<p>I would probably make some arrays and do lookups in them instead of using switches: <a href=\"http://ideone.com/44IB0J\" rel=\"nofollow\">http://ideone.com/44IB0J</a></p>\n\n<pre><code>#include &lt;iostream&gt;\n\nusing std::cout;\nusing std::string;\nusing std::endl;\n\nstring toWords(int num) {\n if (num &gt; 100 || num &lt; 1) {\n throw \"unsupported\";\n }\n if (num == 100) {\n return \"one hundred\";\n }\n\n const string kSpecialCases[] = {\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"};\n if (10 &lt;= num &amp;&amp; num &lt;= 19) {\n return kSpecialCases[num - 10];\n }\n\n const string kOnesPlaces[] = {\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"};\n const string kTensPlaces[] = {\"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n if (num &lt; 10) {\n return kOnesPlaces[num - 1];\n } else if (num % 10 == 0) {\n return kTensPlaces[num / 10 - 2];\n } else {\n return kTensPlaces[num / 10 - 2] + \" \" + kOnesPlaces[num % 10 - 1];\n }\n}\n\nint main() {\n cout &lt;&lt; toWords(1) &lt;&lt; endl;\n cout &lt;&lt; toWords(100) &lt;&lt; endl;\n cout &lt;&lt; toWords(12) &lt;&lt; endl;\n cout &lt;&lt; toWords(29) &lt;&lt; endl;\n cout &lt;&lt; toWords(46) &lt;&lt; endl;\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T20:33:21.197", "Id": "30529", "ParentId": "30525", "Score": "3" } }, { "body": "<p>This is how I would do it:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;map&gt;\n\nstd::vector&lt;std::string&gt; const names[]= {{\"\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\",\n \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\" },\n {\"-\", \"-\", \"twenty--\", \"thirty--\", \"forty--\", \"fifty--\", \"sixty--\", \"seventy--\", \"eighty--\", \"ninety--\"}\n };\n\nvoid print(int&amp; count, int unit, int xx, std::string const&amp; units)\n{\n int div = unit * (xx==0?1:10);\n int index = count / div;\n int sub = index * div * (index &gt;=2 ? 1 : 0);\n std::string name = names[xx][index];\n\n if (name[name.size()-1] == '-') {\n name.erase(name.size()-1);\n index = (count-sub)/unit;\n name.append(names[0][index]);\n }\n if (name != \"\") {\n std::cout &lt;&lt; name &lt;&lt; \" \" &lt;&lt; units &lt;&lt; \" \";\n }\n count = count - (count/unit*unit);\n}\nvoid printNumber(int number)\n{\n if (number == 0) {\n std::cout &lt;&lt; \"zero\";\n return;\n }\n print(number, 1000000, 0, \"million\");\n print(number, 100000, 0, \"hundred\");\n print(number, 1000, 1, \"thousand\");\n print(number, 100, 0, \"hundred\");\n print(number, 1, 1, \"\");\n}\nint main()\n{\n int number;\n std::cin &gt;&gt; number;\n printNumber(number);\n std::cout &lt;&lt; \"\\n\";\n}\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>&gt; ./a.out\n845\neight hundred forty-five\n&gt; ./a.out\n999999\nnine hundred ninety-nine thousand nine hundred ninety-nine\n&gt; ./a.out\n1000001\none million one\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T04:31:05.670", "Id": "30544", "ParentId": "30525", "Score": "0" } }, { "body": "<p>Here's my take on the problem making use of recursion. This works for any number between <strong>0</strong> (<strong>zero</strong>) and <strong>999,999,999</strong> (<strong>nine hundred ninety nine million nine hundred ninety nine thousand nine hundred ninety nine</strong>). </p>\n\n<p><em><strong>Note:</strong> Due to making use of initializer lists, this will only work in C++11.</em></p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;iostream&gt;\n#include &lt;stdexcept&gt;\n\nconst std::vector&lt;std::string&gt; first14 = {\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\" };\nconst std::vector&lt;std::string&gt; prefixes = {\"twen\", \"thir\", \"for\", \"fif\", \"six\", \"seven\", \"eigh\", \"nine\"};\n\nstd::string inttostr( const unsigned int number )\n{\n if( number &lt;= 14 )\n return first14.at(number);\n if( number &lt; 20 )\n return prefixes.at(number-12) + \"teen\";\n if( number &lt; 100 ) {\n unsigned int remainder = number - (static_cast&lt;int&gt;(number/10)*10);\n return prefixes.at(number/10-2) + (0 != remainder ? \"ty \" + inttostr(remainder) : \"ty\");\n }\n if( number &lt; 1000 ) {\n unsigned int remainder = number - (static_cast&lt;int&gt;(number/100)*100);\n return first14.at(number/100) + (0 != remainder ? \" hundred \" + inttostr(remainder) : \" hundred\");\n }\n if( number &lt; 1000000 ) {\n unsigned int thousands = static_cast&lt;int&gt;(number/1000);\n unsigned int remainder = number - (thousands*1000);\n return inttostr(thousands) + (0 != remainder ? \" thousand \" + inttostr(remainder) : \" thousand\");\n }\n if( number &lt; 1000000000 ) {\n unsigned int millions = static_cast&lt;int&gt;(number/1000000);\n unsigned int remainder = number - (millions*1000000);\n return inttostr(millions) + (0 != remainder ? \" million \" + inttostr(remainder) : \" million\");\n }\n throw std::out_of_range(\"inttostr() value too large\");\n}\n\nint main()\n{\n try {\n for( int i = 0; i &lt;= 999999999; i++ )\n std::cout &lt;&lt; i &lt;&lt; \" = \" &lt;&lt; inttostr(i) &lt;&lt; std::endl;\n } catch( std::exception&amp; ex ) {\n std::cerr &lt;&lt; \"Error: \" &lt;&lt; ex.what() &lt;&lt; std::endl;\n }\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T06:51:59.243", "Id": "30675", "ParentId": "30525", "Score": "1" } } ]
{ "AcceptedAnswerId": "30527", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T19:35:33.927", "Id": "30525", "Score": "6", "Tags": [ "c++", "algorithm", "numbers-to-words" ], "Title": "Convert number to words" }
30525
<p>I'm a bit clumsy at writing JavaScript. I have some nice code like this:</p> <pre><code>(function($){ $.fn.forceNumeric = function(){ return this.each(function(){ $(this).keyup(function(){ if (!/^[0-9]+$/.test($(this).val())){ $(this).val($(this).val().replace(/[^0-9]/g, '')); } }); }); }; })(jQuery); </code></pre> <p>I know what it does and how it works. I can call the function and I see why it works.</p> <p>For the life of me, I cannot figure out how to use that same elegant style/approach for my Neanderthal function:</p> <pre><code>function showHideErrorBox(theFriendlyName, check){ var topLevelDiv, numDivsAfter; if(check === 0){ // REMOVE THE OLD ERROR MESSAGE IN THE ERROR BOX $('.form-validation-errors').find('div').each(function(){ if( $(this).html().indexOf(theFriendlyName) != -1 ){ $(this).remove(); } }); } // CHECK WHETHER THE ENTIRE MESSAGE BOX CAN BE REMOVED NOW topLevelDiv = document.getElementById('alert-form-errors'); numDivsAfter = topLevelDiv.getElementsByTagName('div').length; if(check === 0){ if(numDivsAfter &lt;= 1){ $('#alert-form-errors').hide(); } }else if(check === 1){ if(numDivsAfter &gt;= 1){ $('#alert-form-errors').show(); } } } </code></pre> <p>Can anyone help me out? Where do I start? I have Google'd for tutorials, but I have not been able to find something suitable for my needs.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:17:58.960", "Id": "48634", "Score": "0", "body": "can you also show the html? there seem to be an awful lot of divs here, I can't quite maek sense of them" } ]
[ { "body": "<p>You could start by minimizing your function calls. like so </p>\n\n<p><strong>ORIGINAL</strong></p>\n\n<pre><code>$.fn.forceNumeric = function(){\n return this.each(function(){\n $(this).keyup(function(){\n if (!/^[0-9]+$/.test($(this).val())){\n $(this).val($(this).val().replace(/[^0-9]/g, ''));\n }\n });\n });\n};\n</code></pre>\n\n<p><strong>OPTIMIZED</strong></p>\n\n<pre><code>$.fn.forceNumeric = function(){\n return this.each(function(){\n $(this).keyup(function(){\n if (!/^[0-9]+$/.test(this.value)){\n this.value = this.value.replace(/[^0-9]/g, '');\n }\n });\n });\n};\n</code></pre>\n\n<blockquote>\n <p>Just in this little bit you have saved on <strong>3</strong> Function calls.</p>\n</blockquote>\n\n<p>And on the larger part.</p>\n\n<p><strong>OPTIMIZED</strong></p>\n\n<pre><code>function showHideErrorBox(theFriendlyName, check){\n var topLevelDiv,\n numDivsAfter;\n\n if(check === 0){\n // REMOVE THE OLD ERROR MESSAGE IN THE ERROR BOX\n $('.form-validation-errors').find('div').each(function() {\n var $this = $(this);\n if( $this.html().indexOf(theFriendlyName) !== -1 ){\n $this.remove();\n }\n });\n }\n\n // CHECK WHETHER THE ENTIRE MESSAGE BOX CAN BE REMOVED NOW\n topLevelDiv = $(document.getElementById('alert-form-errors'));\n numDivsAfter = topLevelDiv[0].getElementsByTagName('div').length;\n\n if(check === 0 &amp;&amp; numDivsAfter &lt;= 1) {\n return topLevelDiv.hide();\n }\n\n if(check === 1 &amp;&amp; numDivsAfter &gt;= 1) {\n return topLevelDiv.show();\n } \n}\n</code></pre>\n\n<blockquote>\n <p>You have also saved on <strong>3</strong> Function calls here too;</p>\n</blockquote>\n\n<p>Just remember that <code>$</code> is a function and it's better to call a function once than twice right? </p>\n\n<p>if you ever have something like this </p>\n\n<pre><code>$(this).show();\n$(this).val('hello');\n$(this).hide();\n</code></pre>\n\n<p>It should be like this</p>\n\n<pre><code>var $this = $(this);\n$this.show()\nthis.value = 'hello';\n$this.hide();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T23:59:29.303", "Id": "48575", "Score": "0", "body": "That's awesome! Thank you for getting me started. I really, really appreciate your help, a ton. Although I will accept your answer, I was wondering if you knew of an example that would let me \"convert\" my showHideErrorBox() function into something that would look like: $.showHideErrorBox = function(){...}?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T00:45:39.990", "Id": "48578", "Score": "0", "body": "You're going to have to explain more than that, because i can't work out how it will work with the selected element. like `$('#something').showHideErrorBox();`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T20:53:18.507", "Id": "30531", "ParentId": "30528", "Score": "2" } }, { "body": "<pre><code>function showHideErrorBox(theFriendlyName, check){\n //remove the old error message in the error box\n if(check === 0){\n $('.form-validation-errors').find('div').each(function(){\n if( $(this).html().indexOf(theFriendlyName) != -1 ){\n $(this).remove();\n }\n });\n }\n\n //check whether the entire message box can be removed now\n var alertErrors = $('#alert-form-errors');\n var numDivsAfter = alertErrors.find('div').length();\n if(check === 0 &amp;&amp; numDivsAfter &lt;= 1){\n alertErrors.hide();\n } else if(check === 1 &amp;&amp; numDivsAfter &gt;= 1){\n alertErrors.show();\n }\n}\n</code></pre>\n\n<ol>\n<li>There's no need to declare the <code>topLevelDiv</code> and <code>numDivsAfter</code> variables all the way at the top of the function. It's good practice to not declare variables until you actually use them.</li>\n<li>Don't use caps excessively in your comments. Caps should be used rarely, for emphasis.</li>\n<li>You should be able to calculate the value for <code>numDivsAfter</code> by using the same <code>find()</code> method you used at the top of the function. Then, instead of calling <code>each()</code>, call <code>length()</code> to get a count of the number of <code>div</code> elements. However, I'm not that well versed in jQuery, so I might be wrong.</li>\n<li>Assign <code>$('#alert-form-errors')</code> to a variable so you don't have to repeat its ID.</li>\n<li>You can combine the if statements at the bottom of the function for greater clarity.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T00:31:02.780", "Id": "48576", "Score": "0", "body": "Thank you very much for your feedback. That's definitely more elegant than what I had. Is there any way you can think of that I could change my showHideErrorBox() function to something like $.fn.showHideErrorBox = function(){...}?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T15:17:10.920", "Id": "48623", "Score": "1", "body": "@ShawnSpencer I don't know enough about jQuery to know what the significance of `$.fn` is. It is possible to assign the function to a variable instead of declaring it as a named function, if you prefer: `var showHideErrorBox = function(theFriendlyName, check){ ... }`. This is (pretty much) the same as declaring a named function, the syntax is just different." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T20:55:56.763", "Id": "30532", "ParentId": "30528", "Score": "1" } }, { "body": "<p>If your intent is to hide an error box, if there are no errors inside: you can do that with css alone.</p>\n\n<pre><code>div:empty {\n display:none;\n}\n</code></pre>\n\n<p>See <a href=\"http://jsfiddle.net/bjelline/D2P3r/\" rel=\"nofollow\">http://jsfiddle.net/bjelline/D2P3r/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T15:20:23.127", "Id": "48783", "Score": "0", "body": "Thank you very much. In this case, however, the box is never entirely empty. There's always one div inside the box that states the obvious (There are errors...) and there could be many other errors in that box. So my function simply looks for a specific error message and removes it when the error has been resolved. There could still be additional errors." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:26:42.903", "Id": "30578", "ParentId": "30528", "Score": "1" } } ]
{ "AcceptedAnswerId": "30531", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T20:14:21.270", "Id": "30528", "Score": "0", "Tags": [ "javascript", "jquery", "validation" ], "Title": "Function to show or hide validation error messages" }
30528
<p>I'm wondering how I could improve my list's element-adding speed or just the whole list implementation.</p> <p>The adding function first checks if the object is unique. If not, it will just check if the new data is better (the lower the value, the better) than the old one, then swap the values or just skip adding an element.</p> <p>I have no idea how to make it work faster, but I know that something here is probably done terribly wrong. I need to use that list to add about 3 million elements in less than 4 seconds.</p> <p><strong>Note:</strong> Using <code>std::string</code> in my project is unfortunately forbidden.</p> <pre><code>#include &lt;iostream&gt; struct node { long shortestRoute; char* name; node *next; node() { next = 0; } }; class List { public: node *first; List() { first = 0 ;} void add(long shortestRoute, char* name) { node *node = new node; node-&gt;name = name; node-&gt;shortestRoute = shortestRoute; if(first == 0) first = node; else { node *temp = first; while(temp) { if(!strcmp(temp-&gt;name, name) &amp;&amp; temp-&gt;shortestRoute &gt; shortestRoute) { temp-&gt;shortestRoute = shortestRoute; return; } else if (!strcmp(temp-&gt;name, name)) return; else if(temp-&gt;next) temp = temp-&gt;next; else break; } temp-&gt;next = node; node-&gt;next = 0; } } int size() { node *temp = first; int size; if(!first) size = 0; else size = 1; while(temp-&gt;next) { ++size; temp = temp-&gt;next; } return size; } }; struct City { City() { fastConnection = true; } int shortestRoute; char* name; Vector&lt;char*&gt; citiesSoFar; bool fastConnection; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T21:23:38.823", "Id": "48567", "Score": "0", "body": "If this is C++ and not C, shouldn't you be using `std::string` instead of `char*`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T21:26:31.667", "Id": "48568", "Score": "0", "body": "Using std::string in my project is unfortunately forbidden." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T21:36:23.570", "Id": "48571", "Score": "1", "body": "Ah. That's unfortunate. On another note: `struct node` should be within `List` as `private`. The nodes belong to the list and shouldn't be exposed to the public." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T21:45:54.480", "Id": "48572", "Score": "0", "body": "Is `Vector` from your own implementation or a typo from `std::vector`? The capitalization confuses me, coupled with the assumption that all STL containers are forbidden." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T22:11:04.143", "Id": "48573", "Score": "2", "body": "Are you trying to implement Dijkstra's algorithm with your own classes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T22:40:28.243", "Id": "48574", "Score": "0", "body": "Yes, exactly Loki Astari. And yes this vector is also mine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T05:22:24.827", "Id": "48602", "Score": "2", "body": "It would be much easier to implement with standard containers (and probably more efficient). The priority queue provided by the standard can maintain an ordered container with only O(ln(n)) insert complexity (much better than you would do manually (unless you are very good) and using a list the best you can do is O(n))." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T05:59:33.377", "Id": "48753", "Score": "0", "body": "size() dereferences a null pointer in the case that first is null; if (!first) should return 0 rather than setting size to 0." } ]
[ { "body": "<ul>\n<li>Are you suppose to add elements to an empty list? If you are adding to an empty list, then you can add them in ascending order or descending order. </li>\n<li>The problem you have is that you will be adding unknown element to the list i.e it could be &lt; or == or > than this element. In this case, even if you order the list, you just cannot add a new element to the end of list or at the head. You will have to traverse the list to see if this element is greater the ith element.</li>\n<li>So adding would take O(n) as the worst case. Because you are adding the element to the end of the list. If ordering matters.</li>\n<li><p>The larger the list, the more time it will take to add an element.</p></li>\n<li><p>I suggest adding elements to the list in an order. Example, add 1 first, then add 2, then add 3, then add 4 etc. If you can add them in that order, you will only be adding elements to the end of the list which takes O(1).</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T03:50:31.660", "Id": "30670", "ParentId": "30533", "Score": "1" } }, { "body": "<p>One small suggestion in your <code>size()</code> function.:</p>\n\n<pre><code>int size()\n{\n node *temp = first;\n // Initialize size so you don't have to worry about first == 0\n int size = 0;\n // Makes no sense to execute while if (first == 0)\n // so move it inside the if condition\n if(first)\n {\n size = 1;\n while(temp-&gt;next)\n {\n ++size;\n temp = temp-&gt;next;\n }\n }\n return size;\n}\n</code></pre>\n\n<hr>\n\n<p>Also, you may choose to have different names for the <code>size()</code> function and the local variable <code>size</code>, just to avoid confusion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T16:06:46.263", "Id": "48784", "Score": "1", "body": "I'd also make `size` and `size()`'s types `std::size_t`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T06:39:00.760", "Id": "30674", "ParentId": "30533", "Score": "2" } }, { "body": "<ol>\n<li><p>Maintain an inner hash table to look up name duplicates. O(1)</p>\n\n<p>a. char *name => long shortestRoute </p></li>\n<li><p>Don't instantiate (<code>new *node</code>) until absolutely necessary.</p></li>\n</ol>\n\n<p>Should be all that is needed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T08:02:41.710", "Id": "30679", "ParentId": "30533", "Score": "1" } }, { "body": "<p>If I understand correctly, you wish to maintain a list of places, and record only the shortest route to each place. This means that each time you need to find any duplicate entry, and choose which to keep.</p>\n\n<p>For this task, an unordered list is pretty much the worst choice you could use. Your algorithm is O(n<sup>2</sup>) (that is, O(n) for adding each of <code>n</code> elements), and while that isn't important for 10 destinations, it's pretty critical for 3 million!</p>\n\n<p>Given that ordering is not critical here, a <a href=\"http://en.wikipedia.org/wiki/Hash_table\" rel=\"nofollow\">hash table</a> is really the correct implementation to use. This will get you O(1) insert and lookup, and the added programming complexity and memory use is appropriate for that number of elements. If that's not possible somehow, then second best would be some kind of <a href=\"http://en.wikipedia.org/wiki/Balanced_tree\" rel=\"nofollow\">self-balancing tree</a>. </p>\n\n<p>Finally, it makes no sense to count the length of a large list by iterating the elements. Just increment a counter every time you add an element. A reduction from O(n) to O(1). (In theory, if you add and destroy a lot of elements very frequently, but only query the size once in a blue moon, then my statement is untrue, but I doubt that's the case here.)</p>\n\n<p>As far as your existing implementation goes, it's a bad plan to create the new node and then not use it. Maybe in your implementation a garbage collector will sort it out, but otherwise it'll be a huge memory leak, not to mention wasted effort.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T10:00:09.853", "Id": "30685", "ParentId": "30533", "Score": "3" } } ]
{ "AcceptedAnswerId": "30685", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T20:57:06.163", "Id": "30533", "Score": "4", "Tags": [ "c++", "optimization", "linked-list" ], "Title": "How to improve my list's speed" }
30533
<p>I am learning C and tried to make a basic singly linked list. I am looking for some feedback on my implementation. I have implemented deletion and reversal functions. Be hard on me as I am trying to improve.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; //very basic linked list implimentation in C. //basic node structure. No typedef. struct node { int val; struct node *next; }; struct node *deleteNode(struct node *first, int num) { struct node *prev=NULL; struct node *root = first; while (root != NULL) { if (root-&gt;val == num) { if (prev != NULL &amp;&amp; root-&gt;next != NULL) //middle elements { prev-&gt;next = root -&gt; next; free(root); } else if (prev == NULL) //first element { free(first); first = root-&gt;next; root = root-&gt;next; } else if (root-&gt;next == NULL) //last element { prev-&gt;next = NULL; free(root); } } prev = root; root = root -&gt; next; } return first; } struct node *reverseList(struct node *root) { struct node *temp= NULL; struct node *prev= NULL; while (root!= NULL) { temp = root-&gt;next; root-&gt;next = prev; prev = root; root = temp; } return prev; } void printList(struct node *root) { while (root!= NULL) { printf("Value: %d\n", root -&gt; val); root = root -&gt; next; } } int main() { struct node *root = NULL, *tail = NULL; int i=1; for (;i&lt;=20; ++i) { struct node *current = malloc(sizeof(struct node)); current -&gt; val = i; current -&gt; next = NULL; if (root==NULL) root = current; else tail -&gt; next = current; tail = current; } //delete first,last and middle element root = deleteNode(root, 20); root = deleteNode(root, 1); root = deleteNode(root, 10); root = reverseList(root); printList(root); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T22:38:42.977", "Id": "48987", "Score": "0", "body": "Your current `deleteNodes` is wrong. What happens if the first two elements are to be deleted?" } ]
[ { "body": "<p>I suggest using this declaration:</p>\n\n<pre><code>typedef struct _node {\n int val;\n struct _node *next;\n} node;\n</code></pre>\n\n<p>After that, you can declare <code>node *t</code> instead of <code>struct node *t</code>. Also, you'll use <code>sizeof(node)</code> instead of <code>sizeof(struct node)</code>.</p>\n\n<p>Your <code>delete</code> is buggy. I'll quote just a bit:</p>\n\n<pre><code>struct node *deleteNode(struct node *first, int num)\n{\n struct node *prev=NULL;\n struct node *root = first;\n while (root != NULL)\n {\n if (root-&gt;val == num)\n {\n ...\n else if (prev == NULL) //first element\n {\n free(first);\n first = root-&gt;next;\n root = root-&gt;next;\n }\n ...\n }\n ...\n }\n return first;\n}\n</code></pre>\n\n<p>So, you have <code>root = first</code>, then you free the memory of <code>first</code>, and then you access <code>root-&gt;next</code> which is the same as <code>first-&gt;next</code>, which is a value contained in the already freed memory.</p>\n\n<p>I'd write it in two parts:</p>\n\n<ol>\n<li><p>Delete all there is to be deleted from the list start.</p></li>\n<li><p>Delete all there is to be deleted, but is not at the list start.</p></li>\n</ol>\n\n<p>Like this:</p>\n\n<pre><code>node *deleteNodes(node *first, int num) {\n node *prev, *active;\n\n while (first &amp;&amp; first-&gt;val == num) {\n node *tmp = first;\n first = first-&gt;next;\n free(tmp);\n }\n\n if (!first) return NULL;\n\n prev = first;\n active = first-&gt;next;\n\n while (active)\n if (active-&gt;val == num) {\n prev-&gt;next = active-&gt;next;\n free(active);\n active = prev-&gt;next;\n } else {\n prev = active;\n active = active-&gt;next;\n }\n\n return first;\n}\n</code></pre>\n\n<p>I have changed the name of the function because you seem to want to remove <strong>all</strong> the nodes containing the value <code>num</code>.</p>\n\n<p>A matter of personal choice: I prefer to transverse through a list the same way I do with arrays -- by using a <code>for</code> loop.</p>\n\n<pre><code>void printList(node *root) {\n node *t;\n for (t = root; t; t = t-&gt;next)\n printf(\"Value: %d\\n\", t-&gt;val);\n}\n</code></pre>\n\n<p>If you really want to reuse <code>root</code>, you can, but one or few additional variables (like my <code>t</code> (stands for \"<b>t</b>emporary\") in the above code) can make your code much more readable.</p>\n\n<p>It may be useful to finish void functions with <code>return;</code>, as it helps you detect certain problems in code (i.e., if you change the return value to something else, such <code>return</code> will result in error and warn you to fix it).</p>\n\n<p>This</p>\n\n<pre><code>node *current = malloc(sizeof(node));\n</code></pre>\n\n<p>can be written like this like this:</p>\n\n<pre><code>node *current = (node*)malloc(sizeof(node));\n</code></pre>\n\n<p>Read about using such a cast <a href=\"http://en.wikipedia.org/wiki/C_dynamic_memory_allocation#Type_safety\" rel=\"nofollow\">here</a> and decide for yourself. I prefer to use it.</p>\n\n<p>You should always release all your memory (i.e., delete the remaining list) when you program ends, instead of relying on the OS to do it properly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T01:39:49.677", "Id": "48683", "Score": "0", "body": "I disagree about casting `malloc` - see the disadvantages section of the link you gave. I always add a comment that such casts as wrong when reviewing code. On `++i` vs `i++`, the issue comes from C++ where with non-built-in types `++i` is faster than `i++` because no temporary object is created. For C (and for built-in types in C++) I believe it makes no difference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T09:21:20.580", "Id": "48715", "Score": "0", "body": "For cast, I said it can be done, and I gave a reference so that the OP can chose for himself. I prefer it with cast (and I know the disadvantages), but I don't claim that everyone should. As for `++`, it made perfect sense to me that `++i` is faster, so I've been using it for quite a while, but then I've switched. I remember it being for the speed, but I've retested it now, and the two seem to be of an equal speed, at least on my machines, so I'll remove that part of the answer. Thank you." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T00:18:06.170", "Id": "30541", "ParentId": "30536", "Score": "2" } }, { "body": "<p>you can make the list more generic by using <code>void * val</code> and taking a pointer to a comparison function as argument of the deleting function (check out qsort from the standard library to see how it works)</p>\n\n<p>like so:</p>\n\n<pre><code>typedef struct node {\n void * val;\n struct node *next;\n} node;\n\nstruct node *deleteNode(struct node * first, \n void * val_to_delete, \n int (*cmp)(const void *, const void*))\n</code></pre>\n\n<p>where cmp is user-defined function that takes to void pointers, casts them to the actual type used and compares them. this way you can store and delete any value (e.g. another list) as a value.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T02:25:16.373", "Id": "30542", "ParentId": "30536", "Score": "0" } }, { "body": "<p>A few comments: </p>\n\n<ul>\n<li>It is generally considered best practice to define one variable per line.</li>\n<li>Be consistent with variable names (eg <code>tmp</code> and <code>temp</code>, <code>root</code> and <code>first</code>)</li>\n<li><p>Use <code>const</code> and <code>static</code> where possible (eg <code>printList</code> should have a\n<code>const</code> parameter</p></li>\n<li><p>Your <code>delete_list</code> fails if <code>first</code> is NULL (tries to free <code>tmp</code>). Define\n<code>tmp</code> inside the loop where it is first used.</p></li>\n</ul>\n\n<hr>\n\n<p>Your <code>deleteNodes</code> (derived from the answer from @VedranŠego) is still too\ncomplicated and you introduce a fault by omitting the answer's check <code>if\n(!first) return NULL;</code> </p>\n\n<p>And easier solution is this:</p>\n\n<pre><code>static struct node *deleteNodes (struct node *n, int num)\n{\n struct node start = {.next = n};\n struct node *prev = &amp;start;\n\n while (n) {\n if (n-&gt;val == num) {\n prev-&gt;next = n-&gt;next;\n free(n);\n n = prev-&gt;next;\n } else {\n prev = n;\n n = n-&gt;next;\n }\n }\n return start.next;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T13:56:13.770", "Id": "30614", "ParentId": "30536", "Score": "0" } } ]
{ "AcceptedAnswerId": "30541", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T22:42:15.667", "Id": "30536", "Score": "5", "Tags": [ "c", "linked-list" ], "Title": "Simple linked list implementation" }
30536
<p>Any reviews/ways to speed up/general improvements for my Merge Sort? Maybe something to simplify it or add more to it?</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace prjT02L08_Predator_Prey { abstract class MergeSort { public static List&lt;Node&gt; Sort(List&lt;Node&gt; input) { List&lt;Node&gt; Result = new List&lt;Node&gt;(); List&lt;Node&gt; Left = new List&lt;Node&gt;(); List&lt;Node&gt; Right = new List&lt;Node&gt;(); if (input.Count &lt;= 1) return input; int midpoint = input.Count / 2; for (int i = 0; i &lt; midpoint; i++) Left.Add(input[i]); for (int i = midpoint; i &lt; input.Count; i++) Right.Add(input[i]); Left = Sort(Left); //Recursion! :o Right = Sort(Right); Result = Merge(Left, Right); return Result; } private static List&lt;Node&gt; Merge(List&lt;Node&gt; Left, List&lt;Node&gt; Right) { List&lt;Node&gt; Result = new List&lt;Node&gt;(); while (Left.Count &gt; 0 &amp;&amp; Right.Count &gt; 0) { if (Left[0].F &lt; Right[0].F) { Result.Add(Left[0]); Left.RemoveAt(0); } else { Result.Add(Right[0]); Right.RemoveAt(0); } } while (Left.Count &gt; 0) { Result.Add(Left[0]); Left.RemoveAt(0); } while (Right.Count &gt; 0) { Result.Add(Right[0]); Right.RemoveAt(0); } return Result; } } } </code></pre>
[]
[ { "body": "<pre><code>abstract class MergeSort\n</code></pre>\n\n<p>This class shouldn't be <code>abstract</code>, it should be <code>static</code>.</p>\n\n<pre><code>public static List&lt;Node&gt; Sort(List&lt;Node&gt; input)\n</code></pre>\n\n<p>Why does the method require <code>List</code>? Wouldn't it be better if it accepted any <code>IList</code> (or <code>IReadOnlyList</code> if you're on .Net 4.5)? Also, it would make sense to make your code generic, so that it would work on types other than <code>Node</code>.</p>\n\n<pre><code>List&lt;Node&gt; Result = new List&lt;Node&gt;();\n</code></pre>\n\n<p>The usual convention in C# is to name local variables in camelCase, not PascalCase.</p>\n\n<pre><code>return input;\n</code></pre>\n\n<p>Returning the input might be unexpected. If you don't want to change it, you should clearly document it.</p>\n\n<pre><code>Left.RemoveAt(0);\n</code></pre>\n\n<p>This is very inefficient operation for a <code>List</code>. Either use a collection that can do this efficiently (like <code>LinkedList</code> or <code>Queue</code>) or, even better, just use indexes instead of modifying the collection.</p>\n\n<hr>\n\n<p>Your code also does a lot of copying and creating new lists. That's good for readability, but if you want your code to be fast, you need just two lists that you can modify.</p>\n\n<p>You would need to work with sublists (list, start index, length), not whole lists. First, merge the 1-element sublists from list A to list B, then merge the 2-element sublists from B to A, etc.</p>\n\n<p>Also, another optimization is not to start with 1-element sublists, but take advantage of the fast that there are likely to be some sorted sublists in the input already. This is especially effective if the input is already sorted (or mostly sorted). But I think it wouldn't work with your recursive approach.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T04:11:15.740", "Id": "48691", "Score": "0", "body": "Can I ask why to use IList? I'm not really sure how using an interface is better? I've never had any experience with one before" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T11:04:18.847", "Id": "48717", "Score": "2", "body": "@ShivamMalhotra For parameters, it means the users of your class have more choices when deciding which collection to use. For thew return type, it means you can change the returned collection without doing a breaking change. So, in both cases, it is about larger flexibility." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T11:07:52.920", "Id": "30556", "ParentId": "30545", "Score": "5" } }, { "body": "<p>Here we go. First, the class has no need to be <code>abstract</code> as it has no inheritable members. In fact, since it has all <code>static</code> members, the class should also be <code>static</code>. Also followed C# naming conventions, in which local variables should be <code>camelCased</code> rather than the <code>PascalCased</code> you have. Used some LINQ to declare intent rather than implementation by using <code>.Any()</code> in a few places. Also re-declared <code>List&lt;Node&gt;</code> throughout as <code>IList&lt;Node&gt;</code> since programming to interfaces is better for decoupling. For that matter, wherever <code>Node</code> lives, may want to extract an <code>INode</code> interface from it and use it here. Finally, a tiny performance improvement: don't allocate the lists until after the base case has been evaluated (and returned from) so the GC doesn't have as much pressure on it.</p>\n\n<pre><code>namespace prjT02L08_Predator_Prey\n{\n using System.Collections.Generic;\n using System.Linq;\n\n public static class MergeSort\n {\n public static IList&lt;Node&gt; Sort(IList&lt;Node&gt; input)\n {\n if (input.Count &lt;= 1)\n {\n return input;\n }\n\n var midpoint = input.Count / 2;\n IList&lt;Node&gt; left = new List&lt;Node&gt;();\n IList&lt;Node&gt; right = new List&lt;Node&gt;();\n\n for (var i = 0; i &lt; midpoint; i++)\n {\n left.Add(input[i]);\n }\n\n for (var i = midpoint; i &lt; input.Count; i++)\n {\n right.Add(input[i]);\n }\n\n left = Sort(left); // Recursion! :o\n right = Sort(right);\n\n return Merge(left, right);\n }\n\n private static IList&lt;Node&gt; Merge(IList&lt;Node&gt; left, IList&lt;Node&gt; right)\n {\n var result = new List&lt;Node&gt;();\n\n while (left.Any() &amp;&amp; right.Any())\n {\n if (left[0].F &lt; right[0].F)\n {\n result.Add(left[0]);\n left.RemoveAt(0);\n }\n else\n {\n result.Add(right[0]);\n right.RemoveAt(0);\n }\n }\n\n while (left.Any())\n {\n result.Add(left[0]);\n left.RemoveAt(0);\n }\n\n while (right.Any())\n {\n result.Add(right[0]);\n right.RemoveAt(0);\n }\n\n return result;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T04:11:53.400", "Id": "48692", "Score": "0", "body": "Can I ask why to use IList? I'm not really sure how using an interface is better? I've never had any experience with one before" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T12:39:24.607", "Id": "48719", "Score": "0", "body": "Developing to interfaces is a hallmark of object-oriented development as different implementations of that interface can be passed into your methods, or, even better, mocked versions of that interface can be used as invariants for unit testing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-02T05:20:30.087", "Id": "149134", "Score": "0", "body": "@ShivamMalhotra: Particularly, you can pass both `List` and `Array` and it will work equally for both. Otherwise you can't without any real reason for it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-09T08:01:51.213", "Id": "169173", "Score": "0", "body": "Aren't you a lot better of using indices in the merge method instead of using removeAt for everything? A removeAt is a lot more performance intensive than just incrementing an index and going from there..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-09T12:46:54.613", "Id": "169202", "Score": "0", "body": "@ToonCasteele that's a part of the OP's code that I hadn't addressed as part of my answer. You should post an answer with a focus on performance improvements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-28T20:23:34.430", "Id": "200610", "Score": "0", "body": "-1 for using RemoveAt() for no reason, just use indexes" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-28T20:27:47.153", "Id": "200611", "Score": "0", "body": "@BrianOgden no reason, like, maybe, it was that way in the OP's code and that wasn't what I was addressing in my answer? Like I said two comments up?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T14:17:31.503", "Id": "30562", "ParentId": "30545", "Score": "3" } }, { "body": "<p>Just focussing on your Merge method here, since I felt like using it to merge 2 Lists of objects I had, you should note that using <code>RemoveAt</code>is really horrible performance wise. Especially at index 0. What the list has to do in that case is move the index of every object behind that one, down by 1. This is needless and will cause your method to be really slow for big collections (easily noticable when merging 2 lists of 10 000 items or more).</p>\n\n<p>Just use indices on both list and iterate through them like you would with a for loop, instead of removing each item you covered from the list:</p>\n\n<pre><code>private static List&lt;Node&gt; Merge(List&lt;Node&gt; Left, List&lt;Node&gt; Right)\n{\n List&lt;Node&gt; Result = new List&lt;Node&gt;();\n int leftIndex = 0;\n int rightIndex = 0;\n while (Left.Count &gt; leftIndex &amp;&amp; Right.Count &gt; rightIndex )\n {\n if (Left[leftIndex].F &lt; Right[rightIndex].F)\n {\n Result.Add(Left[leftIndex]);\n leftIndex++;\n }\n else\n {\n Result.Add(Right[rightIndex]);\n rightIndex++;\n }\n }\n\n while (Left.Count &gt; leftIndex)\n {\n Result.Add(Left[leftIndex]);\n leftIndex++;\n }\n\n while (Right.Count &gt; rightIndex)\n {\n Result.Add(Right[rightIndex]);\n rightIndex++;\n }\n\n return Result;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-09T12:56:02.927", "Id": "93092", "ParentId": "30545", "Score": "3" } } ]
{ "AcceptedAnswerId": "30556", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T04:34:28.613", "Id": "30545", "Score": "5", "Tags": [ "c#", "performance", "recursion", "sorting", "mergesort" ], "Title": "Merge Sort Implementation" }
30545
<p>I wrote this pretty simple program (it's an exercise from a book). It counts the words in a simple string. The book is a very old one (I think it's from 2003) and uses char arrays. Because of this, I don't know if this solution is a proper one or not.</p> <p>Can you tell me whether it is okay or not? </p> <pre><code>#include &lt;iostream&gt; int main() { int count_words(std::string); std::string input_text; std::cout&lt;&lt; "Enter a text: "; std::getline(std::cin,input_text); std::cout &lt;&lt; "Number of words: " &lt;&lt; count_words(input_text) &lt;&lt; std::endl; return 0; } int count_words(std::string input_text) { int number_of_words = 1; for(int i = 0; i &lt; input_text.length();i++) if(input_text[i] == ' ') number_of_words++; return number_of_words; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T16:47:48.790", "Id": "48628", "Score": "0", "body": "If you enter multiple spaces each will register as a word Try: 'A B C' (note two spaces between words). This will return 5. Its an OK algorithm to start with as long as they then proceed to teach you more." } ]
[ { "body": "<p>I am far from an expert in C++ but I am going to give this a shot.</p>\n\n<pre><code>int count_words(std::string);\n</code></pre>\n\n<p>you have this declared inside of the main() function. This is a function prototype and should be outside of the main function ex:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nint count_words(std::string);\n\nint main()\n{\n std::string input_text;\n</code></pre>\n\n<p>In the count_words function, if somehow a user entered a string with 0 words in it, the function would return 1 which would be incorrect. A solution to this is to check if the string is empty, and if it is, we can return 0. There are a few ways to do this, but I think this way makes sense here:</p>\n\n<pre><code>if (input_text.empty()) return 0;\n</code></pre>\n\n<p>Keep in mind that we are not really counting the number of words in the string with this function, we are simply counting the number of spaces and hoping that the number of spaces plus 1 is equal to the number of words. This will be fine for most text but will fail on example strings such as:</p>\n\n<pre><code>this will return SEVEN\n</code></pre>\n\n<p>Just something to keep in mind. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T16:51:43.887", "Id": "48631", "Score": "0", "body": "Nothing wrong with forward declaring inside a function." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T07:16:27.467", "Id": "30550", "ParentId": "30547", "Score": "6" } }, { "body": "<ul>\n<li><p>Prefer <a href=\"http://en.cppreference.com/w/cpp/types/size_t\" rel=\"nofollow noreferrer\"><code>std::size_t</code></a> for the word count and <code>count_words()</code>'s return type. Also prefer <a href=\"https://stackoverflow.com/questions/409348/iteration-over-vector-in-c/409396#409396\"><code>std::string::size_type</code> for the loop counter</a> (when using indices is needed).</p></li>\n<li><p><code>count_words()</code>'s parameter should be passed by <code>const&amp;</code> since it's not being modified:</p>\n\n<pre><code>std::size_t count_words(std::string const&amp; input_text) {}\n</code></pre></li>\n<li><p><code>count_words()</code> has a problem. If I press <kbd>ENTER</kbd> without typing anything, it gives me 1. To fix this, return 0 if the string is empty:</p>\n\n<pre><code>if (input_text.empty()) return 0;\n</code></pre></li>\n<li><p>In the <code>for</code>-loop, prefer <a href=\"http://en.cppreference.com/w/cpp/string/byte/isspace\" rel=\"nofollow noreferrer\"><code>std::isspace</code></a> for detecting whitespace.</p></li>\n<li><p>Prefer iterators over indices for <code>std::string</code>:</p>\n\n<pre><code>for (auto iter = input_text.cbegin(); iter != input_text.cend(); ++iter)\n{\n if (*iter == isspace)\n {\n number_of_words++;\n }\n}\n</code></pre>\n\n<p>If you have C++11, use this <a href=\"http://www.cprogramming.com/c++11/c++11-ranged-for-loop.html\" rel=\"nofollow noreferrer\">range-based <code>for</code>-loop</a> instead:</p>\n\n<pre><code>for (auto&amp; iter : input_text)\n{\n if (iter == isspace)\n {\n number_of_words++;\n }\n}\n</code></pre></li>\n<li><p>As @r-s mentions, this just counts whitespace. Here's another solution from <a href=\"https://stackoverflow.com/questions/3672234/c-function-to-count-all-the-words-in-a-string/3672259#3672259\">this answer</a>:</p>\n\n<pre><code>unsigned int countWordsInString(std::string const&amp; str)\n{\n std::stringstream stream(str);\n return std::distance(std::istream_iterator&lt;std::string&gt;(stream), std::istream_iterator&lt;std::string&gt;());\n}\n</code></pre>\n\n<p>I realize this may be difficult to understand. I'd still recommend holding onto the answer for future reference. If you want to try it out, include <code>&lt;sstream&gt;</code> and <code>&lt;iterator&gt;</code>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T07:25:30.723", "Id": "48604", "Score": "0", "body": "thanks :) I have some questions :)\nWhich is better? Using function prototypes or putting the whole function under the main()?\nI should always use std::size_t when I only need positive values? Is it better then unsigned int e.g?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T07:30:08.710", "Id": "48605", "Score": "0", "body": "It's better to use function prototypes (above main) and use functions. OR, put main at the very bottom and you won't need the prototypes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T07:32:00.797", "Id": "48606", "Score": "0", "body": "Any unsigned type is preferred when only using positive numbers. So, both of them work for that. Here's a more specific definition of `std::size_t`: http://www.cplusplus.com/reference/cstddef/size_t/." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T07:32:13.750", "Id": "48607", "Score": "0", "body": "thanks :D \nactually my question was wrong (I meant above main) but I thing you understood it :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T07:33:46.850", "Id": "48608", "Score": "0", "body": "You're welcome! Again, I'll continue to look into the last point I mentioned." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T16:48:41.903", "Id": "48629", "Score": "0", "body": "Forward declaring functions inside a function is perfectly valid." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T16:51:03.943", "Id": "48630", "Score": "0", "body": "Your std::distance technique is just as bad as the original. You are using an inexact algorithm for determining words. You can not say that one is better than the other. They are just different techniques." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T16:54:21.077", "Id": "48632", "Score": "0", "body": "@LokiAstari: Oh, okay. I've never seen it done that way." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T07:16:55.483", "Id": "30551", "ParentId": "30547", "Score": "12" } }, { "body": "<p>A few more points:</p>\n\n<p>You are using <code>std::string</code>, and hence should have an <code>#include &lt;string&gt;</code>. <code>&lt;iostream&gt;</code> pulls it in for you in this case, but it's bad to rely on such behaviour.</p>\n\n<p>Likely this is done as a learning exercise. When you get more comfortable with C++, it's good to look into what the algorithms that are part of the C++ standard library can provide you with. In fact, <code>std::string</code> is a <em>sequence</em>, and it exposes <em>iterators</em>. This means that just about every standard algorithm can be used with it. In this case, there is an algorithm for counting: <code>std::count</code> and <code>std::count_if</code>. Using these with <code>std::isspace</code> can make your code both readable and succinct:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;cctype&gt;\n\nstd::size_t count_words(const std::string&amp; str)\n{\n return std::count_if(str.begin(), str.end(), std::isspace);\n}\n</code></pre>\n\n<p>In fact, with the point above that any white space that sits together will be counted as an extra word, you can get quite fancy with the standard algorithms to fix this:</p>\n\n<pre><code>std::size_t count_words(const std::string&amp; str)\n{\n std::string copy_(str);\n copy_.erase(std::unique(copy_.begin(), copy_.end(), \n [](char a, char b) \n { return isspace(a) &amp;&amp; isspace(b); }),\n copy_.end());\n return std::count_if(copy_.begin(), copy_.end(), std::isspace);\n}\n</code></pre>\n\n<p>This is all probably quite mysterious for the moment, but hopefully your book will start guiding you into how to use the standard algorithms to simplify your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T16:55:34.510", "Id": "48633", "Score": "0", "body": "std::distance() and reading words seems more logical. As it reads the input by words. If you want to be exact you just need to convert punctuation to space (this can be done via local rather than modifying the input text)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T05:44:51.357", "Id": "48703", "Score": "0", "body": "I'm not sure if I'd call it more *logical* - more performant, perhaps (I realise my solution does a reasonable amount of copying and 2 passes over the string). You can certainly pass a different lambda/function/functor to `count_if` to deal with punctuation." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T08:12:57.030", "Id": "30552", "ParentId": "30547", "Score": "4" } }, { "body": "<p>One complication might be that if you put a whole bunch of spaces between your words then that increases the word count each time, so \" microwave \" is three words. Also \"hello\\nworld\" is counted as one word. Should \"phase-change\" be one word or two?</p>\n\n<p>How about detecting the boundaries between word and not-word?</p>\n\n<pre><code> unsigned number_of_words = 0;\n previous_char_was_word_character = false;\n\n for(...)\n {\n word_character = is_word_character(input_text[i]);\n\n if(word_character &amp;&amp; !previous_char_was_word_character)\n {\n number_of_words++;\n }\n\n previous_char_was_word_character = word_character;\n }\n</code></pre>\n\n<p>As to the definition of what characters count as being \"in a word\", that's a matter of opinion. </p>\n\n<p>One way of demonstrating this is to consider what happens when you use the ctrl+&larr; and ctrl+&rarr; keys to move back and forth a word in different word-processors.</p>\n\n<p>For example, AbiWord, and LibreOffice count <strong><code>previous_char_was_word_character</code></strong> as 9 words (stopping at the beginning and end of each underscore). GEdit and the Firefox textarea count it as 5 words. Windows' Notepad probably counts it as 1 word. If you used Perl's <strong><code>\\w</code></strong> regular expression to detect, then it would count as 1 word.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:36:47.433", "Id": "48636", "Score": "1", "body": "Good algorithm for checking if it is a word." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T13:41:36.250", "Id": "30561", "ParentId": "30547", "Score": "3" } }, { "body": "<p>The easy way to do it (in steps)</p>\n\n<p>The std::istream_iterator&lt;X&gt; reads <code>X</code> from a stream using <code>operator&gt;&gt;</code>.<br>\nIf <code>X</code> is <code>std::string</code> then it reads one white space separated word from the stream.</p>\n\n<pre><code>std::string words = /* You fill it somehow (maybe getline()) */;\nstd::stringstream wordstream(words);\n\nstd::size_t wordCount = 0;\nfor(auto loop = std::istream_iterator&lt;std::string&gt;(wordstream) != std::istream_iterator&lt;std::string&gt;(); ++loop)\n{\n ++wordCount;\n}\n</code></pre>\n\n<p>Since we are using a loop we can say lets try and use a standard algorithm. This case we are just measuring the number of items from beginning to end of the stream so the easy one to use is <code>std::distance()</code>. In this case the loop can be replaced like this:</p>\n\n<pre><code>std::string words = /* You fill it somehow (maybe getline()) */;\nstd::stringstream wordstream(words);\n\nstd::size_t wordCount = std::distance(std::istream_iterator&lt;std::string&gt;(wordstream),\n std::istream_iterator&lt;std::string&gt;());\n</code></pre>\n\n<p>But hold on.<br>\nThe <code>operator&gt;&gt;</code> only counts white space as word separators. But if we had a real line. There may be other punctuation on the line\"</p>\n\n<blockquote>\n <p>I have,bad,punctuation in this line.</p>\n</blockquote>\n\n<p>This would result in 5 words:</p>\n\n<pre><code>I\nhave,bad,punctuation\nin\nthis\nline.\n</code></pre>\n\n<p>So what you need to do is imbue the stream with information about how to break a word. In this case we will just turn all punctuation into white space.</p>\n\n<pre><code>#include &lt;locale&gt;\n#include &lt;string&gt;\n#include &lt;sstream&gt;\n#include &lt;iostream&gt;\n\n// This is my facet that will treat the ,.- as space characters and thus ignore them.\nclass WordSplitterFacet: public std::ctype&lt;char&gt;\n{\n public:\n typedef std::ctype&lt;char&gt; base;\n typedef base::char_type char_type;\n\n WordSplitterFacet(std::locale const&amp; l)\n : base(table)\n {\n std::ctype&lt;char&gt; const&amp; defaultCType = std::use_facet&lt;std::ctype&lt;char&gt; &gt;(l);\n\n // Copy the default value from the provided locale\n static char data[256];\n for(int loop = 0;loop &lt; 256;++loop) { data[loop] = loop;}\n defaultCType.is(data, data+256, table);\n\n // Modifications to default to include extra space types.\n table[','] |= base::space;\n table['.'] |= base::space;\n table['-'] |= base::space;\n // Add more punctuation here.\n }\n private:\n base::mask table[256];\n};\n</code></pre>\n\n<p>Now you code becomes:</p>\n\n<pre><code>std::string words = /* You fill it somehow (maybe getline()) */;\nstd::stringstream wordstream;\nwordstream.imbue(std::locale(std::locale(), new WordSplitterFacet(std::locale())));\nwordstream &lt;&lt; words;\n\nstd::size_t wordCount = std::distance(std::istream_iterator&lt;std::string&gt;(wordstream),\n std::istream_iterator&lt;std::string&gt;());\n</code></pre>\n\n<p>I would take this a step further.<br>\nI would create a class that wraps the string stream and does the imbue for you:</p>\n\n<pre><code>class RealWordStream: public std::stringstream\n{\n RealWordStream(std::string const&amp; input)\n {\n imbue(std::locale(std::locale(), new WordSplitterFacet(std::locale())));\n (*this) &lt;&lt; words;\n }\n};\n</code></pre>\n\n<p>Now Your code returns to the simpler looking:</p>\n\n<pre><code>std::string words = /* You fill it somehow (maybe getline()) */;\nRealWordStream wordstream(words);\n\nstd::size_t wordCount = std::distance(std::istream_iterator&lt;std::string&gt;(wordstream),\n std::istream_iterator&lt;std::string&gt;());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:35:56.097", "Id": "48635", "Score": "0", "body": "This is quite a lot of boilerplate just to change characters. Is there a way to make it shorter?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:42:36.880", "Id": "48638", "Score": "0", "body": "@busy_wait: If you mean the `WordSplitterFacet`, then not that I know. But modifying the facets is a very rare operation. Write this once put it in a library ready for re-use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:45:35.230", "Id": "48639", "Score": "0", "body": "Where can I learn more about this technique/these parts of the STL? Does this modify the string itself? (I'm no STL expert)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:58:09.230", "Id": "48643", "Score": "1", "body": "Search Stackoverflow for imbue. No it does not change the underlying string." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:09:24.210", "Id": "30572", "ParentId": "30547", "Score": "3" } } ]
{ "AcceptedAnswerId": "30551", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T07:00:55.337", "Id": "30547", "Score": "8", "Tags": [ "c++", "algorithm", "strings" ], "Title": "Number of words in a string" }
30547
<p>I have around 150 lines of code that I managed to optimize.</p> <p>But, because my two methods and the six if-statements almost are identical, could there be room for improvement? Maybe it could be done with only one button and one listbox? </p> <p>As I'm out of ideas and could learn more myself, I'd like to know what could be done to improve this code.</p> <pre><code>public Form1() { InitializeComponent(); timer1.Interval = 100; timer1.Start(); } private void timer1_Tick(object sender, EventArgs e) { lblClock.Text = DateTime.Now.ToString("HH:mm:ss"); } // ADD values BUTTON private void button8_Click(object sender, EventArgs e) { AddValues(); } // REMOVE values BUTTON private void button7_Click(object sender, EventArgs e) { RemoveValues(); } private void AddValues() { // ADD hours if (!box_Hour.Items.Contains(DateTime.Now.Hour)) { box_Hour.Items.Add(DateTime.Now.Hour); } // ADD minutes if (!box_Minute.Items.Contains(DateTime.Now.Minute)) { box_Minute.Items.Add(DateTime.Now.Minute); } // ADD seconds if (!box_Second.Items.Contains(DateTime.Now.Second)) { box_Second.Items.Add(DateTime.Now.Second); } } private void RemoveValues() { // REMOVE hours if (box_Hour.Items.Contains(DateTime.Now.Hour)) { box_Hour.Items.Remove(DateTime.Now.Hour); } // REMOVE minutes if (box_Minute.Items.Contains(DateTime.Now.Minute)) { box_Minute.Items.Remove(DateTime.Now.Minute); } // REMOVE seconds if (box_Second.Items.Contains(DateTime.Now.Second)) { box_Second.Items.Remove(DateTime.Now.Second); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T11:09:06.483", "Id": "48618", "Score": "1", "body": "Please, don't call your controls like `button7`, change that to descriptive names." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T12:00:37.950", "Id": "48619", "Score": "0", "body": "I will keep that in mind . ^^" } ]
[ { "body": "<p>Yeah, you can simplify your code. To have a single method for both of them, you would need to specify whether the check was negated and what action to perform (that could be done using a delegate).</p>\n\n<p>To simplify it even more, use a loop over the three boxes (possibly using a <code>Dictionary</code> to connect each box to the date part).</p>\n\n<p>Also, when working with <code>DateTime.Now</code>, you should make sure to access that property only once, then use its value. If you don't, you could get inconsistent results if the time changes while your method is executing.</p>\n\n<pre><code>private void AddValues()\n{\n ProcessValues(true, (items, value) =&gt; items.Add(value));\n}\n\nprivate void RemoveValues()\n{\n ProcessValues(false, (items, value) =&gt; items.Remove(value));\n}\n\nprivate void ProcessValues(\n bool negateContains, Action&lt;ListBox.ObjectCollection, int&gt; successAction)\n{\n var now = DateTime.Now;\n\n var pairs = new Dictionary&lt;ListBox, int&gt;\n {\n { box_Hour, now.Hour },\n { box_Minute, now.Minute },\n { box_Second, now.Second }\n };\n\n foreach (var pair in pairs)\n {\n bool condition = pair.Key.Items.Contains(pair.Value);\n\n if (negateContains)\n condition = !condition;\n\n if (condition)\n successAction(pair.Key.Items, pair.Value);\n }\n}\n</code></pre>\n\n<p>This makes your code less repetitive, but also more complicated. It's up to you to decide if that's worth it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T12:03:46.900", "Id": "48620", "Score": "0", "body": "Thanks, I will try to play around with your example, Hopefully I learn something new ^_^, great !" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T11:24:46.923", "Id": "30558", "ParentId": "30553", "Score": "1" } } ]
{ "AcceptedAnswerId": "30558", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T08:54:30.787", "Id": "30553", "Score": "4", "Tags": [ "c#", "generics" ], "Title": "Refactoring my windowsFormApp code" }
30553
<p>I am an average coder trying to improve my Python by doing solved problems in it.</p> <p>One of the problem I did is <a href="http://codeforces.com/contest/340/problem/B" rel="nofollow">this</a>, here is the code I tried which I have based on the <a href="http://codeforces.com/contest/340/submission/4383413" rel="nofollow">official solution</a>:</p> <pre><code>def area(A, B, C): return float((x[B] - x[A])*(y[C] - y[B]) - (y[B] - y[A])*(x[C] -x[B]))/2 x, y = {}, {} n = int(raw_input()) for i in xrange(n): arr = raw_input().split() x[i] , y[i] = int(arr[0]), int(arr[1]) maxarea = 0 for i in xrange(n): for j in xrange(i+1, n): maxminus, maxplus = -1, -1 for k in xrange(n): if k != i and k != j: a = area(i,j,k) if(a&lt;0): maxminus = max(maxminus, -a) else: maxplus = max(maxplus, a) if maxplus &gt;= 0 and maxminus &gt;=0: maxarea = max(maxarea, (maxplus+maxminus)) print maxarea </code></pre> <p>The code is still giving me TLE on test case 7. Can anybody suggest further optimization?</p>
[]
[ { "body": "<p>Firstly you need to put all the global statements into a function because of <a href=\"https://stackoverflow.com/questions/11241523/why-does-python-code-run-faster-in-a-function\">Python code runs faster in a function compared to global scope</a>.</p>\n\n<p>You don't need the <code>arr</code> variable. You can just use </p>\n\n<pre><code>x[i], y[i] = map(int, raw_input().split())\n</code></pre>\n\n<p>instead of using the two lines. <code>map</code> uses the function(1st argument) on each of the outputs from the second argument.</p>\n\n<p>After placing the global statements into a function then instead of passing <code>i, j, k</code> you would need to pass the values directly.</p>\n\n<p>I'll look up the algorithm and see if there are other changes that can be made.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T14:20:39.287", "Id": "30563", "ParentId": "30557", "Score": "1" } }, { "body": "<p>You can do some minor optimization as follows:</p>\n\n<pre><code>def main():\n n = int(raw_input())\n coords = list([i] + map(int, raw_input().split()) for i in range(n))\n max_area = 0\n for a, Ax, Ay in coords:\n for b, Bx, By in coords[a+1:]:\n max_minus, max_plus = 0, -1\n for c, Cx, Cy in coords:\n if c != a and c != b:\n ccw = (Bx - Ax) * (Cy - By) - (By - Ay) * (Cx - Bx)\n if ccw &lt; max_minus:\n max_minus = ccw\n elif ccw &gt; max_plus:\n max_plus = ccw\n if max_plus &gt;= 0 and max_minus &lt; 0 and max_plus - max_minus &gt; max_area:\n max_area = max_plus - max_minus\n print(max_area / 2.0)\n\nmain()\n</code></pre>\n\n<p>Note that your use of <code>float</code> doesn't do anything because the values to be passed are integers. Anyway, there's no need to divide by 2 every time - you can just divide the final value by 2 at the end.</p>\n\n<p>I think this still won't pass the speed test, though. If it is doable in python it probably needs an algorithm that makes better use of python's functions and standard library (and are other libraries allowed?). You could try something like this, for example:</p>\n\n<pre><code>from itertools import permutations\ndef main():\n n = int(raw_input())\n coords = list([i] + map(int, raw_input().split()) for i in range(n))\n max_area = 0\n for (a, Ax, Ay), (b, Bx, By) in permutations(coords, 2):\n ccws = [(Bx - Ax) * (Cy - By) - (By - Ay) * (Cx - Bx) \n for c, Cx, Cy in coords if c != a and c != b] \n low, high = min(ccws), max(ccws)\n if low &lt; 0 and high &gt;= 0 and high - low &gt; max_area:\n max_area = high - low\n print(max_area / 2.0)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T08:58:04.107", "Id": "48713", "Score": "0", "body": "Coupled with the optimizations by @aseem-bansal above this reduced the time significantly for smaller test cases but it still fails on bigger test cases, I think the judge needs to update the time limit for Python in this problem. I have gone ahead and implemented the same program in Go and it passed without problems: http://codeforces.com/contest/340/submission/4391625" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:13:48.847", "Id": "30574", "ParentId": "30557", "Score": "1" } } ]
{ "AcceptedAnswerId": "30574", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T11:20:36.880", "Id": "30557", "Score": "0", "Tags": [ "python", "optimization" ], "Title": "Is any further optimization possible? (Codeforces)" }
30557
<p>Consider this code where I read an input file with 6 columns (0-5):</p> <ol> <li>Initialize a variable <code>history_ends</code> to 5000.</li> <li>When the <code>column0</code> value (i.e. job[0] &lt; 5000) I add 5000 lines of the input file in a list (<code>historyjobs</code>) else the rest of the lines until the eof in another list (<code>targetjobs</code>).</li> <li>All the <code>historyjobs</code> list all contents in <code>item3</code>, <code>item4</code>, <code>item5</code> is equal to <code>targetjobs</code>. First list <code>item3</code>, <code>item4</code>, <code>item5</code> when this condition is satisfied. Add those <code>historyjobs</code> all <code>item1</code> to list <code>listsub</code>.</li> <li>Find the running mean of the items in <code>listsub</code> and reverse the list, store it in list <ol> <li>Check the condition if items in <code>listsub &gt; a*0.9</code> which satisfies the condition. Stores the result items in list <code>condsub</code>.</li> </ol></li> <li>Reopen the <code>inputfile</code> and check whether <code>column0</code> is equal to items in <code>condsub</code>. If it satisfies, then add the <code>column1</code> to a list <code>condrun</code>.</li> <li>Open the output file and write in <code>colum0</code> the second item of first list in <code>targetjobs</code> i.e. <code>j</code>, in <code>column1</code>, write the average of list <code>condrun</code>, <code>column2</code> is <code>(j-avg)/j</code>, <code>column3</code> is the maximum item in list <code>condrun</code>, <code>column4</code> is the minimum item in list <code>condrun</code>, <code>column5</code> is the length of the list <code>condrun</code>, the last four columns is based on the condition.</li> <li>I am repeating the whole procedure using a <code>while</code> loop by assigning the variable <code>historyends</code> to the next item <code>int(targetjobs[1][0])</code>.</li> </ol> <p></p> <pre><code>from __future__ import division import itertools history_begins = 1; history_ends = 5000; n = 0; total = 0 historyjobs = []; targetjobs = [] listsub = []; listrun = []; listavg = [] ; F = [] ; condsub = [] ;condrun = [] ;mlistsub = []; a = [] def check(inputfile): f = open(inputfile,'r') #reads the inputfile lines = f.readlines() for line in lines: job = line.split() if( int(job[0]) &lt; history_ends ): #if the column0 is less then history_ends(i,e 5000 initially) historyjobs.append(job) #historyjobs list contains all the lines from the list whose column1 &lt; history_ends else: targetjobs.append(job) #historyjobs list contains all the lines from the list whose column1 &gt; history_ends k = 0 for i, element in enumerate(historyjobs): if( (int(historyjobs[i][3]) == int(targetjobs[k][3])) and (int(historyjobs[i][4]) == int(targetjobs[k][4])) and (int(historyjobs[i][5]) == int(targetjobs[k][5])) ): #historyjobs list all contents in column3,column4,column5 is equal to targetjobs first list column3,column4,column5 listsub.append(historyjobs[i][1]) #when if condition true add those historyjobs column1 to list listsub def runningMean(iterable): """A generator, yielding a cumulative average of its input.""" num = 0 denom = 0 for x in iterable: num += x denom += 1 yield num / denom def newfun(results): results.reverse() # put them back in regular order for value, average in results: a.append(value) return a #to return the value def runcheck(subseq): f = open('newfileinput','r') #again read the same inputfile lines = f.readlines() for line in lines: job = line.split() for i, element in enumerate(subseq): if(int(job[1]) == int(subseq[i])): # if the column1 value of the inputfile becomes equal to list obtained condrun.append(str(job[2])) #return the value of column2 which satisfies the if condition return condrun def listcreate(condrun,condsub): f1 = open('outputfile','a') #outputfile to append the result s = map(int,condrun) j = int(targetjobs[0][2]) targetsub = int(targetjobs[0][1]) if(condsub != []): try: convertsub = int(condsub[-1]) a=sum(s)/len(s) c=max(s) d=min(s) e1=abs(j-a) er1=e1/j g=len(s) h=abs(convertsub-targetsub) f1.write(str(j)) f1.write('\t') f1.write('\t') f1.write(str(round(a,2))) f1.write('\t') f1.write('\t') f1.write(str(round(er1,3))) f1.write('\t') f1.write('\t') f1.write(str(c)) f1.write('\t') f1.write('\t') f1.write(str(d)) f1.write('\t') f1.write('\t') f1.write(str(g)) f1.write('\t') f1.write('\t') f1.write(str(h)) f1.write('\t') f1.write("\t") if (float(er1) &lt; 0.20): f1.write("good") f1.write("\t") else : f1.write("bad") f1.write("\t") if (float(er1) &lt; 0.30): f1.write("good") f1.write("\t") else : f1.write("bad") f1.write("\t") if (float(er1) &lt; 0.40): f1.write("good") f1.write("\t") else : f1.write("bad") f1.write("\t") if (float(er1) &lt; 0.50): f1.write("good") f1.write("\n") else : f1.write("bad") f1.write("\n") except ZeroDivisionError : print 'dem 0' else: print '0' f1.close() def new(): global history_ends while 1: #To repeat the process untill the EOF(end of input file) check('newfileinput') #First function call if(len(targetjobs) != 1): history_ends = int(targetjobs[1][0]) #initialize historyends to targetjobs second lines first item mlistsub = map(int,listsub) results = list(itertools.takewhile(lambda x: x[0] &gt; 0.9 * x[1], itertools.izip(reversed(mlistsub), runningMean(reversed(mlistsub)))))#call runningmean function &amp; check the condition condsub = newfun(results) #function to reverse back the result condrun=runcheck(condsub) #functionto match &amp; return the value listcreate(condrun,condsub) #function to write result to output file del condrun[0:len(condrun)]#to delete the values in list del condsub[0:len(condsub)]#to delete the values in list del listsub[0:len(listsub)]#to delete the values in list del targetjobs[0:len(targetjobs)]#to delete the values in list del historyjobs[0:len(historyjobs)]#to delete the values in list else: break def main(): new() if __name__ == '__main__': main() </code></pre> <p>The sample input file (whole file contains 200,000 lines):</p> <blockquote> <pre><code> 1 0 9227 1152 34 2 2 111 7622 1120 34 2 3 68486 710 1024 14 2 6 265065 3389 800 22 2 7 393152 48438 64 132 3 8 412251 46744 64 132 3 9 430593 50866 256 95 4 10 430730 10770 256 95 4 11 433750 12701 256 14 3 12 437926 2794 64 34 2 13 440070 43 32 96 3 </code></pre> </blockquote> <p>The sample output file contents:</p> <blockquote> <pre><code>930 1389.14 0.494 3625 977 7 15 bad bad bad good 4348 1331.75 0.694 3625 930 8 164 bad bad bad bad 18047 32237.0 0.786 61465 17285 3 325774 bad bad bad bad 1607 1509.0 0.061 1509 1509 1 6508 good good good good 304 40.06 0.868 80 32 35 53472 bad bad bad bad 7246 7247.0 0.0 7247 7247 1 9691 good good good good 95 1558.0 15.4 1607 1509 2 2148 bad bad bad bad 55 54.33 0.012 56 53 3 448142 good good good good 31 76.38 1.464 392 35 13 237152 bad bad bad bad 207 55.0 0.734 55 55 1 370 bad bad bad bad </code></pre> </blockquote> <p>If anyone could suggest some changes to help make the code run faster, that'd be helpful.</p>
[]
[ { "body": "<p>Comments about coding style:</p>\n\n<ul>\n<li>inconsistent indentation makes the code harder to read</li>\n<li>preferred indentation width in python is 4 spaces</li>\n</ul>\n\n<p>Why is the question tagged python3 ? This is python2 code.</p>\n\n<hr>\n\n<pre><code>history_begins = 1; history_ends = 5000; n = 0; total = 0\nhistoryjobs = []; targetjobs = []\nlistsub = []; listrun = []; listavg = [] ; F = [] ; condsub = [] ;condrun = [] ;mlistsub = []; a = []\n</code></pre>\n\n<p>There are variables defined here that aren't actually used in the script, and global variables shouldn't have one-letter names.</p>\n\n<hr>\n\n<pre><code>f = open(inputfile,'r') #reads the inputfile\n</code></pre>\n\n<p>No it doesn't, it just creates a file handle.</p>\n\n<hr>\n\n<pre><code>lines = f.readlines()\nfor line in lines:\n</code></pre>\n\n<p>However, this does read the file, it even loads it all in RAM at once, which is a waste because you don't actually need to, so do this instead:</p>\n\n<pre><code>for line in f:\n</code></pre>\n\n<hr>\n\n<pre><code>f1.write(str(j))\nf1.write('\\t')\nf1.write('\\t')\n...\nif (float(er1) &lt; 0.50):\n f1.write(\"good\")\n f1.write(\"\\n\")\nelse:\n f1.write(\"bad\")\n f1.write(\"\\n\")\n</code></pre>\n\n<p>That's redundant, factor it:</p>\n\n<pre><code>print(j, round(a,2), round(er1,3), c, d, g, h, sep='\\t\\t', end='\\t\\t', file=out)\nw = ('bad', 'good')\nprint(w[er1 &lt; .2], w[er1 &lt; .3], w[er1 &lt; .4], w[er1 &lt; .5], sep='\\t', file=out)\n</code></pre>\n\n<hr>\n\n<pre><code>f = open('newfileinput','r') #again read the same inputfile\n</code></pre>\n\n<p>Why read the same file multiple times ? That's inefficient…</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:11:42.287", "Id": "30573", "ParentId": "30565", "Score": "2" } }, { "body": "<p>OK, your code is a bit of a mess. I take it you are fairly new to python. Read the <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">python style guide</a> and stick to it. It will make it easier for people to read your code. </p>\n\n<p>It is not easy to work out what you are trying to do here. As it stands the code doesn't run. However, here are some thoughts.</p>\n\n<p>building on @Changaco's answer you can iterate through the file and process each row into integers like this.</p>\n\n<pre><code>def check(inputfile):\n f = open(inputfile,'r')\n for line in f:\n job = [int(s) for s in line.split()]\n ...\n</code></pre>\n\n<p>Doing the conversion once up front you can forget all the other int() conversions that clutter up your code. This includes removing the need for your mlistsub global entirely as far as I can tell as it seems to be an integer version of the listsub variable.</p>\n\n<p>I suspect the following reference to job[0] should reference job[1 ] as it is column1, not column0 that you talk about in other comments.</p>\n\n<pre><code>if( int(job[0]) &lt; history_ends ): #if the column0 is less then history_ends(i,e 5000 initially)\n ...\n</code></pre>\n\n<p>Also, brackets are not necessary and with the above int() conversion already done the line becomes</p>\n\n<pre><code>if job[1] &lt; history_ends:\n ...\n</code></pre>\n\n<p>I would reduce the global variables to the absolute minimum (which is usually none). I cannot work out the detail but the only reason I can see to keep globals here would be if they are continually being appended to and this is not happening as far as I can tell.</p>\n\n<p>For example, I think the global variable a = [] can be removed.</p>\n\n<p>Your original function.</p>\n\n<pre><code>def newfun(results):\n results.reverse() # put them back in regular order\n for value, average in results:\n a.append(value)\n return a #to return the value\n</code></pre>\n\n<p>is called like this</p>\n\n<pre><code> condsub = newfun(results) #function to reverse back the result \n</code></pre>\n\n<p>Aside from the terrible function name, this function seems to do very little. You could replace the function call with something like this</p>\n\n<pre><code>condsub = [value for value, average in reversed(results)] #reverse back the result\n</code></pre>\n\n<p>The following code</p>\n\n<pre><code> k = 0 \n for i, element in enumerate(historyjobs):\n if( (int(historyjobs[i][3]) == int(targetjobs[k][3])) and (int(historyjobs[i][4]) == int(targetjobs[k][4])) and (int(historyjobs[i][5]) == int(targetjobs[k][5])) ): #historyjobs list all contents in column3,column4,column5 is equal to targetjobs first list column3,column4,column5\n listsub.append(historyjobs[i][1]) #when if condition true add those historyjobs column1 to list listsub \n</code></pre>\n\n<p>can be significantly cleaned up. There is no need to use enumerate() just to get the i variable. The idiomatic approach is to use 'for hjob in historyjobs:'. With the int() conversion already done you can replace the complicated comparison with a simple comparison of the slice of interest.</p>\n\n<pre><code>tjob = targetjobs[0]\nfor hjob in historyjobs:\n if hjob[3:6] == tjob[3:6]:\n listsub.append(hjob[1])\n</code></pre>\n\n<p>If I understand your intent, you can also create a simple list and return it from the function as a way to remove the listsub global variable.</p>\n\n<pre><code>result = []\ntjob = targetjobs[0]\nfor hjob in historyjobs:\n if hjob[3:6] == tjob[3:6]:\n result.append(hjob[1])\nreturn result\n</code></pre>\n\n<p>A conversion and filter operation can usually be achieved with a list comprehension. Something like this should do the trick.</p>\n\n<pre><code>return [hjob[1] for hjob in historyjobs if hjob[3:6] == targetjobs[0][3:6]]\n</code></pre>\n\n<p>Since you are deleting all your globals at the end of each loop, I am assuming you don't need them at all.</p>\n\n<pre><code>del condrun[0:len(condrun)]#to delete the values in list\ndel condsub[0:len(condsub)]#to delete the values in list\ndel listsub[0:len(listsub)]#to delete the values in list\ndel targetjobs[0:len(targetjobs)]#to delete the values in list\ndel historyjobs[0:len(historyjobs)]#to delete the values in list\n</code></pre>\n\n<p>This is not necessary if you return data from your functions as above and assign the result of the function calls to variables which are created in the scope of your new() function.</p>\n\n<p>As I say, I'm not sure what your doing exactly here so I can't advise on the logic. If you can tidy it up a bit then I'm sure we can help you get to the bottom of it. My feeling is that the code can become much shorter and much clearer than your current version.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T21:54:13.240", "Id": "30931", "ParentId": "30565", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T14:43:14.687", "Id": "30565", "Score": "4", "Tags": [ "python" ], "Title": "Reading an input file with 6 columns" }
30565
<p>Artificial Intelligence is a branch of computer science which aims to replicate or simulate human-style intelligence (or significant aspects of it). The term was coined by <a href="https://en.wikipedia.org/wiki/John_McCarthy_(computer_scientist)" rel="nofollow noreferrer">John McCarthy</a>, who invented the <a href="https://en.wikipedia.org/wiki/Lisp_(programming_language)" rel="nofollow noreferrer">LISP</a> programming language as a natural language processing tool to aid his research in the AI field.</p> <p>Also consult the <a href="https://ai.stackexchange.com/">Artificial Intelligence Stack Exchange</a> site.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T16:42:20.587", "Id": "30568", "Score": "0", "Tags": null, "Title": null }
30568
Artificial intelligence (AI) is the branch of computer science and technology that studies the development of machines able to simulate aspects of human intelligence.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T16:42:20.587", "Id": "30569", "Score": "0", "Tags": null, "Title": null }
30569
<p>I'm trying to get my head around asyncronous programming in node.js. My example is reading all the files from a directory.</p> <p>I know I can avoid asyncronous programming by using the syncronous methods:</p> <pre><code>var fs = require('fs'); names = fs.readdirSync("."); for(i in names) { fileinfo = fs.statSync( names[i] ); if( fileinfo.isFile() ) console.log( names[i] + " has size " + fileinfo.size ); }; </code></pre> <p>I know how to write it in the classic node style:</p> <pre><code>fs.readdir(".", function (err, names) { if (err) throw err; names.forEach(function(n){ fs.stat( n, function(err, fileinfo) { if( fileinfo.isFile() ) console.log( n + " has size " + fileinfo.size ); }); }); }); </code></pre> <p>But now I'm trying "functional reactive programming" with <a href="https://github.com/baconjs/bacon.js" rel="nofollow">bacon.js</a> and I'm not sure if I really get it. This is my first sketch:</p> <pre><code>var fs = require('fs') , Bacon = require("baconjs").Bacon; fs.readdir(".", function (err,names) { if (err) throw err; Bacon.fromNodeCallback( fs.stat_with_filename, Bacon.fromArray(names) ) .filter(".isFile") .onValue(function(stat) { console.log(stat.filename + " has size " + stat.size); }); }); </code></pre> <p>But I had to monkeypatch <strong>fs</strong> to get the filename inside the stat object to achive this:</p> <pre><code>fs.stat_with_filename = function( filename, callback ) { fs.stat( filename, function (err,stats) { stats.filename = filename; callback( err, stats ); }); }; </code></pre> <p>Is there a better way to write this in node + bacon?</p>
[]
[ { "body": "<p>If you want to expose directory contents with stats as a Bacon EventStream or a Property, you can use the combine-family of functions to combine the filename and stats without monkey-patching:</p>\n\n<pre><code>var fs = require(\"fs\")\nvar Bacon = require(\"../dist/Bacon.js\")\n\n// statsForFile :: String -&gt; Property { filename :: String, stats :: Stats }\nfunction statsForFile(filename) {\n return Bacon.combineTemplate({\n name: filename,\n stats: Bacon.fromNodeCallback( fs.stat, filename )\n }) \n}\n</code></pre>\n\n<p>You can expose directory contents as a stream of filenames:</p>\n\n<pre><code>// directoryContents :: String -&gt; EventStream String\nfunction directoryContents(dir) {\n return Bacon.fromNodeCallback(fs.readdir, dir)\n .flatMap(function(names) { return Bacon.fromArray(names)})\n}\n</code></pre>\n\n<p>Then you can compose these two like</p>\n\n<pre><code>function statsForDir(dir) {\n return directoryContents(dir).flatMap(statsForFile)\n}\n</code></pre>\n\n<p>And see what happens:</p>\n\n<pre><code>statsForDir(\".\").log()\n</code></pre>\n\n<p>So that's how you can compose these things asynchronously using Bacon.js and FRP. This is not a prime example of where FRP is really useful yet, but when more composition is involved the benefits will be greater. Hope this helps!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T07:44:17.957", "Id": "30678", "ParentId": "30571", "Score": "3" } } ]
{ "AcceptedAnswerId": "30678", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:05:49.033", "Id": "30571", "Score": "2", "Tags": [ "javascript", "node.js", "bacon.js" ], "Title": "How do I handle the file system?" }
30571
<p>An atomic operation is one which can be considered, from the perspective of the larger computing context in which it occurs, to be executed in a single step. During its execution, no other process can read or alter its state. Atomic operations should either succeed or fail; if the operation can halt in some other, partially-completed state then it is not considered atomic.</p> <p>Atomic operations are crucial to reliable computing processes, particularly in <a href="http://en.wikipedia.org/wiki/Concurrency_%28computer_science%29" rel="nofollow">concurrent</a> and <a href="http://en.wikipedia.org/wiki/Transaction_processing" rel="nofollow">transactional</a> systems.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:19:21.947", "Id": "30575", "Score": "0", "Tags": null, "Title": null }
30575
An atomic operation is one which can be considered, from the perspective of the computing context in which it occurs, to be executed in a single step. Atomic operations either succeed entirely or fail, with no intermediate states.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:19:21.947", "Id": "30576", "Score": "0", "Tags": null, "Title": null }
30576
<p>I am using this as a learning exercise primarily and want to ensure my code is optimal. The main thing is that it is reliable and I am made aware of any flaws.</p> <p>Could it be made more efficient or more readable? How about style?</p> <p>I thought about returning a <code>char*</code>, but then the caller would have to think to deallocate the returned string. I saw this as a problem, so I left to caller to allocate and deallocate. Is that the right decision? Any comments?</p> <pre><code>/* Generate hex string from integer. Odd number of characters must be preceded with zero character Eg. 9 becomes "09", 10 becomes "0A" and 16 becomes "10" */ #include &lt;stdio.h&gt; unsigned int num_hex_digits(unsigned int n) { int ret = 0; while(n) { n &gt;&gt;= 4; ++ret; } return ret; } void make_hex_string_easy(unsigned int invokeid, char** xref) { int pad = 0; int len = num_hex_digits(invokeid); /* if odd number, add 1 - zero pad number */ if(len % 2 != 0) pad = 1; sprintf(*xref, "%s%X", pad ? "0" : "", invokeid); } void make_hex_string_learning(unsigned int invokeid, char** xref) { char* p = *xref; int pad = 0; int len = num_hex_digits(invokeid); /* if odd number, add 1 - zero pad number */ if(len % 2 != 0) pad = 1; /* move to end of number string */ p+= len + pad - 1; while(invokeid) { int tmp = invokeid &amp; 0xF; if(tmp &lt; 10) *p = tmp + '0'; else *p = tmp + 'A' - 10; invokeid &gt;&gt;= 4; p--; } if(pad) { *p = '0'; } } int main() { unsigned int testdata[] = {~0, 1, 255, 256, 0xFFFE, 0xFFFF, 0x10000, 0xABC }; int sz = sizeof(testdata) / sizeof(int); int i; char* test = (char*) calloc (20, 1); printf("Using sprintf method\n"); for(i = 0; i &lt; sz; ++i) { make_hex_string_easy(testdata[i], &amp;test); printf("hex string of %#10x = \t%10s\n", testdata[i], test); memset(test, 0, 20); } printf("\nUsing homegrown method\n"); for(i = 0; i &lt; sz; ++i) { make_hex_string_learning(testdata[i], &amp;test); printf("hex string of %#10x = \t%10s\n", testdata[i], test); memset(test, 0, 20); } free(test); return 0; } </code></pre> <p>Output on my PC:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Using sprintf method hex string of 0xffffffff = FFFFFFFF hex string of 0x1 = 01 hex string of 0xff = FF hex string of 0x100 = 0100 hex string of 0xfffe = FFFE hex string of 0xffff = FFFF hex string of 0x10000 = 010000 hex string of 0xabc = 0ABC Using homegrown method hex string of 0xffffffff = FFFFFFFF hex string of 0x1 = 01 hex string of 0xff = FF hex string of 0x100 = 0100 hex string of 0xfffe = FFFE hex string of 0xffff = FFFF hex string of 0x10000 = 010000 hex string of 0xabc = 0ABC </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T18:03:34.590", "Id": "48646", "Score": "0", "body": "I'd change the name `invokeid` to something more clear and relevant to its role in the function. I'll write an actual answer in a few minutes." } ]
[ { "body": "<ul>\n<li><a href=\"https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc\">Don't typecast return of malloc in C</a>. Same thing goes for <code>calloc</code></li>\n<li><code>invokeid</code> seems to me two words so why no underscore? Be consistent even if it seems obvious.</li>\n<li><code>if(len % 2 != 0)</code> can be replaced by <code>if(len % 2)</code> for efficiency. Eliminates the comparison without any difference in functionality.</li>\n<li><p>You can eliminate <code>len</code> by using the <code>(num_hex_digits(invokeid) % 2)</code> instead of (len % 2). It serves no other purpose and the name of the function is more descriptive here than <code>len</code> anyways</p></li>\n<li><p>Depending upon the length of the integers that you want to change using <code>log base 2</code> should be faster to find the length of the integer.You'll have to time this one.</p></li>\n<li>In the function <code>make_hex_string_learning</code> using the ternary operator should be better for readability when assigning to <code>*p</code>.</li>\n<li>You are inconsistent in your use of braces around single statements in the <code>make_hex_string_learning</code> function. You shouldn't be.</li>\n<li>Your comment <code>/* if odd number, add 1 - zero pad number */</code> is misleading. You are assigning to <code>pad</code>. I don't think the comment will help anyone understand the code.</li>\n<li><code>if(tmp &lt; 10)</code> Why 10? Why not 20 or 30? Magic numbers are bad. You should avoid them when you can. Add a comment if it isn't possible to avoid them. Otherwise you may end end up asking this same question yourself later on.</li>\n<li>You need to add comments in some of your functions. It isn't clear what the purpose of function such as <code>make_hex_string_easy</code> is. What does easy mean here? Not detailed explanation but the expected outputs. </li>\n<li>Any reason that you are using extra newlines in your code? It doesn't make reading the code any easier. A single newline between function definitions is justified. It is justified when separating logical blocks but at random places it is just making more scrolling necessary.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T18:07:48.530", "Id": "48648", "Score": "2", "body": "I disagree with most of this. Adding a variable to improve readability is great practice and most of the time the compiler will optimize it away anyway. I'd say `pad` should stay." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T18:09:02.440", "Id": "48649", "Score": "2", "body": "The `if` is more readable IMO with the comparison. It makes no difference at runtime, but being explicit is better unless the condition is really complicated (and then you have a different problem anyway)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T18:16:32.927", "Id": "48652", "Score": "0", "body": "IMO when assigning to a single variable a ternary operator is better. Yeah it makes no difference at runtime. I never implied that. Using ternary operator is by no means implicit. It is well defined syntax." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T18:20:33.677", "Id": "48653", "Score": "0", "body": "@busy_wait Bad call on `pad` but having `len` serves nothing. The function is readable as such. No?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T18:21:05.257", "Id": "48654", "Score": "0", "body": "I'm just saying the original `sprintf` line is far more readable to me than your suggestion. Yours took me a few seconds to parse." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T18:25:32.167", "Id": "48655", "Score": "0", "body": "@busy_wait As I said bad call on my part about `pad`. I removed that. Is there anything else you find wrong in this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T18:29:47.640", "Id": "48656", "Score": "0", "body": "Actually no, no further objections from me. Maybe saying \"most of this\" was a bit of a hyperbole. I beg your pardon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T18:31:05.843", "Id": "48657", "Score": "0", "body": "@busy_wait No problems. You helped me take care of a mistake." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T18:04:52.633", "Id": "30582", "ParentId": "30579", "Score": "2" } }, { "body": "<p>Nothing jumps out:</p>\n\n<p>Rather than this:</p>\n\n<pre><code> if(tmp &lt; 10)\n *p = tmp + '0';\n else \n *p = tmp + 'A' - 10;\n</code></pre>\n\n<p>I would have used:</p>\n\n<pre><code> *p = tmp + (tmp &lt; 10) ? '0' : 'A' - 10;\n</code></pre>\n\n<p>Even though you pass around a pointer to a pointer (for re-alloc I assume). You don't actually do any reallocation. So I would simplify the code and just pass a pointer.</p>\n\n<pre><code>void make_hex_string_easy(unsigned int invokeid, char** xref) \n ^^^^^^ I would just use char*\n</code></pre>\n\n<p>Note: A lot of common interfaces when you pass a NULL as the destination return how many characters it would have used in the buffer. This leads to a lot of C code that looks like this:</p>\n\n<pre><code>size_t s = make_hex_string_easy(number, NULL); // assuming you changed your code to return a value.\nchar* b = malloc(s+1);\nmake_hex_string_easy(number, b);\n</code></pre>\n\n<p>But Since you don't use dynamic buffers I would remove the calloc.</p>\n\n<pre><code>printf(\"Using sprintf method\\n\");\nfor(i = 0; i &lt; sz; ++i) {\n char test[50] = {0}; // inits to 0\n make_hex_string_easy(testdata[i], test); // assuming you change to just a pointer\n printf(\"hex string of %#10x = \\t%10s\\n\", testdata[i], test);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T18:15:05.987", "Id": "30583", "ParentId": "30579", "Score": "5" } }, { "body": "<p>There are two errors in your code and some aspects that are not so nice. </p>\n\n<p>The errors first. </p>\n\n<ul>\n<li>you don't handle 0</li>\n<li>you don't terminate the string, instead relying on the buffer having been cleared.</li>\n</ul>\n\n<p>The task is a little strange in requiring a leading zero is the length is odd. A leading zero is often used to show that a number is octal (base 8). If it were for real instead of practice I'd try to drop that requirement.</p>\n\n<p>To fix the non-handling of zero, you need to fix <code>num_hex_digits</code>:</p>\n\n<pre><code>static int num_hex_digits(unsigned n)\n{\n if (!n) return 1;\n\n int ret = 0;\n for (; n; n &gt;&gt;= 4) {\n ++ret;\n }\n return ret;\n}\n</code></pre>\n\n<p>Here I added an explicit check for zero and reorganised the loop into a <code>for</code> loop, which is more normal (it keeps the test of the number and its shifting in the same place). Note also that the function is static because it is a support function for use only here.</p>\n\n<p>Your <code>make_hex_string_learning</code> has some issues. Others have already noted that you only need a simple pointer, not a double pointer. And the parameter names are too long/strange. You used <code>n</code> in the previous function so why not be consistent. And the string can simply be <code>s</code>. </p>\n\n<p>Your use of <code>pad</code> at each end of the function is unnecessary. It is used to adjust the \nstring length and add the leading '0'. Both can be done at the start of the function. </p>\n\n<p>Here is a simplified version of the function:</p>\n\n<pre><code>void make_hex_string_learning(unsigned n, char *s)\n{\n const char hex_lookup[] = \"0123456789abcdef\";\n int len = num_hex_digits(n);\n\n if (len &amp; 1) {\n *s++ = '0';\n }\n s[len] = '\\0';\n\n for (--len; len &gt;= 0; n &gt;&gt;= 4, --len) {\n s[len] = hex_lookup[n &amp; 0xf];\n }\n}\n</code></pre>\n\n<p>Notice that I added the leading 0 at the start of the function, that I used a simple lookup table to get the character values, that I terminated the string and that I used <code>len</code> as an index instead of advancing the pointer to the end of the string and regressing. I also changed your <code>while</code> loop to a <code>for</code> for the same reason as above.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T01:22:39.070", "Id": "30604", "ParentId": "30579", "Score": "3" } }, { "body": "<h3>Use variable width format specifier</h3>\n<p>When using <code>sprintf</code>, you can use a variable width specifier, and also a &quot;pad with zero&quot; specifier, so that you don't need to do these things manually:</p>\n<pre><code>void make_hex_string_easy(unsigned int invokeid, char** xref)\n{\n int len = num_hex_digits(invokeid);\n /* if odd number, add 1 - zero pad number */\n if(len % 2 != 0)\n len++;\n\n sprintf(*xref, &quot;%0*X&quot;, len, invokeid);\n}\n</code></pre>\n<p>Here, after the <code>%</code> character, the <code>0</code> tells <code>sprintf</code> to pad the hex value with zeros. For example:</p>\n<pre><code>printf(&quot;%08x&quot;, 0x1234); // Will print &quot;00001234&quot; due to the %08x specifier\n</code></pre>\n<p>After the <code>0</code> there is a <code>*</code> character. This tells <code>sprintf</code> that the width will come from a variable instead of being hardcoded. For example:</p>\n<pre><code>printf(&quot;%0*x&quot;, 6, 0x1234); // Will print &quot;001234&quot; with a width of 6\n</code></pre>\n<p>So putting it all together, <code>&quot;%0*X&quot;</code> prints a zero padded hex string whose width comes from the next argument. In the modified code above, that argument is <code>len</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-12T01:41:32.020", "Id": "116508", "ParentId": "30579", "Score": "2" } } ]
{ "AcceptedAnswerId": "30604", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:34:21.473", "Id": "30579", "Score": "4", "Tags": [ "c", "formatting", "integer" ], "Title": "Integer-to-hex string generator" }
30579
<p>I have been doing some JS lately and I would like to get some constructive criticism.</p> <p><a href="https://github.com/Nikamura/YoutubeToSpotify-JavaScript/" rel="nofollow">The project I am working on</a></p> <pre><code>var SpotifiedList = [], youtubeSongs, spotifySongs = 0, spotifiedSongs = 0, playNext; $(document).ready(function () { var id = window.location.hash; if (id) { $("#playlistID").val(id.substring(1)); startProcess(); } }); function resetTimer() { console.log("timer reset!") clearTimeout(playNext); } function startProcess() { $("#errorOccured").hide(); if ($("#playlistID").val().length &lt; 5) { // Checks if there is something entered $(".alert-danger").fadeIn().html("Please enter a valid Youtube &lt;b&gt;playlist ID&lt;/b&gt;."); } else { window.location.hash = $("#playlistID").val(); $("#list").html('&lt;center&gt;This might take some time.&lt;/center&gt;'); $(".alert-info").html("&lt;center&gt;Loading&lt;/center&gt;"); $(".alert-danger").hide(); retrieveYoutubePlaylist($("#playlistID").val(), 1, [], 1); } } function retrieveYoutubePlaylist(id, startIndex, list, k) { $("#loading").show(); $.ajax({ url: 'https://gdata.youtube.com/feeds/api/playlists/' + id + '?v=2&amp;alt=json&amp;start-index=' + startIndex + '&amp;max-results=50', dataType: 'json', success: function (data) { if (typeof data.feed.entry === 'undefined') {} else { for (var i = 0; i &lt; data.feed.entry.length; i++) { if (k == 1) $("#list").html(""); var title = data.feed.entry[i].title.$t; list.push(title); retrieveSpotify(title); k++; } retrieveYoutubePlaylist(id, startIndex + 50, list, k); youtubeSongs = list.length; } }, error: function (data, a, err) { if (err) { $(".alert-danger").fadeIn().html("Error Happened: " + err); } } }); } function retrieveSpotify(title) { var url = 'http://ws.spotify.com/search/1/track.json?q=' + parseTitle(title); $.getJSON(url, function (data) { spotifySongs += 1; if (data.tracks.length &gt; 0) { spotifiedSongs += 1; $("#list").append('&lt;li&gt;&lt;a href="' + data.tracks[0].href + '" onClick="resetTimer();" title="' + data.tracks[0].artists[0].name + ' - ' + data.tracks[0].name + '"&gt;' + data.tracks[0].artists[0].name + ' - ' + data.tracks[0].name + '&lt;/a&gt;&lt;/li&gt;'); var info = { 'url': data.tracks[0].href, 'length': Math.round(data.tracks[0].length * 1000), 'name': data.tracks[0].artists[0].name + ' - ' + data.tracks[0].name } SpotifiedList.push(info); } if (youtubeSongs == spotifySongs) { $(".alert-info").html('&lt;div class="btn-group"&gt;\ &lt;button type="button" class="btn btn-default" onClick="play();"&gt;\ &lt;span class="glyphicon glyphicon-play"&gt;&lt;/span&gt; Play/Skip\ &lt;/button&gt;\ &lt;/div&gt;&lt;br&gt;Converted songs: &lt;strong&gt;' + spotifiedSongs + '&lt;/strong&gt;/' + youtubeSongs); } }); } function parseTitle(title) { var newTitle = title .replace(/[-!$%^&amp;_+|~=`{}:";'&lt;&gt;?,.\/]/g, '') .replace(/ /g, ' ') .replace(/\[.*\]/g, '') .replace(/lyrics/g, '') .replace(/\(.*\)/g, '') .replace(/\*.*\*/g, '') .replace(/ /g, ' '); return newTitle; } function play() { clearTimeout(playNext); var song = SpotifiedList[Math.floor((Math.random() * SpotifiedList.length))]; window.location = song.url; x = (song.length / 1000) &gt;&gt; 0; seconds = x % 60 x = (x / 60) &gt;&gt; 0; minutes = x % 60; console.log('Playing: ' + song.name + ' (' + minutes + ':' + seconds + ')'); playNext = setTimeout(play, song.length); } </code></pre>
[]
[ { "body": "<h2>General</h2>\n\n<p>I could work with this code, I only have a few remarks.</p>\n\n<p><strong>Globals</strong></p>\n\n<p>You should consider as a minimum to have your 4 globals in an object.</p>\n\n<pre><code>var player = \n{\n spotifiedList : [],\n youtubeSongs : 0,\n spotifySongs : 0,\n spotifiedSongs : 0,\n playNext : 0\n}\n</code></pre>\n\n<p>You could even add most of the functions to the player object</p>\n\n<p><strong>resetTimer</strong></p>\n\n<p>You should remove the <code>console.log</code>, which makes this a simple one liner. If you keep it ( function name neatly explains what it does ), make sure to call it from <code>play()</code> instead of doing a straight <code>clearTimeout(playNext)</code>.</p>\n\n<p><strong>startProcess</strong></p>\n\n<p>You could consider caching the jQuery queries, maybe in the before proposed player object.</p>\n\n<p><strong>retrieveYoutubePlaylist</strong></p>\n\n<p><code>if (typeof data.feed.entry === 'undefined') {} else {</code> is just wrong.</p>\n\n<p><strong>retrieveSpotify</strong></p>\n\n<p>Encoding <code>onclick=</code> is wrong as well. \nBuilding HTML should be contained to separate functions.</p>\n\n<p><strong>parseTitle</strong></p>\n\n<p>I have no idea what that does, a few comments are needed there</p>\n\n<p><strong>play</strong></p>\n\n<p>I am curious, what does <code>&gt;&gt; 0</code> get you ? Force it into an integer?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-20T19:22:20.660", "Id": "37827", "ParentId": "30580", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:48:56.220", "Id": "30580", "Score": "5", "Tags": [ "javascript", "css", "converting" ], "Title": "YouTube-to-Spotify converter" }
30580
<p>I have a very simple code that allows me to keep track of what the user inserts in a <code>raw_input</code>.</p> <p>The kind of controls I check are <code>if the user inserts "f" the program is finished</code> or <code>if the user inserts nothing, the program keeps on running remembering all the inputs the user has inserted</code>.</p> <p>It works but I think it's very ugly and rudimental.</p> <p>I would love to get suggestions from experts so I can learn how to handle correctly simple tasks.</p> <p>Here's the little code:</p> <pre><code>#!/usr/bin/python import os good_receipts = [] done = False inserted_text = '' while not done: # This function is os dependent and will work only if you use linux os.system('clear') inserted_text = raw_input("Insert receipt number (if you finished insert 'f'): ").upper() if inserted_text and inserted_text != 'F': good_receipts.append(inserted_text) while not inserted_text == 'F': # This function is os dependent and will work only if you use linux os.system('clear') if good_receipts: print "Here's your receipts:" print good_receipts if not good_receipts: print "You didn't enter a single receipt..." inserted_text = raw_input("Insert receipt number (if you finished insert 'f'): ").upper() if inserted_text and inserted_text != 'F': good_receipts.append(inserted_text) done = True # This function is os dependent and will work only if you use linux os.system('clear') print "You did a great job, here's your receipts:" print good_receipts </code></pre>
[]
[ { "body": "<p>Here is what I came up with:</p>\n\n<pre><code>#!/usr/bin python\nfrom os import system as sys\n\ndef GetReceipt():\n prompt = \"Insert receipt number (if you finished insert 'f'): \"\n inserted_text = ''\n while True:\n sys('clear')\n inserted_text = raw_input(prompt).upper()\n if inserted_text == 'F': break\n yield inserted_text\n\n\ndef final(receipt):\n sys('clear')\n print [\"You did a great job, here's your receipts:\\n\"+' '.join(receipt), \n \"You did not enter a single receipt...\"][len(receipt) == 0]\n\nif __name__ == '__main__':\n valid_receipts = [ f for f in GetReceipt() ]\n final(valid_receipts)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T12:54:31.870", "Id": "48720", "Score": "0", "body": "`list[bool]` is a useful trick, but in this case I'd say it just makes the code harder to read." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T19:34:00.763", "Id": "30585", "ParentId": "30581", "Score": "2" } }, { "body": "<p>I find it easier to reason about code that actually does something, so I made it display the sum of the inputted numbers.</p>\n\n<pre><code>#!/usr/bin/env python3\n\ntry:\n import readline\nexcept ImportError:\n pass\n\nnumbers = []\nprint('Enter your numbers, one per line. Enter \"f\" when you\\'re done.')\n\nwhile True:\n try:\n inserted_text = input('&gt; ')\n except EOFError:\n print()\n break\n except KeyboardInterrupt:\n print()\n continue\n if inserted_text.lower() == 'f':\n break\n if not inserted_text:\n continue\n try:\n n = int(inserted_text)\n except ValueError:\n print('That\\'s not a valid number.')\n continue\n numbers.append(n)\n\nif numbers:\n print('Here are your numbers and their sum:')\n print(' + '.join(map(str, numbers)), '=', sum(numbers))\nelse:\n print('You did not enter a single number...')\n</code></pre>\n\n<p>I wrote the code in python3 because there is no reason to be using python2 here.</p>\n\n<p>Importing <code>readline</code> improves the usability of the <code>input</code> function on platforms that support it.</p>\n\n<p>I kept the possibility of entering \"f\" to exit, but really most regular console users will just press Ctrl+D, which is handled by the <code>except EOFError:</code> clause.</p>\n\n<p>I removed the calls to <code>clear</code> because they just annoy the user.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T12:50:22.303", "Id": "30613", "ParentId": "30581", "Score": "1" } }, { "body": "<p>I would do:</p>\n\n<pre><code>#!/usr/bin/python\nimport os\ngood_receipts = []\ninserted_text = 'go'\nwhile inserted_text != 'F':\n # This function is os dependent and will work only if you use linux\n os.system('clear')\n inserted_text = raw_input(\"Insert receipt number \"\n \"(if you finished insert 'f'): \").upper()\n if ''!=inserted_text!='F':\n good_receipts.append(inserted_text)\n if good_receipts:\n print \"Here's your receipts:\\n\",good_receipts\n if not good_receipts:\n print \"You didn't enter a single receipt...\"\n# This function is os dependent and will work only if you use linux\nos.system('clear')\nprint \"You did a great job, here's your receipts:\\n\",good_receipts\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T22:02:00.737", "Id": "30751", "ParentId": "30581", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T17:54:38.510", "Id": "30581", "Score": "1", "Tags": [ "python", "beginner" ], "Title": "Python raw_input and conditions" }
30581
<p>This program prints out a 10x10 square and uses only bit operations. It works well, but I don't like that global array. </p> <p>Can you tell me if the code is proper or not?</p> <pre><code>#include &lt;iostream&gt; const std::size_t HEIGHT = 10; const std::size_t WIDTH = 10; char graphics[WIDTH/8][HEIGHT]; inline void set_bit(std::size_t x, std::size_t y) { graphics[(x) / 8][y] |= (0x80 &gt;&gt; ((x) % 8)); } void print_screen(void) { for (int y = 0; y &lt; HEIGHT; y++) { for (int x = 0; x &lt; WIDTH/8+1; x++) { for (int i = 0x80; i != 0; i = (i &gt;&gt; 1)) { if ((graphics[x][y] &amp; i) != 0) std::cout &lt;&lt; "*"; else std::cout &lt;&lt; " "; } } std::cout&lt;&lt;std::endl; } } int main() { for(int x = 0; x &lt; WIDTH; x++) { for(int y = 0; y &lt; HEIGHT; y++) { if(x == 0 || y == 0 || x == WIDTH-1 || y == HEIGHT-1) set_bit(x,y); } } print_screen(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T19:14:50.177", "Id": "48659", "Score": "1", "body": "Why not pass the array as an argument and then make it local to `main`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T19:19:23.963", "Id": "48660", "Score": "0", "body": "because in the set_bit I have to change it. I tried using as a reference, but it said I couldn't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T19:33:11.833", "Id": "48661", "Score": "1", "body": "I'd use a 2D `std::array` as it's easier to handle, adding on to what busy_wait is suggesting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T19:41:59.113", "Id": "48664", "Score": "0", "body": "it's a solution for an exercise (from a c++ book). I had to use bits :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T19:44:17.413", "Id": "48665", "Score": "0", "body": "`std::vector<bool>` is optimized for space and since this is C++ you should prefer to use `vector` over an array anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T19:56:33.510", "Id": "48668", "Score": "0", "body": "@busy_wait: In that case (with bits), you're right. If bits weren't involved here, then in general, `std::array` would be good if dealing with a fixed size." } ]
[ { "body": "<p>That global array is indeed not good. You'll need to pass around an array, but you shouldn't do it with a C-style array. Doing that will cause it to <em>decay to a pointer</em>, which you should avoid in C++. If you have C++11, you could use <a href=\"http://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow noreferrer\"><code>std::array</code></a>, which will be set at an initial size. But if you don't have C++11, and also want to adjust the size, use an <a href=\"http://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow noreferrer\"><code>std::vector</code></a>. You can also compare the two <a href=\"https://stackoverflow.com/questions/4424579/stdvector-versus-stdarray-in-c\">here</a>. Either way, you'll be able to pass any of them around nicely, and it's something you should be doing in C++ anyway.</p>\n\n<p><strong>To match your environment, the following code does <em>not</em> utilize C++11.</strong></p>\n\n<p>I'll use <code>std::vector</code> here, but this can be done with other STL storage containers. Here's what a 2D vector would look like:</p>\n\n<pre><code>std::vector&lt;std::vector&lt;T&gt; &gt; matrix; // where T is the type\n</code></pre>\n\n<p>This type does look long, and you may not want to type it out each time. To \"shorten\" it, you can use <code>typedef</code> to create an alias (which is <em>not</em> a new type):</p>\n\n<pre><code>typedef std::vector&lt;std::vector&lt;T&gt; &gt; Matrix;\n</code></pre>\n\n<p>With that, you can use this type as such:</p>\n\n<pre><code>Matrix matrix;\n</code></pre>\n\n<p>and create the 2D vector of a specific size.</p>\n\n<p><em>However</em>, this is where the syntax gets nasty (especially lengthy). It's not set to a specific size, so you can just push vectors into it to increase the size. For a fixed size (using your size and data type), you'll have something like this:</p>\n\n<pre><code>std::vector&lt;std::vector&lt;char&gt; &gt; matrix(HEIGHT, std::vector&lt;char&gt;(WIDTH));\n</code></pre>\n\n<p>This can be made shorter by having <em>another</em> <code>typedef</code> to serve as a dimension of the matrix. This will also make it a little clearer what the vector means in this context.</p>\n\n<pre><code>typedef std::vector&lt;char&gt; MatrixDim;\n</code></pre>\n\n<p>It is then applied to the <code>Matrix</code> <code>typedef</code>:</p>\n\n<pre><code>typedef std::vector&lt;MatrixDim&gt; Matrix;\n</code></pre>\n\n<p>The 2D initialization will then become this:</p>\n\n<pre><code>Matrix matrix(HEIGHT, MatrixDim(WIDTH));\n</code></pre>\n\n<p>Now you can finally use this in <code>main()</code> and pass it to the other functions. Before you do that, you'll need a different loop counter type. With an STL storage container, you should use <a href=\"https://stackoverflow.com/questions/226302/where-can-i-look-up-the-definition-of-size-type-for-vectors-in-the-c-stl\"><code>std::size_type</code></a>. With <code>std::vector&lt;char&gt;</code>, specifically, you'll have:</p>\n\n<pre><code>std::vector&lt;char&gt;::size_type;\n</code></pre>\n\n<p>You can use yet another <code>typedef</code> for this:</p>\n\n<pre><code>typedef MatrixDim::size_type MatrixDimSize;\n</code></pre>\n\n<hr>\n\n<p>Here's what the functions will look like with the changes (explanations provided). I've also included some additional changes, which are also explained. The entire program with <a href=\"http://ideone.com/rquKtG\" rel=\"nofollow noreferrer\">my changes</a> applied and produces the same output as <a href=\"http://ideone.com/mEaziU\" rel=\"nofollow noreferrer\">yours</a>.</p>\n\n<p><strong><code>setbit()</code>:</strong></p>\n\n<pre><code>inline void set_bit(Matrix&amp; matrix, MatrixDimSize x, MatrixDimSize y)\n{\n matrix[(x) / 8][y] |= (0x80 &gt;&gt; ((x) % 8));\n}\n</code></pre>\n\n<ul>\n<li>An additional parameter of type <code>Matrix</code> is added. The matrix is passed in by reference and modified within the function.</li>\n<li>The <code>std::size_t</code> parameters were replaced with the <code>MatrixDimSize</code> type.</li>\n</ul>\n\n<p><strong><code>print_screen()</code>:</strong></p>\n\n<pre><code>void print_screen(Matrix const&amp; matrix)\n{\n for (MatrixDimSize y = 0; y &lt; HEIGHT; y++)\n {\n for (MatrixDimSize x = 0; x &lt; WIDTH/8+1; x++)\n {\n for (int i = 0x80; i != 0; i &gt;&gt;= 1)\n {\n std::cout &lt;&lt; (((matrix[x][y] &amp; i) != 0) ? '*' : ' ');\n }\n }\n\n std::cout &lt;&lt; \"\\n\";\n }\n}\n</code></pre>\n\n<ul>\n<li>A parameter of type <code>Matrix</code> is added. The matrix is passed in by <code>const&amp;</code>, which is necessary as the function displays the matrix but does not modify it. It's also cheaper to pass it this way as opposed to copying (passing by value).</li>\n<li><code>MatrixDimSize</code> is added for the loop counter types.</li>\n<li>The <code>if</code>/<code>else</code> is replaced with an equivalent ternary statement.</li>\n<li>A newline is done with <code>\"\\n\"</code> as opposed to <code>std::endl</code>. The latter also flushes the buffer, which is slower. You just need the former.</li>\n<li><code>i = (i &gt;&gt; 1)</code> is shortened to <code>i &gt;&gt;= 1</code>.</li>\n</ul>\n\n<p><strong><code>Main()</code>:</strong></p>\n\n<pre><code>int main()\n{\n Matrix matrix(HEIGHT, MatrixDim(WIDTH));\n\n for (MatrixDimSize x = 0; x &lt; WIDTH; x++)\n {\n for (MatrixDimSize y = 0; y &lt; HEIGHT; y++)\n {\n if (x == 0 || y == 0 || x == WIDTH-1 || y == HEIGHT-1)\n {\n set_bit(matrix, x, y);\n }\n }\n }\n\n print_screen(matrix);\n}\n</code></pre>\n\n<ul>\n<li>Both matrix vector <code>typedef</code>s are applied.</li>\n<li><code>MatrixDimSize</code> is added for the loop counter types.</li>\n<li>The matrix is passed to and modified <em>only</em> by <code>set_bit()</code>.\n\n<ul>\n<li>It is passed to <code>print_screen()</code> and is <em>not</em> modified.</li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-20T05:16:02.093", "Id": "42263", "ParentId": "30584", "Score": "12" } } ]
{ "AcceptedAnswerId": "42263", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T19:10:16.350", "Id": "30584", "Score": "11", "Tags": [ "c++", "matrix", "bitwise" ], "Title": "10x10 bitmapped square with bits" }
30584
<p>A function (often anonymous) bound to the referencing environment in its original lexical scope in such a way that it will still have access to that environment (its variables and other references) if executed outside that scope.</p> <p>It is the binding between the function and its original scope which distinguishes a closure from a simple anonymous function. Many imperative languages (e.g. Pascal and C) support function pointers, but when the referenced function is executed, it will only have access to its internal variables and to the referencing environment of the scope in which it is executed.</p> <p>Closures have been closely associated with functional programming since the invention of the Scheme language (in which all lambda functions are closures). While it is possible to construct a functional language without closures (the first versions of LISP did not have them), all modern functional languages currently support them.</p> <p>Closures are found much less frequently in imperative languages (while Smalltalk had them, Java still does not - though they are promised in version 8). Dynamic languages (e.g Perl, Ruby, JavaScript) have historically been much more forward in this area than their non-dynamic cousins.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T20:05:24.533", "Id": "30586", "Score": "0", "Tags": null, "Title": null }
30586
A function (often anonymous) bound to the referencing environment in its original lexical scope in such a way that it will still have access to that environment (its variables and other references) if executed outside that scope.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T20:05:24.533", "Id": "30587", "Score": "0", "Tags": null, "Title": null }
30587
<p>I've got information that is imported from a CSV file that my site grabs every day with PHP. I'm just learning RegEx so I'm able to do what I need to do but am looking to get more efficient with my coding.</p> <p>Some of example of the kinds of strings that would come in would be:</p> <pre><code>15 SE NORFOLK 5 NNE OAKLAND 1 S LOS ANGELES 1 NW SACRAMENTO BOSTON </code></pre> <p>It's basically numbers then directional letters then city name. Sometimes there aren't numbers and letters so I'm checking to see first and then just deleting them with <code>preg_replace</code> if there are (I just need the city name).</p> <p>Here's the expression I have that works:</p> <pre><code>$location = preg_replace('/^[\d]+[\s]+[a-zA-z]+[\s]/', '', $string); </code></pre> <p>I know with regex there are a bunch of different ways to different things so I'm curious if there's a more efficient way to do what I'm doing.</p>
[]
[ { "body": "<p>Leave out the square brackets:</p>\n\n<pre><code>^\\d+\\s+[A-Z]+\\s+\n</code></pre>\n\n<p>Square brackets are used for \"character classes\", like</p>\n\n<pre><code>[A-Z]\n</code></pre>\n\n<p>which matches exactly one letter out of the range A to Z.</p>\n\n<p><code>\\d</code> already is a class: all the numbers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T21:33:01.977", "Id": "48671", "Score": "0", "body": "Ok great! Thanks. I'm just learning, every little bit helps." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T20:50:36.030", "Id": "30591", "ParentId": "30590", "Score": "3" } }, { "body": "<p>Because you know that the City is always the last word of the line, you could always just look for that by doing something like :</p>\n\n<pre><code>$location = preg_replace('(\\S*\\s)*([a-zA-Z]+)(\\s*$)', '\\2', $string);\n</code></pre>\n\n<p>group 1: any non whitespace(\\S) followed by a whitespace(\\s) 0 or more times.\n (in your case up to 2)</p>\n\n<p>group2: any letter 1 or more times (the city name)</p>\n\n<p>group3: any number of spaces followed by the end of the line</p>\n\n<p><strong>note: IDK anything about PHP, so the way you need to reference the group names may be slightly different</strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-15T14:42:54.510", "Id": "57096", "ParentId": "30590", "Score": "1" } } ]
{ "AcceptedAnswerId": "30591", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T20:43:03.373", "Id": "30590", "Score": "1", "Tags": [ "php", "regex", "csv" ], "Title": "Grabbing city names and numbers from a CSV file" }
30590
<pre><code> public static Integer[] eliminateDuplicate(int[] a) { if (a == null) { throw new NullPointerException(); } List&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;(); for (int i = 0; i &lt; a.length; i++) { // include last element by default, if not the last element, do the check for duplication. if (i == a.length - 1 || a[i] != a[i + 1]) { list.add(a[i]); } } return list.toArray(new Integer[0]); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T21:15:00.920", "Id": "48669", "Score": "1", "body": "It would help if you added some comments about your intent and any problems you encountered or things you are unsure of. Code is not, in itself, documentation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-14T13:14:04.607", "Id": "164552", "Score": "0", "body": "Please add a comment detailing what you want improvement on in this code." } ]
[ { "body": "<p>Minor point - don't use an old c-style for loop to iterate through an array unless you absolutely have to (and you don't have to here). Please, this is 2013 not 2003 - generics have been here for a decade. You can use foreach:</p>\n\n<pre><code>if a.length &gt; 0 {\n int lastValue = a[0];\n list.add(lastValue);\n for (int i: a) { \n if (i != lastValue) {\n lastValue = i;\n list.add(i);\n }\n } \n}\n</code></pre>\n\n<p>Using old-style c-loops always opens a possibility of a stupid error. Since you can cache the last value you inserted in the array, you don't have to use the old-style loop. My loop also has just one check, and that check is cheaper to do than yours (or 200_success's) because it doesn't need to do the array look-up.</p>\n\n<p>Note that my solution inserts the first value without checking, while yours does this for the final one. Not only is this more logical (I think), it eliminated a check from the logic.</p>\n\n<p>Your method is called <strong>eliminateDuplicates</strong> but it will only do that if the list has already been sorted. If that was not done, it will only eleminiate <em>sequential</em> duplicates. That is, it will turn <strong>(3, 1, 2, 3, 3, 4, 3)</strong> into <strong>(3,1,2,3,4,3)</strong>.</p>\n\n<p>Is that what you want? The fact that you always keep the last member implies this, but how can we be sure? If it <em>is</em> so, either document the intent or maybe name the function more clearly (e.g. <strong>eliminateAdjacentDuplicates</strong>).</p>\n\n<p>If you want to eliminate all duplicates, then you could start by sorting the array. But since you are using the collections api, why not use a set?</p>\n\n<pre><code>Set&lt;Integer&gt; intSet = new HashSet&lt;Integer&gt;(Arrays.asList(a));\n</code></pre>\n\n<p>Then you just need to turn the set back into an array.</p>\n\n<p>I may have gone on at unnecessary length, but that's because you didn't properly document your intent. Please, if you learn nothing else, learn this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T22:32:52.560", "Id": "48678", "Score": "0", "body": "Since you accepted 200_success's answer, I guess you wanted to eliminate adjacent duplicates ;) But I've left my original comments in, despite having edited my code for clarity." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T21:35:58.390", "Id": "30595", "ParentId": "30592", "Score": "2" } }, { "body": "<p>Your function doesn't handle duplicates in the entire array, but only in consecutive entries. A better name might be <code>collapseConsecutive</code>.</p>\n\n<p>The input is an <code>int[]</code>, but the return type is <code>Integer[]</code>. Consistency would be nice.</p>\n\n<p>You don't need to throw <code>NullPointerException</code> explicitly. If <code>a</code> is <code>null</code>, then a <code>NullPointerException</code> will automatically be thrown when it tries to do <code>a.length</code>. If you really want to explicitly validate your arguments, you could throw <code>IllegalArgumentException</code> instead.</p>\n\n<p>A micro-optimization would be to change to</p>\n\n<pre><code>if (i == 0 || a[i] != a[i - 1]) {\n list.add(a[i]);\n}\n</code></pre>\n\n<p>Comparing against 0 is simpler than comparing against <code>a.length - 1</code> since the JVM (and CPUs) has an <code>ifeq</code> opcode for doing just that. To compare against <code>a.length - 1</code>, the bytecode would have to load <code>a.length - 1</code> into a register before comparing — and that is assuming that the compiler is smart enough to compute <code>a.length - 1</code> just once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T21:39:01.793", "Id": "48672", "Score": "0", "body": "See, JD? It's not just me not being sure of your intent." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T21:36:32.170", "Id": "30596", "ParentId": "30592", "Score": "2" } } ]
{ "AcceptedAnswerId": "30596", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T20:54:03.020", "Id": "30592", "Score": "-2", "Tags": [ "java", "array" ], "Title": "Eliminating duplicates in an array of ints" }
30592
<p>It's an exercise from a book. There is a given long integer that I should convert into 8 4-bit values. The exercise is not very clear for me, but I think I understood the task correctly. </p> <p>I googled how to return with an array in a function. In the splitter function I add the last 4 bits into the values array, then cut the them from the original number. </p> <p>Is this a good way to do this?</p> <pre><code>#include &lt;iostream&gt; int * splitter(long int number) { static int values[8]; for (int i = 0; i &lt; 8; i++) { values[i] = (int)(number &amp; 0xF); number = (number &gt;&gt; 4); } return values; } int main() { long int number = 432214123; int *values; values = splitter(number); for (int i = 7; i &gt;= 0; i--) std::cout &lt;&lt; values[i] &lt;&lt; " "; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T21:57:25.210", "Id": "48674", "Score": "0", "body": "I'm assuming a vector is out of the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T22:13:30.500", "Id": "48675", "Score": "0", "body": "well the book haven't mentioned it before, so I think I should use vectors in this exercise :D but pointers haven't been mentioned too..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T22:16:23.023", "Id": "48676", "Score": "1", "body": "Unless you were in a situation where you *must* use a certain method (such as a school assignment), I'd go for the best one possible. Although, there's nothing wrong with learning the basics (raw pointers). Of course, you can always maintain multiple versions of the same exercise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T22:32:18.217", "Id": "48677", "Score": "0", "body": "Would you like to see a version I've come up with using vectors?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T22:40:01.023", "Id": "48679", "Score": "0", "body": "yeah, sure :) But is my version good with the array?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T22:43:05.980", "Id": "48680", "Score": "1", "body": "If you're getting the correct output, then I'd say it'll work. Nothing wrong with seeing another method." } ]
[ { "body": "<p>This is how I would've implemented it with extensive use of the STL and C++11. It is a bit shorter than yours, but also more idiomatic. I've added comments throughout to help explain what each part does.</p>\n\n<p>The main thing to note here is that you should return a <em>container object</em> instead of a <em>pointer</em> to a <code>static</code> C array. It's best not to mess with raw pointers in C++ when possible, especially when it makes more sense to return a container object itself. The compiler should be able to optimize this via Return Value Optimization (RVO) as well. This object should then <em>not</em> be <code>static</code>.</p>\n\n<p><a href=\"http://ideone.com/m3RNT9\" rel=\"nofollow\">This</a> does produce the same output as <a href=\"http://ideone.com/Io2eSy\" rel=\"nofollow\">yours</a>:</p>\n\n<p></p>\n\n<pre><code>#include &lt;algorithm&gt; // std::reverse_copy()\n#include &lt;cstdint&gt; // std::int32_t\n#include &lt;iostream&gt;\n#include &lt;iterator&gt; // std::ostream_iterator\n#include &lt;vector&gt;\n\n// you could use a typedef to save some typing\n// also to give more meaning to your vector\ntypedef std::vector&lt;int&gt; SplitValues;\n\nSplitValues splitter(std::int32_t number)\n{\n SplitValues values(8);\n\n // work on vector elements using iterators\n for (auto&amp; iter : values)\n {\n iter = static_cast&lt;int&gt;(number &amp; 0xF); // cast the C++ way\n number &gt;&gt;= 4; // shorter form\n }\n\n return values;\n}\n\nint main()\n{\n std::int32_t number = 432214123;\n\n // local vector assigned to one returned from function\n SplitValues values = splitter(number);\n\n // display vector in reverse order using ostream iterator\n // this is done with one (wrapped) line and no loop\n std::reverse_copy(values.begin(), values.end(),\n std::ostream_iterator&lt;int&gt;(std::cout, \" \"));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-18T18:45:08.337", "Id": "95445", "Score": "0", "body": "The solution in this answer has received reviews [here](http://codereview.stackexchange.com/questions/54587/function-for-splitting-an-integer-into-smaller-values)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T22:51:10.860", "Id": "30599", "ParentId": "30593", "Score": "3" } }, { "body": "<p>There are only three issues I take with your code...</p>\n\n<ol>\n<li>The caller of the splitter function has the possibility of trying to access a value outside of the returned array and could cause a memory access violation if they did so. For this reason alone, it would be better to go with the vector approach that @Jamal posted. </li>\n<li>You should use the C++ style casting (e.g. <code>static_cast&lt;int&gt;(number &amp; 0XF)</code>) instead of the C style casting (e.g. <code>(int)(number &amp; 0xF)</code>). </li>\n<li>You should use <code>std::int32_t</code> instead of <code>long</code> or <code>std::uint32_t</code> instead of <code>unsigned long</code>. <code>long</code> is not gauranteed to be 32 bits, especially on 64 bit platforms. I don't take as big of an issue with this as some do though because on <em>most</em> systems, it will be <em>at least</em> 32 bits. </li>\n</ol>\n\n<p>Here is a solution that only returns one nybble at a time and throws an exception if the caller tries to access an invalid portion of the of number. Since your book hasn't talked about pointers or vectors yet, this might actually be the type of approach it is looking for (possibly minus the exception throwing if it hasn't talked about exceptions yet either). If you take away the exception throwing, the caller still cannot cause a memory access violation though. If they passed something lower than 0 or greater than 7 as the value of <code>part</code> they would just get a return value of <code>0</code>. </p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;stdexcept&gt;\n#include &lt;cstdint&gt;\n\nunsigned short get_nybble( std::uint32_t number, const unsigned short part )\n{\n if( part &gt; 7 )\n throw std::out_of_range(\"'part' must be a number between 0 and 7\");\n return (number &gt;&gt; (4 * part)) &amp; 0xF;\n}\n\nint main( int argc, char* argv[] )\n{\n std::uint32_t number = 432214123;\n try {\n for( short i = 7; i &gt;= 0; i-- )\n std::cout &lt;&lt; get_nybble(number, i) &lt;&lt; \" \";\n } catch( std::exception&amp; ex ) {\n std::cerr &lt;&lt; \"Error: \" &lt;&lt; ex.what() &lt;&lt; std::endl;\n }\n return 0;\n}\n</code></pre>\n\n<p>This may not be the best solution, but another approach I find interesting is an anonymous union combined with a bit field struct. This works with the GNU G++ compiler and should also work with Visual C++. Note that as I understand it this is potentially unsafe on non x86 systems due to the structure packing which I'd bet your book has not talked about yet either. </p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;cstdint&gt;\n\n#pragma pack(push, 1)\ntypedef union \n{\n std::uint32_t value;\n struct \n {\n std::uint32_t part1: 4;\n std::uint32_t part2: 4;\n std::uint32_t part3: 4;\n std::uint32_t part4: 4;\n std::uint32_t part5: 4;\n std::uint32_t part6: 4;\n std::uint32_t part7: 4;\n std::uint32_t part8: 4;\n };\n} nybbles;\n#pragma pack(pop)\n\nint main( int argc, char* argv[] )\n{\n nybbles num;\n num.value = 432214123;\n std::cout &lt;&lt; \"Parts = \"\n &lt;&lt; num.part8 &lt;&lt; \", \"\n &lt;&lt; num.part7 &lt;&lt; \", \"\n &lt;&lt; num.part6 &lt;&lt; \", \"\n &lt;&lt; num.part5 &lt;&lt; \", \"\n &lt;&lt; num.part4 &lt;&lt; \", \"\n &lt;&lt; num.part3 &lt;&lt; \", \"\n &lt;&lt; num.part2 &lt;&lt; \", \"\n &lt;&lt; num.part1 &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T04:12:35.467", "Id": "48693", "Score": "0", "body": "After running your first block through Ideone, the exception is already thrown. To fix this, change the `||` to `&&` in your function. Also, the loop in `main()` is printing an extra value. To fix that, change the 8 to 7. In case you haven't ran the OP's code, the expected output is `1 9 12 3 1 0 6 11` (I've also calculated that myself for confirmation)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T04:31:41.957", "Id": "48694", "Score": "0", "body": "This was a \"typo\" on my part. I originally had it as a 7 and changed it to an 8 to test that the exception was thrown correctly. I forgot to change it back to a 7. Changing the logical OR to an AND is bad idea though. The condition would NEVER be met." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T04:34:47.827", "Id": "48695", "Score": "0", "body": "Ah, I see. You're right about the conditions, though. Was being a little hasty trying to check it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T04:35:18.143", "Id": "48696", "Score": "0", "body": "Also, once you correct my typo. The output is `1 9 12 3 1 0 6 11`, the same as the OP's code. But the second solution is backwards though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T04:37:53.793", "Id": "48698", "Score": "0", "body": "Thanks for mentioning Ideone.com too. I had never heard of it before now. Looks handy for when you don't have a compiler to test with :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T04:41:14.480", "Id": "48699", "Score": "0", "body": "Indeed. It's very useful to me, as my computer's compiler (g++ 3.4.2) is old, preventing me from using some C++11 features such as range-based for-loops. Ideone covers all of that. By the way, good demonstration of exception-handling. Although my solution handles all of it, it'll help the OP and others at some point. +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T19:29:08.480", "Id": "48790", "Score": "0", "body": "Be sure to include `<cstdint>` for `std::int32_t`. I will add the same to my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T20:23:37.787", "Id": "48791", "Score": "0", "body": "@Jamal, Good point. `cstdint` is included via `iostream` (at least it is with GCC on GNU/Linux), but that's compiler dependent since it's [not defined in the C++ standard which headers have to include which](http://stackoverflow.com/a/3945920/1017257). I added it to both of my solutions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T20:26:28.113", "Id": "48792", "Score": "0", "body": "Right. It is also unfortunately that my compiler doesn't yell at me whenever I use `sqrt()` instead of `std::sqrt()`, with `<cmath>`." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T03:19:58.527", "Id": "30605", "ParentId": "30593", "Score": "6" } }, { "body": "<p>The C++ standard <a href=\"https://stackoverflow.com/questions/589575\">doesn't guarantee</a> that a <code>long</code> is 4 bytes — it may be longer. If you want 8 nibbles, then make <code>number</code> an <code>int32_t</code>. If you want to split a <code>long</code> into however many nibbles it takes, then use <code>2 * sizeof number</code> instead of <code>8</code>.</p>\n\n<p>Long decimal literals should have an <code>L</code> suffix: <code>long int number = 432214123L;</code></p>\n\n<p>It's fine to use a <code>static</code> array, but you should clearly document that fact in a comment. Also be aware that returning <code>static</code> values makes the design non-reentrant, i.e. not thread-safe. While you are at it, your comment should also mention that the results are least-significant-nibble first.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T09:04:12.620", "Id": "48714", "Score": "1", "body": "+1 That static could also easily kick RVO straight in the teeth. Use a local." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T06:44:38.047", "Id": "30607", "ParentId": "30593", "Score": "5" } } ]
{ "AcceptedAnswerId": "30605", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T21:25:44.023", "Id": "30593", "Score": "5", "Tags": [ "c++", "bitwise", "integer" ], "Title": "Split a long integer into eight 4-bit values" }
30593
<p>I am trying to parse this XML file. I have the extension and I need to get the description, icon, and class from the XML. My code works(ish) (I know how to continue from where I am), but it doesn't seem very elegant. Is there a better way of doing this?</p> <p>Here is the PHP code:</p> <pre><code>&lt;?php if($xml = simplexml_load_file('formats.xml')) { echo 'the file was loaded successfully'; $extn = 'log'; $xmltypes = $xml-&gt;xpath('//type'); foreach($xmltypes as $node) { foreach($node-&gt;attributes() as $name =&gt; $attrib) { if($name=='extension') { if($attrib==$extn) { $parent = $node-&gt;xpath('..'); foreach($parent[0]-&gt;attributes() as $a =&gt; $b) { if($a=='class') $class = $b; if($a=='icon') $icon = $b; } } } } } echo $extn.'&lt;br&gt;'; echo $icon.'&lt;br&gt;'; echo $class.'&lt;br&gt;'; } else { echo 'the file was not loaded'; } ?&gt; </code></pre> <p>Here is the XML file:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;extensions&gt; &lt;group class="doc"&gt; &lt;group icon="./.images/doc.png"&gt; &lt;type extension="doc" description="Legacy Word Document" /&gt; ... ... &lt;type extension="wps" description="Works Document" /&gt; &lt;/group&gt; &lt;/group&gt; &lt;group class="video"&gt; &lt;group icon="./.images/video.png"&gt; &lt;type extension="asf" description="Advanced Streaming Format" /&gt; ... ... &lt;type extension="mpeg" description="Motion Picture Experts Video" /&gt; &lt;/group&gt; &lt;/group&gt; &lt;/extensions&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T21:01:33.123", "Id": "48670", "Score": "0", "body": "You could put the attribute checks into the XPath query. Have a look at this XPath tutorial: http://schlitt.info/opensource/blog/0704_xpath.html" } ]
[ { "body": "<p>I'd make heavier use of <code>xpath</code>:</p>\n\n<pre><code>$xml = simplexml_load_string($x); // assume XML in $x\n$class = $xml-&gt;xpath(\"//type[@extension = 'doc']/../../@class\")[0];\n$icon = $xml-&gt;xpath(\"//type[@extension = 'doc']/../@icon\")[0];\n$description = $xml-&gt;xpath(\"//type[@extension = 'doc']/@description\")[0];\n\necho \"$class | $icon | $description\";\n</code></pre>\n\n<p>My code requires PHP >= 5.4, for older versions, do:</p>\n\n<pre><code>$class = $xml-&gt;xpath(\"//type[@extension = 'doc']/../../@class\");\n$class = $class[0];\n</code></pre>\n\n<p>or...</p>\n\n<pre><code>list($class,) = $xml-&gt;xpath(\"//type[@extension = 'doc']/../../@class\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T21:17:54.327", "Id": "30663", "ParentId": "30594", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T20:58:05.567", "Id": "30594", "Score": "0", "Tags": [ "php", "xml" ], "Title": "Better SimpleXML parsing method" }
30594
<p>I have recently started code kata and learning for myself, as I would like to learn test-first development. I have started doing a shopping cart as my code kata. I have included a test as well. I would like to know what are the ways I could improve my below code. I know I need to use dependency injection next step. If you find anything I can improve in my code, please let me know.</p> <pre><code>using System.Collections; using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace Domain.Tests.Shopping_Cart_Tests { [TestFixture] public class ShoppingCartTest { private IShoppingCart _shoppingCart; [SetUp] public void SetUp() { _shoppingCart = new ShoppingCart(); } [Test] public void ShouldBeAbleToAddToCart() { var item1 = new CartItem{ProductId="P1001",Name = "Logitech Mouse", Qty = 1, Price = 5.00}; _shoppingCart.AddToCart(item1); Assert.AreEqual(_shoppingCart.GetCartItems().Count, 1); } [Test] public void ShouldBeAbleToAddToCartMultipleItems() { var item1 = new CartItem { ProductId = "P1001", Name = "Logitech Mouse", Qty = 1, Price = 5.00 }; var item2 = new CartItem { ProductId = "P1002", Name = "Logitech Keyboard", Qty = 1, Price = 9.00 }; _shoppingCart.AddToCart(item1); _shoppingCart.AddToCart(item2); Assert.AreEqual(_shoppingCart.GetCartItems().Count, 2); } [Test] public void ShouldBeAbleToIncrementWhenAddTheSameItem() { var item1 = new CartItem { ProductId = "P1001", Name = "Logitech Mouse", Qty = 1, Price = 5.00 }; var item2 = new CartItem { ProductId = "P1001", Name = "Logitech Mouse", Qty = 2, Price = 5.00 }; var item3 = new CartItem { ProductId = "P1001", Name = "Logitech Mouse", Qty = 3, Price = 5.00 }; _shoppingCart.CheckItemExistThenAddToCart(item1); Assert.AreEqual(_shoppingCart.GetCartItems().Count, 1); _shoppingCart.CheckItemExistThenAddToCart(item2); Assert.AreEqual(_shoppingCart.GetCartItems().Count, 1); _shoppingCart.CheckItemExistThenAddToCart(item3); Assert.AreEqual(_shoppingCart.GetCartItems().Count,1); } } public interface IShoppingCart { void AddToCart(CartItem item); List&lt;CartItem&gt; GetCartItems(); void CheckItemExistThenAddToCart(CartItem item); } public class ShoppingCart : IShoppingCart, IEnumerable { private static List&lt;CartItem&gt; CartItems = null; public ShoppingCart() { CartItems = new List&lt;CartItem&gt;(); } public void AddToCart(CartItem item) { CartItems.Add(item); } public void CheckItemExistThenAddToCart(CartItem item) { var cartItem = CartItems.FirstOrDefault(ci =&gt; ci.ProductId == item.ProductId); if (cartItem == null) AddToCart(item); else cartItem.Qty += item.Qty; } public List&lt;CartItem&gt; GetCartItems() { return CartItems; } public IEnumerator GetEnumerator() { return (CartItems as IEnumerable).GetEnumerator(); } } public class CartItem { public string Name { get; set; } public double Price { get; set; } public int Qty { get; set; } public string ProductId { get; set; } } } </code></pre>
[]
[ { "body": "<ol>\n<li><code>public double Price { get; set; }</code> clearly should be of type <code>Decimal</code>. That is what <code>Decimal</code> for.</li>\n<li><code>private static List&lt;CartItem&gt; CartItems = null;</code> can be safely refactored to <code>Dictionary&lt;int, CartItem&gt;</code> with <code>ProductId</code> used as keys. Then <code>CheckItemExistThenAddToCart</code> can be refactored using <code>Dictionary.ContainsKey</code> method, and <code>GetCartItems</code> can return dictionary itself, <code>CartItems.Values</code> or <code>CartItems.Values.ToList()</code>. I think the latter option is the best, since it will copy the collection, which will restrict access to <code>CartItems</code> property. As of now, someone might modify it in outer code, which will result it modifying ShoppingCart state. Returning a copy will prevent that.</li>\n<li><code>return (CartItems as IEnumerable).GetEnumerator();</code> cast can be removed.</li>\n<li>I'm not sure i like the idea of having two methods to add items to the cart, which have different logic. It's pretty error-prone. Is it really necessary? I think you should probably stick to one. </li>\n<li>I think your shopping cart interface misses <code>Remove</code> method.</li>\n</ol>\n\n<p>Your unit tests look fine to me (except you should move them to different file), tho i'm not too experienced with them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T06:34:09.727", "Id": "30673", "ParentId": "30600", "Score": "2" } }, { "body": "<p><strong>Comments as method names</strong></p>\n\n<pre><code>public void CheckItemExistThenAddToCart(CartItem item)\n</code></pre>\n\n<p>The following is sufficient:</p>\n\n<pre><code>public void AddItem( CartItem item)\n</code></pre>\n\n<p>... but a XML comment would be excellent:</p>\n\n<pre><code>///&lt;param name=\"item\"&gt;\n/// Does nothing if null. Does not throw an exception\n///&lt;/param&gt;\n</code></pre>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/xmldoc/recommended-tags-for-documentation-comments\" rel=\"nofollow noreferrer\">Commenting code</a></p>\n\n<hr>\n\n<p>And this could also be fine:</p>\n\n<pre><code>public void Add( CartItem item)\n</code></pre>\n\n<p>... because the parameter tells us what's being added.</p>\n\n<hr>\n\n<p><strong>Multiple Add methods</strong></p>\n\n<p>Makes no sense. Why would a method arguement be validated sometimes and other times not? How would a maintenance programmer be expected to know when or why to call one or the other? </p>\n\n<p>If indeed multiple \"add\" methods are needed then overloading is what you want. Overloading is a fabulous way of saying \"hey, you can do the same thing, but differently\" Not overloading obscures the fact that the methods all do the same thing. Then, overloading highlights what's important - that with different object types we get the same result.</p>\n\n<hr>\n\n<p><strong>Superfluous Tests</strong></p>\n\n<p>I argue that the two \"addToCart\" tests is one too many. There's nothing specical about adding one and then several others; unless there are special requirements like duplicate items not allowed. Or something special about adding objects with particular different properties.</p>\n\n<p>Instead I rather see how passing null works. This is clearly a different/special case.</p>\n\n<hr>\n\n<p><strong>Use messages in tests</strong></p>\n\n<p>I strongly urge in the most emphatic way that you add a message parameter to every test. When you are reading oodles of useless generic test output that says, like, \"expected to be equal but was not\" you'll understand. Also the test method signature becomes more self documenting and is a huge help for anyone reading the code. Again, imagine dozens and hundreds of tests that you need to make sense of. </p>\n\n<hr>\n\n<p><strong>Code file organization</strong></p>\n\n<p>Putting the code under a \"testing\" namespace is misleading, the seed for bad solution organization, and just lazy.</p>\n\n<p>The convention I've learned is that test code is not only in separate files but also in its own project(s), generally with file and project naming that \"pairs\" it with the particular target code.</p>\n\n<p>As your applications grow and you implement continuous integration you'll be glad you took the time.</p>\n\n<hr>\n\n<p><strong><code>CartItem</code></strong></p>\n\n<p>Yeah, I know that writing short, so called Data Transfer Objects (DTO) is a thing. But inappropriate here. If you want to \".. use dependency injection next step\", start here. Use a constructor to inject the values. Thus YOU, not the client code, guarantee complete, valid, immuteable objects. </p>\n\n<p>Simple immuteability is its own virtue. The very worst of our code base is due in very large part to changing object properties willy-nilly. </p>\n\n<p>You really, really, really need to develop a defensive mindset, generally. Write code that can't be FUBARed. By hiding state and exposing appropriate functionality you force the coder to do the right thing. And at the same time communicate design, the domain, and behavior. Think \"Application Public Interface.\"</p>\n\n<hr>\n\n<p><strong>Single Responsibility - <code>ShoppingCart</code></strong></p>\n\n<p>Should calcualte it's own total. Client code should only ask for the total, not calculate it. Taxes calculation may or may not be in here. Depends on how the design and requirements evolve. </p>\n\n<p>Don't expose the cart items list to clients; at least I don't think you need too given the code so far.</p>\n\n<p>Consider <code>ToString()</code> override for a nicely formatted \"reciept\".</p>\n\n<hr>\n\n<p><strong>Single Responsibility - An items collection</strong></p>\n\n<p>This is a really excellent exercise for understanding SRP. </p>\n\n<p>Make a <code>ItemsCollection</code> class. Put the enumerator in here. Have simple properties like \"total price\", \"total quantity\" and any others appropriate for lists of things.</p>\n\n<p>Override <code>ToString()</code> for a nice listing. Refactor <code>ShoppingCart.ToString</code> to use that. And generally fine tune the item list and shopping cart classes for SRP-ness. </p>\n\n<p><code>ShoppingCart</code> will still have a total method; which will call the collection total method. This is one example of how a shopping cart client will talk to the shopping cart and be ignorant of shopping cart implementation. It is also an example of \"Maximize cohesion and minimize coupling\" (I love that phrase!).</p>\n\n<p>As for general implementation I prefer to \"have a\" generic List (or other appripriate NET-supplied collection class) instead of inheriting from List or implementing ICollection, etc. Why? Because it hides all the .NET-supplied pubilc properties and methods and I expose precisely and only the functionality I want. It goes to design intent, SRP, defensive coding, user requirements, domain specific language, etc. </p>\n\n<hr>\n\n<p><strong>Single Responsibility - Custom collections</strong></p>\n\n<p>For me has become a no-brainer for good SRP application and enhanced functionality. The .NET framework collections take advantage of \"equals\", \"IComparable\", and \"IEquateable\" (more?). All of a sudden \"Find\", \"Sort\", \"Contains\" collection methods work like magic (from the client code perspective).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-16T01:23:44.657", "Id": "169363", "ParentId": "30600", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T23:31:36.900", "Id": "30600", "Score": "4", "Tags": [ "c#", "e-commerce" ], "Title": "Shopping cart code kata" }
30600
<p>I'm working my way through <em>The Java Programming Language, 4th edition</em>. This is exercise 2.2:</p> <blockquote> <p>Write a LinkedList class that has a field of type Object and a reference to the next LinkedList element in the list.</p> </blockquote> <p>Is this an adequate solution? Is there a more efficient way to build up a test list for this example?</p> <pre><code>class Node { private Object data; private Node next; public Node(Object data) { this(data, null); } public Node(Object data, Node next) { this.data = data; this.next = next; } public void setData(Object data) { this.data = data; } public Object getData() { return data; } public Node getNext() { return next; } } class LinkedListTest { public static void main(String[] args) { Node node3 = new Node("puke"); Node node2 = new Node("vomit", node3); Node node1 = new Node("blah", node2); Node node = node1; while (node != null) { System.out.println("Data = " + node.getData()); node = node.getNext(); } } } </code></pre>
[]
[ { "body": "<p>I would say it is an adequate solution. The product may not feel very useful yet, but it's probably not supposed to be. In some sense, the exercise is formulated ambiguously. Your <code>Node</code> class can be used to construct linked lists and as such is a building block of instantiated linked lists. However, I would not consider that a <code>LinkedList</code> implementation. A <code>LinkedList</code> implementation would consist of a wrapper class that hides this <code>Node</code> from the user and allows you to say thinks like</p>\n\n<pre><code>List list = new LinkedList();\nlist.add(\"foo\"); \nlist.add(\"bar\"); \nlist.remove(\"foo\"); \nint index = list.indexOf(\"bar\");\netc.\n</code></pre>\n\n<p>It may seem somewhat unsatisfactory that you have to construct your test list so clumsily, but ease of use wasn't a goal of the exercise ;)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T21:53:59.330", "Id": "48747", "Score": "0", "body": "Thanks for the feedback. I found a nice overview and basic implementation at: [Linked List Overview](http://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/linked%20lists.html) & [LinkedList.java](http://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/code/LinkedList.java)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T07:24:58.247", "Id": "48759", "Score": "0", "body": "You can find an old version of the LinkedList in the OpenJdk here: http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/9b8c96f96a0f/src/share/classes/java/util/LinkedList.java" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T12:01:17.933", "Id": "30612", "ParentId": "30602", "Score": "4" } } ]
{ "AcceptedAnswerId": "30612", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T00:31:05.517", "Id": "30602", "Score": "2", "Tags": [ "java", "linked-list" ], "Title": "Critique of LinkedList class" }
30602
<p>I am coding a Hanning filter which is a recursive relation: </p> <pre><code>y[i] = 0.25*(x[i] + 2*x[i-1] + x[i-2]) </code></pre> <p>And here is my code were I attempt to unroll 3 times:</p> <pre><code>public void HanningFilter(float[] array) { int len = array.length; int i; for (i = 2; i &lt; len-3; i+=3) { array[i] = 0.25f*(array[i] + 2*array[i-1] + array[i-2]); array[i+1] = 0.25f*(array[i+1] + 2*array[i] + array[i-1]); array[i+2] = 0.25f*(array[i+2] + 2*array[i+1] + array[i]); } //Clean-up at the end for (int j = i; j &lt; len; j++) { array[i] = 0.25f*(array[i] + 2*array[i-1] + array[i-2]); } } </code></pre> <p>Would this help at all with an OoO superscalar processor? Is 3 the right amount of times to unroll? Thanks</p>
[]
[ { "body": "<p>The standard advice is, premature optimization is evil. Write the code cleanly and let the compiler and JIT do their job. If, after profiling the code for your entire program, this particular function is found to be a hot spot, then try it with loop unrolling and see if it makes a difference. But you shouldn't uglify your code unless you have numerical evidence that it improves performance enough to matter.</p>\n\n<p>By the way, each array element is calculated based on itself and two previous values, but the previous values are taken from the output rather than the input. That's a bug. In other words, you implemented</p>\n\n<pre><code>y[i] = 0.25*(x[i] + 2*y[i-1] + y[i-2])\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>y[i] = 0.25*(x[i] + 2*x[i-1] + x[i-2])\n</code></pre>\n\n<p>To convolve the values without allocating extra space, start at the end of the array and work towards the front.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T07:01:21.180", "Id": "30608", "ParentId": "30603", "Score": "3" } }, { "body": "<p>No, rule of thumbs for this case:</p>\n\n<ul>\n<li>Never guess optimizations, use a profiler</li>\n<li>You're not smarter then the JIT compiler</li>\n</ul>\n\n<p>Loop unrolling only makes sense if you profiled the code and found the unrolled version to be faster then the normal version.</p>\n\n<p>I guess you're coming from a C background, so please don't try to bring C-habits to Java. Java is different, always go for readability first.</p>\n\n<hr>\n\n<pre><code>public void HanningFilter(float[] array) {\n</code></pre>\n\n<p>The Java naming conventions dictate that function names are lowerCamelCase.</p>\n\n<p>Also the name <code>array</code> is a bad name, more appropriate would be a name like <code>data</code> or <code>input</code>.</p>\n\n<hr>\n\n<pre><code>int len = array.length;\nint i;\nfor (i = 2; i &lt; len-3; i+=3) {\n</code></pre>\n\n<p>What you're doing here is absolutely unnecessary. Java allows declarations of variables inside the for and there's no need to define a variable for the condition.</p>\n\n<pre><code>for (int idx = 2; idx &lt; data.length; idx++) {\n</code></pre>\n\n<p>Naming loop variables <code>idx</code> or <code>counter</code> is not very famous, I prefer it to <code>i</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T15:02:25.183", "Id": "30617", "ParentId": "30603", "Score": "8" } }, { "body": "<p>The JIT compiler does loop unrolling for you (a lot more than 3 iterations per loop) and it will revert the change if it does not help performance - writing your own is probably counterproductive and detrimental to performance.</p>\n\n<p>You could play with <a href=\"http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html\" rel=\"nofollow\">the <code>-XX:LoopUnrollLimit=n</code> option on hotspot</a> to see if it makes a difference (probably not).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T17:52:04.993", "Id": "30699", "ParentId": "30603", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T01:09:57.220", "Id": "30603", "Score": "4", "Tags": [ "java", "optimization" ], "Title": "Does this loop unrolling make sense?" }
30603
<p>Nearly time to hand this project in, and I want it to be as close to perfect as possible. So, any issue (no matter how small) - let me know. If you have any ideas that would improve the efficiency or readability of my code (e.g. delegates), let me know.</p> <p>I am already aware that I should use camelCase for variables and PascalCase for methods. I will do that at completion of the code.</p> <p><code>AStar</code> class:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace prjT02L08_Predator_Prey { public class AStar //Variant on Dijkstra's Algorithm - faster { public static Node[,] Grid; //Using the data type created below to make a grid, a 2 dimensional array of nodes (squares) public static List&lt;Node&gt; FindPath(Point start, Point end) //Finds the fastest route from the start to end { //Checks that we aren't trying to make a path from one place to the same place if (start.X == end.X &amp;&amp; start.Y == end.Y) { return null; } //Resets all the parent variables to clear the paths created last time for (int x = 0; x &lt;= Grid.GetUpperBound(0); x++) { for (int y = 0; y &lt;= Grid.GetUpperBound(1); y++) { Grid[x, y].Parent = null; } } List&lt;Node&gt; OpenList = new List&lt;Node&gt;(); //Nodes to be considered, ones that may be on the path //The above OpenList would be better as an OrderedList, however, I wanted to implement my own sort //An even better solution, and more "complex", would be to implement a Red-Black Tree //I can get this to work, but am unsure about how to add a delete() method //List&lt;Node&gt; ClosedList = new List&lt;Node&gt;(); //This is replaced by the dictionary below - Faster sorting using a key //Dictionary&lt;UInt64, Node&gt; ClosedList = new Dictionary&lt;UInt64,Node&gt;(); //This is replaced by the HashSet below - O(1) instead of O(n) for searching and removing data. //Also O(1) for adding, unless the size needs to be increased (then O(n)) HashSet&lt;Node&gt; ClosedList = new HashSet&lt;Node&gt;(); //Explored nodes Point CurrentPoint = new Point(0, 0); Node Current = null; List&lt;Node&gt; Path = null; OpenList.Add(Grid[start.X, start.Y]); //Add the starting point to OpenList while (OpenList.Count &gt; 0) { //Explores for the "best" choice in the Openlist Current = OpenList[0]; CurrentPoint.X = Current.X; CurrentPoint.Y = Current.Y; if (CurrentPoint == end) break; //If we have reached the end OpenList.RemoveAt(0); //Removes the starting point ClosedList.Add(Current); foreach (Node neighbour in GetNeighbours(CurrentPoint)) //Checks all the squares adjacent to the current point { //Skips fully explored nodes which have been explored fully if (ClosedList.Contains(neighbour)) continue; //Skips the node if it's a wall if (neighbour.IsWall) continue; //If parent is null, it's our first visit to the node if (neighbour.Parent == null) { neighbour.G = Current.G + 10; //10 is the cost for each horizontal or vertical node moved neighbour.Parent = Current; //Where it came from, final path can be found by linking parents //The following way of calculating the H value is called the Manhattan method, it ignores any obstacles neighbour.H = Math.Abs(neighbour.X - end.X) + Math.Abs(neighbour.Y - end.Y); //Calculates total cost by combining the X distance by the Y neighbour.H *= 10; //Then multiply H by 10 (The cost movement for each square) OpenList.Add(neighbour); } else { //Is this a more efficient route than last time? if (Current.G + 10 &lt; neighbour.G) { neighbour.Parent = Current; neighbour.G = Current.G + 10; } } } //OpenList.Sort(); //This uses the IComparible interface and CompareWith() method to sort //This is very slow to do every time //Could be replaced with a SortedSet //Also very slow - O(In N) OpenList = MergeSort.Sort(OpenList).ToList(); } //If we finished, end will have a parent, otherwise not Path = new List&lt;Node&gt;(); Current = Grid[end.X, end.Y]; //Current = end desination node Path.Add(Current); while (Current.Parent != null) //Won't run if end doesn't have a parent { Path.Add(Current.Parent); Current = Current.Parent; } //Path.Reverse(); //.reverse() (Above) is replaced with the below code for (int i = 0; i &lt; Path.Count() / 2; i++) { Node Temp = Path[i]; Path[i] = Path[Path.Count() - i - 1]; Path[Path.Count() - i - 1] = Temp; } //Checks if we've found our path or used all our options return OpenList.Count &gt; 1 ? Path : null; //Below replaced by Ternary Statement above /*if (OpenList.Count &gt; 1) return Path; else return null;*/ } private static List&lt;Node&gt; GetNeighbours(Point p) //Finds all adjacent nodes to the node at point p { List&lt;Node&gt; Result = new List&lt;Node&gt;(); //All the IF statements below are to check that we're not adding nodes outside of the grid, causing an error //All the code within the IF statements add the nodes adjacent to the node at point p if (p.X - 1 &gt;= 0) { Result.Add(Grid[p.X - 1, p.Y]); //Left } if (p.X &lt; Grid.GetUpperBound(0)) { Result.Add(Grid[p.X + 1, p.Y]); //Right } if (p.Y - 1 &gt;= 0) { Result.Add(Grid[p.X, p.Y - 1]); //Below } if (p.Y &lt; Grid.GetUpperBound(1)) { Result.Add(Grid[p.X, p.Y + 1]); //Above } return Result; //Returns all neighbours } } } </code></pre> <p><code>Node</code> class:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace prjT02L08_Predator_Prey { public class Node// : IComparable&lt;Node&gt; //Inherits from the interface IComparable, allows the nodes to be sorted using .sort() { public int X; //Position on the X axis public int Y; //Position on the Y axis public Node Parent; //The node which this node has just come from public bool IsWall; //States whether the given node is a wall or not public int G; //The amount needed to move from the starting node to the given other public int H; //The estimated cost to move from that given node to the end point - Called Heuristic (Because it's a guess) public int F //G+H { get { return G + H; } //Automatically calculates the latest value when F is accessed } /*This must be added due to IComparable (It requires a method called "CompareTo" to work) - specifies how to sort the nodes*/ //public int CompareTo(Node other) //{ // if (this.F &lt; other.F) return -1; // else if (this.F == other.F) return 0; // else return 1; //} //If a bool is given to reset G, H and Parent then this resets them back to the default values, otherwise makes Result equal to this node public Node Clone(bool ResetGHandParent) { Node Result = new Node(); Result.X = this.X; Result.Y = this.Y; Result.IsWall = this.IsWall; if (ResetGHandParent) { Result.G = 0; Result.H = 0; Result.Parent = null; } else { Result.G = this.G; Result.H = this.H; Result.Parent = this.Parent; } return Result; } //Same as above, but in case the boolean isn't given - false is assumed public Node Clone() { //The code below sets all the variables of results to the same variables of the current node Node Result = new Node(); Result.X = this.X; Result.Y = this.Y; Result.IsWall = this.IsWall; Result.G = this.G; Result.H = this.H; return Result; } public static Node[,] MakeGrid(int Width, int Height) //This function is just to prevent any accidental errors I may make in the Form1 by not wanting any walls { //If a value isn't set for PercentWallChance in Form1, we assume they don't want walls and set the chance to 0 return MakeGrid(Width, Height, 0); //Calls upon the other make grid, so no code is repeated, with 0 as the PercentWallChance } public static Node[,] MakeGrid(int Width, int Height, int PercentWallChance) //Same name as the MakeGrid above, but with different parameters { Node[,] Result = new Node[Width, Height]; //Produces the grid Random r = new Random(); //A random variable to be used later in this method //These two loops mean all nodes in the grid are covered - from 0, 0 to Width - 1, Height - 1 for (int x = 0; x &lt; Width; x++) //Loops through all X co-ordinates { for (int y = 0; y &lt; Height; y++) //Loops through all Y co-ordinates { //Sets all the variables within the Result nodes to default values Result[x, y] = new Node(); Result[x, y].Parent = null; //It has no parent as it hasn't been explored Result[x, y].X = x; //Sets it's X location Result[x, y].Y = y; //Sets it's Y location Result[x, y].G = 0; //Not in use yet Result[x, y].H = 0; //Not in use yet //This section of code below confuses me, so I will reference Jaz's comments: //This takes advantage of the fact that &lt; is a comparison operator, and will give a boolean result //r.Next(100) will generate a number from 0 to 99. //If % wallchance is 100, then r cannot NOT be less than it, and the "&lt;" will always return true (which in turn always sets IsWall to true) //If % wallchance is 0, then r literally cannot be less it, and the comparison will return false (which in turn always sets IsWall to false) Result[x, y].IsWall = r.Next(100) &lt; PercentWallChance; } } return Result; //Returns the grid } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T05:33:19.853", "Id": "48700", "Score": "0", "body": "1. Split that giant method into smaller methods 2. Don't use `List`, use the correct data structure for the [open list](https://bitbucket.org/BlueRaja/high-speed-priority-queue-for-c/wiki/Home) and the [closed list](http://msdn.microsoft.com/en-us/library/bb359438.aspx). 3. If the graph is unweighted, why use a weight of `10` rather than just `1`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T05:34:24.220", "Id": "48701", "Score": "0", "body": "@BlueRaja-DannyPflughoeft What do you mean don't use List? What should I use instead, where and why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T05:39:17.717", "Id": "48702", "Score": "0", "body": "Sorry, I was still writing my comment. `openList` is supposed to be a priority queue - I linked above to an implementation I wrote which is specifically optimized for pathfinding. The `closedList` should be a set with O(1) `.Add()` and `.Contains()`, such as a `HashSet<T>`. Doing this should **significantly** speed up your pathfinding, while simultaneously making your code easier to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T05:45:04.513", "Id": "48704", "Score": "0", "body": "@BlueRaja-DannyPflughoeft Thanks, ClosedList is currently a HashSet in the code above (At least, that's what I think I did before). I was going to implement a Priority Queue, but my teacher said she'd rather see a sort (So I used MergeSort). I think I'll ignore her and do what you say! Nice Priority Queue by the way. Also, what do you mean by unweighted graph?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T05:46:59.290", "Id": "48705", "Score": "0", "body": "@BlueRaja-DannyPflughoeft Sorry, don't think I can use it. I have to use 100% my own code. I can't use external libraries unfortunately :(. And priority queues aren't easy to make yourself, are they?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T06:11:35.447", "Id": "48706", "Score": "1", "body": "A simple one would not be too difficult if you understand how a heap works. But, if this is for an assignment, I would just not use one. Though, I'm surprised your professor didn't provide you with one - emulating a priority queue with a list will cause A\\* to run insanely slower." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T06:37:27.913", "Id": "48708", "Score": "0", "body": "@BlueRaja-DannyPflughoeft Not a university assignment! It's actually for my A-Level. It can be a project of your choice, I chose pathfinding (Predator-Prey). I'm allowed very little help from my teacher, and no code from the internet :P I may use one just because it's fancy, thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T18:49:48.070", "Id": "53839", "Score": "3", "body": "@BlueRaja-DannyPflughoeft you should post all your comments as one answer to this post, so that it shows it has been answered, it looks like you have helped the OP Quite a bit, you should get credit for it." } ]
[ { "body": "<ul>\n<li><p>It is better to declare by interface instead of implementation.</p>\n\n<pre><code>List&lt;Node&gt; OpenList = new List&lt;Node&gt;();\nHashSet&lt;Node&gt; ClosedList = new HashSet&lt;Node&gt;();\n</code></pre>\n\n<p>Can become:</p>\n\n<pre><code>IList&lt;Node&gt; OpenList = new List&lt;Node&gt;();\nISet&lt;Node&gt; ClosedList = new HashSet&lt;Node&gt;();\n</code></pre>\n\n<p>This allows you to more easily change the implementation without having to change on multiple spaces. (This is extra important when passing objects between methods!)</p></li>\n<li><p>Initialize <code>CurrentPoint</code> to null instead of creating a new point at (0, 0). That point is currently not used.</p></li>\n<li><p><strike>3</strike> <strong>10</strong> is a magic number, yes it is, it's a magic number. If you would like to change the move cost on the map you would have to modify at multiple places, modifying some but not all of the occurrences would lead to unexpected behavior (bugs!). Declare a <code>const int MoveCost = 10;</code> and use that throughout your code.</p></li>\n<li><p>I am not so sure about that ternary statement and the condition <code>OpenList.Count &gt; 1</code>. It's been a while since I used A* but I believe it's possible for all nodes to be added to <code>ClosedList</code> and thus the entire map has been exhausted before finally a path was found (consider a map where there is only one possible path to go, entirely surrounded by walls). I would use a different condition here, like <code>Path.Count &gt; 1</code>.</p></li>\n<li><p>In your <code>GetNeighbours</code> method you can use the <code>yield</code> keyword and use the return type <code>IEnumerable&lt;Node&gt;</code> to avoid having to initialize a list.</p></li>\n<li><p>Split the <code>FindPath</code> method at least in two, one for reaching the goal and one for backtracking.</p></li>\n<li><p>Overall, your code is well formatted and very easy to read. You use quite good variable and method names. It has been a pleasure reading your code. You seem to know what you are doing and I hope you will continue on your path. (Where-ever the <code>ClosedList</code> leads you)</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T13:13:33.517", "Id": "79594", "Score": "1", "body": "I'd mention, that the declaration by interface becomes useless when you want to access implementation-specific methods. Thus it somewhat depends on what you want to use, but as there's nothing specific used in OP's code I guess it's fine ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T18:43:12.870", "Id": "45533", "ParentId": "30606", "Score": "5" } }, { "body": "<p>Just a couple random observations...</p>\n\n<blockquote>\n<pre><code>public int X; //Position on the X axis\npublic int Y; //Position on the Y axis\npublic Node Parent; //The node which this node has just come from\npublic bool IsWall; //States whether the given node is a wall or not\npublic int G; //The amount needed to move from the starting node to the given other\npublic int H; //The estimated cost to move from that given node to the end point - Called Heuristic (Because it's a guess)\npublic int F //G+H\n{\n get { return G + H; } //Automatically calculates the latest value when F is accessed\n}\n</code></pre>\n</blockquote>\n\n<p>Except for <code>F</code> (a get-only <em>property</em>), those are <em>public fields</em>, it would probably be best to turn them into <em>properties</em>.</p>\n\n<p>The naming for <code>G</code>, <code>H</code> and <code>F</code> is... without XML comments, not meaningful at all. Naming is hard, but it's worth taking the time to name things properly, for readability's sake.</p>\n\n<p>I find it odd that you're using a <code>Point</code> in <code>GetNeighbours</code>, but that you're not using it as a single <code>Location</code> property for your nodes (instead of having a <code>int X</code> and a <code>int Y</code> field/property, I'd have a single <code>Point Location</code> property there).</p>\n\n<p><code>F</code> has no reason to be <code>public</code>, it's only used in <code>IComparable.CompareTo</code> and could very well be made <code>private</code>.</p>\n\n<hr>\n\n<p>That part:</p>\n\n<pre><code>Result[x, y] = new Node();\nResult[x, y].Parent = null; //It has no parent as it hasn't been explored\nResult[x, y].X = x; //Sets it's X location\nResult[x, y].Y = y; //Sets it's Y location\nResult[x, y].G = 0; //Not in use yet\nResult[x, y].H = 0; //Not in use yet\n</code></pre>\n\n<p>Would be clearer it written like this:</p>\n\n<pre><code>var node = new Node \n { \n Location = new Point(x, y),\n Parent = null, // redundant default value\n G = 0, // redundant default value\n H = 0, // redundant default value \n IsWall = r.Next(100)\n };\nresult[x, y] = node;\n</code></pre>\n\n<p>Now from what I'm reading, it looks like a <code>Node</code>'s <code>Location</code> and <code>IsWall</code> members should be <code>readonly</code>. You can enforce this with a constructor:</p>\n\n<pre><code>public Node(Point location, bool isWall)\n{\n _location = location;\n _isWall = isWall;\n}\n\nprivate readonly Point _location;\npublic Point Location { get { return _location; } }\n\nprivate bool _isWall;\npublic bool IsWall { get { return _isWall; } }\n</code></pre>\n\n<p>Introducing a parameterized constructor will remove the class' <em>default, parameterless constructor</em> unless you explicitly provide one, but here it wouldn't be needed. Instead, you can change your <code>new</code>ing up code to this:</p>\n\n<pre><code>var node = new Node(new Point(x, y), r.Next(100));\nresult[x, y] = node;\n</code></pre>\n\n<hr>\n\n<p>The <code>Point</code> structure <a href=\"http://msdn.microsoft.com/en-US/library/kek25c8y.aspx\" rel=\"nofollow\">overrides <code>ValueType.Equals</code></a>, which means this condition:</p>\n\n<pre><code>if (start.X == end.X &amp;&amp; start.Y == end.Y)\n</code></pre>\n\n<p>Could be rewritten like this:</p>\n\n<pre><code>if (start.Equals(end))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T13:16:01.217", "Id": "79595", "Score": "1", "body": "The naming for G, H and F is **perfect** if you are familiar with the `A*` algorithm. I would actually name them the same thing. No need to describe the variable names such as `cost`, `heuristic` and `sumOfCostAndHeuristic` if you are familiar with the algorithm and therefore know what F, G and H is. `F = G + H` just as `y = kx + m` or `E = mc2`. +1 for the rest of it though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T13:31:04.943", "Id": "79597", "Score": "0", "body": "Thanks, indeed that's not an algorithm I'm familiar with ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T01:05:39.647", "Id": "45570", "ParentId": "30606", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T05:05:17.243", "Id": "30606", "Score": "7", "Tags": [ "c#", "performance", "pathfinding" ], "Title": "Path finding - again" }
30606
<p>I want to make a graph from input from a text file in the format:</p> <pre><code>vertex1 vertex2 cost time </code></pre> <p>where vertex1 and vertex2 are strings that form an edge and cost and time are the properties of that edge. This information will be used to construct the Graph based on cost. I want to plan out the project before coding it so I have a good idea of what to do. So far I decided on the following classes:</p> <pre><code>class Edge { private: int vertex1; int vertex1; int cost; int time; public: Edge(int v1, int v2, int cost, int time) { this-&gt;vertex1 = v1; this-&gt;vertex2 = v2; this-&gt;cost = cost; this-&gt;time = time; } ~Edge(); int getEdgeCost(); int getEdgeTime(); }; class Graph { private: vector&lt;Edges&gt; edge; //edges in graph public: Graph() : edge(0) {} ~Graph(){} int getTotalCost(); int getTotalTime(); void addEdge(Edge e); Graph getMinSpanTree(); }; class Vertex { private: string name; int number; bool visited; vector&lt;Edges&gt; connEdges; // vector of all edges connected to this vertex public: Vertex(string name, int number) { this-&gt;name = name; this-&gt;number = number; visited = true; } ~Vertex(); string getName(); int getNum(); bool wasVisited(); Graph getShortestPath(); }; int main(int argc, char* argv[]) { std::string ifileName = std::string(argv[1]); ifstream ifile; if(ifile) ifile.open(ifileName); Edge edge; Graph* p_graph; Vertex v; string vert1, vert2; int cost, time; int i = 1; // numbers each vertex while(ifile.good()) { // read in input, put it in vars above, skipped for brevity // make the vertices v1 = new Vertex(vert1, i); i++; // increments vertex number v2 = new Vertex(vert2, i); i++; // make the edge edge = new Edge(v1.getNum(), v2.getNum(), cost, time); // add it to graph p_graph-&gt;addEdge(edge); } </code></pre> <p>Is my design correct or is it lacking something? Can it be improved?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-29T04:22:16.150", "Id": "97468", "Score": "0", "body": "In `main()`, where are `v1` and `v2` declared?" } ]
[ { "body": "<p><strong>Overall</strong></p>\n\n<p>Resolve all standard library entities with <code>std::</code>. <em>Never</em> put <code>using namespace</code> declarations in a header file, where most of his belongs.</p>\n\n<p><strong>Class Edge</strong></p>\n\n<p>You use initializer lists in some places (<code>Graph</code>), not in others. Be consistent. I advise using them always <em>where they're needed</em>, and not at all where they're not. Also, there is no need for a destructor in this class unless you're expecting polymorphism and need virtual-dtor for a vtable. Finally, make your getters <code>const</code></p>\n\n<pre><code>class Edge {\nprivate:\n int vertex1;\n int vertex2;\n int cost;\n int time;\n\npublic:\n Edge(int v1, int v2, int cost, int time) \n : vertex1(v1), vertex2(v2), cost(cost), time(time)\n {\n }\n\n int getVertex1() const { return vertex1; }\n // etc...\n};\n</code></pre>\n\n<p><strong>Class Graph</strong></p>\n\n<p>There are outright compilation bugs in this class. There is no such entity as <code>Edges</code>, yet you have a vector of them. Further, properly named it should be <code>edges</code> are a vector of <code>Edge</code>. Also, the initializer list in this class is pointless, as is the destructor and, as-written, the constructor. Finally, you may (or may not) want to pass your incoming edge as a const-ref (lots of opinions on that, I know).</p>\n\n<pre><code>class Graph {\nprivate:\n vector&lt;Edge&gt; edges; //edges in graph\n\npublic:\n int getTotalCost();\n int getTotalTime();\n void addEdge(const Edge&amp; e); \n\n Graph getMST(); // get Minimum Spanning Tree\n};\n</code></pre>\n\n<p><strong>Class Vertex</strong></p>\n\n<p>As previously mentioned, use initializer lists and full <code>std::</code> namespace resolution. Like <code>Graph</code>, this uses <code>Edges</code> as a typename, but no such type exists. Again, we use <code>const</code> qualifiers on all getters, here also returning the name by const-ref rather than value-copy. Finally, no chance of ever <em>setting</em> <code>visited</code> to true unless you provide a setter for it, nor accessing or modifying the <code>edges</code> vector without providing some means to do so.</p>\n\n<pre><code>class Vertex\n{\nprivate:\n std::string name;\n int number;\n bool visited;\n std::vector&lt;Edge&gt; connEdges; // vector of all edges connected to this vertex\n\npublic:\n Vertex(const std::string&amp; name, int number)\n : name(name), number(number), visited(false)\n {\n }\n\n // edge accessors\n void addEdge(const Edge&amp; edge) { connEdges.push_back(edge); }\n const std::vector&lt;Edge&gt;&amp; getEdges() const { return edges; }\n\n // properties\n const std::string&amp; getName() const { return name; }\n int getNum() const { return number; }\n bool wasVisited() const { return visited; }\n void setVisited(bool val = true) { visited = val; }\n\n Graph getShortestPath();\n};\n</code></pre>\n\n<p><strong>main()</strong></p>\n\n<p>This function is simply <em>loaded</em> with errors. Among them:</p>\n\n<ul>\n<li><code>edge</code> is not a pointer type, so that assignment won't event compile.</li>\n<li><code>p_edge</code> is derferenced though it is never initialized, so that will likely outright-fault due to undefined behavior</li>\n<li><code>ifile</code> is never opened before use, so nothing will be read there.</li>\n<li>it leaks memory, but only because of an error previously mentioned above. Were that coded correctly this would be a non-issue.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T14:15:54.010", "Id": "48724", "Score": "0", "body": "when I posted this code on codereview I rewrote main() I opened the ifile, removed p_edge, so you shouldn't be seeing these errors. Do they still show up when you view the thread? Also are there any other variables/functions that I am missing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T16:55:41.303", "Id": "48731", "Score": "0", "body": "On thing you're missing is you *never* \"fix\" the posted code on CodeReview questions. It literally makes nonsense of any answers that were posted to *review* it. Add an addendum instead, but try to keep the original post intact." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T17:07:43.963", "Id": "48734", "Score": "0", "body": "When I posted this post on Stackoverflow C++ site I had these errors, then when you told me to post this on Stackoverflow CodeReview. Only then did I remove them so not to duplicate errors, so I didn't change the code after posting it on CodeReview but was wondering if somehow those errors didn't get changed from my post on C++ since you are still referring to p_edge and ifile not being opened as you did then which I thought I fixed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T17:19:51.720", "Id": "48736", "Score": "0", "body": "Thank you for reviewing my code. Could you explain to my why you are using a reference to set addEdge in Graph class and an instance of Edge in Vertex class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-28T11:26:11.107", "Id": "97370", "Score": "0", "body": "@Napalidon I just realized I changed that to a proper reference long ago and never bothered answering your comment. It was a mistake. it should have been a reference (and is now). Sorry about that. Online editor coding ftl. =P" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T09:34:37.030", "Id": "30610", "ParentId": "30609", "Score": "7" } } ]
{ "AcceptedAnswerId": "30610", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T09:05:06.693", "Id": "30609", "Score": "4", "Tags": [ "c++", "graph" ], "Title": "Do I need to delete a vector?" }
30609
<p>I am reading the book <em>Clean Code</em> by Rob Martin and am trying to write the cleanest possible code. </p> <p>I wrote this script as part of my project. Could you please criticise it and let me know how it could be improved?</p> <pre><code>/** * File Downloading, Unzipping and extracting Content - PHP * * Usage: * * $fileImporter = new FileImporter($fileReference); * $nextRowAsArray = $fileImporter-&gt;readFileRowAsArray(); * * where $fileReference is File Name without Extension * $nextRowAsArray is associative Array representing File Entry * * If $fileReference.zip is not found, it is downloaded using FILE_DOWNLOAD_PATH * The archiv $fileReference.zip is automatically extracted whenever needed, * and first archiv Entry $file.txt is taken * * The File $file.txt is expected of the form: * * field_name1|field_name2 * entry1_field1|entry1_field2 * entry2_field1|entry2_field2 * ... * entryN_field1|entryN_field2 * * Here FILE_ENTRY_SEPARATOR is '|' * * Then the returned arrays $nextRowAsArray are subsequently of the form: * * array( 'field_name1' =&gt; 'entry1_field1', 'field_name2' =&gt; 'entry1_field2', ) * array( 'field_name1' =&gt; 'entry2_field1', 'field_name2' =&gt; 'entry2_field2', ) * ... * array( 'field_name1' =&gt; 'entryN_field1', 'field_name2' =&gt; 'entryN_field2', ) */ class FileImporter { private $_download_path = FILE_DOWNLOAD_PATH; private $_separator = FILE_ENTRY_SEPARATOR; private $_fileReference; private $_fileHandleCache = null; private $_fileHeadRow = array(); public function __construct ($fileReference) { $this-&gt;_fileReference = $fileReference; } public function readFileRowAsArray () { $fileHandle = $this-&gt;_getCachedOrNewFileHandle(); $fileEntryArray = $this-&gt;_getNextRowAsArray($fileHandle); if ( $this-&gt;_fileHeadRow ) { $keys = $this-&gt;_fileHeadRow; $values = $fileEntryArray; } else { $this-&gt;_fileHeadRow = $fileEntryArray; $keys = $fileEntryArray; $values = $this-&gt;_getNextRowAsArray($fileHandle); } return array_combine($keys, $values); } private function _getCachedOrNewFileHandle () { return $this-&gt;_fileHandleCache ? $this-&gt;_getCachedFileHandle() : $this-&gt;_getNewFileHandle(); } private function _getNextRowAsArray ($fileHandle) { $fileNextLine = fgets($fileHandle); if ( feof($fileHandle) ) return array(); $fileNextLineTrimmed = trim($fileNextLine); return explode($this-&gt;_separator, $fileNextLineTrimmed); } private function _getCachedFileHandle () { return $this-&gt;_fileHandleCache; } private function _getNewFileHandle () { $zipFileName = $this-&gt;_getZipFileName(); if (!file_exists($zipFileName)) $this-&gt;_downloadFile($zipFileName); return $this-&gt;_unzipAndGetFileHandle($zipFileName); } private function _getZipFileName () { // return "{$this-&gt;_fileReference . '.zip'; return "{$this-&gt;_fileReference}.zip"; } private function _downloadFile ($fileName) { $sourceStream = fopen($this-&gt;_downloadPath . $fileName, 'r') or die("Could not download $fileName"); $destinationStream = fopen($fileName, 'w'); echo "\n Downloading $fileName\n"; stream_copy_to_stream($sourceStream, $destinationStream); } private function _unzipAndGetFileHandle ($zipFileName) { $firstZipEntryName = $this-&gt;_getFirstZipEntryName($zipFileName); if ( !file_exists($firstZipEntryName) ) $this-&gt;_ZipExtract($zipFileName); $fileHandle = fopen($firstZipEntryName, "rt") or die(" Can't Read File $firstZipEntryName"); $this-&gt;_fileHandleCache = $fileHandle; return $fileHandle; } private function _getFirstZipEntryName ($zipFileName) { if ( !file_exists($zipFileName) ) { throw new Exception("Attempting to read non-existing Zip File $zipFileName, exitting ...."); } $zipArchiv = zip_open($zipFileName); $firstZipEntry = zip_read($zipArchiv); $firstZipEntryName = zip_entry_name($firstZipEntry); zip_close($zipArchiv); return $firstZipEntryName; } private function _zipExtract ($zipFileName) { echo "\n Begin extraction at ", date('r').", file $zipFileName"; $zipArchiv = new ZipArchive; $zipArchiv-&gt;open($zipFileName); $zipArchiv-&gt;extractTo("."); $zipArchiv-&gt;close(); } } </code></pre> <p>Here are my tests, which have all passed:</p> <pre><code>/** * Testing FileImporter */ // case 0: both Zip and Text files exist - creating function createTextAndZipFiles ($fileRef, $textData) { $textFile = $fileRef . '.txt'; $zipFile = $fileRef . '.zip'; // creating text file file_put_contents($textFile, $textData); // creating zip file $zip = new ZipArchive; $zip-&gt;open($zipFile, ZipArchive::CREATE); $zip-&gt;addFile($textFile); $zip-&gt;close(); } $testFile = 'file-test'; $testText = &lt;&lt;&lt;EOT day|year 10|2011 31|1843 EOT; createTextAndZipFiles($testFile, $testText); $importer_test = new FileImporter($testFile); $rowArray = $importer_test-&gt;readFileRowAsArray(); $rowArray = $importer_test-&gt;readFileRowAsArray(); assert( $rowArray['year'] === '1843' ); // empty row $testText = &lt;&lt;&lt;EOT day|year 10|2011 31|1843 EOT; createTextAndZipFiles($testFile, $testText); $importer_test = new FileImporter($testFile); $rowArray = $importer_test-&gt;readFileRowAsArray(); assert( $rowArray['day'] === '10' ); $rowArray = $importer_test-&gt;readFileRowAsArray(); assert( $rowArray['year'] === '1843' ); $rowArray = $importer_test-&gt;readFileRowAsArray(); assert( $rowArray === array() ); // too long row $testText = &lt;&lt;&lt;EOT day|year 10|2011|ha 31|1843 EOT; createTextAndZipFiles($testFile, $testText); $importer_test = new FileImporter($testFile); $rowArray = $importer_test-&gt;readFileRowAsArray(); assert( $rowArray === array() ); $rowArray = $importer_test-&gt;readFileRowAsArray(); assert( $rowArray['year'] === '1843' ); $rowArray = $importer_test-&gt;readFileRowAsArray(); assert( $rowArray === array() ); // too short row $testText = &lt;&lt;&lt;EOT day|year 2011 31|1843 EOT; createTextAndZipFiles($testFile, $testText); $importer_test = new FileImporter($testFile); $rowArray = $importer_test-&gt;readFileRowAsArray(); assert( $rowArray === array() ); $rowArray = $importer_test-&gt;readFileRowAsArray(); assert( $rowArray['year'] === '1843' ); $rowArray = $importer_test-&gt;readFileRowAsArray(); assert( $rowArray === array() ); // case 1: Zip exists but Text doesn't createTextAndZipFiles($testFile, $testText); // delete Text unlink($testFile . '.txt'); $importer_test = new FileImporter($testFile); $rowArray = $importer_test-&gt;readFileRowAsArray(); assert( $rowArray === array() ); $rowArray = $importer_test-&gt;readFileRowAsArray(); assert( $rowArray['year'] === '1843' ); $rowArray = $importer_test-&gt;readFileRowAsArray(); assert( $rowArray === array() ); // case 2: Text exists but Zip doesn't // faking download by using local subdirectory // creating subdirectory 'test' $subdirName = 'test'; // make sure directory exists and is not a file if ( file_exists($subdirName) ) { if ( !is_dir($subdirName) ) { unlink($subdirName); mkdir($subdirName); } } else { mkdir($subdirName); } createTextAndZipFiles($testFile, $testText); // now move zipfile into the subdirectory $zipFileName = $testFile . '.zip'; rename($zipFileName, $subdirName . '/' . $zipFileName); $importer_test = new FileImporter($testFile, $subdirName . '/'); $rowArray = $importer_test-&gt;readFileRowAsArray(); assert( $rowArray === array() ); $rowArray = $importer_test-&gt;readFileRowAsArray(); assert( $rowArray['year'] === '1843' ); </code></pre>
[]
[ { "body": "<p>I haven't read the book you mention, although it looks good so I might buy it and have a read.</p>\n\n<p>A few things for me</p>\n\n<p>There are echo statements in the code, I am assuming that is for debugging and you are going to remove them.</p>\n\n<p>In a couple of places you use die(), and then elsewhere you throw an exception. \nPersonally I would throw exceptions and let it bubble up to somewhere that can handle them properly. </p>\n\n<p>Your class is called fileImporter, but it also has a download aspect to it as well. I am wondering if fileDownloader should be separated out.</p>\n\n<p>You have a private getter function</p>\n\n<pre><code> private function _getCachedFileHandle () {\n return $this-&gt;_fileHandleCache;\n }\n</code></pre>\n\n<p>Which I find unusual, I normally only use publicly accessible getters.</p>\n\n<pre><code>// It is just as easy to use this internally \n$f= $this-&gt;_fileHandleCache;\n\n// as it is to use, so why make it more complex\n$f = $this-&gt;_getCachedFileHandle();\n</code></pre>\n\n<p>Code reuse, when I design stuff I only create a separate method if I can reuse the same code, or due to it's complexity/size of the function it is best to break it into smaller parts to make it more readable.</p>\n\n<pre><code>// this bit of code is only called once and is simple, so it could be included inline\npublic function readFileRowAsArray () {\n $fileHandle = $this-&gt;_getCachedOrNewFileHandle();\n\n// like this\npublic function readFileRowAsArray () {\n $fileHandle = $this-&gt;_fileHandleCache ? $this-&gt;_getCachedFileHandle() : $this-&gt;_getNewFileHandle();\n</code></pre>\n\n<p>There also appears to be no way to overide these private variables which are set to constant values.</p>\n\n<pre><code>class FileImporter {\n private $_download_path = FILE_DOWNLOAD_PATH;\n private $_separator = FILE_ENTRY_SEPARATOR;\n</code></pre>\n\n<p>If that is the case, then why re-declare then, why not use FILE_DOWNLOAD_PATH and FILE_ENTRY_SEPARATOR directly in your code</p>\n\n<p>If you do want to allow them to be overridden, then you could extend your constructor</p>\n\n<pre><code>public function __construct ($fileReference, $download_path = FILE_DOWNLOAD_PATH, $separator = FILE_ENTRY_SEPARATOR) {\n $this-&gt;_fileReference = $fileReference;\n $this-&gt;_download_path = $download_path ;\n $this-&gt;_separator = $separator ;\n\n}\n</code></pre>\n\n<p>Hope that gives you some ideas to think about</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T20:26:42.310", "Id": "30652", "ParentId": "30611", "Score": "1" } } ]
{ "AcceptedAnswerId": "30652", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T11:55:49.703", "Id": "30611", "Score": "1", "Tags": [ "php", "object-oriented", "classes" ], "Title": "File-downloading, unzipping and extracting content with a PHP script and tests" }
30611
<pre><code> class PropFinal(CrawlSpider): name = "propfinal" allowed_domains = [over 200 allowed domains here] start_urls = ["http://www.putnam-fl.com/coc/index.php?option=com_content&amp;view=article&amp;id=385&amp;Itemid=114" ] def __init__(self, *args, **kwargs): ##Is there a better way to add all 200 or more requests? self.requests_list=[] link = 'http://www.putnam-fl.com/clerks_web_apps/foreclosure_trans/get_cases.php' request = Request(link, callback=self.parse_putnam) self.requests_list.append(request) link = 'https://mypalmbeachclerk.clerkauction.com/' request = Request(link, callback=self.parse_palmbeach) self.requests_list.append(request) link = 'http://www.clerk.co.okeechobee.fl.us/Foreclosurecalender.htm' request = Request(link, callback=self.parse_okeechobee) self.requests_list.append(request) </code></pre> <p>This code populates my requests_list and then the parse function iterates over it to add requests to the scheduler. This just doesn't seem like the do not repeat yourself programming mantra. There's got to be a better way?</p> <pre><code>def parse(self, response): for r in self.requests_list: yield r def parse_realforeclose(self, response): ##i hate realforeclose and javascript + selenium global county ##code to set the county based on the URL county = str(response.url).replace('https://www.', '').replace('.realforeclose.com/index.cfm', '').title() print county logdir=os.getcwd() ##this try catch is not needed if the code at the end of the script doing the same thing worked correctly try: logfiles = sorted([ f for f in os.listdir(logdir) if f.startswith('QuickSearch')]) logfiles = str(logfiles).replace("['", "").replace("']", "") os.remove('QuickSearch.csv') except: print "&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;QuickSearch deleted previously" pass item = PropfinalItem() ##set firefox preferences to auto download csv files fp = webdriver.FirefoxProfile() fp.set_preference("browser.download.folderList",2) fp.set_preference("browser.download.manager.showWhenStarting",False) fp.set_preference("browser.download.dir", os.getcwd()) fp.set_preference("browser.helperApps.neverAsk.saveToDisk","text/csv") self.selenium = webdriver.Firefox(firefox_profile=fp) sel = self.selenium sel.get(response.url) userName = sel.find_element_by_id("LogName") userName.send_keys(username) passWord = sel.find_element_by_id("LogPass") passWord.send_keys(password) submit = sel.find_element(By.CSS_SELECTOR, "#LogButton").click() time.sleep(3) ##if the county is volusia, babysit the clicking of buttons, weird responses if "volusia" in response.url: clear = sel.find_element(By.XPATH, '//*[@id="BNOTACC"]').click() print "&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;VOLUSIA" time.sleep(3) print "sleep" clear = sel.find_element(By.XPATH, '//*[@id="BNOTACC"]').click() time.sleep(3) print "sleep" clear time.sleep(3) print "sleep" clear time.sleep(3) print "sleep" clear try: clear = sel.find_element(By.XPATH, '//*[@id="BNOTACC"]').click() clear clear clear clear except: pass w = WebDriverWait(sel, 15, 1) w.until(lambda sel: sel.find_element(By.XPATH, "/html/body/table/tbody/tr/td/div[2]/div/div/div[8]/a/span")) inputs = sel.find_element(By.XPATH, "/html/body/table/tbody/tr/td/div[2]/div/div/div[8]/a/span").click() time.sleep(9) i=0 while i &lt; 10: i+=1 try: searchType = sel.find_element(By.XPATH, '/html/body/table/tbody/tr/td/div[2]/div/div[2]/div[2]/div[3]/select/option[2]').click() filters = sel.find_element(By.XPATH, '/html/body/table/tbody/tr/td/div[2]/div/div[2]/div[2]/div[7]/button').click() removeSold = sel.find_element(By.XPATH, '/html/body/table/tbody/tr/td/div[2]/div/div[2]/div[2]/div[7]/div/ul/li[3]/label').click() removeCancel = sel.find_element(By.XPATH, '//*[@id="ui-multiselect-CaseStatus-option-3"]').click() submit = sel.find_element(By.XPATH, '//*[@id="testBut"]').click() pass except ElementNotVisibleException as e: print e time.sleep(2) continue break time.sleep(2) ##grid showing dataset, go ahead and download download = sel.find_element(By.XPATH, '/html/body/table/tbody/tr/td[2]/div[2]/div/div/div[3]/div[2]/a/img').click() ##broward has enormous CSV files if 'broward' in response.url: ##cheap fix for fucking broward time.sleep(15) else: time.sleep(10) logfiles = sorted([ f for f in os.listdir(logdir) if f.startswith('QuickSearch')]) logfiles = str(logfiles).replace("['", "").replace("']", "") try: t0 = time.clock() t1 = time.time() with open(logfiles, 'rU') as f: print "&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;CSV PARSING NOW" reader = csv.reader(f) ##need to skip first line eventually j = 0 for row in reader: j+=1 ##scrapy only parses 50 of these before starting the next request item['state'] = 'Florida' item['county'] = county item['saleDate'] = row[0] item['caseNumber'] = row[2] item['finalJudgement'] = row[4] item['aV'] = row[6] item['plaintiff'] = row[7] item['propertyAddress'] = row[10] item['propertyCity'] = row[11] item['propertyZip'] = row[12] item['parcelID'] = row[13] print "&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;", j yield item f.close() print time.clock() - t0, "seconds process time" print time.time() - t1, "seconds wall time" except: pass print "&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;F CLOSED" os.remove(logfiles) sel.close() </code></pre> <p>The biggest issue here is the bottom portion of the parse_realforeclose function. You can review the issue with my stackoverflow post here: <a href="https://stackoverflow.com/questions/18538644/scrapy-hanging-on-csv-parse">https://stackoverflow.com/questions/18538644/scrapy-hanging-on-csv-parse</a></p> <p>Basically, I've got every available scrapy setting for concurrency set to 1. concurrent_requests, concurrent_requests_per_ip, etc. If the CSV is large, Scrapy will parse 50-100 of the items in the CSV file, and then it pauses and sends out the next requests. I'm not sure why this is happening as I didn't get any feedback on the StackOverflow post. I have a feeling scrapy thinks the request / response is dead since it get's taken by selenium to finish the javascript parsing. </p> <p>Any help cleaning up this code and or debugging the CSV parsing issue would be phenomenal.</p>
[]
[ { "body": "<p>For your requests list, I suggest defining a dictionary like that:</p>\n\n<pre><code>requests_dict = {\n 'putnam': 'http://www.putnam-fl.com/clerks_web_apps/foreclosure_trans/get_cases.php',\n 'palmbeach': 'https://mypalmbeachclerk.clerkauction.com/',\n ...\n}\n</code></pre>\n\n<p>and then doing something like:</p>\n\n<pre><code>requests_list = [Request(url, callback=getattr(self, 'parse_'+name)) for name, url in requests_dict.items()]\n</code></pre>\n\n<hr>\n\n<p><strong>EDIT</strong></p>\n\n<p>Other possible solution, attach the URL as an attribute of the callback function:</p>\n\n<pre><code>class PropFinal(CrawlSpider):\n\n def __init__(self, *args, **kwargs):\n self.requests_list = []\n for name, obj in self.__class__.__dict__.items():\n if name.startswith('parse_'):\n self.requests_list.append(Request(obj.url, callback=obj))\n ...\n\n def parse_foo(...):\n ...\n parse_foo.url = 'http://foo.example.org/'\n\n def parse_bar(...):\n ...\n parse_bar.url = 'http://bar.example.net/'\n</code></pre>\n\n<p>Or, if you prefer to have the URL before the function, you can use a decorator:</p>\n\n<pre><code>def attach(**params):\n def f(g):\n g.__dict__.update(params)\n return g\n return f\n\nclass PropFinal(CrawlSpider):\n\n def __init__(self, *args, **kwargs):\n self.requests_list = []\n for name, obj in self.__class__.__dict__.items():\n if name.startswith('parse_'):\n self.requests_list.append(Request(obj.url, callback=obj))\n ...\n\n @attach(url='http://foo.example.org/')\n def parse_foo(...):\n ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T16:21:29.643", "Id": "48728", "Score": "0", "body": "This is a great idea. Do you think writing the dictionary of requests to a local file or database for lookup would be a good alternative as well?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T16:54:00.117", "Id": "48729", "Score": "0", "body": "Since the dictionary keys are tied to function names, I'm not sure it makes much sense to put it elsewhere." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T16:15:43.750", "Id": "30621", "ParentId": "30615", "Score": "1" } } ]
{ "AcceptedAnswerId": "30621", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T14:03:23.963", "Id": "30615", "Score": "2", "Tags": [ "python", "object-oriented", "scrapy" ], "Title": "Scrapy -- Very Procedural -- Better Alternatives?" }
30615
<p>This is my first attempt at Quick Sort and am looking for some helpful criticisms on how I can make my code better. Thank you</p> <pre><code>def manSort(self, unSorted): if len(unSorted) &lt;= 1: return unSorted else: greater = [] less = [] pivots = unSorted[len(unSorted)/2] pivotPlace = [pivots] for i in range(len(unSorted)): if unSorted[i] &lt; pivots: less.append(unSorted[i]) elif unSorted[i] &gt; pivots: greater.append(unSorted[i]) elif i == len(unSorted)/2: pass else: pivotPlace.append(unSorted[i]) return self.manSort(less) + pivotPlace + self.manSort(greater) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T08:06:53.703", "Id": "64520", "Score": "0", "body": "What about the function that has 2 nested `for` loops that iterate over each element and swaps the lowest, returns the same list but sorted?\nIt's not what the task requires but, is it faster?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T09:15:08.810", "Id": "64521", "Score": "0", "body": "There are [alternative quick-sort implementations](http://en.wikipedia.org/wiki/Quicksort) that use less space. It also possible that they might be faster, but that would depend on the implementation of the python interpreter, so you'd have to measure it to be sure. I don't know that any of them have nested for loops?" } ]
[ { "body": "<p>There is an unnecessary complication: you put <code>pivots</code> in <code>pivotPlace</code> before the loop, and then do extra work to skip it in the loop.</p>\n\n<p>You could also loop over <code>unSorted</code> directly instead of looping with an index.</p>\n\n<pre><code>pivotPlace = []\nfor item in unSorted:\n if item &lt; pivots:\n less.append(item)\n elif item &gt; pivots:\n greater.append(item)\n else:\n pivotPlace.append(item)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T09:51:21.930", "Id": "30683", "ParentId": "30624", "Score": "1" } }, { "body": "<p>Looks pretty good. There are a few small things that can use improvement. For clarity, I'd avoid the name <code>pivotPlace</code> in favor of <code>equal</code>, since that's what the function does, it places the values equal to the pivot there.</p>\n\n<p>As Janne mentioned, the <code>for</code> loop can be replaced by one that loops over the items in the unsorted list.</p>\n\n<p>A floor division instead of regular division ensures that this will also work for Python 3.</p>\n\n<p>Lastly, the <code>else</code> can be removed entirely (control never flows there if the initial condition is true), pulling code further to the baseline.</p>\n\n<pre><code>def manSort(unsorted):\n if len(unsorted) &lt;= 1:\n return unsorted\n\n less = []\n equal = []\n greater = []\n pivot = unsorted[len(unsorted) // 2]\n for item in unsorted:\n if item &lt; pivot:\n less.append(item)\n elif item &gt; pivot:\n greater.append(item)\n else:\n equal.append(item)\n\n return manSort(less) + equal + manSort(greater)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T13:07:31.187", "Id": "30693", "ParentId": "30624", "Score": "5" } }, { "body": "<p>You could use a list-comprehension or the filter function. What you are effectively doing is an inline-filter.</p>\n\n<h3>List comprehension</h3>\n\n<pre><code>def quicksort(xs):\n if xs == []: return []\n pivot = xs[0]\n lesser = [x for x in xs[1:] if x &lt; pivot]\n greater = [x for x in xs[1:] if x &gt;= pivot]\n return quicksort(lesser) + [pivot] + quicksort(greater)\n</code></pre>\n\n<h3>Filter</h3>\n\n<pre><code>def quicksort(xs):\n if xs == []: return []\n pivot = xs[0]\n lesser = list(filter(lambda x: x &lt; pivot, xs))\n greater = list(filter(lambda x: x &gt;= pivot, xs))\n return quicksort(lesser) + [pivot] + quicksort(greater)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T15:11:22.720", "Id": "30738", "ParentId": "30624", "Score": "0" } }, { "body": "<p>You are not following the <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a> style guide, which is the <em>official</em> style for python code. to fix this:</p>\n\n<ul>\n<li>Identifiers should be <code>lower_case_with_underscore</code></li>\n<li>functions should be <code>lower_case_with_underscore</code></li>\n<li>classes should be <code>FullCamelCase</code></li>\n</ul>\n\n<p>You are iterating over the <em>indeces</em> of the list, this is not pythonic at all. Use a plain <code>for</code> instead:</p>\n\n<pre><code>for element in sequence:\n # work with element\n</code></pre>\n\n<p>If you <em>need</em> also the index, then use the <code>enumerate</code> built-in:</p>\n\n<pre><code>for index, element in enumerate(sequence):\n # work with element and its index\n</code></pre>\n\n<p>Your method is actually a <em>function</em>. It never uses <code>self</code> except when performing the recursive calls, hence you should consider putting this outside the class, or make this method a <code>staticmethod</code>.</p>\n\n<p>Some identifiers have strange names (e.g. <code>pivot_place</code>).</p>\n\n<p>Lastly, your code is suboptimal. It uses <code>O(nlog(n))</code> space instead of <code>O(log(n))</code>. The usual implementations of quicksort use a <code>partition</code> algorithm that moves the elements <em>in-place</em>, without creating temporary <code>lesser</code>, <code>greater</code> lists. With such a function the whole implementation of quicksort becomes:</p>\n\n<pre><code>def quicksort(sequence, start=0, end=None):\n if end is None:\n end = len(sequence)\n if end - start &gt; 1:\n q = partition(sequence, start, end)\n quicksort(sequence, start, q)\n quicksort(sequence, q+1, end)\n</code></pre>\n\n<p>Where the <code>partition</code> can be something like:</p>\n\n<pre><code>def partition(sequence, start, end):\n pivot = sequence[start]\n sequence[start], sequence[end-1] = sequence[end-1], pivot\n # i: index of the last \"lesser than\" number.\n i = start - 1\n # j: index to scan the array\n for j in range(start, end-1):\n element = sequence[j]\n if element &lt;= pivot:\n i += 1\n sequence[i], sequence[j] = sequence[j], sequence[i]\n # move pivot in the correct place\n i += 1\n sequence[i], sequence[end-1] = sequence[end-1], sequence[i]\n return i\n</code></pre>\n\n<p>In this code I did iterate over the indices because the iteration starts at some index <code>start</code>. In your case you always iterated over the whole sequence.</p>\n\n<p>Note that this implementation uses <code>O(log(n))</code> memory in the average case, <code>O(n)</code> in the worst case, but the worst-case may be a problem since it's when the input is ordered.</p>\n\n<p>To increase performance you should randomize the <code>partition</code> function. You simply have to change the initial lines:</p>\n\n<pre><code>import random\n\ndef partition(sequence, start, end):\n # use a random element instead of the first element.\n pivot_index = random.randint(start, end-1)\n pivot = sequence[pivot_index]\n sequence[pivot_index], sequence[end-1] = sequence[end-1], pivot\n # same as before.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T19:07:53.817", "Id": "30746", "ParentId": "30624", "Score": "2" } } ]
{ "AcceptedAnswerId": "30693", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T18:30:25.270", "Id": "30624", "Score": "1", "Tags": [ "python", "algorithm", "quick-sort" ], "Title": "QuickSort critique" }
30624
<p>I'd like to extract HTML content of websites and save it into a file. To achieve this, I have the following (working) code:</p> <pre><code>output = codecs.open("test.html", "a", "utf-8") def first(): for i in range(1, 10): root = lxml.html.parse('http://test'+str(i)+'.xyz'+'?action=source').getroot() for empty in root.xpath('//*[self::b or self::i][not(node())]'): empty.getparent().remove(empty) tables = root.cssselect('table.main') tables = root.xpath('//table[@class="main" and not(ancestor::table[@class="main"])]') txt = [] txt += ([lxml.html.tostring(t, method="html", encoding="utf-8") for t in tables]) text = "\n".join(re.sub(r'\[:[\/]?T.*?:\]', '', el) for el in txt) output.write(text.decode("utf-8")) output.write("\n\n") </code></pre> <p>Is this "nice" code? I ask because I'm not sure if it's a good idea to use strings, and because of the fact that other HTML texts I've seen use one tag-ending (for example <code>&lt;/div&gt;</code>) per line. My code produces partly more tag-endings per line.</p> <p>Is it possible not to use strings or/and to achieve that we receive not things like </p> <p><code>&lt;td class="cell" valign="top" style=" width:0.00pt;"&gt;&lt;/td&gt;</code> but things like:</p> <pre><code>&lt;td class="cell" valign="top" style=" width:0.00pt;"&gt; &lt;/td&gt; </code></pre> <p>? Thanks for any proposition :)</p>
[]
[ { "body": "<p>Try something like this, you can definitely clean up the two list comprehensions you have, but for now this should suffice. </p>\n\n<pre><code>def first():\n with codecs.open(\"test.html\", \"a\", \"utf-8\") as output:\n for i in range(1, 10):\n txt = []\n root = lxml.html.parse('http://test'+str(i)+'.xyz'+'?action=source').getroot()\n for empty in root.xpath('//*[self::b or self::i][not(node())]'):\n empty.getparent().remove(empty)\n\n #tables = root.cssselect('table.main') &lt;--Dont need this, its is being overwritten\n tables = root.xpath('//table[@class=\"main\" and not(ancestor::table[@class=\"main\"])]')\n\n txt += ([lxml.html.tostring(t, method=\"html\", encoding=\"utf-8\") for t in tables])\n text = \"\\n\".join(re.sub(r'\\[:[\\/]?T.*?:\\]', '', el) for el in txt)\n\n output.write(text.decode(\"utf-8\") + \"\\n\\n\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T21:51:47.073", "Id": "30749", "ParentId": "30627", "Score": "2" } }, { "body": "<p>I like beautifulsoup, which is based on lxml but has a cleaner interface, imho.</p>\n\n<p><a href=\"http://www.crummy.com/software/BeautifulSoup/bs4/doc/\" rel=\"nofollow\">http://www.crummy.com/software/BeautifulSoup/bs4/doc/</a></p>\n\n<p>I'm not quite sure what the \"for empty in root.xpath\" does - it looks like it's looking for empty b or i tags and removing them. I recommend a comment for that line.</p>\n\n<p>Also, the 'text =' line needs a comment showing an example of what you're stripping out of the text string. Treat the next reader / maintainer of the code nicely. Or avoid the regexp if you can. I am biased, tho, because I don't use regexps until I'm absolutely forced to, and I always feel bad for the next developer having to maintain my regexps. But I digress onto my regexp soapbox. I'm sorry...</p>\n\n<pre><code>import urllib2\nfrom bs4 import BeautifulSoup\n\nfirst():\n with codecs.open(\"test.html\", \"a\", \"utf-8\") as output:\n for i in range(1, 10):\n html_doc = urllib2.urlopen('http://test'+str(i)+'.xyz'+'?action=source').read()\n soup = BeautifulSoup(html_doc)\n\n #remove empty 'b' and 'i' tags:\n for tag in soup.find_all(['b', 'i']):\n if not tag.text: tag.extract()\n\n #get all tables, but not sub-tables\n tables = soup.find_all(\"table\", class_=\"main\", recursive=False)\n\n #not sure what the output regexp is doing, but I suggest:\n for table in tables:\n table.string = re.sub(r'\\[:[\\/]?T.*?:\\]', '', table.string) \n output.write(table.prettify())\n</code></pre>\n\n<blockquote>\n <p>Is it possible not to use strings or/and to achieve that we receive not things like ... but things like:</p>\n</blockquote>\n\n<p>This is what the prettify() method will do for you, so you don't have to worry about the newlines. You can also pass your own output formatter to BeautifulSoup if you so choose.</p>\n\n<p>Code untested and unrun... Just a thought at another approach. Beware bugs and syntax errors.</p>\n\n<p>Enjoy! I hope this helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T17:42:11.560", "Id": "30783", "ParentId": "30627", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T19:21:07.903", "Id": "30627", "Score": "3", "Tags": [ "python", "html" ], "Title": "Simplification of Python code (HTML extraction)" }
30627
A command-line interface (CLI) is a means of interacting with a computer program where the user (or client) issues commands to the program in the form of successive lines of text (command lines).
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T19:46:43.823", "Id": "30629", "Score": "0", "Tags": null, "Title": null }
30629
Gradle is a project automation tool that builds upon the concepts of Apache Ant and Apache Maven and introduces a Groovy-based DSL instead of the more traditional XML form of declaring the project configuration.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T19:48:39.270", "Id": "30631", "Score": "0", "Tags": null, "Title": null }
30631
<p>Elm is a functional language that compiles to JavaScript. It competes with projects like React as a tool for creating websites and web apps. Elm has a very strong emphasis on simplicity, ease-of-use, and quality tooling.</p> <p>References: </p> <ul> <li><p><a href="http://guide.elm-lang.org/" rel="nofollow">An Introduction to Elm (documentation)</a></p></li> <li><p><a href="https://en.wikipedia.org/wiki/Elm_(programming_language)" rel="nofollow">Elm programming language on Wikipedia</a></p></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T19:51:35.657", "Id": "30632", "Score": "0", "Tags": null, "Title": null }
30632
Elm is a functional programming language for declaratively creating web browser based graphical user interfaces.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T19:51:35.657", "Id": "30633", "Score": "0", "Tags": null, "Title": null }
30633
<p><strong><a href="https://eclipse.org/" rel="nofollow noreferrer">Eclipse IDE</a></strong> is an open-source IDE platform written mostly in Java and primarily used for Java development through the use of the <a href="https://www.eclipse.org/jdt/" rel="nofollow noreferrer">Java Development Tools</a> (JDT) plug-ins. It is notable for its rich ecosystem of free and commercial plugins and that it is predominantly itself composed of plug-ins.</p> <p><strong><a href="https://eclipse.org/" rel="nofollow noreferrer">Eclipse IDE</a></strong> is built on an <code>OSGI</code> implementation called Equinox; the same <code>OSGI</code>-based framework is used for managing its plug-ins at runtime. Eclipse can also be used as a development environment for non-IDE GUI applications, leveraging many of the same plug-ins as the IDE to form a more general Rich Client Platform, called Eclipse RCP.</p> <p>For C/C++ development, the <a href="https://www.eclipse.org/cdt/" rel="nofollow noreferrer">Eclipse CDT Project</a> provides plug-ins to create a <code>C/C++</code> development environment within Eclipse IDE.</p> <p>The <a href="http://eclipse.org/webtools" rel="nofollow noreferrer">Eclipse Web Tools Platform project</a> supplies plug-ins for developing Open web standards-based and Java web applications, and frameworks for building higher-level web tools.</p> <p>For PHP development, the <a href="https://www.eclipse.org/pdt/" rel="nofollow noreferrer">Eclipse PDT Project</a> provides a plugin to create a <code>PHP</code> development environment within Eclipse IDE, building on features of the Web Tools Platform. The popular commercial Zend Studio is also based on Eclipse IDE.</p> <p>For Python development, <a href="http://pydev.org/" rel="nofollow noreferrer">PyDev</a> provides plug-ins, called PyDev, to create a Python development environment within Eclipse IDE.</p> <p>For Perl development, the <a href="http://www.epic-ide.org/" rel="nofollow noreferrer">EPIC</a> project provides a plugin to create a Perl development environment within Eclipse IDE.</p> <p>Note that Google has ceased developing the <a href="https://developer.android.com/tools/sdk/eclipse-adt.html" rel="nofollow noreferrer">Android Development Tools</a> in favor of another solution.</p> <p>When combined with Cygwin (or MinGW), Mono, and its many plugins, Eclipse IDE provides a crucial part of viable open-source alternatives to using Microsoft Visual-Studio as a Windows software development platform in Windows, whilst also including comprehensive native support for Java.</p> <p><a href="https://eclipse.org/downloads/" rel="nofollow noreferrer">Download the latest version of Eclipse IDE from eclipse.org</a><br /> <a href="http://download.eclipse.org/eclipse/downloads/" rel="nofollow noreferrer">Download site for the Eclipse Platform project itself</a>, including the core runtime and SDK<br /> <a href="https://marketplace.eclipse.org/" rel="nofollow noreferrer">Eclipse Marketplace featuring Plug-ins, Bundles and Products</a></p> <h3>Useful Links:</h3> <ul> <li><a href="https://en.wikipedia.org/wiki/Eclipse_IDE" rel="nofollow noreferrer">Eclipse Wikipedia Article</a></li> <li><a href="https://www.eclipse.org/org/" rel="nofollow noreferrer">About Eclipse Foundation</a></li> <li><a href="http://community.bonitasoft.com/blog/comparing-eclipse-and-netbeans-rcps" rel="nofollow noreferrer">Eclipse vs. NetBeans</a> as Rich Client Platforms</li> <li><a href="https://wiki.eclipse.org/Older_Versions_Of_Eclipse" rel="nofollow noreferrer">List Of Older Versions</a></li> <li><a href="https://wiki.eclipse.org/FAQ_How_do_I_upgrade_Eclipse%3F" rel="nofollow noreferrer">Upgrading Eclipse</a></li> <li><a href="http://www.tutorialspoint.com/eclipse/" rel="nofollow noreferrer">Eclipse Tutorials</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-09-01T19:52:40.363", "Id": "30634", "Score": "0", "Tags": null, "Title": null }
30634
In computer programming, Eclipse is a multi-language integrated development environment (IDE) comprising a base workspace and an extensible plug-in system for customizing the environment. THIS TAG SHOULD ONLY BE USED FOR CODE INVOLVING THE IDE ITSELF, NOT FOR CODE SIMPLY WRITTEN WITH IT.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T19:52:40.363", "Id": "30635", "Score": "0", "Tags": null, "Title": null }
30635
In computer science, a pointer is a programming language data type whose value refers directly to (or "points to") another value stored elsewhere in the computer memory using its address.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T19:54:57.653", "Id": "30637", "Score": "0", "Tags": null, "Title": null }
30637
Wikipedia is a collaboratively edited, multilingual, free Internet encyclopedia supported by the non-profit Wikimedia Foundation.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T19:57:13.243", "Id": "30639", "Score": "0", "Tags": null, "Title": null }
30639
An assembly language is a low-level programming language for a computer, or other programmable device, in which there is a very strong (generally one-to-one) correspondence between the language and the architecture's machine code instructions.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T20:08:00.757", "Id": "30641", "Score": "0", "Tags": null, "Title": null }
30641
Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some node as the root in the graph case) and explores as far as possible along each branch before backtracking.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T20:10:45.347", "Id": "30643", "Score": "0", "Tags": null, "Title": null }
30643
<p>Since the mid-1970's versions of BASIC was the most popular or in many cases, the only programming language available on microcomputers. Like today when you buy a computer, the OS is slightly different, or an OEM version.</p> <p>BASIC was developed at Dartmouth College in 1964, and it is said to be based on or influenced by ALGOL 60, FORTRAN II, and JOSS.</p> <p>(JOSS is the acronym of <strong>JOHNNIAC</strong> <strong>O</strong>pen <strong>S</strong>hop <strong>S</strong>ystem and was one of the very first interactive, time-sharing programming languages. JOSS I, developed by J. Clifford Shaw at RAND was first implemented in 1963.)</p> <p>BASIC was the same way. Each computer shipped with a BASIC often in the machine's firmware.</p> <p>BASIC allowed business owners, hobbyists, consultants and professionals the ability to develop custom software solutions at a price most consumers could afford.</p> <p>Today, BASIC remains popular in many computing dialects and in new languages influenced by BASIC, such as Microsoft's Visual Basic.</p> <p>The major implementation of BASIC are: </p> <blockquote> <p>Dartmouth BASIC, Apple BASIC, Atari BASIC, Sinclair BASIC, Commodore BASIC, BBC BASIC, TI-BASIC, Casio BASIC, Microsoft BASIC, Liberty BASIC, Visual Basic, FreeBASIC, PowerBASIC, and Gambas.</p> </blockquote> <p>And you can find BASIC dialects only available on iOS mobile devices, such as SmartBASIC and techBASIC, where you can, without the need for an Internet connection write, debug and test your code on the very device you are programming for.</p> <p>When asking questions about BASIC code, since each dialect has unique features, such as SpriteBASIC (new as of Jan 2017) is a game engine design language, where techBASIC is geared towards IoT programming. SmartBASIC is great for file processing and graphical interfaces, and is very well suited for writing games.</p> <p>This and countless other dialects means that syntax of even what was once standard (in what we call Vintage BASIC, which should have its own tag), will not work in other dialects. Portability of code is often difficult.</p> <p>So it is important to those reviewing your code to know what you wrote it in. And while some code is generic enough where it may run in other dialects, one should not assume that is the case. Let those who answer the question try and see if they can get it to work.</p> <p>Those answering a question where there are more than 100 dialects of BASIC for Windows and Macs, can convert the code to work in their dialect, but when giving the answer, must reveal that, then give a detailed description of what the OP needs to solve their problem.</p> <p>Just don't assume the code is broken because it does not run in your dialect of BASIC.</p> <p>For more information on BASIC, here are some important links:</p> <p><a href="https://en.m.wikipedia.org/wiki/BASIC" rel="nofollow noreferrer"><strong>Wikipedia for BASIC</strong></a></p> <p><a href="https://en.m.wikipedia.org/wiki/List_of_BASIC_dialects#S" rel="nofollow noreferrer"><strong>Comprehensive List of BASIC Dialects (Interpreters &amp; Compilers)</strong></a> </p> <p><a href="https://www.cs.bris.ac.uk/~dave/basic.pdf" rel="nofollow noreferrer"><strong>Original Dartmouth College BASIC Manual (1964) in PDF Version</strong></a></p> <p><a href="http://www.onlineprogrammingbooks.com/basic/" rel="nofollow noreferrer"><strong>Free Online Books on BASIC Programming (From Online Programming Books)</strong></a></p> <p>NOTE: For the free book site, only the older editions are free, and every page has a watermark. This may affect some people's enjoyment in reading their books.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-09-01T20:12:22.523", "Id": "30644", "Score": "0", "Tags": null, "Title": null }
30644
BASIC (an acronym for Beginner's All-purpose Symbolic Instruction Code) is a family of general-purpose, high-level programming languages whose design philosophy emphasizes ease of use.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T20:12:22.523", "Id": "30645", "Score": "0", "Tags": null, "Title": null }
30645
<p><a href="http://blog.codinghorror.com/why-cant-programmers-program/" rel="nofollow">Link - The original blog post by Jeff Atwood</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T20:20:28.543", "Id": "30646", "Score": "0", "Tags": null, "Title": null }
30646
A programming challenge, popularized by Jeff Atwood, that prints the numbers from 1 to 100, where multiples of three print "Fizz," multiples of five print "Buzz," and multiples of both three and five print "FizzBuzz."
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T20:20:28.543", "Id": "30647", "Score": "0", "Tags": null, "Title": null }
30647
In computer science, garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T20:22:24.693", "Id": "30649", "Score": "0", "Tags": null, "Title": null }
30649
In computer science, a literal is a notation for representing a fixed value in source code.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T20:23:53.043", "Id": "30651", "Score": "0", "Tags": null, "Title": null }
30651
In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T20:26:55.257", "Id": "30654", "Score": "0", "Tags": null, "Title": null }
30654
RSS Rich Site Summary (originally RDF Site Summary, often dubbed Really Simple Syndication) is a family of web feed formats used to publish frequently updated works—such as blog entries, news headlines, audio, and video—in a standardized format.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T20:28:17.217", "Id": "30656", "Score": "0", "Tags": null, "Title": null }
30656
In computer programming, the scope of an identifier is the part of a computer program where the identifier, a name that refers to some entity in the program, can be used to find the referred entity.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T20:28:57.813", "Id": "30658", "Score": "0", "Tags": null, "Title": null }
30658
<p>In computer science, a tree is a <a href="/questions/tagged/graph" class="post-tag" title="show questions tagged &#39;graph&#39;" rel="tag">graph</a> in which there is exactly one path between any two nodes. Often, the nodes are treated as a hierarchical data structure, such that there is a root node, and each child node also acts as a "root" of its subtree. An <a href="/questions/tagged/algorithm" class="post-tag" title="show questions tagged &#39;algorithm&#39;" rel="tag">algorithm</a> that uses a tree as a data structure will often traverse the tree starting at the root using <a href="/questions/tagged/recursion" class="post-tag" title="show questions tagged &#39;recursion&#39;" rel="tag">recursion</a>, working in logarithmic time.</p> <p>Special-purpose trees include:</p> <ul> <li><a href="/questions/tagged/binary-search" class="post-tag" title="show questions tagged &#39;binary-search&#39;" rel="tag">binary-search</a> tree</li> <li>B-tree</li> <li><a href="/questions/tagged/heap" class="post-tag" title="show questions tagged &#39;heap&#39;" rel="tag">heap</a></li> <li><a href="/questions/tagged/trie" class="post-tag" title="show questions tagged &#39;trie&#39;" rel="tag">trie</a></li> <li>abstract syntax tree (for example, an <a href="/questions/tagged/xml" class="post-tag" title="show questions tagged &#39;xml&#39;" rel="tag">xml</a> document may be thought of as a tree)</li> </ul> <p>For a connected graph, a <em>spanning tree</em> consists of the nodes of the graph and a subset of the edges such that there is only one path between any pair of nodes.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T20:31:19.183", "Id": "30659", "Score": "0", "Tags": null, "Title": null }
30659
A tree is a graph in which there is exactly one path between any two nodes. It is often used as a hierarchical data structure.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T20:31:19.183", "Id": "30660", "Score": "0", "Tags": null, "Title": null }
30660
Twitter is an online social networking service and microblogging service that enables its users to send and read text-based messages of up to 140 characters, known as "tweets". Use this tag for questions which may arise when developing FOR Twitter. This tag is NOT for support questions about using the Twitter website or the official Twitter app.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T20:31:54.967", "Id": "30662", "Score": "0", "Tags": null, "Title": null }
30662
<p>Please review my code to help improve its quality.</p> <pre><code>public void printHeadOfNonIntersectingLinkedList(List&lt;Standalone&gt; listStandalones) { final Map&lt;Node, Node&gt; tailHeads = new HashMap&lt;Node, Node&gt;(); for (Standalone ll : listStandalones) { Node temp = ll.first; while (temp.next != null) { temp = temp.next; } if (tailHeads.containsKey(temp)) { tailHeads.put(temp, null); } else { tailHeads.put(temp, ll.first); } } for (Entry&lt;Node, Node&gt; entry : tailHeads.entrySet()) { if (entry.getValue() != null) { System.out.println(entry.getValue().element); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T14:35:51.107", "Id": "48781", "Score": "1", "body": "It needs some comments to tell people what the hell it's supposed to do ...." } ]
[ { "body": "<p>First of all, you have provided very little context for your code. Therefore, my criticism may not be valid in the context of your full program.</p>\n\n<p>Second, you have not a <em>single</em> comment in your code. One can argue that code does not need comments once it is self-documenting. But your code does not achieve that.</p>\n\n<hr>\n\n<ul>\n<li><p>Your method does not use any variables defined outside of your function. This shows that</p>\n\n<ul>\n<li>… it should be marked as <code>static</code> – it clearly does not operate on an instance of the class where this function is defined.</li>\n<li>… Static methods can be an indication that your code is not object oriented. It may need to be redesigned.</li>\n<li>… You do operate on an object: <code>List&lt;Standalone&gt;</code>. Maybe that should be a class of its own, and this method be an instance method over there.</li>\n</ul></li>\n<li><p><code>printHeadOfNonIntersectingLinkedList</code> is far to long as a name. I know that Java code has the tendency to prefer such long names, but you are not doing anyone a favour with that. In addition:</p>\n\n<ul>\n<li>The name does not match the behaviour of the method. Doesn't it print the heads belonging to unique tails of linked lists? The lists itself may intersect.</li>\n<li>The name tells us that this method is doing too many unrelated things. It needs to be refactored. The different parts are: finding the tails of all lists, deduplicating the nodes, and printing them out.</li>\n</ul></li>\n<li><p><code>List&lt;Standalone&gt;</code> – why not <code>Iterable&lt;Standalone&gt;</code>? There is no need to be extra specific, and all we do is call an implicit <code>.iterator()</code> on it.</p></li>\n<li><p>+1 for using <code>final</code>, although you could designate the loop variables as <code>final</code> as well.</p></li>\n<li><p><code>tailHeads</code> is a <em>confusing</em> name. <code>seenTails</code> might be better.</p></li>\n<li><p><code>ll</code> is a bad name. Avoid short names, especially abbreviations. Exceptions to this rule are integer loop variables (<code>i</code>, <code>j</code>, …) and domain-specific code where <em>not</em> using common abbreviations would be <em>more</em> confusing. Examples would be highly mathematical (e.g. cryptographic) code. In this case, <code>linkedList</code> could be a better choice.</p></li>\n<li><p>Finding the last element in a list is an implementation detail, and should be encapsulated in the <code>Standalone</code> class – it doesn't seem to be very “standalone” after all. If you didn't write that class: Subclass it and implement these helpers there.</p>\n\n<pre><code>final Node tail = linkedList.tail();\n</code></pre></li>\n<li><p>The next part makes a lot of sense, and can't be written any better. But it is crucial to use comments to tell a reader what you are doing here:</p>\n\n<pre><code>// If that tail is already known, mark it as seen,\n// but unwanted with a null.\nif (seenTails.containsKey(tail)) {\n seenTails.put(tail, null);\n} ...\n</code></pre></li>\n<li><p>Using <code>.entrySet()</code> is a bit akward, considering that you are only interested in the values. Why not <code>for (final Node head : seenTails.values()) { ... }</code>?</p></li>\n<li><p>Let another method do the printing – just return a collection or iterator of the values of each head, and be done with it.</p></li>\n</ul>\n\n<hr>\n\n<p>Here is my take on making that code more self-documenting, heeding some of my above criticism. Untested.</p>\n\n<pre><code>class Standalone {\n private Node head; // proper encapsulation\n private NodeValue element;\n ...\n\n public Node head() {\n return head;\n }\n\n // you might want to cache this\n public Node tail() {\n // handle zero-length lists\n if (head == null)\n return null;\n\n // find and return last element\n Node pointer = head;\n while (pointer.next != null)\n pointer = pointer.next;\n return pointer;\n }\n\n public NodeValue element() {\n return element;\n }\n\n public static Iterable&lt;Standalone&gt; withUniqueTails(Iterable&lt;Standalone&gt; standaloneCollection) {\n final HashMap&lt;Node, Standalone&gt; uniqueTails = new HashMap&lt;Node, Node&gt;();\n final HashSet&lt;Node&gt; duplicates = new HashSet&lt;Node&gt;();\n\n for (final Standalone list : standaloneCollection) {\n final Node tail = list.tail();\n if (duplicates.contains(tail)\n continue;\n if (uniqueTails.containsKey(tail)) {\n uniqueTails.remove(tail);\n duplicates.add(tail);\n } else {\n uniqueTails.put(tail, list)\n }\n }\n\n return uniqueTails.values();\n }\n}\n</code></pre>\n\n<p>Calling code could be like</p>\n\n<pre><code>for(final Standalone standalone : Standalone.withUniqueTails(someStandalones)) {\n System.out.println(standalone.head().element());\n}\n</code></pre>\n\n<p>Do you notice something? The method is actually just a filter that skips over some values (we could lift this kind of code to all kinds of iterator transformation strategies). And this is the <em>only</em> thing my version of that method does. If you need a wrapper that extracts the head values, you can write it, without having to concern yourself with filtering out unwanted values.</p>\n\n<p>If you need a helper that prints out each element in some iterable one line at a time, you can write that too. Make it <code>private</code> to reduce the shame.</p>\n\n<pre><code>private static &lt;T&gt; void printCollection(OutputStream stream, Iterable&lt;T&gt; collection) {\n for(final T item : collection)\n stream.println(item);\n}\n</code></pre>\n\n<hr>\n\n<h2>Update:</h2>\n\n<p>Programming is a game of tradeoffs. We can optimize along axes of readability, theoretical elegance, memory usage, speed, and sometimes other resources like network requests. If in doubt, it is advisable to optimize for readability.</p>\n\n<p>In my suggested rewrite, I introduced <code>duplicates</code> mostly in order to make the code more self-documenting: If a duplicate node is detected, then it is literally removed from the unique nodes, and added to the <code>duplicates</code>. I avoided the (otherwise completely legitimate) use of <code>null</code> as a special value. This intends to make the code simpler to understand.</p>\n\n<p>We can estimate the performance characteristics of introducing another data structure.</p>\n\n<h3>Space</h3>\n\n<p>First, memory usage. The worst case scenario is that our input data is unique throughout the first half of the input, then repeats one or more times: <code>A, B, C, ..., Z, A, B, C, ..., Z</code>, where the number of elements <em>n</em> is chosen in a way that it forces a resizing of the hash table.</p>\n\n<p>After that code has been filtered, we find zero elements in <code>uniqueTails</code>, because all were duplicates. That data structure has capacity for <code>(n-1)*2</code> elements (hash table size is doubled when a certain load factor is reached). We have <em>n</em> elements in <code>duplicates</code>, which also has size for <code>(n-1)*2</code> elements. Thus in the worst case, we have allocated 2× as much memory as neccessary. But if one of those elements is unique, we can avoid the table size doubling in <code>duplicates</code>, thus using only 1.5× as much memory. If the duplicates are adjacent (<code>A, A, B, B</code>), then the <code>uniqeTails</code> never grow (best case scenario).</p>\n\n<p>Depending on the exact numbers of unique duplicate elements, the acceptable load factor, and the longest streak of unique elements, we can get anything from 1× to 2× the memory usage (plus overhead), but will rather stay at the lower end of that range. I consider this acceptable for most scenarios.</p>\n\n<h3>Time</h3>\n\n<p>The addition of another data structure comes at the cost of more recalculations of the hash. The hash code must be calculated for <code>contains</code>, <code>containsKey</code>, <code>remove</code>, <code>add</code>, <code>put</code>. Per element, a 1–4 calculations can occur in my code. Your original code does this in always exactly 2 calculations. Only when a key occurs more than eight times, less recalculations occur.</p>\n\n<p>Summary: My code will quite certainly perform worse – but it was never tuned for performance. By all means, use tricks like null pointers as special values to express an extra level of information. But if you do so, document it with a comment (you'll note that I did exactly that in the main part of my review).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T22:23:12.613", "Id": "48796", "Score": "0", "body": "My only concern is with final HashSet<Node> duplicates = new HashSet<Node>();. If this is an interview interviewer might ask me to reduce an additional data structure used. My implementation only uses Map and not a Set, Let me know your thoughts over this point. Great feedback, and very helpful" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T23:53:56.300", "Id": "48798", "Score": "0", "body": "@JavaDeveloper I compared the (theoretical) performance with and without the extra data structure in my update – your code is better performance wise, but we are only talking about a constant factor ≤ 2. Using tricks to improve performance is ok – your code does this quite nicely – as long as it is properly commented and explained and does not massively impact readability. My suggested rewrite only tried to improve self-documenting properties of the code and to refactor the behaviour into single-purpose methods, but was not intended to increase performance." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T21:53:38.980", "Id": "30704", "ParentId": "30666", "Score": "4" } } ]
{ "AcceptedAnswerId": "30704", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T00:30:27.957", "Id": "30666", "Score": "2", "Tags": [ "java", "linked-list" ], "Title": "Printing heads of stand-alone lists" }
30666
<p>I am a newbie to C. I've just wrote a linked list program, compiled it, and received a segmentation error. I have no clue where it went wrong. Can somebody help me?</p> <pre><code># include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; struct snode{ struct snode *next; int val; }; struct slist{ struct snode *head; struct snode *tail; int len; }; struct slist *mylist; void slist_insert(int v){ struct snode *newnode; newnode = (struct snode*)malloc(sizeof(struct snode)); newnode -&gt; val = v; newnode -&gt; next = NULL; if(mylist-&gt;head = NULL){ mylist-&gt;head = malloc (sizeof(struct snode)); mylist-&gt;tail = (struct snode*)malloc (sizeof(struct snode)); mylist-&gt;head = newnode; mylist-&gt;tail = newnode; } else{ mylist -&gt; tail -&gt; next = (struct snode*)malloc (sizeof(struct snode)); mylist -&gt; tail -&gt; next = newnode; }; mylist -&gt; len +=1; }; void main(){ slist_insert(1); slist_insert(2); slist_insert(3); slist_insert(4); slist_insert(5); struct snode *temp; temp = (struct snode*)malloc(sizeof(struct snode)); temp = mylist-&gt; head; while(temp -&gt; next != NULL){ printf("%d\n", temp -&gt; val); temp = temp -&gt; next; }; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T05:44:19.973", "Id": "48752", "Score": "1", "body": "There's at least an argument that this belongs on Stack Overflow since you aren't asking for a review of working code but are asking for help with resolving a bug." } ]
[ { "body": "<p>One key problem is:</p>\n\n<pre><code> if(mylist-&gt;head = NULL){\n</code></pre>\n\n<p>First, you've not checked whether <code>mylist</code> itself is NULL, and on the first call to <code>slist_insert()</code>, it is NULL. That alone leads to trouble.</p>\n\n<p>Second, you've got an assignment in there instead of a comparison; you need a comparison.</p>\n\n<p>When it comes down to it, you need to handle the empty list case and not <code>mylist-&gt;head == NULL</code>. The code inside the <code>if (mylist-&gt;head = NULL)</code> is extremely problematic. You allocate two node values, then you overwrite the pointers with <code>newnode</code>, leaking memory. The code does not set <code>mylist-&gt;len</code> either. You have a similar memory leak in the <code>else</code> clause.</p>\n\n<pre><code>if (mylist == NULL)\n{\n mylist = malloc(sizeof(*mylist)); // or sizeof(struct slist)\n mylist-&gt;head = newnode;\n mylist-&gt;tail = newnode;\n mylist-&gt;len = 1;\n}\nelse\n{\n mylist-&gt;tail-&gt;next = newnode;\n mylist-&gt;tail = newnode;\n mylist-&gt;len++;\n}\n</code></pre>\n\n<p>You have a number of places where you leave spaces around the <code>-&gt;</code> operator; don't! It binds very tightly and should never have spaces around it. Ditto for the <code>.</code> operator.</p>\n\n<p>Do not write <code>void main()</code>. It isn't valid in standard C; <s>it isn't valid in Microsoft C</s> (see Stack Overflow and <a href=\"https://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c/18721336#18721336\">What should <code>main()</code> return in C and C++</a> for more detailed information). Further, since Microsoft C is based on C89, you must also include a <code>return 0;</code> at the end of <code>main()</code>. In C99 and C11, that is optional (though that is IMNSHO a bug in the standard) and you are best off always using <code>return 0;</code> or equivalent at the end of <code>main()</code>.</p>\n\n<p>In the <code>main()</code> function, you don't need the allocation.</p>\n\n<pre><code>struct snode *temp = mylist-&gt;head;\nwhile (temp != NULL)\n{\n printf(\"%d\\n\", temp-&gt;val);\n temp = temp-&gt;next;\n}\n</code></pre>\n\n<p>You should not have an empty declaration after the <code>main()</code> program — the semicolon after the close brace is technically an empty declaration. Omit the semicolon. Ditto after <code>slist_insert()</code>.</p>\n\n<p>You don't need the empty statement (semicolon) after the <code>while</code> loop in <code>main()</code>, either. Nor do you need the empty statement after the <code>else</code> block in <code>slist_insert()</code>. These don't do much harm, but they don't do any good either.</p>\n\n<p>At some point, you need to add the code to release the list.</p>\n\n<p>Your code is not very general. You are tied to a single list. You should be able to create an empty list, and then pass that list to <code>slist_insert()</code> so you could have multiple lists concurrently. Global variables (like <code>mylist</code>) are bad when they can be avoided — and this one could be avoided. However, this is a secondary issue; you have a lot of primary issues to resolve first.</p>\n\n<p>An alternative design would use <code>struct slist mylist;</code> as the global variable, avoiding the need to dynamically allocate the list. However, that doesn't work well for the generalized version, so I don't recommend implementing it (except as an exercise).</p>\n\n<p>Personally, I'd create types for the structures:</p>\n\n<pre><code>typedef struct snode snode;\ntypedef struct slist slist;\n</code></pre>\n\n<p>and I'd use those in the code. I haven't implemented that.</p>\n\n<p>Your code does not check that <code>malloc()</code> returns a non-null pointer; neither does mine, but that is lazy. However, you also don't have an easy way to indicate the problem with the current interface — other then a unilateral exit from the program. I've used <code>assert()</code> statements to deal with this. I've also tagged the lines 'reprehensible' because using <code>assert()</code> for checking memory allocation is a very bad idea — only marginally less bad than not checking at all.</p>\n\n<p>Here is working code incorporating most of the points raised above (and probably a few other minor details). I left the debugging code I added while sorting out the problems; you can see what I used and work out why. Every print except the one in the <code>while</code> loop in <code>main()</code> is debugging code.</p>\n\n<pre><code>#include &lt;assert.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nstruct snode\n{\n struct snode *next;\n int val;\n};\n\nstruct slist\n{\n struct snode *head;\n struct snode *tail;\n int len;\n};\n\nstruct slist *mylist;\n\nextern void slist_insert(int v);\nextern void slist_destroy(void);\n\nvoid slist_insert(int v)\n{\n struct snode *newnode = (struct snode*)malloc(sizeof(struct snode));\n assert(newnode != NULL); // Reprehensible\n newnode-&gt;val = v;\n newnode-&gt;next = NULL;\n\n if (mylist == NULL)\n {\n mylist = malloc(sizeof(*mylist));\n assert(mylist != NULL); // Reprehensible\n mylist-&gt;head = newnode;\n mylist-&gt;tail = newnode;\n mylist-&gt;len = 1;\n }\n else\n {\n assert(mylist-&gt;head != 0);\n assert(mylist-&gt;tail != 0);\n assert(mylist-&gt;tail-&gt;next == 0);\n mylist-&gt;tail-&gt;next = newnode;\n mylist-&gt;len++;\n mylist-&gt;tail = newnode;\n }\n}\n\nvoid slist_destroy(void)\n{\n struct snode *curr = mylist-&gt;head;\n while (curr != NULL)\n {\n printf(\"Free: %d\\n\", curr-&gt;val);\n struct snode *next = curr-&gt;next;\n free(curr);\n curr = next;\n }\n printf(\"Free: mylist\\n\");\n free(mylist);\n mylist = 0;\n}\n\nint main(void)\n{\n printf(\"Before 1\\n\");\n assert(mylist == 0);\n slist_insert(1);\n assert(mylist != 0);\n printf(\"Before 2\\n\");\n slist_insert(2);\n printf(\"Before 3\\n\");\n slist_insert(3);\n printf(\"Before 4\\n\");\n slist_insert(4);\n printf(\"Before 5\\n\");\n slist_insert(5);\n\n printf(\"Before loop\\n\");\n\n struct snode *temp = mylist-&gt;head;\n while (temp != NULL)\n {\n printf(\"%d\\n\", temp-&gt;val);\n temp = temp-&gt;next;\n }\n\n slist_destroy();\n\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T06:01:00.200", "Id": "48754", "Score": "0", "body": "+1 good points and revised code. Although the OP was just concerned about the error, I'm sure this information was needed as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T02:30:45.880", "Id": "48877", "Score": "0", "body": "Thanks so much! I definitely helped out! Really appericiated" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T05:18:02.793", "Id": "30672", "ParentId": "30667", "Score": "3" } } ]
{ "AcceptedAnswerId": "30672", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T01:23:17.983", "Id": "30667", "Score": "-2", "Tags": [ "c", "linked-list" ], "Title": "Linked list in C" }
30667
The brainfuck programming language is an esoteric programming language noted for its extreme minimalism. It is a Turing tarpit, designed to challenge and amuse programmers, and was not made to be suitable for practical use.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T07:24:58.380", "Id": "30677", "Score": "0", "Tags": null, "Title": null }
30677
<p>I have been looking around for a good place to get my code reviewed for some time. I just stumbled on this site and I was hoping some people could tell me if I'm progressing in the right direction. This is a snippet from a sudoku game I'm making. The full source code can be viewed at <a href="http://www.lesshardtofind.com/Sudoku/sudoku.js" rel="nofollow">http://www.lesshardtofind.com/Sudoku/sudoku.js</a> and a working example (only the user input segment) at <a href="http://www.lesshardtofind.com/Sudoku/main.html" rel="nofollow">http://www.lesshardtofind.com/Sudoku/main.html</a></p> <pre><code>function Cell(X, Y){ // Object that contains all the data needed for a sudoku cell this.Size = CELLSIZE; // This object's size this.Value = 0; // Displayed value 1-9 this.Color = '#DDDDFF'; // I wanted to use CellColor but a glitch caused some of them to turn black this.BorderColor = 'black' this.Xloc = X; // Xcoordinate value on the canvas this.Yloc = Y; // Ycoordinate value on the canvas this.Draw = function(){ // The function to draw the cell on the screen var CNV = Get(CANVASID); // setup the context var CTX = CNV.getContext('2d'); CTX.fillStyle = this.Color; // setup and draw the rectangle CTX.fillRect(this.Xloc, this.Yloc, this.Size, this.Size); CTX.moveTo(this.Xloc, this.Yloc); // draw the boarder CTX.lineTo(this.Xloc+this.Size, this.Yloc); CTX.lineTo(this.Xloc+this.Size, this.Yloc+this.Size); CTX.lineTo(this.Xloc, this.Yloc+this.Size); CTX.lineTo(this.Xloc, this.Yloc); CTX.strokeStyle = this.BorderColor; CTX.lineWidth = 1; CTX.stroke(); if(this.Value){ // if the value isn't 0 draw the current value to the screen CTX.fillStyle = 'black'; CTX.font = "30px kaushan_scriptregular"; CTX.fillText(this.Value, this.Xloc+14, this.Yloc+33); } } } function Board(){ // the main game board object definition this.Rows = new Array; // the array to hold the cells of the board this.Born = false; // boolean to say if this is the initiation of the object this.Setup = function(){ // setup the board and initiate all variables to appropriate values and instantiate objects var CurX = 280; // The starting X coordinate var CurY = 50; // The starting Y coordinate for(var x = 0; x &lt; 9; x++) // Set all the Rows array data position as arrays creating a 9x9 grid this.Rows[x] = new Array; for(var x = 0; x &lt; 9; x++){ // loop through all 81 cells and create them at the right location for(var y = 0; y &lt; 9; y++){ this.Rows[x][y] = new Cell(CurX, CurY); this.Rows[x][y].Value = 0; CurX += this.Rows[x][y].Size; } CurY += this.Rows[x][0].Size; CurX = 280; } this.Born = true; // set the flag that the board was initiated } this.Draw = function(){ // draw method to handle all objects within the board for(var r = 0; r &lt; 9; r++){ // loop through all cells and call their draw method for(var c = 0; c &lt; 9; c++){ this.Rows[r][c].Draw(); } } } } </code></pre>
[]
[ { "body": "<p>I don't seem to see the need for the methods to be declared <em>inside</em> the constructor. You aren't making any property <em>\"private\"</em>. Also, declaring methods this way makes copies of the methods for each instance.</p>\n\n<p>I suggest you move them out to the prototype instead. That way, they are declared once, and shared across instances, saving memory.</p>\n\n<pre><code>function Cell(x,y){\n this.size = CELLSIZE;\n //properties here\n}\n\n//Methods out here\nCell.prototype = {\n constructor : Cell, //refer back the constructor\n draw : function(){...},\n //more methods for Cell here\n}\n</code></pre>\n\n<p>I also notice <code>CELLSIZE</code> and <code>CANVASID</code>. If they are globals, then I suggest you not make them globals.</p>\n\n<p>Lastly, I suggest you use a canvas framework instead of drawing the shapes by hand. Learning the basics is good, but most developers don't code from scratch (unless there's a compelling need to do so). I suggest using <a href=\"http://paperjs.org/\" rel=\"nofollow\">PaperJS</a> or <a href=\"http://kineticjs.com/\" rel=\"nofollow\">KineticJS</a> for drawing your shapes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T18:32:39.950", "Id": "48788", "Score": "0", "body": "CELLSIZE and CANVASID are CONSTs inside the Sudoku Object therefore would still not conflict with any other JavaScript code, but could still be shared by all methods and only changed in one place. Is this bad?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T13:05:23.000", "Id": "30692", "ParentId": "30680", "Score": "1" } } ]
{ "AcceptedAnswerId": "30692", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T08:18:12.543", "Id": "30680", "Score": "1", "Tags": [ "javascript", "sudoku", "canvas" ], "Title": "Drawing a sudoku board to a canvas" }
30680
<p>I'm currently learning programming for the first time and I've created the following implementation of quick sort in C#. I basically read a very basic overview of how quick sort works recursively and implemented it without looking at any concrete examples of its implementation so that I could learn the most from it.</p> <p>Could you let me know what you think and where it could be optimized?</p> <pre><code>class Program { static void Main(string[] args) { var input = new int[] { 10, 3, 20, 5, 200 }; QuickSort(0, 0, input.Length-1, input); Console.WriteLine("Sorted output: :"); new List&lt;int&gt;(input).ForEach(x =&gt; Console.Write(x + ",")); Console.ReadLine(); } /// &lt;summary&gt; /// sample input: 5 7 3 9 2 /// same output: 2 3 5 7 9 /// &lt;/summary&gt; /// &lt;param name="numbers"&gt;&lt;/param&gt; public static void QuickSort(int pivotIndex, int startIndex, int endIndex, int[] numbers) { if (startIndex == endIndex) return; int pivotNumber = numbers[pivotIndex]; var lowerThanPivot = new List&lt;int&gt;(); var higherThanPivot = new List&lt;int&gt;(); for(int i = startIndex; i &lt;= endIndex; i++) { if(i != pivotIndex) { if( numbers[i] &lt;= pivotNumber ) lowerThanPivot.Add(numbers[i]); else higherThanPivot.Add(numbers[i]); } } // now lets put the pivot number in the correct place numbers[startIndex + lowerThanPivot.Count] = pivotNumber; // reinsert the numbers lower than pivot in the right place int z = startIndex; lowerThanPivot.ForEach(x =&gt; numbers[z++] = x); z++; // *** skip over the new pivot index *** // reinsert the numbers higher than pivot in the right place higherThanPivot.ForEach(x =&gt; numbers[z++] = x); // recursively call to sort each remaining elements int newLeftPivot = startIndex; int newEndLeftIndex = newLeftPivot + lowerThanPivot.Count - 1 ; int newRightPivot = lowerThanPivot.Count + 1; int newEndRightIndex = newRightPivot + higherThanPivot.Count - 1; if(lowerThanPivot.Count&gt; 0) QuickSort(newLeftPivot, newLeftPivot, newEndLeftIndex, numbers); if(higherThanPivot.Count &gt; 0) QuickSort(newRightPivot, newRightPivot, newEndRightIndex, numbers); } } </code></pre>
[]
[ { "body": "<pre><code>new List&lt;int&gt;(input).ForEach(x =&gt; Console.Write(x + \",\"));\n</code></pre>\n\n<p>I see absolutely no reason to do this. In general, <code>List.ForEach()</code> is <a href=\"https://stackoverflow.com/a/226299/41071\">considered bad form by some and you should use normal <code>foreach</code> instead</a>.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// sample input: 5 7 3 9 2\n/// same output: 2 3 5 7 9\n/// &lt;/summary&gt;\n/// &lt;param name=\"numbers\"&gt;&lt;/param&gt;\n</code></pre>\n\n<p>This is not a very good documentation comment. The comment should describe in words what your code does. Example input and output might help to clarify that further, but I think that's not necessary for sorting.</p>\n\n<p>Also, you should either describe your parameters using <code>&lt;param&gt;</code>, or don't use it (if you think the meaning of the parameters is clear). But empty <code>&lt;param&gt;</code> is not useful.</p>\n\n<pre><code>var lowerThanPivot = new List&lt;int&gt;();\nvar higherThanPivot = new List&lt;int&gt;();\n</code></pre>\n\n<p>You don't need these two lists. QuickSort can be implemented as an in-place algorithm. That means you don't need any additional collections to use it.</p>\n\n<p>The way this is done is that you iterate the array from the start and at the same time from the end, switching elements between the two positions if the left one is larger than the pivot and the right one is smaller.</p>\n\n<p>This will make your code somewhat more complicated, but it also potentially saves a lot memory.</p>\n\n<pre><code>int newLeftPivot = startIndex;\n\nint newRightPivot = lowerThanPivot.Count + 1;\n</code></pre>\n\n<p>This is not a very good choice for a pivot. If the array is already sorted (or mostly sorted, with often isn't that uncommon), then your code will run in O(n^2) time, which will make it very slow on large inputs. You should consider <a href=\"https://en.wikipedia.org/wiki/Quicksort#Choice_of_pivot\" rel=\"nofollow noreferrer\">a better way to choose the pivot</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T10:22:44.443", "Id": "30686", "ParentId": "30681", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T08:47:09.583", "Id": "30681", "Score": "4", "Tags": [ "c#", "beginner", "sorting", "quick-sort" ], "Title": "Implementation of quick sort in C#" }
30681
<p>I have a <code>VenuesController</code> and an <code>EventsController</code>. My venues controller has an <code>admin_add</code> method that, well, allows an administrator to add a venue to the database. It looks like this:</p> <pre><code>public function admin_add() { if ($this-&gt;request-&gt;is('post')) { if ($this-&gt;Venue-&gt;save($this-&gt;request-&gt;data)) { $message = 'Venue has been created.'; $this-&gt;response-&gt;statusCode(201); if ($this-&gt;request-&gt;params['ext'] == 'json') { $this-&gt;set('id', $this-&gt;Venue-&gt;id); $this-&gt;set('_serialize', array('id')); } else { $this-&gt;Session-&gt;setFlash($message, 'flash', array('class' =&gt; 'success')); $this-&gt;redirect(array('action' =&gt; 'index')); } } else { if ($this-&gt;request-&gt;params['ext'] == 'json') { $this-&gt;set('validationErrors', $this-&gt;Venue-&gt;validationErrors); $this-&gt;set('_serialize', array('validationErrors')); $this-&gt;response-&gt;statusCode(400); } } } } </code></pre> <p>As you can see, there are a lot of <code>if ()</code> statements which seem like code smells to me. But they’re there because in my CMS’s events section, you can add a venue inline via a modal, which sents the request to this function via AJAX.</p> <p>So my question is: can I improve the above <code>VenuesController::admin_add()</code> method, make it more intelligent without the need for the <code>if ()</code> statements, and just generally make it more CakePHP-ier?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T03:18:19.513", "Id": "87049", "Score": "0", "body": "Sometimes you can't avoid having lots of `if` statements in your code. In your case the only thing I notice that I personally don't like is that you have sections of code inside `if` statements which would be prevented by calling `if(!$some_condition) return false;` then continuing with your logic." } ]
[ { "body": "<p>Why do you have the following lines repeating:</p>\n\n<pre><code> if ($this-&gt;Venue-&gt;save($this-&gt;request-&gt;data)) {\n if ($this-&gt;Venue-&gt;save($this-&gt;request-&gt;data)) {\n</code></pre>\n\n<p>I think you may try to merge them to one and the associated logic too.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T10:38:15.687", "Id": "48770", "Score": "0", "body": "I didn’t actually know I had, that’s a bug! There should only be one `save()` call. That’s late night coding for you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T09:54:54.540", "Id": "30684", "ParentId": "30682", "Score": "2" } }, { "body": "<p>For Aditional security i would definitely include the session or the cookie component </p>\n\n<pre><code>public $components = array('Session', 'Cookie');\n</code></pre>\n\n<p>and inside the function this if</p>\n\n<pre><code>if ($this-&gt;Session-&gt;read('Auth.User.role') == 'admin' || $this-&gt;Cookie-&gt;read('User.role') == 'admin') {\n</code></pre>\n\n<p>for more details you could check these</p>\n\n<ul>\n<li><a href=\"http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html\" rel=\"nofollow\">Sessions</a></li>\n<li><a href=\"http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html\" rel=\"nofollow\">Cookies</a></li>\n<li><a href=\"http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html\" rel=\"nofollow\">Auth</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T10:00:31.377", "Id": "64688", "Score": "1", "body": "This is redundant, as I check the user role in a `beforeAction()` method in my `AppController` to keep things DRY." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T08:15:04.393", "Id": "38735", "ParentId": "30682", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T09:31:36.940", "Id": "30682", "Score": "3", "Tags": [ "php", "controller", "cakephp" ], "Title": "Admin method in CakePHP to add a venue to the database" }
30682
<p>I am making a GWT application and have to prevent client code from using null values in collections. I found <a href="https://stackoverflow.com/a/6997191">an answer</a> but GWT doesn't support <code>Queue</code> and its implementations as <a href="http://www.gwtproject.org/doc/latest/RefJreEmulation.html#Package_java_util" rel="nofollow noreferrer">the GWT documentation says.</a></p> <p>So, I had to make my own implementation.</p> <pre><code>import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; /** * This implementation of {@link ArrayList} does not allow to add null values * * @author Maxim Dmitriev * * @param &lt;E&gt; */ public class NonNullArrayList&lt;E&gt; extends ArrayList&lt;E&gt; implements Serializable { private static final String NULL_VALUES_ARE_PROHIBITED = "Null values are prohibited"; private static final String CLONING_IS_UNSUPPORTED = "Cloning is unsupported. Please support if necessary"; public NonNullArrayList() { // For serialization. super() is called automatically. } public NonNullArrayList(int initialCapacity) { super(initialCapacity); } public NonNullArrayList(Collection&lt;? extends E&gt; c) { super(c); if (contains(null)) { throw new NullPointerException(NULL_VALUES_ARE_PROHIBITED); } } /** * */ private static final long serialVersionUID = 7716772103636691126L; public boolean add(E e) { if (e == null) { throw new NullPointerException(NULL_VALUES_ARE_PROHIBITED); } return super.add(e); }; @Override public boolean addAll(Collection&lt;? extends E&gt; c) { if (c.contains(null)) { throw new NullPointerException(NULL_VALUES_ARE_PROHIBITED); } return super.addAll(c); } public void add(int index, E element) { if (element == null) { throw new NullPointerException(NULL_VALUES_ARE_PROHIBITED); } super.add(index, element); }; @Override public boolean addAll(int index, Collection&lt;? extends E&gt; c) { if (c.contains(null)) { throw new NullPointerException(NULL_VALUES_ARE_PROHIBITED); } return super.addAll(index, c); } public E set(int index, E element) { if (element == null) { throw new NullPointerException(NULL_VALUES_ARE_PROHIBITED); } return super.set(index, element); }; @Override public Object clone() { throw new Error(CLONING_IS_UNSUPPORTED); } } </code></pre> <p>Besides I want to prevent code from using the <code>clone()</code> method because I just don't need it.</p> <p>Is the implementation good or not?</p>
[]
[ { "body": "<ul>\n<li><p>Throwing <code>NullPointerException</code> from methods like <code>add</code>, <code>set</code> are OK, cause the element to be added can't be <code>null</code>. But throwing NPE from <code>addAll</code> method is not cool. From <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#addAll%28java.util.Collection%29\" rel=\"nofollow noreferrer\">Javadoc</a> </p>\n\n<blockquote>\n <p>Throws: NullPointerException - if the specified <strong>collection</strong> is null</p>\n</blockquote>\n\n<p>that means if there exists a null value in the <code>Collection</code> throwing NPE doesn't make sense. You can throw <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/IllegalArgumentException.html\" rel=\"nofollow noreferrer\"><code>IllegalArgumentException</code></a> or a custom exception like <code>FoundNullValueInCollectionException</code>(I think this is better). </p>\n\n<p>In your defense you can point towards the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Map.html#containsKey%28java.lang.Object%29\" rel=\"nofollow noreferrer\"><code>Map.containsKey</code> Javadoc</a>, where it throws NPE <em>if the specified key is null and this map does not permit null keys (optional)</em>.</p></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><blockquote>\n <p>I want to prevent code from using the clone() method</p>\n</blockquote>\n\n<p>So you can throw a <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/UnsupportedOperationException.html\" rel=\"nofollow noreferrer\"><code>UnsupportedOperationException</code></a> or <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/CloneNotSupportedException.html\" rel=\"nofollow noreferrer\"><code>CloneNotSupportedException</code></a>(as <a href=\"https://codereview.stackexchange.com/a/30700/26200\">JohnMark13</a> suggested).</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T13:15:56.793", "Id": "48777", "Score": "0", "body": "thanks. But any exception can be caught. Errors can't be caught." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T13:43:09.030", "Id": "48778", "Score": "0", "body": "@RedPlanet and when did I say anything about Errors?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T13:46:02.640", "Id": "48779", "Score": "4", "body": "@RedPlanet of course Errors can be caught" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T12:55:47.290", "Id": "30691", "ParentId": "30688", "Score": "7" } }, { "body": "<p>In your case I think that you should consider the use of IllegalArgumentException it will save you a headache in the long run. When it comes to looking at code and trying to work out what broke and why NPEs are very well understood and very useful in debugging, but IAE describes your situation better. </p>\n\n<p>The bottom line is that you have asked a question with no right or wrong answer and you will find very strong opinions form both camps - here is a good example of a short debate with many convincing <em>opinions</em> on <a href=\"https://stackoverflow.com/questions/3881/illegalargumentexception-or-nullpointerexception-for-a-null-parameter\">StackOverflow</a></p>\n\n<p>I'm not sure why the conversation around the clone method, if you want to extend ArrayList without clone you should throw the standard <code>CloneNotSupportedException</code>.</p>\n\n<p>A similar discussion was had the other day, are you sure that you want to extend ArrayList at all, would you be better off having a private ArrayList member variable, delegating the methods that you care about to it and not exposing the others.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T19:00:26.127", "Id": "30700", "ParentId": "30688", "Score": "2" } } ]
{ "AcceptedAnswerId": "30691", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T11:59:52.737", "Id": "30688", "Score": "1", "Tags": [ "java", "array", "collections", "null" ], "Title": "A custom Java collection which doesn't support nulls" }
30688
<p>I have a PDO class below:</p> <pre><code>class DB { private $dbh; private $stmt; static $db_type; static $connections; public function __construct($db, $id="") { switch($db) { case "db1": try{ $this-&gt;dbh = new PDO("mysql:host=localhost;dbname=ms".$id, 'root', '', array( PDO::ATTR_PERSISTENT =&gt; true )); } catch(PDOException $e){ print "Error!: " . $e-&gt;getMessage() . "&lt;br /&gt;"; die(); } break; case "db2": try{ $this-&gt;dbh = new PDO("mysql:host=localhost;dbname=users", 'root', '', array( PDO::ATTR_PERSISTENT =&gt; true )); } catch(PDOException $e){ print "Error!: " . $e-&gt;getMessage() . "&lt;br /&gt;"; die(); } break; } self::$db_type = $db; } static function init($db_type = "", $id){ if(!isset(self::$connections[$db_type])){ self::$connections[$db_type] = new self($db_type, $id); } return self::$connections[$db_type]; } public static function query($query) { self::$connections[self::$db_type]-&gt;stmt = self::$connections[self::$db_type]-&gt;dbh-&gt;prepare($query); return self::$connections[self::$db_type]; } public function bind($pos, $value, $type = null) { if( is_null($type) ) { switch( true ) { case is_int($value): $type = PDO::PARAM_INT; break; case is_bool($value): $type = PDO::PARAM_BOOL; break; case is_null($value): $type = PDO::PARAM_NULL; break; default: $type = PDO::PARAM_STR; } } self::$connections[self::$db_type]-&gt;stmt-&gt;bindValue($pos, $value, $type); return self::$connections[self::$db_type]; } public function execute() { return self::$connections[self::$db_type]-&gt;stmt-&gt;execute(); } } </code></pre> <p>Is it ok for multiple DB connections or not?</p>
[]
[ { "body": "<p>A <a href=\"https://stackoverflow.com/questions/18572590/pdo-connection-to-multiple-databases/18572640#18572640\">quick recap from SO</a></p>\n\n<ol>\n<li><p>If you want to implement the Singleton pattern (first read about SOLID, though, and pay special attention to injection), make the constructor private.</p></li>\n<li><p>Your query method is static, why? it defaults (without the user being able to do anything about this) to the last connection that was established. Are you sure that's what the user wanted? Of course not! But then again, all of the other methods, like <code>execute</code> exhibit the same behaviour, so Everybody will end up working on the same connection, until they run into trouble and revert to using their own instances of <code>PDO</code>.</p></li>\n</ol>\n\n<p>As ever, everything I have to say about custom wrapper classes around an API like <code>PDO</code> offers, <a href=\"https://codereview.stackexchange.com/questions/29362/very-simple-php-pdo-class/29394#29394\">can be read here</a>. What I think of DB wrappers in general <a href=\"https://codereview.stackexchange.com/questions/29670/minimalistic-mysql-db-class/29688#29688\">can be found here</a>.</p>\n\n<p>If you want to have all current connections available globally, then your code should shift towards a <em>Factory</em>, not a <em>Singleton</em> pattern:</p>\n\n<pre><code>class Factory\n{\n private static $connections = array();\n public static function getDB($host, array $params)\n {\n if (!isset(self::connections[$host]))\n {\n self::connections[$host] = new DB($params);\n }\n return self::connections[$host];\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T12:14:51.387", "Id": "48774", "Score": "0", "body": "Do you know any code examples to look at?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T12:17:16.270", "Id": "48775", "Score": "0", "body": "@user889349: check the links, there's a lot of info in them, including code examples. I've just quit smoking and have a lot of work to do, so I can't be bothered writing long answers today, sorry :s" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T12:10:57.070", "Id": "30690", "ParentId": "30689", "Score": "3" } } ]
{ "AcceptedAnswerId": "30690", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T12:05:10.763", "Id": "30689", "Score": "1", "Tags": [ "php", "mysql", "singleton" ], "Title": "PDO class for multiple databases" }
30689
<p>I use a worker thread for some data processing in my MFC project. In the thread-controlling function, it needs to use some parameters (declared as member variables) to the data-processing. I use a sub-dialog (which is triggered by a menu item and contains a few edit controls) to change the values of the parameters, that the user inputs are first stored in a <code>struct</code>, which is then used in the thread controlling function when needed. In order to prevent data-corruption, I also use Mutex to sync the worker thread and main thread, since both of them need to access the shared resource <code>m_structBlkContSimPara</code> (the <code>struct</code> that stores parameter values).</p> <pre><code>/*the following code is in my MFC Dlg Project head file*/ struct RecExtractParam { bool bMod; float fSimBlkShpWt; float fSimGrPosWt; float fSimGrTxtAttWt; float fSimGrTypesWt; float fDataUnitGroupSimThld; float fVertDistThld; RecExtractParam() { bMod = false; fSimBlkShpWt = 0; fSimGrPosWt = 0; fSimGrTxtAttWt = 0; fSimGrTypesWt = 0; fDataUnitGroupSimThld = 0; fVertDistThld = 0; }}; RecExtractParam m_structBlkContSimPara; // parameters for some data processing float m_fSimBlkShpWt; float m_fSimGrPosWt; float m_fSimGrTxtAttWt; float m_fSimGrTypesWt; float m_fDataUnitGroupSimThld; float m_fVertDistThld; CMutex m_Mutex; afx_msg void OnToolsBlockContentSimilarityThreshold(); static UINT RecExtractThreadCtrlFunc(LPVOID pParam); UINT DoThreadProc(); // button clicked handler for launching data processing void CXMLDOMFromVCDlg::OnBnClickedDataRecExtractButton() { // TODO: Add your control notification handler code here // some code for other processing // start the thread for data record extraction AfxBeginThread(RecExtractThreadCtrlFunc, this); // some code for other processing } // menu item command handler for parameter inputs void CXMLDOMFromVCDlg::OnToolsBlockContentSimilarityThreshold() { // TODO: Add your command handler code here // CBlkContSimThldDlg is a sub-dialog for user input CBlkContSimThldDlg dlgBlkContSimThld(this); if (dlgBlkContSimThld.DoModal() == IDOK) { CSingleLock singleLock(&amp;m_Mutex); // try to capture the shared resource singleLock.Lock(); m_structBlkContSimPara.bMod = true; m_structBlkContSimPara.fDataUnitGroupSimThld = dlgBlkContSimThld.m_fDlgBlkContSimThld; m_structBlkContSimPara.fSimBlkShpWt = dlgBlkContSimThld.m_fDlgGrShpWt; m_structBlkContSimPara.fSimGrPosWt = dlgBlkContSimThld.m_fDlgGrPosWt; m_structBlkContSimPara.fSimGrTxtAttWt = dlgBlkContSimThld.m_fDlgGrTxtAttWt; m_structBlkContSimPara.fSimGrTypesWt = dlgBlkContSimThld.m_fDlgGrContTypeWt; m_structBlkContSimPara.fVertDistThld = dlgBlkContSimThld.m_fDlgGrVertDistThld; singleLock.Unlock(); } } // thread controlling function UINT CXMLDOMFromVCDlg::RecExtractThreadCtrlFunc(LPVOID pParam) { CXMLDOMFromVCDlg* pDlg = (CXMLDOMFromVCDlg*)pParam; return pDlg-&gt;DoThreadProc(); } UINT CXMLDOMFromVCDlg::DoThreadProc() { // Create object for Single Lock CSingleLock singleLock(&amp;m_Mutex); // try to capture the shared resource singleLock.Lock(); // use the shared resource m_structBlkContSimPara if(m_structBlkContSimPara.bMod) { m_fSimBlkShpWt = m_structBlkContSimPara.fSimBlkShpWt; m_fSimGrPosWt = m_structBlkContSimPara.fSimGrPosWt; m_fSimGrTxtAttWt = m_structBlkContSimPara.fSimGrTxtAttWt; m_fSimGrTypesWt = m_structBlkContSimPara.fSimGrTypesWt; m_fDataUnitGroupSimThld = m_structBlkContSimPara.fDataUnitGroupSimThld; m_fVertDistThld = m_structBlkContSimPara.fVertDistThld; m_structBlkContSimPara.bMod = false; } // After we done, let other threads use m_structBlkContSimPara singleLock.Unlock(); /*some code for data processing*/ } </code></pre> <p>I am new to multithreading and synchronization. Is my code correct? If not, what should I do to improve it?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T14:34:19.260", "Id": "30694", "Score": "3", "Tags": [ "c++", "multithreading", "synchronization" ], "Title": "Simple multithreading and synchronization problems in MFC" }
30694
<p>I am trying to display the leave history of a particular employee. But, when I choose a particular month (for example, I choose to display January instead of displaying the history of January), it displays all the history from this year. Is there anything wrong with my code?</p> <pre><code>&lt;?php echo 'View the application history by :&lt;select name="date"&gt; &lt;option value="january" selected="selected"&gt;January&lt;/option&gt; &lt;option value="february" &gt;February&lt;/option&gt; &lt;option value="march"&gt;March&lt;/option&gt; &lt;option value="april"&gt;April&lt;/option&gt; &lt;option value="may"&gt;May&lt;/option&gt; &lt;option value="june"&gt;June&lt;/option&gt; &lt;option value="july"&gt;July&lt;/option&gt; &lt;option value="august"&gt;August&lt;/option&gt; &lt;option value="september"&gt;September&lt;/option&gt; &lt;option value="october"&gt;October&lt;/option&gt; &lt;option value="november"&gt;November&lt;/option&gt; &lt;option value="december"&gt;December&lt;/option&gt;'; echo'&lt;/select&gt;'; $value = 'value'; if($value=='january') { $check_user=mysql_query("select*from employee e, `leave` l where e.emp_id = l.emp_id and l.Emp_ID='".$aid."' and Date_Apply &gt;='2013-01-01' and Date_Apply&lt;'2013-01-31'"); } else if($value=='february') { $check_user=mysql_query("select*from employee e, `leave` l where e.emp_id = l.emp_id and l.Emp_ID='".$aid."' and Date_Apply &gt;='2013-02-01' and Date_Apply&lt;'2013-02-28'"); } else if($value=='march') { $check_user=mysql_query("select*from employee e, `leave` l where e.emp_id = l.emp_id and l.Emp_ID='".$aid."' and Date_Apply &gt;='2013-03-01' and Date_Apply&lt;'2013-03-31'"); } else if($value=='april') { $check_user=mysql_query("select*from employee e, `leave` l where e.emp_id = l.emp_id and l.Emp_ID='".$aid."' and Date_Apply &gt;='2013-04-01' and Date_Apply&lt;'2013-04-30'"); } else if($value=='may') { $check_user=mysql_query("select*from employee e, `leave` l where e.emp_id = l.emp_id and l.Emp_ID='".$aid."' and Date_Apply &gt;='2013-05-01' and Date_Apply&lt;'2013-05-31'"); } else if($value=='june') { $check_user=mysql_query("select*from employee e, `leave` l where e.emp_id = l.emp_id and l.Emp_ID='".$aid."' and Date_Apply &gt;='2013-06-01' and Date_Apply&lt;'2013-06-30'"); } else if($value=='july') { $check_user=mysql_query("select*from employee e, `leave` l where e.emp_id = l.emp_id and l.Emp_ID='".$aid."' and Date_Apply &gt;='2013-07-01' and Date_Apply&lt;'2013-07-31'"); } else if($value=='august') { $check_user=mysql_query("select*from employee e, `leave` l where e.emp_id = l.emp_id and l.Emp_ID='".$aid."' and Date_Apply &gt;='2013-08-01' and Date_Apply&lt;'2013-08-31'"); } else if($value=='september') { $check_user=mysql_query("select*from employee e, `leave` l where e.emp_id = l.emp_id and l.Emp_ID='".$aid."' and Date_Apply &gt;='2013-09-01' and Date_Apply&lt;'2013-09-30'"); } else if($value=='october') { $check_user=mysql_query("select*from employee e, `leave` l where e.emp_id = l.emp_id and l.Emp_ID='".$aid."' and Date_Apply &gt;='2013-10-01' and Date_Apply&lt;'2013-10-31'"); } else if($value=='november') { $check_user=mysql_query("select*from employee e, `leave` l where e.emp_id = l.emp_id and l.Emp_ID='".$aid."' and Date_Apply &gt;='2013-11-01' and Date_Apply&lt;'2013-11-30'"); } else if($value=='december') { $check_user=mysql_query("select*from employee e, `leave` l where e.emp_id = l.emp_id and l.Emp_ID='".$aid."' and Date_Apply &gt;='2013-12-01' and Date_Apply&lt;'2013-12-31'"); } echo "&lt;table border='1'&gt;"; echo "&lt;tr&gt;"; echo "&lt;th&gt;Leave No&lt;/th&gt;"; echo "&lt;th&gt;Leave Start&lt;/th&gt;"; echo "&lt;th&gt;Leave End&lt;/th&gt;"; echo "&lt;th&gt;Date Apply&lt;/th&gt;"; echo "&lt;th&gt;Duration&lt;/th&gt;"; echo "&lt;th&gt;Leave Type&lt;/th&gt;"; echo "&lt;th&gt;Leave Reason&lt;/th&gt;"; echo "&lt;th&gt;Status&lt;/th&gt;"; $counter = 0; while($rows = mysql_fetch_assoc($check_user)) { echo"&lt;tr&gt;"; echo"&lt;td&gt;" . $rows['Leave_ID'] . "&lt;/td&gt;"; echo"&lt;td&gt;" . $rows['Leave_Start'] . "&lt;/td&gt;"; echo"&lt;td&gt;" . $rows['Leave_End'] . "&lt;/td&gt;"; echo"&lt;td&gt;" . $rows['Date_Apply'] . "&lt;/td&gt;"; echo"&lt;td&gt;" . $rows['Duration'] . "&lt;/td&gt;"; echo"&lt;td&gt;" . $rows['Leave_Type'] . "&lt;/td&gt;"; echo"&lt;td&gt;" . $rows['Leave_Reason'] . "&lt;/td&gt;"; echo"&lt;td&gt;" . $rows['Status'] . "&lt;/td&gt;"; $counter++; } echo "&lt;/table&gt;"; </code></pre> <p>?></p>
[]
[ { "body": "<p>To answer your question: everything</p>\n\n<p>Now you may ask, why?</p>\n\n<ul>\n<li>Very bad variable naming style</li>\n<li>unreadable code (so manh if-else if -else</li>\n<li>You Repeat yourself all over the code</li>\n<li>No seperation of concern (business logic and presentation is tightly coupled)</li>\n</ul>\n\n<p>Let's start with the 'design' of your code.</p>\n\n<p>What you actually are trying to create is a Form where a user can select a month. A little script that performs a query depending on the month selected and a presentation file that presents the result of the query.</p>\n\n<p>3 things, so split them up into 3 files.</p>\n\n<p>after that, the form will have to comunicate with the script. This should be the GET method since you are getting data (with a filter, the month). The form should perform a GET request to the controller that then fires the little script passing in the selected month (using the php $_GET var) and then pass on the result of that little script to the presentation file (a 'template').</p>\n\n<p>So, now we have sorted out how our application should work. You can go back to work.</p>\n\n<p>However what I think is the real problem: you don't understand how client and server communicate with each other.</p>\n\n<p>PHP = server-side. this way it doesn't know what the user is doing at the Client side.\nYou therefore have to pass in all the required data (e.g. what month was selected) to the server. Then the server (PHP script in your case) can create the required output that is then shown to the client.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T16:05:56.093", "Id": "30698", "ParentId": "30696", "Score": "2" } } ]
{ "AcceptedAnswerId": "30698", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T15:17:23.380", "Id": "30696", "Score": "-1", "Tags": [ "php" ], "Title": "Is there anything wrong with my code?" }
30696
<p>Recently, I've noticed that my code looks so ugly because there were a bunch of functions and global variables. So, I started reading a little bit about design patterns. Now I come with something that's working for me, but I am not sure if it's good practice.</p> <p>Anyway, I would like you to take a look at the code and tell me what can I improve. I'd also like to know a better way to start using modular pattern in JavaScript. Finally, I'd like suggestions on material for learning about modular pattern and JavaScript.</p> <pre><code>var responsiveModule = { settings: { device: false, button: $(".responsive-btn"), target: $("nav ul"), mobileClass: "toggle-menu", bgImage: '&lt;img class="background-image" src="img/background.jpg" alt=""&gt;', bgImageSelector: $(".background-image"), windowWidth: $(window).width(), }, init: function(){ responsiveModule.checkDevice(); responsiveModule.replaceImages(); responsiveModule.bindFunctions(); responsiveModule.listenResize(); }, checkDevice: function(){ if(this.settings.windowWidth &gt; 992){ this.settings.device = "desktop"; } else { this.settings.device = "mobile"; } }, bindFunctions: function(){ var buton = this.settings.button, muelleBtn = this.settings.muelleBtn; buton.on("click touchstart", function(e){ e.preventDefault(); responsiveModule.animateMenu(responsiveModule.settings); }); }, animateMenu: function(settings){ var device = settings.device, target = settings.target, mobileAnimation = settings. mobileClass; if(device == "mobile"){ target.toggleClass(mobileAnimation); } }, replaceImages: function(){ var bgContainer = $("#main-content"), bgImage = responsiveModule.settings.bgImage, device = responsiveModule.settings.device, backgroundSelector = $(".background-image"); if(device == "desktop" &amp;&amp; backgroundSelector.length == 0){ bgContainer.append(bgImage); }else if(device == "mobile" &amp;&amp; backgroundSelector.length == 1){ backgroundSelector.remove(); } }, listenResize: function(){ $(window).on("resize", function(){ responsiveModule.checkDevice(); responsiveModule.replaceImages(); responsiveModule.settings.windowWidth = $(window).width(); }); } } var tooltipModule = { settings: { tooltipState: false }, init: function(){ tooltipModule.bindUIfunctions(); }, bindUIfunctions: function(){ var device = responsiveModule.settings.device; if(device == "mobile"){ $(".ship").on("click", function(e){ e.preventDefault(); tooltipModule.manageTooltip(e); }); }else{ $(".muelle-item").addClass("desktop"); } }, manageTooltip: function(e){ var tooltip = $(e.currentTarget).next(), tooltips = $(".tooltip"); tooltips.removeClass("display"); tooltip.addClass("display"); } } $(document).on("ready", function(){ responsiveModule.init(); tooltipModule.init(); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T15:31:44.580", "Id": "48835", "Score": "6", "body": "Contrary to some of the answers below, note that a lot of people define prototypes as a *form of OOP* http://stackoverflow.com/questions/186244/what-does-it-mean-that-javascript-is-a-prototype-based-language" } ]
[ { "body": "<p>The best pattern to start \"OOP\" in JavaScript is the Revealing Pattern:</p>\n\n<pre><code>var revealed = function(){\n var a = [1,2,3];\n var abc = function(){\n return (a[0]*a[1])+a[2];\n }\n\n return {\n name: 'revealed',\n abcfn: abc\n }\n}();\n</code></pre>\n\n<p>From <a href=\"https://stackoverflow.com/questions/5647258/how-to-use-revealing-module-pattern-in-javascript\">here</a>. </p>\n\n<p>Then read <a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/\" rel=\"nofollow noreferrer\">this book</a>.</p>\n\n<p>And learn RequireJS, which will increase the modularity of your code and will load your JS files on demand.</p>\n\n<p>I see you are using JS for create HTML elements. To help you with this, take a look at UnderscoreJS templates and Mustache.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T00:44:53.753", "Id": "48800", "Score": "2", "body": "That “revealing pattern” is not related to OOP." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T02:06:28.623", "Id": "48809", "Score": "0", "body": "why not, don't is encapsulation the key concept of OOP?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T04:45:08.503", "Id": "48811", "Score": "0", "body": "@icktoofay could you explain more why is thtath revealing pattern not related to OOP?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T05:30:32.317", "Id": "48816", "Score": "1", "body": "@Claudio: Object-oriented programming centers around objects, usually with functionality attached. I'll admit that that “revealing pattern” *does* create an object, but it's only one, ever, and that one object only functions as a set of namespaced variables, and I don't think that utilizing an object for that purpose counts as object-oriented programming." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T10:53:32.623", "Id": "48826", "Score": "0", "body": "@icktoofay as you see, I use quotes to refer to the js's OOP, because we have limitations in javascript, but in my opinion this is the best pattern to simulate an \"OOP\" in js." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T04:16:05.323", "Id": "48881", "Score": "0", "body": "@Claudio: I very much disagree; if you had a function to create objects, perhaps with functionality attached, and you could reasonably have multiple of them, then I think you'd have something that could be called object-oriented programming. Faking namespaces using anonymous functions is a neat trick, but it's not object-oriented programming." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T12:13:08.273", "Id": "48907", "Score": "0", "body": "@icktoofay Please don't stuck on names and features that other language implement, the main benefit of an OOP Language is to ensure that the outside don't change that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T12:17:44.523", "Id": "48908", "Score": "1", "body": "@icktoofay [here](https://github.com/cld-santos/simplologia/blob/master/javascript-lessons/src/test/javascript/Basic-Objects.js) you can see an example of inheritance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T15:39:38.377", "Id": "48944", "Score": "1", "body": "Requirejs doesn't increase modularity, per se... you don't even _have_ to learn to use it, just learn to require scripts on-the-fly... it's not that hard" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T17:00:00.320", "Id": "48953", "Score": "0", "body": "@EliasVanOotegem Yes, I agreed with you, from the begin if you break your code in different files will be a good start." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T20:32:15.363", "Id": "48978", "Score": "0", "body": "This isn't really an answer to the question; it doesn't suggest any improvements to the sample of code. This is CodeReview, not StackOverflow or Programmers. (This failing also extends to Aegis and Pinoniq's answers, for that matter)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-05T03:45:38.887", "Id": "48999", "Score": "0", "body": "@Claudio: I'm as much as possible trying not to drag in any other languages, and I'm not contesting that JavaScript *can* be object-oriented (although that's a debate on its own); what I am contesting is that the revealing pattern you've shown is in itself object-oriented programming. Yes, that revealing pattern facilitates encapsulation of state, but you've only got one set of state within a namespace. Just because it encapsulates some state doesn't mean it's object-oriented." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T00:40:47.373", "Id": "30709", "ParentId": "30701", "Score": "1" } }, { "body": "<p>Don't, just don't.</p>\n\n<p>JavaScript is not an OO language, it is a prototype language, something a lot of people tend to forget.</p>\n\n<p><a href=\"https://www.destroyallsoftware.com/talks/wat\" rel=\"nofollow\">There are no 'classes' or 'interfaces' in javascript. Everything is an object. Even a function is an object</a>.</p>\n\n<p>So how do JavaScript Objects work? what is 'this'? and what does 'new' do?\nA good place to start is <a href=\"http://ryanmorr.com/understanding-scope-and-context-in-javascript/\" rel=\"nofollow\">understanding Scope and context</a>.</p>\n\n<p>So, what are JavaScript objects? Again there is a <a href=\"http://davidwalsh.name/javascript-objects\" rel=\"nofollow\">good article</a>. </p>\n\n<p>Once you understand that and you still feel like writing OO Js. There are tons of frameworks out there that pretend to be OO, my personal favorite MooTools. These frameworks give you an interface to write OO-like code. But then again, in big applications that code tends to get slow, leak memory, since we forget how prototypes really work and what the 'new' operator means.</p>\n\n<hr>\n\n<p>Let's recap and go back to your question. Your real problem is that your code is becoming hard to read.</p>\n\n<p>So you are looking for a certain pattern in JavaScript to help in maintaining your code. My favorite pattern is the Module Pattern, but there are <a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/\" rel=\"nofollow\">many more very strong patterns for JavaScript</a>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T13:58:35.007", "Id": "48833", "Score": "0", "body": "wow thank you for the awesome answer, I am going to read all the resources you post it in order to understand better the language!!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T15:37:16.300", "Id": "48837", "Score": "0", "body": "@JhonnatanGonzalezRodriguez Pinoniq is quite wrong. \"Object Oriented\" is a much debated term without one absolute definition, but it is broadly accepted that classes are one way to implement OO - and that prototypes are another." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T15:40:26.810", "Id": "48838", "Score": "6", "body": "-1 for saying that JavaScript isn't Object-Oriented and then stressing how *everything* in JavaScript is an **object**. Can you spot the contradiction? If I could -1 you again for recommending Adnan's book, I would; It's a waffly rehash of things Adnan has read else where and doesn't understand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T15:44:28.083", "Id": "48841", "Score": "0", "body": "@itbruce plus to your comment could you please recomend some resources different to Adna's to see your point? i will appreciate it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T15:45:14.610", "Id": "48842", "Score": "1", "body": "Object-oriented and everything is an object is not contradictory... Object-oriented design pattersn need abstract classes, interfaces,... these don't exist in javascript. Simply because everything is an object.\nIn javascript there is no inheritance chain, but prototypes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T15:52:23.643", "Id": "48844", "Score": "0", "body": "Read the answer here: http://stackoverflow.com/questions/107464/is-javascript-object-oriented His last sentence acutally sums up my answer. You can implement every OOD pattern, but everytime with special methods. (Just look at all the frameworks out there, the OO patterns don't simply work out of the box)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T16:03:17.337", "Id": "48845", "Score": "0", "body": "I really don't think you've understood the debate on that page." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T16:12:21.040", "Id": "48846", "Score": "1", "body": "@JhonnatanGonzalezRodriguez My usual recommendation for people new to JavaScript is to start with Douglas Crockford's website and his book, JavaScript: The Good Parts. http://javascript.crockford.com/ Looking at your code, I think you need to get a better feel for the basics of the language before reaching for larger patterns. Patterns are overused, mostly by people who don't understand their language of choice well enough to know where they are truly appropriate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T12:45:30.497", "Id": "58315", "Score": "3", "body": "@Pinoniq javascript not only has object oriented capability, it has strong object oriented capability. Yes, it is a prototype based programming and that is in turn a style of object oriented programming." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T09:32:35.550", "Id": "30728", "ParentId": "30701", "Score": "-7" } }, { "body": "<p>Bad idea. JavaScript is prototype-based, not object-oriented. Embrace it!</p>\n\n<ul>\n<li><p>I would <strong>strongly</strong> advice you <a href=\"http://rads.stackoverflow.com/amzn/click/0321812182\" rel=\"nofollow\">this book</a> as well as <a href=\"http://calculist.org/\" rel=\"nofollow\">his blog</a>.</p></li>\n<li><p>Mess around with a REPL (nodejs / chrome dev tools), try to understand the unexpected or surprising behaviours.</p></li>\n<li><p>I found it useful sometimes to take a look at how your code is actually parsed, you can do this very easily online with the <a href=\"http://esprima.org/demo/parse.html\" rel=\"nofollow\">Esprima project</a>.</p></li>\n<li><p>Make sure you completely understand how the prototype chain, functions and type coercion work, they are, imo, the core concepts in javascript.</p></li>\n<li><p>Get familiar with things such as IIFE (immediately invoked function expressions), scoping rules, etc.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T15:35:39.277", "Id": "48836", "Score": "5", "body": "-1 for stating that OO requires classes. Many OO languages use classes, but it is not essential. http://en.wikipedia.org/wiki/Prototype-based_programming http://en.wikipedia.org/wiki/Object_oriented http://www.crockford.com/javascript/javascript.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T15:47:52.140", "Id": "48843", "Score": "0", "body": "The wikipedia page you link to isn't that correct imho. 'cloning existing objects to serve as prototypes' weut? ugh" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T04:18:37.130", "Id": "48882", "Score": "2", "body": "@Pinoniq: That's how prototypes work. What's the problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-17T16:17:12.163", "Id": "72113", "Score": "0", "body": "@icktoofay: It's not really accurate for JS. Prototypes in JS have very little to do with cloning; inheritance works mostly by setting the child's internal [[Prototype]] property to refer to the parent. It's a pretty big difference, in that adding or changing the parent's behavior also changes the child (which wouldn't happen, or would happen in very odd and broken'ish ways, if the parent were cloned)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T15:19:08.907", "Id": "30739", "ParentId": "30701", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T20:35:35.820", "Id": "30701", "Score": "7", "Tags": [ "javascript", "jquery", "object-oriented" ], "Title": "Responsive module and tooltip module" }
30701
<p>I'm fairly new at JavaScript, and I'm finding that JS is a language with what seems like an unusually high number of gotchas for the inexperienced, so some criticisms of this code would be particularly appreciated.</p> <p>The function <code>getProperties</code> below is a relatively simple function that returns an array of the <em>names</em> (not the values) of all the properties that an object has (either "owned" or "inherited"). Here's the code, followed by some description of what it does:</p> <pre><code>function getProperties(o) { var seenobj = new Set(); var seenprop = new Set(); function _proto(obj) { return obj instanceof Object ? Object.getPrototypeOf(obj) : obj.constructor.prototype; } function _properties(obj) { var ret = []; if (obj === null || seenobj.has(obj)) { return ret; } seenobj.add(obj); if (obj instanceof Object) { var ps = Object.getOwnPropertyNames(obj); for (var i = 0; i &lt; ps.length; ++i) { if (!seenprop.has(ps[i])) { ret.push(ps[i]); seenprop.add(ps[i]); } } } return ret.concat(_properties(_proto(obj))); } return _properties(o); } </code></pre> <p>This function has four local variables: <code>_proto</code>, <code>_properties</code>, <code>seenobj</code>, <code>seenprop</code>. The first one, <code>_proto</code> is a helper function to streamline computing an object's prototype. The second one, <code>_properties</code>, is a recursive function, and it actually does all the work. The third one, <code>seenobj</code>, is a (ECMAScript 6) <code>Set</code> object used to keep track of the objects already encountered in the recursion (and therefore avoid infinite recursion). The fourth one, <code>seenprop</code>, also a <code>Set</code> object, similarly keeps track of the names of properties already seen, and thus ensures that property names are not repeated in the returned value. (NOTE: <code>Set</code> objects are available only in a few browsers. An obvious improvement would be to replace these objects with a more portable alternative.)</p> <p>If the argument <code>obj</code> of <code>_properties</code> is <code>null</code>, or if it is already present in <code>seenobj</code>, <code>_properties</code> returns an empty array. (These are the conditions that terminates the recursion.)</p> <p>Otherwise, if <code>obj</code> is an instance of <code>Object</code>, <code>_properties</code> gets the list of its properties with <code>Object.getOwnPropertyNames</code>. <code>_properties</code> then returns as its result the array consisting of those properties of <code>obj</code> (if any) that are not already in the <code>seen</code> variable concatenated with the array returned by a recursive call with <code>Object.getPrototypeOf(obj)</code> as argument.</p> <p>Here's <code>getProperties</code> applied to some standard items (the interaction shown is from the Firefox/Firebug console, though I've added line breaks in the output to avoid long lines):</p> <pre><code>&gt;&gt;&gt; getProperties({}) [] &gt;&gt;&gt; getProperties(0) ["constructor", "toSource", "toString", "toLocalString", "toFixed", "toExponential", "toPrecision"] &gt;&gt;&gt; getProperties("") ["length", "constructor", "quote", "toSource", "toString", "valueOf", "substring", "toLowerCase", "toUpperCase", "charAt", "charCodeAt", "contains", "indexOf", "lastIndexOf", "startsWith", "endsWith", "trim", "trimLeft", "trimRight", "toLocaleLowerCase", "toLocaleUpperCase", "localeCompare", "match", "search", "replace", "split", "substr", "concat", "slice", "bold", "italics", "fixed", "fontsize", "fontcolor", "link", "anchor", "strike", "small", "big", "blink", "sup", "sub", "iterator"] &gt;&gt;&gt; getProperties([]) ["length", "constructor", "toSource", "toString", "toLocaleString", "join", "reverse", "sort", "push", "pop", "shift", "unshift", "splice", "concat", "slice", "indexOf", "lastIndexOf", "forEach", "map", "reduce", "reduceRight", "filter", "some", "every", "iterator"] &gt;&gt;&gt; getProperties(function () {}) ["prototype", "length", "name", "arguments", "caller", "constructor", "toSource", "toString", "apply", "call", "bind", "isGenerator"] </code></pre> <p>Thanks for reading this. I look forward to your comments.</p> <hr> <p>EDIT: The code shown above incorporates fixes to various problems that I noticed after posting the original version. This original version is shown below, FWIW.</p> <pre><code>function getProperties(o) { var seen = {}; function _properties(obj) { var ret = []; if (obj === null) { return ret; } try { var ps = Object.getOwnPropertyNames(obj); } catch (e if e instanceof TypeError &amp;&amp; e.message === "obj is not an object") { return _properties(obj.constructor.prototype); } for (var i = 0; i &lt; ps.length; ++i) { if (typeof seen[ps[i]] === "undefined") { ret.push(ps[i]); seen[ps[i]] = true; } } return ret.concat(_properties(Object.getPrototypeOf(obj))); } return _properties(o); } </code></pre>
[]
[ { "body": "<p>As you said, I have a little issue with the use of a try/catch statement. I tried to write it again using, imo, neater constructs:</p>\n\n<pre><code>function getProperties(o) {\n var results = []; \n function properties(obj) {\n var props, i;\n if (obj == null) {\n return results;\n } \n if (typeof obj !== 'object' &amp;&amp; typeof obj !== 'function') {\n return properties(obj.constructor.prototype);\n } \n props = Object.getOwnPropertyNames(obj);\n i = props.length;\n while (i--) {\n if (!~results.indexOf(props[i])) {\n results.push(props[i]);\n } \n } \n return properties(Object.getPrototypeOf(obj));\n } \n return properties(o);\n}\n</code></pre>\n\n<p>There is one big difference between my code and your code though: you remove all the properties of <code>object</code> on the line <code>typeof seen[ps[i]] === \"undefined\"</code>. I don't know if it was intended behaviour or not; just pointing out!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T14:57:08.463", "Id": "30737", "ParentId": "30702", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T21:36:33.710", "Id": "30702", "Score": "1", "Tags": [ "javascript" ], "Title": "Function to get all properties of an object" }
30702
<p>The following is a code to detect a loop in a linked list. This question is prepared strictly for interview purposes. This code has been modeled as per Linkedlist.java</p> <ol> <li><p>How should I decide if a function like <code>hasLoop()</code> should be included as an instance method or should be a static method similar to <code>sort</code> in Collections.java?</p></li> <li><p>Ideally I would inherit <code>Linkedlist</code> and add an extra function <code>mergeSort</code> to the subclass, but the interviewer would not like it, thus I should keep my solution without inheriting linkedlist for interview sake. Do you agree?</p></li> </ol> <p></p> <pre><code> public class DetectLoopExistance&lt;E&gt; { private Node&lt;E&gt; first; private Node&lt;E&gt; last; public void add(E element) { final Node&lt;E&gt; l = last; final Node&lt;E&gt; newNode = new Node&lt;E&gt;(element, null); last = newNode; if (first == null) { first = newNode; } else { l.next = newNode; } } private static class Node&lt;E&gt; { E element; Node&lt;E&gt; next; Node(E element, Node&lt;E&gt; next) { this.element = element; this.next = next; } } public boolean hasLoop() { Node&lt;E&gt; fast = first; Node&lt;E&gt; slow = first; while (fast != null &amp;&amp; fast.next != null) { fast = fast.next.next; slow = slow.next; if (slow == fast) { return true; } } return false; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T18:57:46.923", "Id": "48863", "Score": "1", "body": "I know this is for an interview, but if I were hiring, I would want you to tell me that you would design the linked list api such that you would never end up with a loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T01:38:47.683", "Id": "64816", "Score": "0", "body": "@toto2 And how would you show that your library created good loops? With a test - one that should become a unit test, bundled with the library source. If you tried to tell me that the test was not necessary, I would know never to hire you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T15:45:26.197", "Id": "65250", "Score": "0", "body": "@itsbruce Agreed that it makes sense as a unit test. It should probably not be a public class method however. And I still stand by my main point that the public api of that linked list class should never allow a loop to be created." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-22T13:18:29.313", "Id": "103203", "Score": "0", "body": "possible duplicate of [Linked list loop detection in Java(interview question)](http://codereview.stackexchange.com/questions/2711/linked-list-loop-detection-in-javainterview-question)" } ]
[ { "body": "<p>To answer your first question, I would create the method as a static method, because similar to sorting, detecting loops is basic functionality, that is applicable to <code>List</code>s in general, not only a specific <code>List</code> object.</p>\n\n<p>I would not recommend inheriting from the original List implementation in order to create the merge sort functionality. If you do so you will end up with <code>List</code> objects that can be sorted using merge sort and <code>List</code> objects, that cannot. But there is not really a difference between the two in structure, the only difference is that one is you inherited version and one is the <code>LinkedList</code> implementation. This complicates things unnecessarily. Again I would create a static method to merge sort any <code>List</code>, which would add the ability to merge sort any <code>LinkedList</code>, any <code>ArrayList</code> and any other custom <code>List</code> implementation, that implements the Java <code>List</code> interface.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T02:53:36.183", "Id": "48878", "Score": "0", "body": "where would u add the static function ? Would it be in the 'DetectLoopExistance' class or in another UtilityClass ? If its added in DetectLoopExistance the it would it take List as parameter ? If it does then if i want to sort an instance, I would need to do somthing like DetectLoopExistance.mersort(instance) rather than instance.mergeSort(). If I create a utility function then it how would it do ptr.next, when next belongs to 'private nested class' ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T08:32:13.370", "Id": "49114", "Score": "0", "body": "i would go for another utility class. `DetectLoopExistance.mergeSort(someList)` wouldn't really make sense although `SortHelper.mergeSort(someList)` would.\nFor the `ptr.next` thing I guess I would try and find the implementation of the default sort functions and see how it is done there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T05:33:41.630", "Id": "49251", "Score": "0", "body": "Thanks but how would For the ptr.next be used ? I mean for all linkedlist interview questions we need to use ptr.next ? What would we do it then ?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T08:40:10.110", "Id": "30723", "ParentId": "30707", "Score": "2" } }, { "body": "<p>Your loop detection will almost always take longer than the classic hare and tortoise implementation; in the case where the entire list is one loop, it will take nearly twice as long. Consider that latter case:</p>\n\n<p>You will not detect the loop until the <strong>slow</strong> node has caught up with the <strong>fast</strong> node, while the classic implementation detects when <strong>fast</strong> catches and passes <strong>slow</strong>. Your implementation will only return when <strong>slow</strong> has run once through the list and returned to the first node (and <strong>fast</strong> has therefore looped twice through the list). The classic method will return once <strong>slow</strong> has reached <strong>list.size() - 2</strong> where <strong>list.size()</strong> is even or <strong>list.size() - 1</strong> where it is odd (this is the point at which it will be lapped). In a list of 1 or 2 nodes, <strong>slow</strong> never moves at all.</p>\n\n<p>Adapting your version minimally to make it into the classic implementation gives this:</p>\n\n<pre><code>public boolean hasLoop() {\n Node&lt;E&gt; fast = first;\n Node&lt;E&gt; slow = first;\n\n while (fast != null &amp;&amp; fast.next != null) {\n if (slow == fast.next || slow == fast.next.next) {\n return true;\n } else {\n fast = fast.next.next;\n slow = slow.next;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>This can be optimised to remove the duplicated iterations of <strong>fast.next</strong> but I left it like this for greater clarity.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T13:31:26.947", "Id": "30734", "ParentId": "30707", "Score": "2" } } ]
{ "AcceptedAnswerId": "30723", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T23:07:47.187", "Id": "30707", "Score": "0", "Tags": [ "java", "linked-list", "interview-questions" ], "Title": "Detect if linked list contains a loop" }
30707
<p><a href="https://stackoverflow.com/questions/18564239/c-sharp-implementing-ilistt-ilist-inotifycollectionchanged">I posted this question over at Stackoverflow, which was off-topic</a>.</p> <p>I was using <code>ObservableCollection</code> in a number of places in my WPF application for very large arrays. This caused a problem as <code>ObservableCollection</code> did not take an argument for capacity like List did. This was an important optimization for locking down my memory usage and ensuring that these collections did not double to a much larger size than required.</p> <p>So I implemented the following class:</p> <pre><code>public class ObservableList&lt;T&gt; : IList&lt;T&gt;, IList, INotifyCollectionChanged { public event NotifyCollectionChangedEventHandler CollectionChanged; #region Properties private List&lt;T&gt; _List { get; set; } public T this[int index] { get { return _List[index]; } set { if (index &lt; 0 || index &gt;= Count) throw new IndexOutOfRangeException("The specified index is out of range."); var oldItem = _List[index]; _List[index] = value; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, value, oldItem, index)); } } public int Count { get { return _List.Count; } } public bool IsReadOnly { get { return ((IList&lt;T&gt;)_List).IsReadOnly; } } bool IList.IsFixedSize { get { return ((IList)_List).IsFixedSize; } } object IList.this[int index] { get { return ((IList)_List)[index]; } set { if (index &lt; 0 || index &gt;= Count) throw new IndexOutOfRangeException("The specified index is out of range."); var oldItem = ((IList)_List)[index]; ((IList)_List)[index] = value; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, value, oldItem, index)); } } public bool IsSynchronized { get { return ((IList)_List).IsSynchronized; } } public object SyncRoot { get { return ((IList)_List).SyncRoot; } } #endregion #region Methods private void OnCollectionChanged(NotifyCollectionChangedEventArgs args) { if (CollectionChanged != null) CollectionChanged(this, args); } public void AddRange(IEnumerable&lt;T&gt; collection) { _List.AddRange(collection); var iList = collection as IList; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } public int IndexOf(T item) { return _List.IndexOf(item); } public void Insert(int index, T item) { _List.Insert(index, item); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); } public void RemoveAt(int index) { if (index &lt; 0 || index &gt;= Count) throw new IndexOutOfRangeException("The specified index is out of range."); var oldItem = _List[index]; _List.RemoveAt(index); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, oldItem, index)); } public void Add(T item) { _List.Add(item); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item)); } public void Clear() { _List.Clear(); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } public bool Contains(T item) { return _List.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { _List.CopyTo(array, arrayIndex); } public bool Remove(T item) { var result = _List.Remove(item); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item)); return result; } public IEnumerator&lt;T&gt; GetEnumerator() { return _List.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } int IList.Add(object value) { var result = ((IList)_List).Add(value); ; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, value)); return result; } bool IList.Contains(object value) { return ((IList)_List).Contains(value); } int IList.IndexOf(object value) { return ((IList)_List).IndexOf(value); } void IList.Insert(int index, object value) { ((IList)_List).Insert(index, value); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, value, index)); } void IList.Remove(object value) { ((IList)_List).Remove(value); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, value)); } public void CopyTo(Array array, int index) { ((IList)_List).CopyTo(array, index); } #endregion #region Initialization public ObservableList() { _List = new List&lt;T&gt;(); } public ObservableList(int capacity) { _List = new List&lt;T&gt;(capacity); } public ObservableList(IEnumerable&lt;T&gt; collection) { _List = new List&lt;T&gt;(collection); } #endregion } </code></pre> <p>It seems to be working fine, but I have noticed an increase in processing time since switching to this implementation. Have I implemented the interfaces correctly?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T02:50:21.610", "Id": "48810", "Score": "2", "body": "Can you compare the two pieces of code. Perhaps it's just a red herring the increase in processing occurring around the same time as your code change?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T14:32:37.490", "Id": "48931", "Score": "1", "body": "Further to @dreza's comment, to help make sure that inefficiency is related to this change, you'll want to do some benchmarking and profiling. Eric Lippert has an excellent series on this start here (http://tech.pro/blog/1293/c-performance-benchmark-mistakes-part-one). As far as anything obvious with the code itself that may be causing a slow down... the casting (`((IList)_List)`) throughout looks like a possible suspect to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-09T08:53:22.887", "Id": "297919", "Score": "0", "body": "FWIW ObservableCollection has a ctor which takes a List<T> (https://msdn.microsoft.com/en-us/library/ms653202(v=vs.110).aspx), albeit it copies the elements. You could perform the list generation up front, then create the OC from that list. You can also use reflection/LINQ Expressions to modify the Capacity of Collection<T>'s internal IList (which is a List by default https://referencesource.microsoft.com/#mscorlib/system/collections/objectmodel/collection.cs,28). Less code to maintain and test." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-09T08:57:10.920", "Id": "297920", "Score": "0", "body": "Also, both your implementation and .NET's ObservableCollection will always allocate the ThingChangedEvent objects for all events, even when there are no subscribers. If you were populating the OC directly, with elements one at a time, it may be hurting your performance as well (GC news/collects are not cheap)." } ]
[ { "body": "<ol>\n<li>The implementation of <code>IList</code> is inconsistent: You have implemented <code>IsFixedSize</code> explicitly while <code>IsSynchronized</code> and <code>SyncRoot</code> are not, yet they are all three part of the <code>IList</code> interface. You should probably implement <code>IList</code> entirely explicitly.</li>\n<li>You occasionally do some unnecessary casting, like here <code>((IList)_List)[index]</code>. Only cast if necessary (e.g. when casting the underlying <code>List&lt;T&gt;</code> into <code>IList</code> because you need access to some explicitly implemented interface methods/properties).</li>\n<li><p>There is a potential race condition in your event raising method:</p>\n\n<pre><code>private void OnCollectionChanged(NotifyCollectionChangedEventArgs args)\n{\n if (CollectionChanged != null)\n CollectionChanged(this, args);\n}\n</code></pre>\n\n<p>If the subscriber unsubscribes after your <code>if</code> but before the actual call you will get a <code>NullReferenceException</code>. The idiomatic C# way of implementing this is:</p>\n\n<pre><code>private void OnCollectionChanged(NotifyCollectionChangedEventArgs args)\n{\n var handler = CollectionChanged;\n if (handler != null)\n handler(this, args);\n}\n</code></pre>\n\n<p>Note that this can still pose a problem on the subscriber side because it might get called just after it has unsubscribed but it should be dealt with there.</p></li>\n<li>Calling event handlers happens synchronously. So if something has subscribed to the <code>CollectionChanged</code> event then the registered event handlers will be called synchronously on every operation raising the event. It is not totally surprising that this slows down the operation a bit. In the unobserved case however it should not make a huge difference.</li>\n<li>To truly track down where the problem is you'll have to use a profiler.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T18:50:31.230", "Id": "52506", "Score": "1", "body": "Partial explicit implementation can make sense, especially for members that are more or less obsolete, like `SyncRoot` (I realize that in the original code, this one is not explicit). And it's actually necessary in the case of `this[]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-17T19:34:03.730", "Id": "52509", "Score": "0", "body": "@svick: Hm, my point was that he should probably implement the entire `IList` explicitly. Bringing more or less obsolete members back to life is not really a good thing, is it?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-16T23:47:55.880", "Id": "32787", "ParentId": "30708", "Score": "8" } } ]
{ "AcceptedAnswerId": "32787", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T00:19:36.680", "Id": "30708", "Score": "9", "Tags": [ "c#", ".net" ], "Title": "Implementing IList<T>, IList & INotifyCollectionChanged" }
30708