body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Consider this class:</p> <pre><code>using Ninject; using Ninject.Syntax; using Ninject.Parameters; namespace MyApp.Dependencies.Factories { public abstract class FactoryBase&lt;T&gt; where T : class { private IResolutionRoot _resolutionRoot; protected FactoryBase(IResolutionRoot resolutionRoot) { _resolutionRoot = resolutionRoot; } protected T Create(params IParameter[] parameters) { return _resolutionRoot.Get&lt;T&gt;(parameters); } } } </code></pre> <p>What this class really abstracts away, is the <code>_resolutionRoot.Get&lt;T&gt;</code> part, allowing for concrete factory classes to look something like this:</p> <pre><code>//using Ninject; // not needed using Ninject.Syntax; using Ninject.Parameters; public interface IUnicornFactory { Unicorn Create(string name, int hornLength, Color color); } public class UnicornFactory : FactoryBase&lt;Unicorn&gt;, IUnicornFactory { public UnicornFactory(IResolutionRoot resolutionRoot) : base(resolutionRoot) { } public Unicorn Create(string name, int hornLength, Color color) { return Create(new ConstructorArgument("name", name), new ConstructorArgument("hornLength", hornLength), new ConstructorArgument("color", color)); } } </code></pre> <p>Is this overkill, or something that I'll thank myself for later, when I have dozens of factory classes? I find the base factory merely allows for synctactic sugar in the concrete factory implementations - are there any side-effects to this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T15:17:46.963", "Id": "38724", "Score": "0", "body": "Couldn't create a 'ninject' tag. Or does this question belong in StackOverflow?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T16:38:43.263", "Id": "38731", "Score": "0", "body": "I think it's covered by `dependency-injection`, but this is the right place to ask it. No experience with Ninject, so I can't answer, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T17:33:48.753", "Id": "38733", "Score": "0", "body": "@Bobson: Ninject stuff tossed aside, the only thing I don't like is that the protected constructor is hiding the need for an `IResolutionRoot` in the concrete factory implementation - I believe ReSharper (R#) would help here but as far as \"good design practices\" are concerned is it ok for an abstract class to require a constructor argument that the concrete implementation can't quite know about until compilation fails with a \"[base class] does not contain a constructor that takes 0 arguments\" error? VS doesn't give a \"Implement abstract class\" shortcut for the constructor..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T17:43:50.390", "Id": "38734", "Score": "0", "body": "You can't require any specific form of the constructor be implemented, but by specifying *any* constructor on the abstract class, you require all children to call one of them, with all the appropriate arguments. The children can either hardcode those or take them in their own parameters and pass them on, but they have to supply them." } ]
[ { "body": "<p>Line-by-line I had exactly the same factory code. It smells, isn't it?</p>\n\n<p>The correct solution would be to use <a href=\"http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/\" rel=\"nofollow\">Ninject Factory extension</a>. I am happy since.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T01:03:32.790", "Id": "49187", "Score": "0", "body": "Sorry I took so long - the factory extension works nice, but for some weird reason I'm having issues with it when I use it with COM interop (see http://stackoverflow.com/questions/18395022/error-activating-iinterceptor-only-through-com), so for that specific project I'm discarding this idea, but in other .net projects it's indeed the perfect solution." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-31T02:05:09.153", "Id": "29203", "ParentId": "25038", "Score": "3" } } ]
{ "AcceptedAnswerId": "29203", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T15:17:06.020", "Id": "25038", "Score": "4", "Tags": [ "c#", "dependency-injection", "factory-method" ], "Title": "Are there side-effects to having a generic Ninject factory?" }
25038
<p>The <code>struct</code> and the prototypes of the functions were given in the question. I am unfortunately aware that this is more C code and less C++ code. </p> <p>I am looking to compact my functions (specifically <code>ordered_insert</code> and <code>find_remove</code>) without removing functionality. For example, at the moment my <code>find_remove</code> function works if there exists two matching nodes at the start, two matching nodes in the middle or two matching nodes at the end.</p> <p>For example, could I make more use of <code>head_insert</code> and <code>tail_insert</code> in my ordered insert function?</p> <pre><code>#include &lt;iostream&gt; using namespace std; struct node_ll { int payload; node_ll* next;//Pointer to the next node }; void print_ll (node_ll** list) { node_ll* temp = *list;//Let temp be the address of the node that is the head of the list. while(temp)// != NULL { cout &lt;&lt; temp-&gt;payload &lt;&lt; endl;//Print out payload of the struct whose address is temp. temp = temp-&gt;next;//Set the address of temp equal to the address stored in next of the struct whose address is temp. } } void head_insert(node_ll** list, int pload) { node_ll* temp = new node_ll;//Create a new node, and let temp be the address of that node. temp-&gt;payload = pload;//Set the payload of the struct whose address is temp to pload. temp-&gt;next = *list;//Set the next of the struct whose address is temp to the address of the old head of the list. *list = temp;//The address of the old head of the list is changed to the address of the struct temp. }; void tail_insert(node_ll** list, int pload) { if (*list == NULL) { head_insert(list, pload); } else { node_ll* temp = new node_ll; for (temp = *list; temp-&gt;next; temp = temp-&gt;next); temp-&gt;next = new node_ll; temp-&gt;next-&gt;payload = pload; temp-&gt;next-&gt;next = NULL; } } int head_return (node_ll** list) { if (*list != NULL) { int temp = (*list)-&gt;payload; node_ll* trash = *list; *list = (*list)-&gt;next; delete trash; return temp; } else { return 0; } } int tail_return (node_ll** list) { if (*list != NULL) { if ((*list)-&gt;next == NULL) { return head_return(list); } else { node_ll* trash; for (trash = *list; trash-&gt;next-&gt;next; trash = trash-&gt;next); int temp = trash-&gt;next-&gt;payload; delete trash-&gt;next; trash-&gt;next = NULL; return temp; } } else { return 0; } } bool ordered_list(node_ll** list) { if (*list != NULL &amp;&amp; (*list)-&gt;next != NULL) { node_ll* temp; for (temp = *list; temp-&gt;next; temp = temp-&gt;next) { if (temp-&gt;payload &gt; temp-&gt;next-&gt;payload) { return false; } } } return true; } void ordered_insert(node_ll** list, int pload) { if (ordered_list(list)) { if (*list == NULL || (*list)-&gt;payload &gt; pload) { head_insert(list, pload); } else { bool inserted = false; node_ll* temp; for (temp = *list; temp-&gt;next; temp = temp-&gt;next) { if (temp-&gt;next-&gt;payload &gt; pload &amp;&amp; !inserted) { node_ll* next = temp-&gt;next; temp-&gt;next = new node_ll; temp-&gt;next-&gt;payload = pload; temp-&gt;next-&gt;next = next; inserted = true; } } if (!inserted) { tail_insert(list, pload); } } } } void find_remove (node_ll** list, int pload) { if (*list != NULL) { while (*list &amp;&amp; (*list)-&gt;payload == pload) { head_return(list); } if (*list != NULL) { node_ll* temp; for (temp = *list; temp-&gt;next; temp = temp-&gt;next) { while (temp-&gt;next-&gt;next != NULL &amp;&amp; temp-&gt;next-&gt;payload == pload) { node_ll* trash = temp-&gt;next; temp-&gt;next = temp-&gt;next-&gt;next; head_return(&amp;trash); } } if (temp-&gt;next == NULL &amp;&amp; temp-&gt;payload == pload) { tail_return(list); } } } } int main() { node_ll* alist = NULL; cout &lt;&lt; "Empty list a to start." &lt;&lt; endl; head_insert(&amp;alist, 2); head_insert(&amp;alist, 4); head_insert(&amp;alist, 6); cout &lt;&lt; "List a after head insertion of 2,4,6 is: " &lt;&lt; endl; print_ll(&amp;alist); cout &lt;&lt; endl; node_ll* blist = NULL; cout &lt;&lt; "Empty list b to start." &lt;&lt; endl; tail_insert(&amp;blist, 2); tail_insert(&amp;blist, 4); tail_insert(&amp;blist, 6); cout &lt;&lt; "List b after tail insertion of 2,4,6 is: " &lt;&lt; endl; print_ll(&amp;blist); cout &lt;&lt; endl; node_ll*clist = NULL; cout &lt;&lt; "Empty list c to start." &lt;&lt; endl; tail_insert(&amp;clist, 2); tail_insert(&amp;clist, 4); tail_insert(&amp;clist, 6); cout &lt;&lt; "List c after tail insertion of 2,4,6 is: " &lt;&lt; endl; print_ll(&amp;clist); if (ordered_list(&amp;clist)) { cout &lt;&lt; "List c is ordered." &lt;&lt; endl; } else { cout &lt;&lt; "List c is not ordered." &lt;&lt; endl; } ordered_insert(&amp;clist, 1); ordered_insert(&amp;clist, 3); ordered_insert(&amp;clist, 7); cout &lt;&lt; "List c after ordered insertion of 1,3,7 is: " &lt;&lt; endl; print_ll(&amp;clist); cout &lt;&lt; endl; node_ll* dlist = NULL; cout &lt;&lt; "Empty list d to start." &lt;&lt; endl; tail_insert(&amp;dlist, 2); tail_insert(&amp;dlist, 2); tail_insert(&amp;dlist, 3); tail_insert(&amp;dlist, 4); tail_insert(&amp;dlist, 4); tail_insert(&amp;dlist, 9); tail_insert(&amp;dlist, 6); tail_insert(&amp;dlist, 6); cout &lt;&lt; "List d after tail insertion of 2,2,3,4,4,5,6,6 is: " &lt;&lt; endl; print_ll(&amp;dlist); if (ordered_list(&amp;dlist)) { cout &lt;&lt; "List d is ordered." &lt;&lt; endl; } else { cout &lt;&lt; "List d is not ordered." &lt;&lt; endl; } find_remove(&amp;dlist, 2); find_remove(&amp;dlist, 4); find_remove(&amp;dlist, 6); cout &lt;&lt; "List c after find and remove of 2,4,6 is: " &lt;&lt; endl; print_ll(&amp;dlist); cout &lt;&lt; endl; system("PAUSE"); return 0; } </code></pre>
[]
[ { "body": "<p>The <code>tail_insert()</code> function could be improved a bit:</p>\n\n<pre><code>node_ll* tmp = new node_ll;\n...\nwhile(*list)\n list = &amp;(*list)-&gt;next;\n*list = tmp;\n</code></pre>\n\n<p>In any case, you should separate the code for setting up the new node and inserting it a bit, then you would notice that you allocate two(!) nodes there.</p>\n\n<p>Then, <code>tail_return()</code> and <code>head_return()</code>, are these really supposed to erase the front element? Also, both should check first thing that <code>*list</code> is not zero, I'd even prefer using <code>assert()</code> for that, but that depends on the intended semantics. </p>\n\n<p>In <code>ordered_list()</code>, I'd also put the check for an empty list at the beginning and not use an else clause afterwards. Then, the check if there is a next element is redundant, the loop does that correctly. I'd also declare and init the loop variable in the loop header, not separately to that. Lastly, your call (3,2,1) ordered, but I would rather say that (1,2,3) is ordered! Again, it depends on the intended semantics that must be documented.</p>\n\n<p>Then, <code>ordered_insert()</code>, what exactly is it doing when the list is not sorted? What is it supposed to do in that case even? I wouldn't bother doing anything, so just add <code>assert(ordered_list(list))</code> at the beginning and declare it a fault in the calling code if it tries to do an ordered insert on an unordered list. In the loop, you could just return after inserting an element, saving the <code>inserted</code> flag.</p>\n\n<p>In <code>find_remove()</code>, your nesting levels are too deep. Simply returning after finding out that the list is already empty would decrease this and at the same time split the function in two parts, allowing the reader to understand each of them separately. I for one don't understand what all those loops are doing there, but that might be caused by the lack of comments concerning what they are supposed to do.</p>\n\n<p>Lastly, you could rewrite some functions to use recursion. For example, a list is sorted if</p>\n\n<ol>\n<li>it is empty (<code>*list == 0</code>)</li>\n<li>it has only a single element (<code>(*list)-&gt;next == 0</code>)</li>\n<li>its first two elements are sorted (<code>(*list)-&gt;payload &lt; (*list)-&gt;next-&gt;payload)</code>) and the list starting with the second element is sorted (<code>ordered_list(&amp;(*list)-&gt;next)</code>).</li>\n</ol>\n\n<p>Doing that would make code a bit more readable in my eyes, although the iterative solution is fine, too. Note that the recursion only requires steps 2 and 3, the first one would be redundant.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T10:24:21.530", "Id": "38835", "Score": "0", "body": "with regard to your third point, the question states: int head_return(node_ll **list);//Returns the first integer from the head of the list, and deletes it from the list. int tail_return(node_ll **list);//Returns the last integer from the tail of the list, and deletes it from the list. With regard to your fourth point, the question states: bool ordered_list(node_ll **list);//Returns true if the list is in ascending order, and false otherwise." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T07:26:00.717", "Id": "25052", "ParentId": "25043", "Score": "6" } }, { "body": "<p>Here's a few comments to add to those of @uli (+1)</p>\n\n<p>Would one ever use a linked list in c++ when there are nice STL containers available for such things? Seems unlikely, but I'm not strong on c++. But in a c++ exercise on the subject of linked lists, I'd expect to see some use of c++ facilities. </p>\n\n<p>For example you could usefully use exceptions to avoid the ambiguity in your <code>head_return</code> and <code>tail_return</code> functions. These two currently return 0 on failure but this is a valid value for the payload (you don't check for it when inserting, so I assume it is a valid payload). You might also use an exception when doing an ordered insert (as opposed to an <code>assert</code> suggested by @uli).</p>\n\n<p>I would change some of your variable names. For example you have three names for a payload, <code>payload</code>, <code>pload</code> and <code>temp</code>. Why not use just one consistently if possible? And you also use <code>temp</code> for a temporary node, but <code>node</code> would be more descriptive.</p>\n\n<p>Here are some detailed comments (some are pedantic and others perhaps only opinion):</p>\n\n<ul>\n<li>importing everything from std (<code>using namespace std</code>) is best avoided.</li>\n<li>I prefer to see <code>type *var</code> rather than <code>type* var</code> - consider the type for var2 in the declaration <code>type* var1, var2</code>. EDIT: as noted by @LokiAstari in the comments, this is a preference carried over from C and is not applicable to C++, where <code>type* var</code> is the convention.</li>\n<li>you don't have many comments, but those you have are noise (no useful information) and should be deleted. Write useful comments - don't state the obvious.</li>\n<li><p>empty loops should be made explicit with braces:</p>\n\n<pre><code>for (temp = *list; temp-&gt;next; temp = temp-&gt;next) {\n /* loop */\n}\n</code></pre></li>\n<li><p>ending a function with </p>\n\n<pre><code>else\n{\n return 0;\n}\n</code></pre>\n\n<p>is better written as just <code>return 0</code></p></li>\n<li><p>where possible, define loop variables in the loop:</p>\n\n<pre><code>for (node_ll *temp = *list; temp-&gt;next; temp = temp-&gt;next) {...}\n</code></pre></li>\n<li><p>in <code>ordered_insert</code> you'd be better to break the loop by adding a <code>!inserted</code> condition once you've inserted the value rather than continuing to loop:</p>\n\n<pre><code>for (temp = *list; temp-&gt;next &amp;&amp; !inserted; temp = temp-&gt;next)\n</code></pre></li>\n<li><p>I'm sure that a new_node() function would be useful:</p>\n\n<pre><code>static node_ll* new_node(node_ll *next, int payload)\n{\n node_ll *node = new node_ll;\n node-&gt;payload = payload;\n node-&gt;next = *next;\n return node;\n}\n</code></pre></li>\n<li><p>is it really expected that find_remove removes all occurrences of a payload instead of just one? </p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T10:21:55.020", "Id": "38834", "Score": "0", "body": "with regard to your last point, the question states: void find_remove (node_ll **list, int pload);// Find all nodes with payload pload and remove them from the linked list. (If there is no node with payload pload, do not do anything.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T15:03:08.493", "Id": "38846", "Score": "0", "body": "The usage `type *vat` is C like. C++ convention is `type* var` as the `*` is part of the type information. Yes this has the problem `type* x,y;` issue but that is resolved by not having more than one variable per line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T16:20:49.710", "Id": "38851", "Score": "0", "body": "@LokiAstari - I didn't know it was a convention, thanks. I edited the answer. Is there a good reason for it, bearing in mind that people **do** in practice declare multiple variables on a line.?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T20:02:46.950", "Id": "38859", "Score": "0", "body": "Like all things C/C++ their is debate. But the majority in C++ consider it part of the type and thus it belongs on the left. While in C old style conventions put it on the right more often. There is one obscure corner case with a typedef where it is better for the type conversely there is the obscure case were people put multiple variable on a line where it is better." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T15:57:25.397", "Id": "25057", "ParentId": "25043", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T18:20:10.607", "Id": "25043", "Score": "5", "Tags": [ "c++", "linked-list" ], "Title": "Singly linked list" }
25043
<p>This script updates a MySQL database with golf scores and calculates how many strokes under the player is in real time and is working. I'm just looking for a better way to make it cleaner and compact.</p> <pre><code>&lt;?php // Get values from form $uid=$_POST['uid']; $name=$_POST['name']; $course=$_POST['course']; $h01=$_POST['h01']; $h02=$_POST['h02']; $h03=$_POST['h03']; $h04=$_POST['h04']; $h05=$_POST['h05']; $h06=$_POST['h06']; $h07=$_POST['h07']; $h08=$_POST['h08']; $h09=$_POST['h09']; $h10=$_POST['h10']; $h11=$_POST['h11']; $h12=$_POST['h12']; $h13=$_POST['h13']; $h14=$_POST['h14']; $h15=$_POST['h15']; $h16=$_POST['h16']; $h17=$_POST['h17']; $h18=$_POST['h18']; $played=$_POST['played']; $n01=4; $n02=5; $n03=4; $n04=3; $n05=5; $n06=3; $n07=4; $n08=4; $n09=4; $n10=4; $n11=4; $n12=4; $n13=4; $n14=3; $n15=5; $n16=3; $n17=4; $n18=5; $d01=4; $d02=5; $d03=4; $d04=3; $d05=5; $d06=3; $d07=4; $d08=4; $d09=4; $d10=4; $d11=4; $d12=4; $d13=4; $d14=3; $d15=5; $d16=3; $d17=4; $d18=5; $s01=4; $s02=5; $s03=4; $s04=3; $s05=5; $s06=3; $s07=4; $s08=4; $s09=4; $s10=4; $s11=4; $s12=4; $s13=4; $s14=3; $s15=5; $s16=3; $s17=4; $s18=5; if ($course = 'Augusta') { if( $h01 &gt; 0) { $s01 = $h01 - $n01; }else{ $s01 = 0; } if( $h02 &gt; 0) { $s02 = $h02 - $n02; }else{ $s02 = 0; } if( $h03 &gt; 0) { $s03 = $h03 - $n03; }else{ $s03 = 0; } if( $h04 &gt; 0) { $s04 = $h04 - $n04; }else{ $s04 = 0; } if( $h05 &gt; 0) { $s05 = $h05 - $n05; }else{ $s05 = 0; } if( $h06 &gt; 0) { $s06 = $h06 - $n06; }else{ $s06 = 0; } if( $h07 &gt; 0) { $s07 = $h07 - $n07; }else{ $s07 = 0; } if( $h08 &gt; 0) { $s08 = $h08 - $n08; }else{ $s08 = 0; } if( $h09 &gt; 0) { $s09 = $h09 - $n09; }else{ $s09 = 0; } if( $h10 &gt; 0) { $s10 = $h10 - $n10; }else{ $s10 = 0; } if( $h11 &gt; 0) { $s11 = $h11 - $n11; }else{ $s11 = 0; } if( $h12 &gt; 0) { $s12 = $h12 - $n12; }else{ $s12 = 0; } if( $h13 &gt; 0) { $s13 = $h13 - $n13; }else{ $s13 = 0; } if( $h14 &gt; 0) { $s14 = $h14 - $n14; }else{ $s14 = 0; } if( $h15 &gt; 0) { $s15 = $h15 - $n15; }else{ $s15 = 0; } if( $h16 &gt; 0) { $s16 = $h16 - $n16; }else{ $s16 = 0; } if( $h17 &gt; 0) { $s17 = $h17 - $n17; }else{ $s17 = 0; } if( $h18 &gt; 0) { $s18 = $h18 - $n18; }else{ $s18 = 0; } } else { if( $h01 &gt; 0) { $s01 = $h01 - $d01; }else{ $s01 = 0; } if( $h02 &gt; 0) { $s02 = $h02 - $d02; }else{ $s02 = 0; } if( $h03 &gt; 0) { $s03 = $h03 - $d03; }else{ $s03 = 0; } if( $h04 &gt; 0) { $s04 = $h04 - $d04; }else{ $s04 = 0; } if( $h05 &gt; 0) { $s05 = $h05 - $d05; }else{ $s05 = 0; } if( $h06 &gt; 0) { $s06 = $h06 - $d06; }else{ $s06 = 0; } if( $h07 &gt; 0) { $s07 = $h07 - $d07; }else{ $s07 = 0; } if( $h08 &gt; 0) { $s08 = $h08 - $d08; }else{ $s08 = 0; } if( $h09 &gt; 0) { $s09 = $h09 - $d09; }else{ $s09 = 0; } if( $h10 &gt; 0) { $s10 = $h10 - $d10; }else{ $s10 = 0; } if( $h11 &gt; 0) { $s11 = $h11 - $d11; }else{ $s11 = 0; } if( $h12 &gt; 0) { $s12 = $h12 - $d12; }else{ $s12 = 0; } if( $h13 &gt; 0) { $s13 = $h13 - $d13; }else{ $s13 = 0; } if( $h14 &gt; 0) { $s14 = $h14 - $d14; }else{ $s14 = 0; } if( $h15 &gt; 0) { $s15 = $h15 - $d15; }else{ $s15 = 0; } if( $h16 &gt; 0) { $s16 = $h16 - $d16; }else{ $s16 = 0; } if( $h17 &gt; 0) { $s17 = $h17 - $d17; }else{ $s17 = 0; } if( $h18 &gt; 0) { $s18 = $h18 - $d18; }else{ $s18 = 0; } } $score = $s01 + $s02 + $s03 + $s04 + $s05 + $s06 + $s07 + $s08 + $s09 + $s10 + $s11 + $s12 + $s13 + $s14 + $s15 + $s16 + $s17 + $s18; // update data in mysql database $sql="UPDATE $tbl_name SET name='$name', course='$course', h01='$h01', h02='$h02', h03='$h03', h04='$h04', h05='$h05', h06='$h06', h07='$h07', h08='$h08', h09='$h09', h10='$h10', h11='$h11', h12='$h12', h13='$h13', h14='$h14', h15='$h15', h16='$h16', h17='$h17', h18='$h18', played='$played', score='$score' WHERE uid='$uid'"; $result=mysql_query($sql); // if successfully updated. if($result){ // echo "&lt;script&gt;window.location = 'index.php'&lt;/script&gt;"; echo "&lt;h1&gt;UPDATED - &lt;a href='index.php'&gt;Back to Admin Page&lt;/a&gt;&lt;/h1&gt;"; } else { echo "&lt;h1&gt;ERROR&lt;/h1&gt;"; } ?&gt; </code></pre>
[]
[ { "body": "<p>There are a number of ways to improve this code:</p>\n\n<ol>\n<li>You really need to use arrays for this.</li>\n<li><code>$d</code> and <code>$n</code> are identical so I don't see any need for the <code>if ($course = 'Augusta')</code> condition.</li>\n<li>Use <code>msqli</code> methods instead of <code>mysql</code>, as they've been deprecated.</li>\n<li>Use prepared statements to guard against <a href=\"http://en.wikipedia.org/wiki/SQL_injection\">sql injection</a>.</li>\n</ol>\n\n<p>Try this:</p>\n\n<pre><code>function _getName($i) { return 'h' . str_pad($i, '0', 2, STR_PAD_LEFT); }\nfunction _getPost($n) { return $_POST[$n]; }\nfunction _getSqlParam($n) { return $n.'=?'; }\n$hNames = array_map(_getName, range(1, 18));\n$h = array_map(_getPost, $hNames);\n$played=$_POST['played'];\n$n = array(4, 5, 4, 3, 5, 3, 4, 4, 4, 4, 4, 4, 4, 3, 5, 3, 4, 5);\n$s = $n; // copy array\n\nfor($i = 0; $i &lt; count($h); ++$i) {\n if( $h[$i] &gt; 0) {\n $s[$i] = $h[$i] - $n[$i];\n } else {\n $s[$i] = 0;\n }\n}\n\n$sqlSetClause = implode(',', array_map(_getSqlParam, $hNames));\n$sql=\"UPDATE $tbl_name \n SET name=?,course=?,played=?,score=?,$sqlSetClause\n WHERE uid=?\";\n$mysqli = new mysqli(\"localhost\", \"my_user\", \"my_password\", \"world\");\nif ($stmt = $mysqli-&gt;prepare($sql)) {\n $allParams = array_merge(array($name, $course, $played, $score), $h, array($uid));\n $stmt-&gt;bind_param(str_repeat('s', count($allParams)), $allParams);\n $result = $stmt-&gt;execute();\n\n if($result) {\n // echo \"&lt;script&gt;window.location = 'index.php'&lt;/script&gt;\";\n echo \"&lt;h1&gt;UPDATED - &lt;a href='index.php'&gt;Back to Admin Page&lt;/a&gt;&lt;/h1&gt;\";\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T19:58:26.587", "Id": "25046", "ParentId": "25045", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T19:20:30.427", "Id": "25045", "Score": "3", "Tags": [ "php", "mysql" ], "Title": "Populating a database with golf scores and stroke calculations" }
25045
<p>This is a security question.</p> <p>I'm quite new to PHP and just a beginner in SQLite.</p> <p>For practical, and educational reasons, I'm writing a small PHP site that will serve as one-threaded discussion (meaning, only one topic / no topics) between me and my friends.</p> <p>The site will be open to the Internet and the final version will include authentication, but I haven't reached the point of authentication yet. I have, however, reached the point where I can write and read posts in a database, and I need your opinion on how secure my ways are.</p> <p>This is code taken, and simplified from my prototype. It demonstrates how I read and write things with SQLite. I've removed things such as paging (dividing into pages) and posting a message, along with the sane checks for those things (i.e.: posts have a limit of 10kB).</p> <p>You can see the code bellow, but in summary these are my security measures:</p> <ul> <li>I escape strings</li> <li>I replace HTML special characters</li> <li>I use PDO</li> <li>I use prepared statements</li> <li>I make sure my queries/statements end with a ';'</li> </ul> <p>My questions are:</p> <ol> <li><p>I'm using a prepared statement to write data inside the db. Can, and should I use a prepared statement to read data from the db? If yes, then can you make an example?</p></li> <li><p>Are these measures enough to avoid SQL injections and XSS injections?</p></li> <li><p>What else do you see wrong in this code? What security holes does it have that I haven't found yet?</p></li> </ol> <p>Also, if you have a performance recommendation, that doesn't compromise security, then go right ahead :)</p> <pre><code>&lt;?php // script settings error_reporting(E_ALL); ini_set('default_charset', 'UTF-8'); date_default_timezone_set('Europe/Helsinki'); // time $unixtime = time(); $localtime_offset = date('Z'); // our input $message = 'hello world'; if (!isset($message)) die("Give me something to store."); $message = SQLite3::escapeString($message); $message = htmlspecialchars($message, ENT_XHTML); echo "&lt;html&gt;\n&lt;head&gt;\n&lt;/head&gt;\n&lt;body&gt;\n\n"; try { $db = new PDO('sqlite:stackoveflow.db') or die("Can't create database."); $db-&gt;setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); $db-&gt;exec("CREATE TABLE IF NOT EXISTS Wall (Id INTEGER PRIMARY KEY, Message TEXT NOT NULL, Unixtime INTEGER NOT NULL, Localtime_offset INTEGER NOT NULL);"); // write the data $statement = "INSERT INTO Wall (Message, Unixtime, Localtime_offset) VALUES (:Message,:Unixtime,:Localtime_offset);"; $query = $db-&gt;prepare($statement); $query-&gt;bindValue(':Message', $message, SQLITE3_TEXT); $query-&gt;bindValue(':Unixtime', $unixtime, SQLITE3_INTEGER); $query-&gt;bindValue(':Localtime_offset', $localtime_offset, SQLITE3_INTEGER); $query-&gt;execute() or die($db-&gt;errorInfo()); // read the data $result = $db-&gt;query('SELECT * FROM Wall'); if (!$result) die("Can't execute database query."); foreach($result as $row) { $localtime = date("Y-m-d H:i:s P", $row['Unixtime']); print "&lt;h2&gt;Post #" . $row['Id'] . ", on " . $localtime . "&lt;/h2&gt;\n"; print $row['Message'] . "\n\n"; } $db = NULL; } catch(PDOException $exception) { echo $exception-&gt;getMessage(); } echo "\n&lt;/body&gt;\n&lt;/html&gt;"; ?&gt; </code></pre> <p><strong>Update 1 : 2013-04-15</strong></p> <p>I've made some adjustments based on user88171's suggestions. <pre><code>// script settings error_reporting(E_ALL); ini_set('default_charset', 'UTF-8'); date_default_timezone_set('Europe/Helsinki'); // time $unixtime = time(); $localtime_offset = date('Z'); $date = date('Y-m-d H:i:s O'); // our input $message = "hello 气 " . chr(27) . "world á, é, í, ó, ú, ü, ñ, ¿, ¡ \xEF\xBB\xBF"; // function to end the script and write a log report for the admin function error($msg) { // write the message to the error log and send an email to the admin echo "&lt;p&gt;An internal error occured. The administrator has been notified.&lt;/p&gt;"; exit(1); } echo "&lt;html&gt;\n&lt;head&gt;\n&lt;/head&gt;\n&lt;body&gt;\n\n"; // show us the input before insirting into the db $hex = bin2hex($message); $hex = chunk_split($hex,2," "); echo "&lt;p&gt;&lt;b&gt;Our input:&lt;/b&gt; $message&lt;/p&gt;\n\n"; echo "&lt;p&gt;&lt;b&gt;Out input in hex:&lt;/b&gt; $hex&lt;/p&gt;\n\n"; echo "&lt;hr&gt;\n\n"; if (!isset($message)) die("&lt;p&gt;You need to give me an input.&lt;/p&gt;"); $message = str_replace("\r", '', $message); $message = SQLite3::escapeString($message); $message = htmlspecialchars($message, ENT_XHTML); try { $db = new PDO('sqlite:stackoveflow.db') or error("Can't open or create database."); $db-&gt;setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); $db-&gt;exec("CREATE TABLE IF NOT EXISTS Wall (Id INTEGER PRIMARY KEY, Message TEXT NOT NULL, Unixtime INTEGER NOT NULL, Localtime_offset INTEGER NOT NULL);"); // write the data $statement = "INSERT INTO Wall (Message, Unixtime, Localtime_offset) VALUES (:Message,:Unixtime,:Localtime_offset);"; $query = $db-&gt;prepare($statement); $query-&gt;bindValue(':Message', $message, SQLITE3_TEXT); $query-&gt;bindValue(':Unixtime', $unixtime, SQLITE3_INTEGER); $query-&gt;bindValue(':Localtime_offset', $localtime_offset, SQLITE3_INTEGER); $query-&gt;execute() or error($db-&gt;errorInfo()); // read the data $result = $db-&gt;query('SELECT * FROM Wall'); if (!$result) error("Can't execute database query."); foreach($result as $row) { $localtime = date("Y-m-d H:i:s P", $row['Unixtime']); print "&lt;h2&gt;Post #" . $row['Id'] . ", on " . $localtime . "&lt;/h2&gt;\n\n"; print "\t&lt;p&gt;" . $row['Message'] . "&lt;/p&gt;\n\n"; } $db = NULL; } catch(PDOException $exception) { error($exception-&gt;getMessage()); } echo "&lt;/body&gt;\n&lt;/html&gt;"; ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-28T09:06:33.257", "Id": "39625", "Score": "0", "body": "1. Doesn't `$query->bindValue()` escape `$message`? 2. You should call `htmlspecialchars()` in your view code, not before you store it in the DB." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-28T09:11:50.260", "Id": "39626", "Score": "0", "body": "Oh, and you're using `SQLITE3_` constants in your PDO `bindValue()` calls. It's only luck that this works. Use `PDO::PARAM_INT` and `PDO::PARAM_STR` in preference." } ]
[ { "body": "<p>Your sample <code>$message</code> is, frankly, kind of boring. Make it use accented vowels and the Chinese glyph 气 (\"life\"). Put an ASCII NUL in the middle. Ensure that SQLite3::escapeString() will insert at least two escapes, and that htmlspecialchars() will change one of them. You might want to write a predicate, no_angle_brackets() or some such, that verifies the result of htmlspecialchars() is \"safe\", and then call the same predicate on each $message retrieved from the database. This guards against bit rot, since you might improve your checking code a month from now but neglect to update stored rows.</p>\n\n<p>Unicode is significantly more complex than Latin-1. You might choose to reject any $message with characters outside a fairly conservative range. No need to accept the BOM, Combining Ring, or the Devanagari Combining Vowel Sign U, for example.</p>\n\n<p>In <code>$query = $db-&gt;prepare($statement);</code>, you chose a gratuitously confusing name; better to call it something like <code>$insert</code>. Is autocommit on, so insert doesn't need a commit?</p>\n\n<p>The new <code>PDO() or die()</code> is a very nice idiom, which we see again after the insert; I recommend reusing the <code>or die</code> idiom after the select.</p>\n\n<p>The select should probably mention <code>order by id</code>.</p>\n\n<p>The <code>&lt;h2&gt;</code> should probably be <code>&lt;div&gt;</code> + CSS.</p>\n\n<p>Consider ripping out the catch / try. That is, think about what you're trying to accomplish with it. Would it be so bad if the exception continued on up the stack? Are (non-PDO) traces reported the way you want them? Think about ugly non-escaped characters that might sneak into the <code>getMessage()</code> text or the <code>$db-&gt;errorInfo()</code>text.</p>\n\n<p>Consider writing external unit tests, which simulate \"friendly\" writing / reading, and \"hostile\" transactions. Verify that SQLite3 locking copes with \"simultaneous\" web transactions.</p>\n\n<p>Overall, it looks fairly good, the boring <code>$message</code> test seems the greatest deficiency. The simple fact that you have your paranoid hat on and are carefully reviewing the code makes it unlikely that Bobby Tables will trash your site.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T21:18:03.643", "Id": "38768", "Score": "0", "body": "I'm confused by you supporting exceptions, but encouraging him to use `or die`. If an exception is thrown, the `die` won't execute. And `or die` is most certainly **not** a nice idiom. http://www.phpfreaks.com/blog/or-die-must-die" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T05:07:00.440", "Id": "38789", "Score": "0", "body": "@Corbin, granted, `die()` is unfortunate, `trigger_error()` or `throw new Exception()` would be better. Better still would be for `new PDO()` to throw an exception if it fails, so the caller needn't check for empty result. The key is to ensure that after an unexpected thing happens, we don't blithely keep on executing code in the known bad state. BTW, there seems to be little need to check for empty `select *` result -- the loop body will simply execute zero times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T08:24:36.457", "Id": "38794", "Score": "0", "body": "On a website dedicated to pedantic pursuit of the better option, presenting an inferior option as good is bad. Also, those does literally cannot run. Exceptions will pull the execution off that path." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T15:22:02.130", "Id": "38848", "Score": "0", "body": "@user88171: The script works even with a Chinese character, an ASCII NULL, and BOM. I've posted an updated version which removes carriages and don't just `or die()`. You make a number of points. I want to sit on one for now: what should I allow inside the post body (the $message). Why reject the BOM, the Combining Ring, or the Devanagari Combining Vowel Sign U? The last two are valid punctuation in some languages. I don't want to limit my users in what language they'll write. As for the BOM, it doesn't seem to cause a problem. I'm not going against what you say. I just want to understand." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T18:42:11.947", "Id": "25058", "ParentId": "25049", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T21:33:06.677", "Id": "25049", "Score": "3", "Tags": [ "php", "security", "sqlite" ], "Title": "how secure is this way of writing and reading with PHP and SQLite?" }
25049
<p>I am writing a method to find me a price range for special price as well as the retail price. Such as in example below I have price range for retail from 129 to 329 where as special price range is 89 to 199</p> <pre><code>array 0 =&gt; array 'id' =&gt; 83739000038374 'special-price' =&gt; 99.99 'retail-price' =&gt; 199 1 =&gt; array 'id' =&gt; 83739000038374 'special-price' =&gt; 199.99 'retail-price' =&gt; 299 2 =&gt; array 'id' =&gt; 83739000038374 'special-price' =&gt; 89 'retail-price' =&gt; 129 3 =&gt; array 'id' =&gt; 83739000038374 'special-price' =&gt; 179 'retail-price' =&gt; 329 </code></pre> <p>my code is </p> <pre><code>public function getPriceRange(){ $priceRange = array(); $showRange = true; if($originalArray &amp;&amp; count($originalArray) &gt; 1){ foreach($originalArray as $idx =&gt; $originalArraySingle){ if($idx == 0){ $priceRange['price']['max'] = $originalArraySingle['price']; $priceRange['price']['min'] = $originalArraySingle['price']; $priceRange['original-price']['max'] = $originalArraySingle['original-price']; $priceRange['original-price']['min'] = $originalArraySingle['original-price']; }else{ if($originalArraySingle['price'] &gt; $priceRange['price']['max'] ){ $priceRange['price']['max'] = is_int($originalArraySingle['price']) ? number_format((float)$originalArraySingle['price'], 2, '.', '') : $originalArraySingle['price']; } if($originalArraySingle['price'] &lt; $priceRange['price']['min'] ){ $priceRange['price']['min'] = is_int($originalArraySingle['price']) ? number_format((float)$originalArraySingle['price'], 2, '.', '') : $originalArraySingle['price']; } if($originalArraySingle['original-price'] &gt; $priceRange['original-price']['max'] ){ $priceRange['original-price']['max'] = is_int($originalArraySingle['original-price']) ? number_format((float)$originalArraySingle['original-price'], 2, '.', '') : $originalArraySingle['original-price']; } if($originalArraySingle['original-price'] &lt; $priceRange['original-price']['min']){ $priceRange['original-price']['min'] = is_int($originalArraySingle['original-price']) ? number_format((float)$originalArraySingle['original-price'], 2, '.', '') : $originalArraySingle['original-price']; } } } //doesnt make sense to show price range if its same. if($priceRange['price']['max']===$priceRange['price']['min'] || $priceRange['price']['max']===$priceRange['price']['min']){ $showRange = false; } } return $showRange ? $priceRange : null; } </code></pre> <p>I am looking for scalability and for fastest code processing.</p>
[]
[ { "body": "<pre><code>if($originalArraySingle['original-price'] &lt; $priceRange['original-price']['min']){\n $priceRange['original-price']['min'] = is_int($originalArraySingle['original-price']) ? number_format((float)$originalArraySingle['original-price'], 2, '.', '') : $originalArraySingle['original-price'];\n}\n</code></pre>\n\n<p>You could write a function for this. And one for maximize.</p>\n\n<pre><code>protected function minimize($a,&amp;$b){\n if($a&lt;$b){\n $b = is_int($a)?number_format((float)$a,2,'.',''):$a;\n }\n}\n</code></pre>\n\n<p>I would also write.</p>\n\n<pre><code>if($priceRange['price']['max']===$priceRange['price']['min'] || $priceRange['price']['max']===$priceRange['price']['min']){\n return null;\n }\n</code></pre>\n\n<p>and change </p>\n\n<pre><code>return $showRange ? $priceRange : null;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>return $priceRange;\n</code></pre>\n\n<p>so you have one variable less.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T12:55:02.663", "Id": "25056", "ParentId": "25051", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T23:54:59.357", "Id": "25051", "Score": "1", "Tags": [ "php", "php5" ], "Title": "array to return on conditions" }
25051
<p>The exercise is as follows:</p> <blockquote> <p>Create a class called Fraction that can be used to represent the ratio of two integers. Include appropriate constructors, properties, and methods. If the denominator becomes zero, throw and handle an exception. Create an application class to test the Fraction class.</p> </blockquote> <p>The program runs. Will someone look over my code for this exercise?</p> <p>Fraction.cs</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Part2 { public class Fraction { private int numerator; private int denominator; /// &lt;summary&gt; /// Initialize the fraction properties /// &lt;/summary&gt; /// &lt;param name="numerator"&gt;Upper number&lt;/param&gt; /// &lt;param name="denominator"&gt;Lower number&lt;/param&gt; public Fraction(int numerator, int denominator) { this.Numerator = numerator; this.Denominator = denominator; } /// &lt;summary&gt; /// Access tot he numerator property /// &lt;/summary&gt; public int Numerator { get { return this.numerator; } set { this.numerator = value; } } /// &lt;summary&gt; /// Access to the denominator property /// &lt;/summary&gt; public int Denominator { get { return this.denominator; } set { if (value == 0) { throw new Exception("0 denominator"); } this.denominator = value; } } /// &lt;summary&gt; /// Return a string representation of a fraction /// &lt;/summary&gt; /// &lt;returns&gt;Displayable attribute&lt;/returns&gt; public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(this.Numerator + "/" + this.numerator); sb.Append(" or "); sb.Append(this.Numerator / this.Denominator); return sb.ToString(); } } } </code></pre> <p>Application.cs</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Part2 { public class Application { /// &lt;summary&gt; /// Entry point of the program /// &lt;/summary&gt; public static void Main(string[] args) { // Create a fraction Fraction f1 = new Fraction(1, 2); Console.WriteLine(f1); try { // Create another fraction Fraction f2 = new Fraction(2, 0); Console.WriteLine(f2); } catch(Exception e) { Console.WriteLine(e.Message); } Console.ReadKey(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T19:24:37.620", "Id": "38762", "Score": "0", "body": "Would he allow unit testing to be considered a class to \"test\" your class?" } ]
[ { "body": "<p>I think your class is pretty much useless. If you have a class that represents a fraction, you should be able to do operations with it that you can do with a fraction, like addition, subtraction, multiplication and division (possibly using operator overloading). Another possible operation is fraction simplification.</p>\n\n<p>Also, you shouldn't throw <code>Exception</code>, you should instead a custom type that inherits from <code>Exception</code> (called something like <code>ZeroDenominatorException</code>) and throw that.</p>\n\n<p>And your <code>Main()</code> isn't very realistic. In real code, you wouldn't write code that you know will always throw an exception. So I think that your <code>try</code> should be around both of your <code>new Fraction()</code> statements.</p>\n\n<p>Also, if you're going to have all the operations I have mentioned above, a better application to show that would be a very simple fraction calculator.</p>\n\n<p>Something like:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Enter numerator:\n1\nEnter denominator:\n4\nEnter operation:\n+\nEnter numerator:\n3\nEnter denominator:\n4\nResult: 4/4\nSimplifies result: 1/1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T19:39:00.817", "Id": "38763", "Score": "0", "body": "Thank you. I will change some of the things you mentioned. I will refrain from adding anything that the exercise doesn't explicitly call for like math operations(although it would be a better program). Less to grade = less chance for grade deduction. Thank you very much for your help!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T19:45:45.657", "Id": "38764", "Score": "0", "body": "[you should actually throw an `IllegalArgumentException`.](http://stackoverflow.com/questions/1657887/how-should-i-throw-a-divide-by-zero-exception-in-java-without-actually-dividing)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T21:17:15.907", "Id": "38767", "Score": "1", "body": "@JakobWeisblat This is not Java. In .Net you could use `ArgumentException` or `ArgumentOutOfRangeException`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T23:53:10.207", "Id": "38780", "Score": "0", "body": "@svick oops. I should look at tags more carefully." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T23:01:12.630", "Id": "38868", "Score": "0", "body": "Could also use `DivideByZeroException`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T12:52:36.040", "Id": "25055", "ParentId": "25054", "Score": "8" } } ]
{ "AcceptedAnswerId": "25055", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T10:07:50.933", "Id": "25054", "Score": "5", "Tags": [ "c#", "homework", "rational-numbers" ], "Title": "Creating and testing a Fraction class" }
25054
<p>I have some code that allows me to enumerate over months in a year. This code is used both in a Web application as well as a standalone exe. Although it doesn't have to be efficient it is used a lot so if there are any improvements that would be great (I haven't done any profiling). It also needs to be thread-safe.</p> <pre><code>public enum MonthEnum { Undefined, // Required here even though it's not a valid month January, February, March, April, May, June, July, August, September, October, November, December } public static class MonthEnumEnumerator { private static readonly ReadOnlyCollection&lt;MonthEnum&gt; MonthsInYear = CreateYear(); private static readonly ReadOnlyCollection&lt;MonthEnum&gt; ReversedMonthsInYear = CreateYear(janToDec: false); private static ReadOnlyCollection&lt;MonthEnum&gt; CreateYear(bool janToDec = true) { var months = new List&lt;MonthEnum&gt;(); for (int i = 1; i &lt;= 12; i++) months.Add((MonthEnum)i); return new ReadOnlyCollection&lt;MonthEnum&gt;(janToDec ? months : months.OrderByDescending(p =&gt; (int)p).ToList()); } /// &lt;summary&gt; /// Returns an array of MonthEnums without the MonthEnum.Undefined value /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public static IEnumerable&lt;MonthEnum&gt; GetValues() { return MonthsInYear; } /// &lt;summary&gt; /// Returns an array of Months starting from December to January not including the Undefined value /// &lt;/summary&gt; public static IEnumerable&lt;MonthEnum&gt; GetValuesReversed() { return ReversedMonthsInYear; } /// &lt;summary&gt; /// Gets a list of months in range of start and end. For example with a start month of Feb and end of April this function /// would return Feb, March, April. If the start month was Nov and end Month Feb it would return Nov, Dec, Jan, Feb. /// &lt;/summary&gt; /// &lt;param name="start"&gt;Start of month range to return&lt;/param&gt; /// &lt;param name="end"&gt;End of month range to return&lt;/param&gt; /// &lt;returns&gt;Array of months in order from start to end&lt;/returns&gt; public static IEnumerable&lt;MonthEnum&gt; GetInRange(MonthEnum start, MonthEnum end) { var range = new List&lt;MonthEnum&gt;(); if(start &lt;= end) { // simple start to end of months with no december rollover for(MonthEnum month = start; month &lt;= end; month++) range.Add(month); } else { // end month wraps around december i.e. Nov - Feb for (MonthEnum month = start; month &lt;= MonthEnum.December; month++) range.Add(month); // now jan - end month for (MonthEnum month = MonthEnum.January; month &lt;= end; month++) range.Add(month); } return new ReadOnlyCollection&lt;MonthEnum&gt;(range); } public static IEnumerable&lt;MonthEnum&gt; GetInRange(MonthEnum start) { return GetInRange(start, start.Previous()); } public static MonthEnum Next(this MonthEnum month) { return month == MonthEnum.December ? MonthEnum.January : month + 1; } public static MonthEnum Previous(this MonthEnum month) { return month == MonthEnum.January ? MonthEnum.December : month - 1; } public static MonthEnum Subtract(this MonthEnum month, int months) { MonthEnum subtracted = month; while ((months--) &gt; 0) subtracted = subtracted.Previous(); return subtracted; } public static MonthEnum Add(this MonthEnum month, int months) { MonthEnum added = month; while ((months--) &gt; 0) added = added.Next(); return added; } } </code></pre> <p>I use it like so:</p> <pre><code>foreach (var month in MonthEnumEnumerator.GetValues()) { // do stuff that is month related } </code></pre> <p>or</p> <pre><code>// for getting the months from July to December foreach (var month in MonthEnumEnumerator.GetInRange(MonthEnum.July, MonthEnum.December)) { // do something } </code></pre> <p>or if I want to get the previous month to what I'm on I can do</p> <pre><code>var previousMonth = currentMonth.Previous(); </code></pre> <p>UPDATE: I updated my answer after comments/answers below. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T21:12:21.883", "Id": "38766", "Score": "0", "body": "Is there a reason why `Undefined` is required? Couldn't you just use `January = 1`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T21:26:26.770", "Id": "38771", "Score": "0", "body": "Yes, the enumeration is serialized as part of an XML document and it is an optional field. We didn't know how else to show that so included an Undefined (It's serialized as empty string). It's littered through code modules so to move it out with be to much of a major at this point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T21:31:37.007", "Id": "38772", "Score": "1", "body": "In that case, I think it would make more sense to remove `Undefined` and use `MonthEnum?` instead, but I understand that you can't change that now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T21:51:51.180", "Id": "38774", "Score": "0", "body": "Never thought to use a MonthEnum?. Will have to try that out in our serialization process and put it down as a possible refactor later. cheers." } ]
[ { "body": "<p>Here's my take - note the <code>ReadOnlyCollection</code> creations to keep the callers from being able to modify the members of the static collection:</p>\n\n<pre><code>public enum Month\n{\n /// &lt;summary&gt;\n /// Required here even though it's not a valid month.\n /// &lt;/summary&gt;\n Undefined,\n\n January,\n\n February,\n\n March,\n\n April,\n\n May,\n\n June,\n\n July,\n\n August,\n\n September,\n\n October,\n\n November,\n\n December\n}\n\npublic static class MonthEnumerator\n{\n private static readonly ReadOnlyCollection&lt;Month&gt; monthsInYear = new ReadOnlyCollection&lt;Month&gt;(\n Enumerable.Range((int)Month.January, (int)Month.December).Cast&lt;Month&gt;().ToList());\n\n private static readonly ReadOnlyCollection&lt;Month&gt; reversedMonthsInYear = new ReadOnlyCollection&lt;Month&gt;(\n monthsInYear.Reverse().ToList());\n\n /// &lt;summary&gt;\n /// Returns an enumerable of MonthEnums without the Month.Undefined value.\n /// &lt;/summary&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static IEnumerable&lt;Month&gt; Values\n {\n get\n {\n return monthsInYear;\n }\n }\n\n /// &lt;summary&gt;\n /// Returns an enumerable of Months starting from December to January not including the Undefined value.\n /// &lt;/summary&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static IEnumerable&lt;Month&gt; ReversedValues\n {\n get\n {\n return reversedMonthsInYear;\n }\n }\n\n public static IEnumerable&lt;Month&gt; GetInRange(Month start, Month end)\n {\n var range = new List&lt;Month&gt;();\n\n if (start &lt;= end)\n {\n // Simple start to end of months with no December rollover.\n for (var month = start; month &lt;= end; month++)\n {\n range.Add(month);\n }\n }\n else\n {\n // End month wraps around December i.e. Nov - Feb.\n for (var month = start; month &lt;= Month.December; month++)\n {\n range.Add(month);\n }\n\n // Now Jan - end month.\n for (var month = Month.January; month &lt;= end; month++)\n {\n range.Add(month);\n }\n }\n\n return new ReadOnlyCollection&lt;Month&gt;(range);\n }\n\n public static IEnumerable&lt;Month&gt; GetInRange(Month start)\n {\n return GetInRange(start, start.Previous());\n }\n\n public static Month Next(this Month month)\n {\n return month == Month.December ? Month.January : month + 1;\n }\n\n public static Month Previous(this Month month)\n {\n return month == Month.January ? Month.December : month - 1;\n }\n\n public static Month Subtract(this Month month, int months)\n {\n var subtracted = month;\n\n while (months-- &gt; 0)\n {\n subtracted = subtracted.Previous();\n }\n\n return subtracted;\n }\n\n public static Month Add(this Month month, int months)\n {\n var added = month;\n\n while (months-- &gt; 0)\n {\n added = added.Next();\n }\n\n return added;\n }\n}\n</code></pre>\n\n<p>Use as:</p>\n\n<pre><code>foreach (var month in MonthEnumerator.Values)\n{\n // Do stuff that is month related.\n Console.WriteLine(month);\n}\n\nConsole.WriteLine();\n\n// For getting the months from July to December.\nforeach (var month in MonthEnumerator.GetInRange(Month.July, Month.December))\n{\n // Do something.\n Console.WriteLine(month);\n}\n\nConsole.WriteLine();\n\nvar currentMonth = Month.May;\nvar previousMonth = currentMonth.Previous();\nConsole.WriteLine(previousMonth);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T21:50:23.500", "Id": "38773", "Score": "0", "body": "In the case of Values and ReversedValues is a new collection created on every get? If so do we need to make a new instance each time given the underlying values will never change? static stuff still catches me out a bit..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T21:59:51.453", "Id": "38775", "Score": "0", "body": "@dreza Yes, it would. I think a better solution would be to keep the `ReadOnlyCollection`s in the fields." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T22:33:38.980", "Id": "38776", "Score": "0", "body": "@Jess One question. Is making Getvalues() a property of Values a style/preference thing here or is the concept/abstraction of the access important in this case. Just trying to understand the reasoning. cheers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T15:18:23.530", "Id": "38804", "Score": "0", "body": "@dreza to your first comment: yes, because the caller could always cast it back to a `List<T>` and mutate the contents. A new instance keeps the original completely intact. As to your second comment: it is a style/preference thing. It kinda looked like a duck and quacked like a duck when I saw it, so I changed it to a duck (property)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T20:37:53.043", "Id": "38810", "Score": "0", "body": "@JesseC.Slicer LOL duck. I did do a quick search and ToList() creates a new copy of the list so in this instance as the underlying objects are not reference types you wouldn't be modifying the underlying contents. I actually realized that I missed a unit test for this case so added one in just to be sure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T22:52:04.940", "Id": "38819", "Score": "0", "body": "@dreza I thought I had read somewhere that `ToList()` will just return the list itself if the underlying type is `List<T>` already. But I'm using Reflector on the extension method and it looks like it effectively winds up calling `Array.CopyTo()` internally." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T21:32:05.013", "Id": "25061", "ParentId": "25059", "Score": "2" } }, { "body": "<p>It took me a while to figure out what the purpose of <code>janToDec</code> was. Given that you're using Linq, I can't see any reason not to just implement <code>ReversedMonthsInYear</code> as</p>\n\n<pre><code>private static readonly IEnumerable&lt;MonthEnum&gt; ReversedMonthsInYear = MonthsInYear.Reverse();\n</code></pre>\n\n<p>IMO that's a lot easier on the maintenance programmer.</p>\n\n<p>But then <code>CreateYear</code> without the parameter is simply duplicating code, and you can eliminate it in favour of</p>\n\n<pre><code>private static readonly IEnumerable&lt;MonthEnum&gt; MonthsInYear = GetInRange(MonthEnum.January, MonthEnum.December);\n</code></pre>\n\n<hr>\n\n<p>Since you're not afraid to use arithmetic on your enum, you can make <code>Subtract</code> and <code>Add</code> a bit less loopy.</p>\n\n<pre><code>public static MonthEnum Subtract(this MonthEnum month, int months)\n{\n if (months &lt; 0) throw new ArgumentOutOfRangeException(\"months\", \"months must be non-negative\");\n\n MonthEnum subtracted = month - (months % 12);\n if (subtracted &lt; MonthEnum.January) subtracted += 12;\n return subtracted;\n}\n</code></pre>\n\n<p>and similarly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T23:29:23.140", "Id": "38778", "Score": "0", "body": "Yes, getting rid of the loops seems like a good idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T00:34:30.623", "Id": "38783", "Score": "0", "body": "I like the idea of having ReversedMonthsInYear = MonthsInYear.Reverse() but then this means that we need to ensure that MonthsInYear is always called before ReversedMonthsInYear when constructing. Is that a good dependency to have?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T12:36:43.863", "Id": "38838", "Score": "0", "body": "@dreza, if you're worried about that you can always create a static initialiser to force the initialisation order." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T21:18:01.107", "Id": "38864", "Score": "0", "body": "Excellent. Yes that would be a preferred solution I think. Cheers." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T22:41:33.103", "Id": "25063", "ParentId": "25059", "Score": "2" } }, { "body": "<p>First allow me to comment on the current implementation.</p>\n\n<ul>\n<li><p><code>Undefined</code> is a poor name for a default value, particularly with an enum. Undefined could mean many things in many different contexts. I'd avoid using it. A better name would be <code>None</code> as its value doesn't represent a month but nothing.</p></li>\n<li><p>The name of the enum itself is also poor. Hungarian notation, especially in a class name is just a terrible idea. We don't need the name of the enum to tell us it is an enum. Let the IDE or documentation tell us that. Just name it <code>Month</code>.</p></li>\n<li><p>A common naming convention that I would suggest adopting would be to name your extension classes as <code>[ClassItsExtending]Extensions</code>.</p></li>\n<li><p>There are way too many things wrong with your <code>MonthEnumEnumerator</code> implementation. Since the point of the class is to generate enumerators to enumerate over, return instances of <code>IEnumerable&lt;Month&gt;</code>, not <code>IList&lt;Month&gt;</code>. By doing so, you're implicitly telling the user that the list is modifiable. That compounded by the fact that you're returning the internal list directly, you're just asking for trouble.</p></li>\n</ul>\n\n<hr>\n\n<p>I was debating whether this would be more useful as a <code>struct</code> or an <code>enum</code>, considering all the operations you were trying to add to it. A struct would have been a safer bet. However enums are much more lightweight and the way you're using it, it doesn't need to be more complicated than that.</p>\n\n<pre><code>public enum Month\n{\n None,\n January,\n February,\n March,\n April,\n May,\n June,\n July,\n August,\n September,\n October,\n November,\n December,\n}\n</code></pre>\n\n<p>There are many improvements to be made. If you think of the months as indexes, it will simplify everything. You shouldn't have to loop n times just to figure out what the n'th month is after January, a simple addition should be enough. By doing this, this will allow you to remove many of the redundant operations that you currently have.</p>\n\n<p>First let's start with the extensions:</p>\n\n<pre><code>public static class MonthExtensions\n{\n public static Month FromIndex(int index)\n {\n if (index == 0)\n return Month.None;\n else if (index &gt; 0)\n return (Month)(((index - 1) % 12) + 1);\n else // if (index &lt; 0)\n return (Month)(12 - (Math.Abs(index + 1) % 12));\n }\n\n public static int ToIndex(this Month month)\n {\n return (int)month;\n }\n\n public static Month Add(this Month month, int months)\n {\n if (months == 0)\n return month;\n\n var newIndex = ToIndex(month) + months;\n // need to offset the \"None\" year\n if (newIndex &lt; 1 &amp;&amp; month != Month.None) newIndex = newIndex - 1;\n return FromIndex(newIndex);\n }\n\n public static Month Next(this Month month)\n {\n return Add(month, 1);\n }\n\n public static Month Previous(this Month month)\n {\n return Add(month, -1);\n }\n}\n</code></pre>\n\n<p>When looking at months as indexes, you can take advantage that wrapping will be taken care of automatically. So with this, you don't even need to have a <code>Subtract()</code> method, <code>Add()</code> could be used and accepts negative numbers. This works nicely as it is similar to the <code>DateTime</code> methods available.</p>\n\n<p>It would be cleaner if you have your enumerable methods in a separate class from your extensions. With this new \"indexing\" scheme, this simplifies everything and you can make better use of LINQ.</p>\n\n<pre><code>public static class MonthEnumerable\n{\n public static IEnumerable&lt;Month&gt; YearAscending()\n {\n return RangeAscending(1, 12);\n }\n\n public static IEnumerable&lt;Month&gt; YearDescending()\n {\n return RangeDescending(1, 12);\n }\n\n public static IEnumerable&lt;Month&gt; Range(Month start)\n {\n return Range(start, start.Previous());\n }\n\n public static IEnumerable&lt;Month&gt; Range(Month start, Month end)\n {\n if (start == Month.None)\n return Enumerable.Empty&lt;Month&gt;();\n else if (start &lt;= end)\n return RangeAscending(start.ToIndex(), end.ToIndex());\n else\n return RangeAscending(start.ToIndex(), end.ToIndex() + 12);\n }\n\n private static IEnumerable&lt;Month&gt; RangeAscending(int startIndex, int endIndex)\n {\n return Range(startIndex, endIndex, i =&gt; MonthExtensions.FromIndex(i));\n }\n\n private static IEnumerable&lt;Month&gt; RangeDescending(int startIndex, int endIndex)\n {\n return Range(startIndex, endIndex, i =&gt; MonthExtensions.FromIndex(-i));\n }\n\n private static IEnumerable&lt;Month&gt; Range(int startIndex, int endIndex,\n Func&lt;int, Month&gt; monthSelector)\n {\n return Enumerable.Range(startIndex, endIndex - startIndex + 1)\n .Select(monthSelector);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T23:27:29.117", "Id": "38777", "Score": "0", "body": "Just a note. You may have seen a previous post where I return IList. I edited the question so the items return IEnumerable instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T23:30:37.850", "Id": "38779", "Score": "0", "body": "Also, I agree with the naming conventions but this code is following the conventions of the project so IMHO it's better to stick with project naming conventions rather than apparent \"best practices\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T00:27:34.937", "Id": "38781", "Score": "0", "body": "I'm also not sure if I see the point in recalculating the YearAscending and YearDescending values when they will not change once worked out once?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T02:21:07.357", "Id": "38784", "Score": "0", "body": "There's no point in keeping around a small collection of values either, especially when the values can be generated in constant time. Besides, there is no \"calculations\" being performed here. LINQ queries create generators. The only calculations being performed are done only when you enumerate over the collection but all we're doing here ultimately is mapping a number to another value which is trivial. If you can measure a noticeable performance hit, then by all means, do what you must. But you shouldn't concern yourself with that until you have evidence to say that this isn't fast enough." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T22:50:21.760", "Id": "25064", "ParentId": "25059", "Score": "5" } } ]
{ "AcceptedAnswerId": "25063", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-13T20:07:42.457", "Id": "25059", "Score": "0", "Tags": [ "c#" ], "Title": "Enumerating over a enum that defines months in the year" }
25059
<p>When a user is created, deleted and update the system will give feed back. e.g. User Deleted/Updated/Create success or unsuccessfully, but I'm sure there is a better way to do it than what I have done because I repeat the same code in all functions within my class.</p> <p>Code to create user</p> <pre><code>$userOne = new userActions($database, 'Greg', '324b2643243');// echo $userOne-&gt;create(); </code></pre> <p>Code to delete user</p> <pre><code>$userOne = new userActions($database, 'Abel'); // echo $userOne-&gt;delete(); </code></pre> <p>Code for user creation</p> <pre><code>public function create() {//Works $outPut = ""; if(!$this-&gt;user_exists) { list($password_hash, $salt) = $this-&gt;hash($this-&gt;password); echo 'Hash: ' . $password_hash . '&lt;br&gt;' . 'Salt: ' . $salt . '&lt;br /&gt;'; $result = $this-&gt;connection-&gt;query("INSERT INTO users VALUES( NULL, '{$this-&gt;username}' , '{$password_hash}' , '{$salt}' ) "); if($result) { $outPut = "User has been created"; } else { $outPut = "User could not be created"; } } else { $outPut = 'Username already exists'; } return $outPut; } </code></pre> <p>Is there a better way to display feedback to the user istead of having $outPut every time in all of my create, delete and update functions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T11:40:24.087", "Id": "38796", "Score": "0", "body": "You could make them static functions. echo userActions::create($database, 'Greg', '324b2643243'); If you don't use them for something else." } ]
[ { "body": "<p>I recommend splitting your model (the database operation) from your view (the localization of your message).</p>\n\n<p>Depending if you prefer a return code or a exception flow your code could look like:</p>\n\n<pre><code>public function create()\n{\n if($this-&gt;user_exists) return \"\"; //do you really want to show nothing?\n $error=UserModel::create($this-&gt;password,$salt,$this-&gt;username); // don't have to be static! It's up to you.\n if ($error==-1) return \"User could not be created\"; //could be a constant UserModel::ERROR_GENERAL\n if ($error==0) return \"Username already exists\"; //UserModel::ERROR_EXISTS\n return \"User has been created\";\n}\n</code></pre>\n\n<p>Translating this to exception is up to the reader :)</p>\n\n<p>Actually I even would prefer to give the <code>$error</code> code to my template and let it handle the localization:</p>\n\n<pre><code>public function create()\n{\n if($this-&gt;user_exists) return \"\";\n $error=UserModel::create($this-&gt;password,$salt,$this-&gt;username); \n $view=new View(\"templatefile.php\");\n $view-&gt;assign('error',$error);\n return $view-&gt;render();\n}\n\n//\"templatefile.php\"\n&lt;?if ($error==1):?&gt;...\n&lt;?elseif ($error==0):?&gt;...\n&lt;?else:?&gt;...\n&lt;?endif?&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T04:25:38.507", "Id": "25095", "ParentId": "25066", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T01:19:51.580", "Id": "25066", "Score": "2", "Tags": [ "php", "mysql", "user-interface" ], "Title": "Better way to have output code?" }
25066
<p>I am working out a bit of Clojure code that will take a ref to a map and increment a key value pair in the map. I think I am using ref correctly, but Im not sure about atom. Do I need to use swap! to be more idiomatic? I am new to STM and Clojure, does this look thread-safe / sane? What am I missing?</p> <pre><code>(defn increment-key [ref key] (dosync (if (= (get @ref key) nil) (alter ref assoc key (atom 1)) (alter ref assoc key (atom (inc @(get @ref key))))))) (defn -main [&amp; args] (def my-map (ref {})) (increment-key my-map "yellow") (println my-map) (increment-key my-map "yellow") (println my-map)) </code></pre> <p>Prints</p> <pre><code>$ lein run #&lt;Ref@494eaec9: {yellow #&lt;Atom@191410e5: 1&gt;}&gt; #&lt;Ref@494eaec9: {yellow #&lt;Atom@7461373f: 2&gt;}&gt; </code></pre>
[]
[ { "body": "<p><strong>Don't always create new atoms</strong></p>\n\n<p>My first comment is that your use of <code>atom</code> seems quite wrong to me: atoms are mutable entities which you're supposed to mutate via e.g. <code>swap!</code> or <code>reset!</code>, which alter the value the atom points to without changing the atom reference itself. What your code is doing is to create new atoms at every call, i.e. you change the atom reference completely. A more proper approach would be:</p>\n\n<pre><code>(defn increment-key [ref key] \n (dosync \n (if-let [current (@ref key)] ; maps are functions of their keys, no need for 'get'\n (do (swap! current inc) @ref) ; 'do' here is only used to return the current map\n (alter ref assoc key (atom 1))))) ; change the atom in place\n</code></pre>\n\n<p><strong>Do you need an atom?</strong></p>\n\n<p>My second comment is that you most likely don't need <code>atom</code> at all, unless you want to also use it directly as shared state among different threads. If you only plan to use the ref map as the shared state, you can just drop the <code>atom</code> and make your code easier to handle. One of the benefits of Clojure immutable data structures is that values are inherently thread safe. The following code would be perfectly thread safe:</p>\n\n<pre><code>(defn increment-key [ref key]\n (dosync\n (if-let [current (@ref key)]\n (alter ref assoc key (inc current))\n (alter ref assoc key 1))))\n</code></pre>\n\n<p><strong>Do you need a ref?</strong></p>\n\n<p>A last comment is about choosing the right tool for the job: <code>ref</code> is intended for coordinated state change. This means that it helps you in case you have several mutable state references that need to mutate all in a single transaction, which you create with <code>dosync</code>. Your code doesn't seem to need transactions at all, it just needs a single mutable state reference to change atomically, i.e. in a thread safe manner. This is better achieved with a straight atom, which relieves you from the need to establish a transaction:</p>\n\n<pre><code>(defn increment-key [atm key]\n (if-let [current (@atm key)]\n (swap! atm update key inc)\n (swap! atm assoc key 1)))\n</code></pre>\n\n<p>A next step might be to let the change to be asynchronous by using an <code>agent</code> instead of an <code>atom</code>, but that's slightly beyond the scope here IMO.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T10:31:51.870", "Id": "25130", "ParentId": "25067", "Score": "7" } } ]
{ "AcceptedAnswerId": "25130", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T02:52:06.527", "Id": "25067", "Score": "3", "Tags": [ "thread-safety", "clojure" ], "Title": "Atomically incrementing a value in a map in Clojure" }
25067
<p>I am doing exercises for the <em>Art and Science of Java</em> textbook. I had an exercise that required me to program the simulation of flipping a coin until 3 consecutive "Heads" result appeared.</p> <p>I did it, but I'm not sure if my code is simple enough - since I used an instance variable to count the heads and a function that not only flips the coins but counts the consecutive heads as well.</p> <p>I avoided placing too much lines in the run method (the main method since im using acm libraries) but i'm not sure if this is the most efficient coding.</p> <p>Here's the code:</p> <pre><code>import acm.program.*; import acm.util.*; public class ConsecutiveHeads extends ConsoleProgram { private static final int CONSECUTIVE_HEADS_LIM = 3; public void run () { int nFlips = 0; while (nConsecutiveHeads &lt; CONSECUTIVE_HEADS_LIM) { flipCoin(); nFlips++; } println ("You needed " + nFlips + " flips to get " + CONSECUTIVE_HEADS_LIM + " Consecutive Heads."); } private void flipCoin () { String coinFace = rgen.nextBoolean() ? "Heads" : "Tails"; if (coinFace.equals("Heads")) { nConsecutiveHeads++; } else if (coinFace.equals("Tails")){ nConsecutiveHeads = 0; } println (coinFace); } private int nConsecutiveHeads = 0; private RandomGenerator rgen = RandomGenerator.getInstance(); } </code></pre>
[]
[ { "body": "<p>The one thing that really stands out to me: you don't need to convert the boolean result of <code>nextBoolean()</code> to a human-readable string, then test the string. Just test the result directly, <em>then</em> convert it to a human-readable string. </p>\n\n<pre><code>private void flipCoin () {\n boolean result = rgen.nextBoolean();\n String coinFace;\n if (result) {\n nConsecutiveHeads++;\n coinFace = \"Heads\";\n } else {\n nConsecutiveHeads = 0;\n coinFace = \"Tails\";\n }\n System.out.println(coinFace);\n}\n</code></pre>\n\n<p>Although you can do this for brevity:</p>\n\n<pre><code>private void flipCoin () {\n boolean result = rgen.nextBoolean();\n nConsecutiveHeads = result ? nConsecutiveHeads + 1 : 0;\n System.out.println(result ? \"Heads\" : \"Tails\");\n}\n</code></pre>\n\n<p>You should probably get into the habit of using <a href=\"http://docs.oracle.com/javase/tutorial/essential/io/formatting.html\">format strings</a> rather than string concatenation. It's generally better practice.</p>\n\n<p>This next bit is more a matter of style, but if you don't need to keep <code>nConsecutiveHeads</code> as a state variable, I wouldn't keep it as a class member. You can define it as a variable within the <code>run</code> method and pass it in to <code>flipCoin</code> instead, like this:</p>\n\n<pre><code>public void run () {\n int nFlips = 0;\n int nHeads = 0;\n while (nHeads &lt; CONSECUTIVE_HEADS_LIM) {\n nHeads = flipCoin(nHeads);\n nFlips++;\n }\n\n System.out.printf(\"You needed %d flips to get %d consecutive heads.\", nFlips, nHeads);\n}\n\nprivate int flipCoin (int nHeads) {\n boolean result = rgen.nextBoolean();\n System.out.println(result ? \"Heads\" : \"Tails\");\n return result ? nHeads + 1 : 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T11:18:30.740", "Id": "38795", "Score": "0", "body": "Uau! I wasn't aware you could insert boolean results with a ? : conditional statement inside the println itself! That was a eye opener! Indeed that code like this is simpler and more clear! Ty, I learned something nice today! ps. - I still didn't learn how to format Strings - i'm doing the Stanford University Course, that's why I only use Concatenation yet. Im sure to use it once I learn more :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T05:03:49.673", "Id": "25069", "ParentId": "25068", "Score": "7" } }, { "body": "<p>Building upon <a href=\"https://codereview.stackexchange.com/a/25069/24141\">@p.s.w.g</a>'s excellent answer, you can similarly use the <code>? :</code> conditional operator within the <code>while-loop's</code> condition to manipulate the value of <code>nHeads</code>.</p>\n\n<pre><code>public class HavingFun {\n private static final int CONSECUTIVE_HEADS_LIM = 3;\n private static java.util.Random rgen = new Random(System.currentTimeMillis());\n public static void main(String[] args) {\n int nFlips = 1;\n int nHeads = 0;\n while ((nHeads = (rgen.nextBoolean() ? ++nHeads : 0)) &lt; CONSECUTIVE_HEADS_LIM) {\n System.out.println(nHeads == 0 ? \"Tails\" : \"Heads\");\n nFlips++;\n }\n System.out.printf(\"Heads\\nYou needed %d flips to get %d consecutive heads.\",\n nFlips, nHeads);\n }\n}\n</code></pre>\n\n<p>The condition reads: if <code>rgen.nextBoolean</code> is true, <em>increment <code>nHeads</code> and use the new value</em> (hence the <code>++</code> preceding the variable, otherwise known as a pre-increment operator) for <code>nHeads</code>, else set <code>nHeads</code> to <code>0</code>. Within the loop, we check if <code>nHeads</code> was reset to <code>0</code> or not, printing <code>Tails</code> or <code>Heads</code> accordingly.</p>\n\n<p>You can also see that the loop exits upon the last throw of <code>Heads</code>, and that explains why the final output statement has an extra <code>Heads</code> line. For the same reason, <code>nFlips</code> is initialized as <code>1</code>, since it will need to be incremented at the end anyways.</p>\n\n<p>I think <a href=\"https://codereview.stackexchange.com/a/25069/24141\">@p.s.w.g</a>'s answer is a good start for introductory Java programming, whereas my solution is just a shorter solution, not necessary better (given the extra explanations above). Hope you'll have a better idea of nifty tips-and-tricks in Java programming!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T12:01:27.747", "Id": "38837", "Score": "1", "body": "+1 for the insight that your code is harder to read :) I think in general if there are no other requirements you should always optimize for readability and nothing else. Any further optimization should be addressed if you run in trouble with your current code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T09:50:44.213", "Id": "25102", "ParentId": "25068", "Score": "5" } } ]
{ "AcceptedAnswerId": "25069", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T03:02:04.343", "Id": "25068", "Score": "5", "Tags": [ "java", "performance" ], "Title": "Coin flipping code" }
25068
<p>I'm writing a program that downloads stuff from the internet. While the program is working fine, I want to get one critical part reviewed. I use System.Diagnostics.StopWatch object to measure the time taken for the ns (NetworkStream) object to read the bytes in buffer. I then divide the number of elapsed seconds in stopwatch by number of bytes received to calculate the speed of my download in KBPS.</p> <p>However, this method is giving me some extraordinarily large speeds (in excess of 8000KBPS), whereas I know that my internet bandwidth is not that fast. Is there anything wrong with this method? If not, then what is the correct way of getting the download speed? Here is my code:</p> <pre><code>while(true) //(bytesToRead&gt;0) { sw.Start(); int n = ns.Read(buffer, 0, buffer.Length); sw.Stop(); Speed = (float)n / sw.Elapsed.TotalSeconds; if (n==0) break; fs.Write(buffer,0,n); BytesRead+=n; //TODO: Persist the bytesRead object somewhere, so that it can be taken back for resumes bytesToRead -= n; OnProgress(this,new System.EventArgs()); if (Status == DownloadStatusEnum.Paused) break; } </code></pre>
[]
[ { "body": "<blockquote>\n <p>I then divide the number of elapsed seconds in stopwatch by number of\n bytes received to calculate the speed of my download in KBPS.</p>\n</blockquote>\n\n<p>Just an idea: NetworkStream.Read returns the number of bytes received. If you divide this with the number of seconds, you'll get the download speed in bytes per second.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T20:02:26.317", "Id": "38807", "Score": "0", "body": "Yes, but even if I divide by 1000, the number was too high to be a realistic estimate of the actual KBPS of my internet connection." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T15:06:10.457", "Id": "25076", "ParentId": "25070", "Score": "0" } }, { "body": "<p>Your summary complaint is that you're measuring short term xfer rate from system buffers to user space, rather than long term xfer rate from distant server to local network interface.</p>\n\n<p>After a few roundtrips, TCP opens the congestion window and can have many KiB of data in flight. I don't know what your <code>buffer.length</code> is, but you make it sound like it is short enough that you're not blocking on read. That is, <code>ns.Read()</code> finds quite a lot of data buffered at the OS level, and returns a buffer's worth of it at once, so that your timing represents local CPU / memory bandwidth rather than network bandwidth.</p>\n\n<p>The simplest remedy is to record initial starting time and <em>don't touch it</em>, report cumulative bytes read over cumulative elapsed time.</p>\n\n<p>If your residential ISP does traffic shaping, and you want the display to reflect the fact that the first 30 seconds goes at 3 Mbps but longer downloads go at 1 Mbps, then keep a circular buffer of the last dozen or so timestamps, and use that to report on recent progress. Old measurements will age out, so after a while they will no longer affect the display.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T19:51:47.753", "Id": "25085", "ParentId": "25070", "Score": "5" } } ]
{ "AcceptedAnswerId": "25085", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T07:14:05.773", "Id": "25070", "Score": "6", "Tags": [ "c#", "networking" ], "Title": "Better way to code download speed calcuation" }
25070
<p>For a WordPress login form I have written a small plugin. It adds a checkbox with a unique name to the form and if that name is not present in the login POST request it just dies.</p> <p>The idea is preventing <a href="http://www.metasploit.com/modules/auxiliary/scanner/http/wordpress_login_enum" rel="nofollow noreferrer">scripted attacks made for regular WordPress login forms</a>.</p> <p>The PHP code is okay (imho), but I think the JavaScript code looks rather … inelegant. Everything works as expected, it is just not beautiful. What could I improve?</p> <pre><code>&lt;?php # -*- coding: utf-8 -*- /** * Plugin Name: T5 Unique Log-in Field * Description: Adds a checkbox with a unique name to the login form to prevent scripted log-in attempts. * Plugin URI: * Version: 2013.04.14 * Author: Thomas Scholz * Author URI: http://toscho.de * Licence: MIT * License URI: http://opensource.org/licenses/MIT */ add_action( 'login_init', 't5_unique_login_field' ); add_action( 'login_footer', 't5_unique_login_field' ); /** * Add a checkbox with a unique name to the login form. * * @wp-hook login_init * @wp-hook login_footer * @return void */ function t5_unique_login_field() { if ( ! empty ( $GLOBALS['interim_login'] ) ) return; if ( defined( 'LOGGED_IN_SALT' ) ) $salt = constant( 'LOGGED_IN_SALT' ); else $salt = filemtime( __FILE__ ); $unique = md5( $_SERVER[ 'HTTP_HOST' ] . $salt ); if ( 'POST' === $_SERVER[ 'REQUEST_METHOD' ] ) { if ( ! isset ( $_POST[ 'log' ] ) ) return; if ( empty ( $_POST[ $unique ] ) or 'on' !== strtolower( $_POST[ $unique ] ) ) exit; return; } ?&gt; &lt;script&gt; var unique = '&lt;?php echo $unique; ?&gt;', checkBox = document.createElement( 'input' ), paragraph = document.createElement( 'p' ), label = document.createElement( 'label' ), labelText = document.createTextNode( ' I am human' ); checkBox.setAttribute( 'name', unique ); checkBox.setAttribute( 'type', 'checkbox' ); checkBox.setAttribute( 'id', unique + '_id' ); label.setAttribute( 'for', unique + '_id' ); label.appendChild( checkBox ); label.appendChild( labelText ); paragraph.appendChild( label ); paragraph.setAttribute( 'style', 'clear:both;float:none' ); // get the same font style as the last checkbox paragraph.setAttribute( 'class', 'forgetmenot' ); document.getElementById( 'loginform' ).appendChild( paragraph ); &lt;/script&gt; &lt;?php } </code></pre> <p>Screenshots: </p> <p>Before plugin activation</p> <p><img src="https://i.stack.imgur.com/Ny55Z.png" alt="enter image description here"></p> <p>After plugin activation</p> <p><img src="https://i.stack.imgur.com/ZqEn8.png" alt="enter image description here"></p>
[]
[ { "body": "<p>This is not meant to be a comprehensive answer:</p>\n\n<p>If you do not want a bug that happens only in some browsers and only some of the time, use a <a href=\"https://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html\">safe, conservative format as an id</a></p>\n\n<pre><code>checkBox.setAttribute( 'id', unique + '_id' );\n</code></pre>\n\n<p>If id is a random 64-bit integer or a GUID in the following form (b362e877-95c3-4e88-99dc-ceb4600639b5), then you would want id to be <code>'id_' + unique</code> instead of <code>unique + '_id'</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T07:28:09.600", "Id": "25098", "ParentId": "25071", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T07:32:58.293", "Id": "25071", "Score": "2", "Tags": [ "javascript", "optimization", "form" ], "Title": "Add checkbox with label to a form" }
25071
<p>with below query i'm getting the results that i want but it's quite slow taking nearly 0.2 seconds (on an i5 machine). Is there a more optimized way to get the same results.</p> <p>Basically this query fetches the last 20 rows in the table and shows only one row per yzr.name and orders by yzr.favorite_count </p> <pre><code>SELECT gzt.name AS gazete, yz.*, yzr.name, yzr.gazete_id, yzr.yazar_image_link, yzr.favorite_count, DATE_FORMAT(tarih,'%d.%m.%Y') As formatted_tarih FROM yazar AS yzr INNER JOIN yazi yz ON yzr.id=yz.yazar_id INNER JOIN gazete gzt ON yzr.gazete_id = gzt.id GROUP By yzr.name ORDER BY yzr.favorite_count DESC LIMIT 20 OFFSET 0 </code></pre>
[]
[ { "body": "<p>As you have no range specific functions applied in the <code>SELECT</code> clause I don't understand why you need the <code>GROUP BY</code> clause.</p>\n\n<p>The expression is way to simple to be optimized (its hard to see how you can go wrong). </p>\n\n<p>For any optimization advice you will need to provide the table definitions and an explanation of the <code>Normal Form</code> the data has been decomposed to. Optimization of SQL queries usually lies in the table structure and not decomposing the data to full actualized third <code>Normal Form</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T15:02:07.753", "Id": "25075", "ParentId": "25074", "Score": "2" } } ]
{ "AcceptedAnswerId": "25075", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T10:06:56.170", "Id": "25074", "Score": "2", "Tags": [ "optimization", "mysql", "sql" ], "Title": "Is there a more optimized way for this MySql Query" }
25074
<p>I have to write this program in java.</p> <blockquote> <p>Write a program name sorting.java that will use an array to store 10,000 randomly generated numbers (ranging from 1 to 10,000 no repeat number).</p> </blockquote> <p>Here is what I have so far:</p> <pre><code>public class Sort { public static void main(String[] args) { Random rgen = new Random(); // Random number generator int[] nums = new int[10,000]; //array to store 10000 random integers (1-10,000) //--- Initialize the array to the ints 1-10,000 for (int i=0; i&lt;nums.length; i++) { nums[i] = i; } //--- Shuffle by exchanging each element randomly for (int i=0; i&lt;nums.length; i++) { int randomPosition = rgen.nextInt(nums.length); int temp = nums[i]; nums[i] = nums[randomPosition]; nums[randomPosition] = temp; } //Print results for (int i = 0; i &lt; nums.length; i++){ System.out.println(nums[i]); System.out.println("\n"); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T21:50:25.620", "Id": "38818", "Score": "0", "body": "I would like to thank everyone as all your post have been excellent." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-13T05:31:44.280", "Id": "82395", "Score": "1", "body": "Three remarks: 1) `Sort` is just the opposite of `Shuffle`, which is what you should have named the class. 2) The comma in `new int[10,000]` is illegal syntax. 3) Your braces don't match." } ]
[ { "body": "<p>Nearly right. </p>\n\n<p>List item</p>\n\n<p>You want:</p>\n\n<pre><code>for (int i=0; i&lt;nums.length; i++) {\n nums[i] = i + 1;\n}\n</code></pre>\n\n<p>or you'll get 0-9,999, the question says 1-10,000</p>\n\n<p>Also, the print loop is missing a closing <code>}</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T16:42:19.110", "Id": "25078", "ParentId": "25077", "Score": "4" } }, { "body": "<p>You can simplify you shuffle like this:</p>\n\n<pre><code>Collections.shuffle(Arrays.asList(nums));\n</code></pre>\n\n<p>This will replace the complete for loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T17:18:14.100", "Id": "25079", "ParentId": "25077", "Score": "12" } }, { "body": "<p><em>To add to what others have said so far</em> </p>\n\n<p>One small thing about coding style!</p>\n\n<p>Try to keep your variable names as consistent as possible.</p>\n\n<blockquote>\n <p><code>randomPosition</code> versus <code>rgen</code></p>\n</blockquote>\n\n<p>If you choose to use <em>full words in camelCase</em>, try keeping the same style everywhere. </p>\n\n<p>So <code>rgen</code> should be change to something, at least like <code>rGen</code>, but even better to <code>randomGenerator</code>. Also the variable <code>nums</code> should be change to <code>numbers</code>.</p>\n\n<p>This will keep the code cleaner and increases readability.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T17:26:57.817", "Id": "25080", "ParentId": "25077", "Score": "1" } }, { "body": "<p>Apart from the compiler errors, implementation issues and code style suggestions others have pointed out, <strong>your shuffling algorithm is fundamentally flawed</strong>.</p>\n\n<p>Wikipedia <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Implementation_errors\" rel=\"nofollow noreferrer\">explains it nicely</a>:</p>\n\n<blockquote>\n <p>Similarly, always selecting i from the entire range of valid array\n indices on every iteration also produces a result which is biased,\n albeit less obviously so. This can be seen from the fact that doing so\n yields n<sup>n</sup> distinct possible sequences of swaps, whereas there are only\n n! possible permutations of an n-element array. Since n<sup>n</sup> can never be\n evenly divisible by n! when n > 2 (as the latter is divisible by n−1,\n which shares no prime factors with n), some permutations must be\n produced by more of the n<sup>n</sup> sequences of swaps than others. As a\n concrete example of this bias, observe the distribution of possible\n outcomes of shuffling a three-element array [1, 2, 3]. There are 6\n possible permutations of this array (3! = 6), but the algorithm\n produces 27 possible shuffles (3<sup>3</sup> = 27). In this case, [1, 2, 3], [3,\n 1, 2], and [3, 2, 1] each result from 4 of the 27 shuffles, while each\n of the remaining 3 permutations occurs in 5 of the 27 shuffles.</p>\n</blockquote>\n\n<p>To demonstrate this bias, I changed your code to only create three elements per array and ran it sixty million times. Here are the results:</p>\n\n<pre><code>Permutation Occurences \n[1, 2, 3]: 8884128\n[2, 3, 1]: 11111352\n[3, 1, 2]: 8895318\n[3, 2, 1]: 8891062\n[2, 1, 3]: 11107744\n[1, 3, 2]: 11110396\n</code></pre>\n\n<p>If your shuffling algorithm were correct, one would expect a relatively uniform distribution. However, the standard deviation is huge at about 1215764 (or ~2%) which should ring alarm bells. For comparison, here are the results of using the proven <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow noreferrer\">Fisher–Yates shuffle</a>:</p>\n\n<pre><code>Permutation Occurences \n[1, 2, 3]: 10000566\n[2, 3, 1]: 9998971\n[3, 1, 2]: 10000640\n[3, 2, 1]: 10000873\n[2, 1, 3]: 9998249\n[1, 3, 2]: 10000701\n</code></pre>\n\n<p>As one would expect from a correct implementation, the standard deviation is low at about 1105 (or ~0.002%).</p>\n\n<p>Here's the correct implementation for reference:</p>\n\n<pre><code>for (int i = numbers.length - 1; i &gt; 0; i--)\n{\n int swapIndex = random.nextInt(i + 1);\n int temp = numbers[i];\n numbers[i] = numbers[swapIndex];\n numbers[swapIndex] = temp;\n}\n</code></pre>\n\n<p>However, another problem presents itself even with a correct shuffling algorithm: </p>\n\n<p><strong>A pseudo-random number generator <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Pseudorandom_generators:_problems_involving_state_space.2C_seeding.2C_and_usage\" rel=\"nofollow noreferrer\">is limited by its <em>period</em></a>, i.e. it can only produce a certain number of unique shuffles:</strong></p>\n\n<blockquote>\n <p>[...] a shuffle driven by such a generator cannot possibly produce more distinct permutations than the generator has distinct possible states.</p>\n</blockquote>\n\n<p><code>java.util.Random</code> <a href=\"https://stackoverflow.com/a/453554/1106367\">has a period no larger than 2<sup>48</sup></a> which is unable to produce an overwhelming majority of the 10000! (approximately 2.85 × 10<sup>35659</sup>) possible permutations of your array. The <a href=\"http://www.javamex.com/tutorials/random_numbers/securerandom.shtml\" rel=\"nofollow noreferrer\">default implementation of <code>SecureRandom</code></a> isn't much better at no more than 2<sup>160</sup>. </p>\n\n<p>In the case of such a long array, the <a href=\"http://en.wikipedia.org/wiki/Mersenne_twister\" rel=\"nofollow noreferrer\">Mersenne Twister</a> is a more adequate choice with a period of 2<sup>19937</sup>-1 and excellently uniform distribution (although still not enough to produce all the possible permutations. At some point, it makes more sense to look into true random number generators that are based on physical phenomena). </p>\n\n<p>So, in my opinion, the real moral of the story is this:</p>\n\n<blockquote>\n <p>Take special care when working with randomness or pseudorandomness as the consequences of tiny mistakes can be hard to detect but devastating. Use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#shuffle%28java.util.List%29\" rel=\"nofollow noreferrer\"><code>Collections.shuffle</code></a> instead of reinventing the wheel. For your (presumably) casual use, you might not need to worry about these inadequacies at all. On the other hand, it doesn't hurt to be aware of them.</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T17:51:14.693", "Id": "25081", "ParentId": "25077", "Score": "50" } } ]
{ "AcceptedAnswerId": "25081", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T16:25:48.203", "Id": "25077", "Score": "15", "Tags": [ "java", "sorting", "random" ], "Title": "Sorting 10,000 unique randomly-generated numbers" }
25077
<p>I've found two ways of writing the same program (one that only uses local variables, but no methods other than the main one) and other that uses one instance variable that is used in two methods.</p> <p>This program aims to simulate the radioactive decay of atoms and uses a random number generator.</p> <p>Here are the two versions of the code:</p> <pre><code>/* * File: HalfLife.java * * This program simulates the decaying process of radioactive atoms that * have a half life of one year. The program will show the amount of atoms * remaining at the end of each year until all atoms has decayed */ import acm.program.*; import acm.util.RandomGenerator; public class HalfLife extends ConsoleProgram { /* Number of atoms */ private static final int NATOMS = 10000; public void run() { println("There are " + NATOMS + " atoms initially."); int remainingAtoms = NATOMS; int year = 0; while (remainingAtoms &gt; 0) { /* Simulate decaying process for each atom. Each atom has a 50% chance of decay. */ for (int i = remainingAtoms; i &gt; 0; i--) { if (rgen.nextBoolean()) { remainingAtoms--; } } year++; println("There are " + remainingAtoms + " atoms at the end of year " + year); } } /* Create an instance variable for the random number generator */ private RandomGenerator rgen = RandomGenerator.getInstance(); } </code></pre> <p>That one had only local variables, now for the other one (I removed comments in this one since it's redundant):</p> <pre><code>public class AtomicReduction extends ConsoleProgram { private static final int BEG_ATOMS = 10000; public void run () { int nYears = 1; println ("There are " + BEG_ATOMS + " atoms in the beginning"); while (nAtoms &gt; 0) { println ("There are " + (atomicRed (nAtoms)) + " atoms at the end of year " + nYears); nYears++; } } private int atomicRed (int initialAtoms) { for (int i = 0; i &lt; initialAtoms; i++) { boolean isReduced = rGen.nextBoolean(); if (isReduced) nAtoms--; } return nAtoms; } private int nAtoms = BEG_ATOMS; private RandomGenerator rGen = RandomGenerator.getInstance(); } </code></pre> <p>Which is "the better" version? And why? I kind of prefer the first one because it keeps everything local, however the latter has more decomposition and can be potentially easier to understand (with proper comments).</p> <p>Note: this makes use of ACM libraries so the main method is <code>public void run</code>.</p>
[]
[ { "body": "<p>Firstly, some minor nitpicks on your code: </p>\n\n<pre><code> for (int i = remainingAtoms; i &gt; 0; i--) {\n</code></pre>\n\n<p>Why are you counting down instead of up? I can see why after careful inspection, but a comment would be useful.</p>\n\n<pre><code> println (\"There are \" + (atomicRed (nAtoms)) + \" atoms at the end of year \" + nYears);\n</code></pre>\n\n<p>You've violated Command-Query Seperation. <code>atomicRed</code> changes the state of the object, and so it really shouldn't return information about the object. It certainly shouldn't appear in the middle of a print a call.</p>\n\n<pre><code> boolean isReduced = rGen.nextBoolean();\n if (isReduced) nAtoms--;\n</code></pre>\n\n<p>Why did you seperate <code>isReduced</code> onto its own line?</p>\n\n<p>As for your actual question: people differ on this point. My general theory is that seperating out functions is good. But don't move previously local variables to the class in order to do that. Doing so only makes your class harder to follow. </p>\n\n<p>In this case, I suggest something like</p>\n\n<pre><code>while(nAtoms &gt; 0)\n{\n nAtoms = remainingAtomsAfterYear(nAtoms);\n println(\"There are \" + nAtoms + \" atoms at the end of year \" + nYears);\n nYears++;\n}\n</code></pre>\n\n<p>This allows you to pull the logic regarding atom decay into a separate function, but avoids storing state on the class. I think this actually gets the best of both approaches.</p>\n\n<p>Alternately, you could do:</p>\n\n<pre><code>while(!atoms.empty())\n{\n atoms.simulateYear();\n println(\"There are \" + atoms.count() + \" atoms at the end of year \" + atoms.years());\n}\n</code></pre>\n\n<p>And move all the logic into another class. That's overkill here, but is helpful if the state gets more complicated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T20:25:52.313", "Id": "38809", "Score": "0", "body": "Depending on the stage of learning, I would say moving the logic into its own class would be very helpful. You could even encapsulate the decay logic into a [strategy](http://en.wikipedia.org/wiki/Strategy_pattern) to allow different rates of decay. Learning these good habits early is easier if you're ready for it. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T20:40:27.720", "Id": "38812", "Score": "0", "body": "\"You've violated Command-Query Seperation. atomicRed changes the state of the object, and so it really shouldn't return information about the object. It certainly shouldn't appear in the middle of a print a call.\" - Why is this bad? Does it make the code harder to understand or is prone to bugs?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T20:43:42.267", "Id": "38813", "Score": "1", "body": "@AntonioRicardoDieguesSilva, it makes code easier to follow which helps it be less prone to bugs. As you've used the code it looks like atomicRed() is just returning some information that you are printing. But atomicRed() is actually the part that does all the work. It would be really easy to miss that its there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T20:43:56.233", "Id": "38814", "Score": "0", "body": "As for creating a class just for the logic that seems an interesting idea but I'm just learning to build java classes. Ill keep that idea in mind as I'll progress in my studies! Thanks to both of you for your input!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T20:45:39.153", "Id": "38815", "Score": "0", "body": "@AntonioRicardoDieguesSilva, good luck with your studies!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T20:09:00.063", "Id": "25088", "ParentId": "25083", "Score": "4" } } ]
{ "AcceptedAnswerId": "25088", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T19:24:21.870", "Id": "25083", "Score": "1", "Tags": [ "java", "random" ], "Title": "Simulating the radioactive decay of atoms using a random number generator" }
25083
<p>Basically, I'm performing an <code>if</code> statement on an array based on the returned value</p> <pre><code>&lt;?php if($array[1]&gt;10000 AND $array[1]&lt;50000){ $selling = $array[1] - 250; } elseif($array[1]&gt;50000 AND $array[1]&lt;100000){ $selling = $array[1] - 500; } else{ $selling = $array[1] - 100; } $buying = $array[1] - 1000; if($array[1]&gt;=10000){ $buying = $buying-1000; if($array[1]&gt;=20000){ $buying = $buying-1000; if($array[1]&gt;=30000){ $buying = $buying-1000; } if($array[1]&gt;=40000){ $buying = $buying-1000; } if($array[1]&gt;=50000){ $buying = $buying-750; } if($array[1]&gt;=60000){ $buying = $buying-500; } if($array[1]&gt;=70000){ $buying = $buying-500; } } } ?&gt; </code></pre> <p>As you can see it's VERY messy, would anyone be able to point me in the correct direction for cleaning this up please?</p>
[]
[ { "body": "<p>First of all, replace <code>$array</code> with a descriptive name, and copy <code>$array[1]</code> into some other descriptive name.</p>\n\n<p>Next, create a new array that describes those price ranges, in $10k increments, along with 1000, 750, 500, whatever. Give them a descriptive name, too, perhaps <code>$discount</code>. Now you can map a price range to a discount (or whatever business logic it is that your problem focuses on). Have a <code>for</code> loop scan through the map until it finds a matching price range, and apply the corresponding discount. For bonus points, wrap all that logic in a function, and have a unit test invoke the function with several different prices.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T19:59:15.850", "Id": "25087", "ParentId": "25084", "Score": "2" } }, { "body": "<p>I seem to get the feeling you are either not comfortable using maps as others have suggested here...so why not throw in a switch instead?</p>\n\n<pre><code>$volume = $array[1];\n\nif($volume &gt; 10000 &amp;&amp; $volume &lt; 50000){\n $selling = $volume - 250;\n} else if($volume &gt; 50000 &amp;&amp; $volume &lt; 100000){\n $selling = $volume - 500;\n} else {\n $selling = $volume - 100;\n}\n\n$buying = $volume - 1000;\n\nswitch($volume){\n case 10000:\n case 20000:\n case 30000:\n case 40000:\n $buying = $buying - 1000; break;\n case 50000:\n $buying = $buying - 750; break;\n case 60000:\n case 70000:\n $buying = $buying - 500; break;\n default:\n $buying = $buying;\n}\n</code></pre>\n\n<p><strong>REVISIT 01/26/2015</strong>: Revisiting this to say that I would now rewrite this code as follows:</p>\n\n<pre><code>function bound_check($bounds, $bound_check, $default_value) {\n $return_data = NULL;\n foreach($bounds as $bound){\n if($bound_check &gt;= $bound[0] &amp;&amp; $bound_check &lt;= $bound[1]){\n $return_data = $bound_check - $bound[2];\n }\n }\n return $return_data ?: $default_value;\n}\n\n$selling_bounds = [\n [10000, 50000, 250],\n [50000, 100000, 500],\n];\n\n$buying_bounds = [\n [10000, 40000, 1000],\n [50000, 50000, 750],\n [60000, 70000, 500]\n]\n\n$selling = bound_check($selling_bounds, $array[1], $volume - 100);\n$buying = bound_check($selling_bounds, $array[1], $volume - 1000);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-26T18:37:38.697", "Id": "142493", "Score": "2", "body": "Your recent addition to your answer would probably be a good candidate for a second answer. Alternatively, since edits are not automatically part of the notification trigger to the OP, this comment itself will notify Curtis that this answer has changed. Note, on Code Review it is common, and acceptable, to post multiple answers to questions if the answers address things differently, or address different components of the original question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-27T08:30:59.663", "Id": "142595", "Score": "0", "body": "Ah! Thanks @rolfl. I was not aware that multiple answers were acceptable here. Will keep that in mind with future edits" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T14:01:43.673", "Id": "25105", "ParentId": "25084", "Score": "3" } } ]
{ "AcceptedAnswerId": "25105", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T19:45:53.313", "Id": "25084", "Score": "0", "Tags": [ "php" ], "Title": "Cleaner method of doing IF" }
25084
<p>Here's my code. Please review it for correctness, readability and efficiency. If you think it can be improved also let me know. This code works fine for positive numbers but doesn't for negative. How can I change it ? Any comments for improvement will be appreciated. </p> <pre><code>int sum(int a, int b) { int sum = 0; int carry = 0; int mask = 1; sum = doAdd(a,b,mask,carry, 0); return sum; } int doAdd(int a,int b, int mask, int carry, int sum) { int aBit = a&amp;mask; int bBit = b&amp;mask; if(mask&lt;a||mask&lt;b||carry!=0) { sum = sum | (carry^aBit^bBit); carry = (carry==0) ? (aBit&amp;bBit) : (carry&amp;a|carry&amp;b); mask = mask &lt;&lt; 1; if(carry!=0) carry = mask; return (doAdd(a,b,mask,carry, sum)); } return sum; } </code></pre>
[]
[ { "body": "<p>Nice.</p>\n\n<p>Start by following Java <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-139411.html#16712\" rel=\"nofollow\">Code Conventions</a>; 8.2 asks for spaces around binary operators.</p>\n\n<p>Add a unit test with nested loops that compares your results with <code>+</code> results.</p>\n\n<p>There's no need for temp variables (though they <em>do</em> have nice self documenting names!) in <code>sum()</code>; it would be enough to just have it invoke the helper function like this: <code>return doAdd(a, b, 0x1, 0, 0)</code>. Consider renaming <code>doAdd</code> to <code>sum1</code> to more clearly show how they're related. Consider renaming the final argument to <code>acc</code> or <code>accumulator</code>.</p>\n\n<p>Adding a comment (or an <code>assert</code>) that points out that <code>mask</code> only has a single bit on would be an aid to the reader. Another way to do that would be to change the API so <code>currentBitPosition</code> is what's passed in, and then immediately assign <code>mask = 1 &lt;&lt; currentBitPosition</code>.</p>\n\n<p>There seems to be a typo - looks like you wanted <code>carry &amp; aBit...</code>. Oh, wait, now I see, carry can be as large as mask. Wow, that's surprising. Rename it to carryMask. Better yet, change the type to boolean to minimize reader surprise. Maybe refactor to:</p>\n\n<pre><code>...\nsum |= carry ^ aBit ^ bBit;\ncarry = carry ? (aBit | bBit) : (aBit &amp; bBit);\nmask &lt;&lt;= 1; (or: mask *= 2)\n...\n</code></pre>\n\n<p>As far as signed arithmetic goes, you're going to have to declare your word length, and turn the comparison between <code>mask</code> and <code>a</code> into a test of whether <code>mask</code> is about to overflow. Good luck!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T21:34:31.780", "Id": "25090", "ParentId": "25089", "Score": "0" } }, { "body": "<p>Your algorithm looks good, but the best algorithm (as far as I know) is following:</p>\n\n<ol>\n<li>Add 2 binary numbers without considering carry (an xor operation)</li>\n<li>Construct the difference with the actual solution, i.e., construct a number in the carry positions (a and operation then a left shift)</li>\n<li>Add the result of step 1 with step 2 (by recursion), until step2 is 0.</li>\n</ol>\n\n<p>The code will look like this:</p>\n\n<pre><code>int add(int a, int b) {\n if (b == 0) return a;\n return add(a ^ b, (a &amp; b) &lt;&lt; 1);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T03:26:17.863", "Id": "38921", "Score": "0", "body": "why does you step#2 work ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T05:04:02.977", "Id": "38925", "Score": "0", "body": "We can mathametically prove that the algorithm will converge (step 2 will eventually become zero)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T05:29:11.203", "Id": "38929", "Score": "0", "body": "The proof goes like this: if we can prove that (a & b) << 1) will have less or equal number of 1 bits as b, then the algorithm will converge. Since \"b is bitwise and\" with a, it will always have less or equal number of 1 bits than b. So, the algorithm will converge (WORST CASE SCENARIO: a has same 1 bit positions as b for all the recursive calls, even then because of the left shift (a&b)<<1 will eventtually have less number of 1 bit than b). I did not want to tap into theoritical computer science, but hope this helps :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T01:06:42.840", "Id": "25093", "ParentId": "25089", "Score": "3" } }, { "body": "<p>Formal tip : as you past <em>zero</em> and do nothing with <em>sum</em> you can remove it : </p>\n\n<pre><code>int sum(int a, int b)\n {\n int carry = 0;\n int mask = 1;\n return doAdd(a,b,mask,carry, 0);\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T07:05:40.383", "Id": "25097", "ParentId": "25089", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T20:44:51.690", "Id": "25089", "Score": "1", "Tags": [ "java" ], "Title": "Code Review for Adding two numbers without using the + operator" }
25089
<p>I feel this is deeply inelegant, but I really want the option of classical inheritance in the future. How could this be written better. FYI animation here is from <a href="http://www.greensock.com/gsap-js/" rel="nofollow">GSAP</a> if you are curious.</p> <pre><code>class Modal angular.element(document).ready =&gt; @modalElem = document.getElementById 'modal' @overlayElem = document.getElementById 'overlay' @isOpen = false @getWindowDim : -&gt; return dim = height : window.innerWidth or document.documentElement.clientWidth width : window.innerHeight or document.documentElement.clientHeight @openModal : (attrs) -&gt; unless @isOpen @isOpen = true width = attrs.width height = attrs.height content = attrs.content wDim = @getWindowDim() @modalElem.style.width = 0 @modalElem.style.height = 0 @overlayElem.style.display = 'block' TweenLite.to @modalElem, 0.75, width : width height : height marginTop : (height/-2) marginLeft : (width/-2) opacity : 1 ease : Back.easeOut @ @closeModal : -&gt; if @isOpen @isOpen = false TweenLite.to @modalElem, 0.33, width : 0 height : 0 marginTop : 0 marginLeft : 0 opacity : 0 ease : Back.easeOut onComplete : =&gt; @overlayElem.style.display = 'none' @ modal = angular.module 'modal' modal.directive 'openmodal', -&gt; return (scope, element, attrs) -&gt; element.bind 'click', -&gt; Modal.openModal attrs modal.directive 'closemodal', -&gt; return (scope, element, attrs) -&gt; element.bind 'click', -&gt; Modal.closeModal() </code></pre>
[]
[ { "body": "<p>Honestly, I'd recommend against creating a class. You <em>may</em> want classical inheritance in the future, but right now it's not necessary. Premature optimization rarely benefits anyone. Besides, if you do want classical inheritance later, it's pretty trivial to convert the code.</p>\n\n<p>I'd just write it as simply as possible for now, and see what I'll actually need later:</p>\n\n<pre><code>do -&gt; # wrap in an IIFE\n # simple local variables\n isOpen = false\n modalElem = null\n overlayElem = null\n modal = angular.module 'modal'\n\n angular.element(document).ready -&gt;\n modalElem = document.getElementById 'modal'\n overlayElem = document.getElementById 'overlay'\n\n open = (attrs) -&gt;\n return if isOpen # return early\n isOpen = true\n\n options =\n opacity: 1\n ease: Back.easeOut\n height: attrs.height\n width: attrs.width\n marginTop: attrs.height / -2\n marginLeft: attrs.width / -2\n\n modalElem.style.width = 0\n modalElem.style.height = 0\n overlayElem.style.display = 'block'\n TweenLite.to modalElem, 0.75, options\n\n close = -&gt;\n return unless isOpen # return early\n TweenLite.to modalElem, 0.33,\n width: 0\n height: 0\n marginTop: 0\n marginLeft: 0\n opacity: 0\n ease: Back.easeOut\n onComplete: -&gt;\n overlayElem.style.display = 'none'\n isOpen = false # moved this here, so it flips when the modal's fully closed\n\n\n modal.directive 'openmodal', -&gt;\n (scope, element, attrs) -&gt;\n element.bind 'click', -&gt; open attrs\n\n modal.directive 'closemodal', -&gt;\n (scope, element, attrs) -&gt;\n element.bind 'click', -&gt; close()\n</code></pre>\n\n<p>If you're compiling this as a single file with CoffeeScript's default IIFE wrapper, you can skip the <code>do -&gt;</code> and indentation; it'll be added automatically.</p>\n\n<hr>\n\n<p>If you don't want to take the approach above, here are some tips for your current code:</p>\n\n<p>Using explicit <code>return</code> is only necessary if you want something <em>other</em> than the last evaluated expression to be returned. In you open/close functions, it'd be beneficial to simply return early (like I do in the code above) instead of having a big <code>if</code> branch.</p>\n\n<p>Also, a neat trick:</p>\n\n<pre><code>getWindowDim : -&gt;\n return dim =\n height : window.innerWidth or document.documentElement.clientWidth\n width : window.innerHeight or document.documentElement.clientHeight\n</code></pre>\n\n<p>can be written as</p>\n\n<pre><code>getWindowDim : -&gt;\n height : window.innerWidth or document.documentElement.clientWidth\n width : window.innerHeight or document.documentElement.clientHeight\n</code></pre>\n\n<p>The <code>return</code> is implicit, there's no need for a variable assignment, and CoffeeScript will automatically make an object.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T16:25:40.947", "Id": "38852", "Score": "0", "body": "actually it turns out `getWindowDim` is not consumed at all! In your finished example, please replace `height` and `width` with the version from `attrs` and I will accept your answer. +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T16:33:34.463", "Id": "38853", "Score": "0", "body": "@Fresheyeball Whoops - fixed now" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T03:00:03.427", "Id": "71042", "Score": "0", "body": "It's a trend I don't really like in coffeescript (and ruby). People tends to write as less characters as possible and it alters the readability of the code. I'm not sure that getting rid of the `return`really helps clarity. When the `return`keyword is present, it's clear that the function is meant to return something. It might be personal, but I'm pretty sure I'm not the only one out there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-12T03:59:33.650", "Id": "71214", "Score": "0", "body": "@jackdbernier I know what you're saying. But it also depends on how you view the code overall. If you regard it as more functional (as you can with ruby and js/cs), variables and function calls become interchangeable; a function just _is_ its return value - and all functions always return something, even if it's `undefined`. (Obviously, this looks better in languages - like ruby - where you can leave out the `()` in calls). Naming is key, though; nouns for pseudo-variable functions, verbs for _function_ functions (i.e. the above should be called `windowDimensions` without the `get` prefix)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T14:30:20.153", "Id": "25106", "ParentId": "25092", "Score": "2" } } ]
{ "AcceptedAnswerId": "25106", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T23:54:01.093", "Id": "25092", "Score": "0", "Tags": [ "coffeescript", "angular.js" ], "Title": "coffeescript and angular directive" }
25092
<p>How can I optimize this code to have fewer loops and return values for unit testing?</p> <pre><code> public class Diamond { public void DiamondShape(int num) { for(int ucount=num;ucount&gt;0;ucount--) { //Loop to print blank space for(int count_sp=1;count_sp&lt;ucount;count_sp++) System.out.printf(" "); //Loop to print * for(int count_ast=num;count_ast&gt;=ucount;count_ast--) System.out.printf("* "); System.out.println(); } //Loop for lower half for(int lcount=1;lcount&lt;num;lcount++) { //Loop to print blank space for(int count_sp=0;count_sp&lt;lcount;count_sp++) System.out.printf(" "); //Loop to print * for(int count_ast=num-1;count_ast&gt;=lcount;count_ast--) System.out.printf("* "); System.out.println(); } } } </code></pre> <p>Output when <code>num</code> = 3:</p> <blockquote> <pre><code> * * * * * * * * * </code></pre> </blockquote> <p>This is how the output should be. <code>num</code> indicates the star in center line.</p>
[]
[ { "body": "<p>First of all: Use a StringBuilder instead of System.out.println so you can easily compare the result of your method with an expected output.</p>\n\n<p>Your test could look like: (I renamed you method to draw and moved the size to the instance.)</p>\n\n<pre><code>@Test\npublic void test4()\n{\n StringBuilder expected = new StringBuilder();\n expected.append( \" * \\n\" );\n expected.append( \" * * \\n\" );\n expected.append( \" * * * \\n\" );\n expected.append( \"* * * * \\n\" );\n expected.append( \" * * * \\n\" );\n expected.append( \" * * \\n\" );\n expected.append( \" * \\n\" );\n assertEquals( expected.toString(), new Diamond( 4 ).draw() );\n}\n</code></pre>\n\n<p>After you have all your tests (I have just created some for 0-4) you can try to extract some methods with duplicate code.</p>\n\n<pre><code>public class Diamond\n{\n private int size;\n\n public Diamond( int size )\n {\n this.size = size;\n }\n\n public String draw()\n {\n StringBuilder result = new StringBuilder();\n for( int ucount = size; ucount &gt; 0; ucount-- )\n {\n appendSpaces( result, ucount - 1 );\n appendStars( result, size - ucount + 1 );\n newLine( result );\n }\n\n for( int lcount = 1; lcount &lt; size; lcount++ )\n {\n appendSpaces( result, lcount );\n appendStars( result, size - lcount );\n newLine( result );\n }\n return result.toString();\n }\n\n private void newLine( StringBuilder result ) // just for better readability\n {\n result.append( \"\\n\" );\n }\n\n private void appendStars( StringBuilder result, int count ) // just for better readability\n {\n repeat( result, \"* \", count );\n }\n\n private void appendSpaces( StringBuilder result, int count ) // just for better readability\n {\n repeat( result, \" \", count );\n }\n\n private void repeat( StringBuilder result, String string, int count )\n {\n for( int c = 0; c &lt; count; c++ )\n result.append( string );\n }\n}\n</code></pre>\n\n<p>If you want to get rid of one of the loops you could even merge it to:</p>\n\n<pre><code>public String draw()\n{\n StringBuilder result = new StringBuilder();\n for( int ucount = size; ucount &gt;= -size; ucount-- )\n {\n boolean isMiddleRows = ucount == 0 || ucount == -1;\n if( isMiddleRows ) continue;\n appendSpaces( result, Math.abs( ucount ) - 1 );\n appendStars( result, size - Math.abs( ucount ) + 1 );\n newLine( result );\n }\n return result.toString();\n} \n</code></pre>\n\n<p>It's pretty cool to have enough tests do try such refactoring :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T05:22:28.107", "Id": "38928", "Score": "0", "body": "What other tests can we perform in this program" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T05:43:57.927", "Id": "38930", "Score": "0", "body": "I think checking the output for 0 to 4 is enough. Maybe you can test negative values, but in general you just need to find all border cases. -1, 0, 1, odd(3), even(4), maybe some larger number too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T11:27:34.433", "Id": "38943", "Score": "0", "body": "I am raising an exception if value is negative or a string so can we create a test case for the exception that I am raising" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T11:43:17.717", "Id": "38944", "Score": "0", "body": "http://stackoverflow.com/questions/3083161/junit-exception-testing" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T07:08:35.470", "Id": "39100", "Score": "0", "body": "how can i test methods appendStars() appendSpaces() and repeat()" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T07:10:34.417", "Id": "39101", "Score": "0", "body": "http://codereview.stackexchange.com/a/25254/21181" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T07:14:41.980", "Id": "39102", "Score": "0", "body": "I wouldn't test the append methods. As soon as the repeat is tested or used from a library the other method are trivial forwards to this method and test are useless." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T08:46:09.093", "Id": "25100", "ParentId": "25099", "Score": "5" } }, { "body": "<p>If you want to unit test the <code>System.out</code> output, you can set the <code>PrintStream</code> of <code>System.out</code> by using the <code>setOut</code> method.</p>\n\n<pre><code>private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();\n\n@Before\npublic void setUpStreams() {\n System.setOut(new PrintStream(outContent));\n}\n\n@After\npublic void cleanUpStreams() {\n System.setOut(null);\n}\n\n@Test\npublic void testOut() {\n System.out.println(\"hello\");\n System.out.println(\"hi\");\n String[] linesOfOutput = outContent.toString().split(System.getProperty(\"line.separator\"));\n assertEquals(\"hello\", linesOfOutput[0]);\n assertEquals(\"hi\", linesOfOutput[1]);\n}\n</code></pre>\n\n<p>Of course, it would be better to pass an <code>OutputStream</code> as parameter to the method and write to that.</p>\n\n<pre><code>public void writeDiamondShape ( int num, OutputStream outputStream ) {\n ...\n}\n</code></pre>\n\n<p>As for optimization</p>\n\n<pre><code>public static void writeDiamond(int num){\n int loops = num * 2 - 1;\n int stars = 1;\n for ( int i = 0; i &lt; loops; i++ ) {\n\n // Print spaces\n int spaces = Math.abs(num - i - 1);\n for ( int j = 0; j &lt; spaces; j++ ) {\n System.out.print ( \" \" );\n }\n\n // Print stars\n for ( int j = 0; j &lt; stars; j++ ) {\n System.out.print ( \"* \" );\n }\n System.out.println();\n\n // Increment / Decrement stars to print next time\n stars += (i+1 &lt; num) ? 1 : -1;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T11:07:27.657", "Id": "38836", "Score": "1", "body": "I think you should definitely go with the parameter solution if you don't want to use a string return. Changing in, err and out might lead do unexpected behavior, e.g. if you debug a failing test by System.out.print()." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T09:59:48.353", "Id": "25103", "ParentId": "25099", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T08:25:26.263", "Id": "25099", "Score": "4", "Tags": [ "java", "unit-testing", "formatting", "junit" ], "Title": "Printing a diamond-shaped figure" }
25099
<p>I wrote a Connect Four game including a AI in Clojure and since I'm rather new to Clojure, some review would be highly appreciated. It can include everything, coding style, simplifications, etc. But keep in mind the AI is not finished yet, other heuristics will be added in the near future. Currently it only cares about connected coins (not e.g. whether those 3 connected coins can actually result into 4).</p> <p>The whole source code can be found on <a href="https://github.com/naeg/clj-connect-four/tree/master/src/clj_connect_four">GitHub</a>.</p> <p>I'm asking specifically for the AI, but if you have suggestions regarding the board.clj, check_board.clj or core.clj I am happy to hear them too.</p> <p><strong>ai_minimax.clj:</strong></p> <pre class="lang-clj prettyprint-override"><code>(ns clj-connect-four.ai-minimax (:require [clj-connect-four.board :as board] [clj-connect-four.check-board :as check])) ;;; HEURISTIC FUNCTIONS ;;; ;; consider connected coins ; define score points for 2, 3 and 4 connected coins (def CC4 1048576) (def CC3 32) (def CC2 4) (defn bit-count "Checks how many bits are set on given bitboard." [board] (map #(bit-test board %) board/board-bits)) (defn get-score "Determines score of a bitboard manipulated by check-board-*." [check points] (* points (apply + (map #(count (filter true? (bit-count %))) check)))) (defn heuristic "Calculates the main heuristic value of given bitboards for a player." [boards player-num] (apply + (map (fn [[c p]] (get-score c p)) [[(check/check-board-4 (boards player-num)) CC4] [(check/check-board-3 (boards player-num)) CC3] [(check/check-board-2 (boards player-num)) CC2] [(check/check-board-4 (boards (- 3 player-num))) (- 1 CC4)] [(check/check-board-3 (boards (- 3 player-num))) (- 1 CC3)] [(check/check-board-2 (boards (- 3 player-num))) (- 1 CC2)]]))) ;; consider possible winning combinations ;; (only when first heuristic returns equal values) (defn get-diags "Generates diagonals of given starting position using given step-f." [step-fn start-pos] (for [pos start-pos] (take 4 (iterate step-fn pos)))) (def win-combos "All 69 possible winning combinations." (let [rows (for [y (range 6), j (range 4)] (for [i (range 4)] [y (+ i j)])) columns (for [x (range 7), j (range 3)] (for [i (range 4)] [(+ i j) x])) diagonals (concat ; descending diagonals \ (get-diags (partial mapv inc) (for [y (range 3), x (range 4)] [y x])) ; ascending diagonals / (get-diags (fn [[y x]] [(inc y) (dec x)]) (for [y (range 3), x (range 3 7)] [y x])))] (concat rows columns diagonals))) (defn filter-current-move [y x coll] "Filter win-combos for coords including given [y x]." (if (nil? y) (some #{[0 x]} coll) (some #{[(inc y) x]} coll))) (defn filter-open-combos [player-num boards coll] "Filter for combos which are still open." (some (fn [[y x]] (or (not (bit-test (boards 0) (+ y (* 7 x)))) (bit-test (boards player-num) (+ y (* 7 x))))) coll)) (defn heuristic2 "Calculate second heuristic value." [boards player-num x] (count (filter #(and (filter-current-move (board/get-y (boards 0) x) x %) (filter-open-combos player-num boards %)) win-combos))) ;;; MINIMAX ALGORITHM ;;; (defn not-nil? [x] (not (nil? x))) (defn get-max [coll] (if (empty? coll) 0 (apply max coll))) (defn minimax "Minimax algorithm using only main heuristic." [boards player-num x depth] (if (or (nil? boards) (nil? (board/insert boards x player-num))) nil (if (= depth 0) (heuristic (board/insert boards x player-num) player-num) (- (heuristic (board/insert boards x player-num) player-num) (get-max (filter not-nil? (map #(minimax (board/insert boards x player-num) (- 3 player-num) % (- depth 1)) [0 1 2 3 4 5 6]))))))) (defn get-highest-index [coll] (apply max-key second (filter #(not-nil? (second %)) coll))) (defn make-move "Generate next move using minimax and second heuristic if needed." [boards player-num depth] (let [heuristics (map #(minimax boards player-num % depth) [0 1 2 3 4 5 6]) highest (get-highest-index (map-indexed vector heuristics))] (println heuristics) (if (&gt; (count (filter #{(second highest)} heuristics)) 1) ; equal values from first heuristics - look at second (first (get-highest-index (map #(vector (first %) (heuristic2 boards player-num (first %))) ; only consider the highest and equal values (filter #(= (second highest) (second %)) (map-indexed vector heuristics))))) (first highest)))) </code></pre> <p>The algorithm used to check the board is a slightly modified version of the algorithm explained in the paragraph "Algorithm 2: Bitboard" <a href="http://programmablelife.blogspot.co.at/2012/09/clojure-connect-four-1-checking-winner.html">here</a>.</p>
[]
[ { "body": "\n\n<p><em>This is two and a half years old, but for the sake of future viewers:</em></p>\n\n<p>Overall your coding style looks pretty good, especially for someone new to Clojure. I don't have any comments on the AI engine itself, but here are a few structural notes:</p>\n\n<p><code>not-nil?</code> already exists in <code>clojure.core</code> as <code>some?</code>.</p>\n\n<p>Docstrings are usually phrased actively: e.g. \"Returns the result of..\" or \"Generates y based on...\"</p>\n\n<p>There are some places where the <code>-&gt;</code> or <code>-&gt;&gt;</code> macros could be used instead of deeply nested forms. How extensively you do this is largely up to personal taste. I like reading functions as pipelines so, for example, <code>get-score</code> could be written as:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(defn get-score\n [check points]\n (let [count-true-bits #(count (filter true? (bit-count %)))]\n (-&gt;&gt; check\n (map count-true-bits)\n (apply +)\n (* points))))\n</code></pre>\n\n<p><code>minimax</code> could benefit from a <code>let</code> to avoid repeating <code>(board/insert boards x player-num)</code> four times, and could use <code>when-let</code> with <code>and</code> instead of explicitly returning <code>nil</code>:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(defn minimax\n \"Minimax algorithm using only main heuristic.\"\n [boards player-num x depth]\n (when-let [boards' (and boards (board/insert boards x player-num))]\n (let [heuristic-val (heuristic boards' player-num)]\n (if (zero? depth)\n heuristic-val\n (- heuristic-val\n (-&gt;&gt; (range 7)\n (map #(minimax boards' (- 3 player-num) % (dec depth)))\n (filter some?)\n get-max))))))\n</code></pre>\n\n<p>I would rename the functions <code>filter-current-move</code> and <code>filter-open-combos</code>, since they seem to be more like predicates than filters -- <code>some</code> will return the first logical true value of <code>(pred item-in-coll)</code> or else <code>nil</code>. Also, their docstrings should come before their parameter lists.</p>\n\n<p><code>make-move</code> could be flattened a bit, again depending on your preference for nesting-vs-threading (<code>-&gt;&gt;</code>), and could use <code>keep-indexed</code> if you want to get fancy:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(defn make-move\n \"Generates next move using minimax and second heuristic if needed.\"\n [boards player-num depth]\n (let [heuristics (map #(minimax boards player-num % depth)\n (range 7))\n [highest-index highest] (get-highest-index (map-indexed vector heuristics))]\n (println heuristics)\n (if (&gt; (count (filter #{highest} heuristics)) 1)\n ; equal values from first heuristics - look at second\n (-&gt;&gt; heuristics\n (keep-indexed (fn [index x]\n (when (= highest x)\n [index (heuristic2 boards player-num index)]))\n get-highest-index\n first)\n highest-index)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-18T06:59:36.507", "Id": "114353", "ParentId": "25101", "Score": "16" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T09:07:35.817", "Id": "25101", "Score": "49", "Tags": [ "beginner", "functional-programming", "lisp", "clojure", "ai" ], "Title": "Connect Four AI (Minimax) in Clojure" }
25101
<p>I have a user model, a task model, and a junction model user_task that saves the data joining the two:</p> <pre><code>class Task &lt; ActiveRecord::Base attr_accessor :completed_on has_many :user_tasks class UserTask &lt; ActiveRecord::Base attr_accessible :task_id, :user_id, :completed_on belongs_to :user belongs_to :task class User &lt; ActiveRecord::Base has_many :user_tasks, :dependent =&gt; :destroy has_many :tasks, :through =&gt; :user_tasks </code></pre> <p>In order to query the tasks and show if they're complete or not when a user is logged in, I have a transient attribute, (I think that's the correct terminology) an attr_accessor on the task model :completed_on. Right now I'm looping through the tasks as follows in order to get this attribute filled out. </p> <p>This just thrown in a controller as a quick hack to provide what I need.</p> <pre><code> @tasks.each do |task| if current_user.tasks.include? task task.completed_on = current_user.user_tasks.find_by_task_id(task.id).completed_on end end </code></pre> <p>I need something that, given an array of tasks and a user_id, loops through the tasks and fills that variable with the completed_on date if the user has finished that task. The goal for this is that when responding to JSON, I have overriden as_json on the task model to merge the completed_on attribute into the JSON hash:</p> <pre><code>h.merge({:completed_on =&gt; completed_on}) </code></pre> <p>Possible ideas to get this done more properly:</p> <ul> <li>Create a function on the tasks model that takes a user ID, joins the user_tasks table to the tasks table, with a where clause to specify the user. This idea is actually half baked and I'm not sure where to go from here. </li> <li>Pretty much put the code above into the user model and change current_user to self. I'm not sure what to name it though,<br> completed_tasks doesn't fit since not all of them would be completed. fill_completed_on may work.</li> <li>Utilize a decorator somehow? Is it worth it just for this single attribute? If so, how would I structure it?</li> <li>Something like Task.where(conditions) then Task.where(conditions).completed_by(user) then setting the completed_on on the latter and merging the two results.</li> </ul> <p>It feels like I'm doing this the a bad way, and could be leveraging ActiveRelation/scopes somehow.</p> <p>I also think there is a better way to do include completed_on in when needed and not have to override the task model's as_json to get it to appear.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T18:40:26.057", "Id": "38855", "Score": "0", "body": "Why do you have the `UserTask` model and table? Since you're not using a `has_and_belongs_to_many` relationship anywhere, and `UserTask` isn't adding any new information, there's no need for it as far as I can tell. It could simply be \"user has_many tasks\" (or vice-versa), period. It'd simplify everything" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T18:45:28.373", "Id": "38856", "Score": "0", "body": "The UserTask model actually will store data specific to the task. What I didn't say (didn't think it was necessary) was that the tasks have an hstore column and I'm using single table inheritance to create different types of tasks, and same with the UserTask model in order to store different types of data related to whatever info the task needs to save on the user." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T21:11:48.483", "Id": "38863", "Score": "0", "body": "I cannot fathom why `completed_on` is a virtual attribute instead of a normal column in database. Can you explain?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T22:25:52.953", "Id": "38865", "Score": "0", "body": "@tokland Yah. I'm interested in serializing the tasks as JSON. Tasks can be completed by users via user_tasks. The JSON is for a mobile API to show whether the user finished the task or not when viewing the list of tasks. It is a normal column on the database -- it's on the user_tasks table." } ]
[ { "body": "<p>The problem is that the data to render does not match the modelling. You call it \"task\", but if it includes a <code>completed_on</code> it's not a task, it's something more of a <code>user_task</code>. I definitely wouldn't use an accessor to accomplish this, that's messing with <code>Task</code>, this model should know nothing about completion dates of a particular user.</p>\n\n<p>Even if you call it \"tasks\" in the frontend, conceptually in your app you should be rendering a collection of <code>user_tasks</code>. Something to start with (make sure, using <code>includes</code> or whatever, that <code>user_task_by</code> doesn't hit the DB repeatedly):</p>\n\n<pre><code>user_tasks = Task.where(...).includes(:users_tasks).map do |task|\n task.user_task_by(user) || task.user_tasks.new\nend\n</code></pre>\n\n<p>Now you'd override <code>UserTask#as_json</code> to build a hash with the mixed structure (getting some attributes from <code>task</code> and <code>completed_on</code> from <code>user_task</code>).</p>\n\n<p>Was this any help?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T21:35:16.687", "Id": "38916", "Score": "0", "body": "I apologize if I've added confusion by omitting most of the code, and I have been programming by myself for a long time, so it's hard to communicate about this sometimes... Basically the tasks are a collection that belong to another entity. Multiple users can complete the same task. I have a mobile API and the person building the mobile app is only interested in rendering the task collection on the entities, with a small addition to see whether the logged on user completed that particular task. Hope that clears things up! Let me know if this is still too ambiguous." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T21:38:42.137", "Id": "38917", "Score": "0", "body": "Also, I feel this is more of an architectural/design type of question. Does it suit this stackexchange? Or would it be more suited for stackoverflow?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T15:46:25.110", "Id": "38966", "Score": "0", "body": "This actually helped. I'm not going to go with setting a transient attribute, instead return both the task and user_task (if present) using includes. Thanks!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T14:38:57.040", "Id": "25140", "ParentId": "25108", "Score": "1" } } ]
{ "AcceptedAnswerId": "25140", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T18:08:46.983", "Id": "25108", "Score": "1", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Rails: Setting a transient attribute on a set of objects from one model based on information from a junction model" }
25108
<p>I was writing a calendar a long time ago and, coming back to the code, I've realized that it's not the best. I was fairly mediocre at programming back then.</p> <p>I'm using jQuery, Mousetrap, and Hammer.js. Here is <a href="http://8b51d1abd8.test-url.ws/" rel="nofollow">a working example</a> and the <a href="http://8b51d1abd8.test-url.ws/main.js" rel="nofollow">code</a>.</p> <p>Sorry that this is long - I'm not sure if 250 lines is too long, the FAQ says "a few thousand is too long" but didn't give a specific limit. I've tried to comment it (the vast majority of comments are from today) so it's easier on the eyes, though.</p> <pre><code>/*jshint globalstrict: true*/ /*jshint eqeqeq:true, bitwise:true, strict:false, undef:true, unused:true, curly:true, browser:true */ var dtu = new Date(); //Always equal to [currently selected month] [day of pageload] [currently selected year] [time of pageload] //example: if page was loaded on Mar 15, 2013 at 11:57:55, and you navigated to June 2015, dtu would be Jun 15 2015 11:57:55 var yearsShowing = false; //whether or not the years calendar ('yearendar') is showing var dfb = 0; //how many days from the beginning of the calendar does the month start (e.g. Aug 2013 starts 4 days from the start of the calendar - on a Thurs) var highlighted = -1; //Which cell ID is highlighted as the current date. Only applicable, of course, when on the current month. var oldHighlighted = -1; //When the "highlighted" date was last changed, whatever its' prior value was var isHighlighted = true; //Whether or not something on the current page is highlighted. var go; //Tells yearOnClick whether or not it's OK to do its' thing. var years = {i:0}; //An object that keeps track of the what date the yearendar starts. function chYr(n) { //Change the year - p=previous year, n=next if (n === 'n') { refreshYears(parseInt(($('#ytext')[0].innerText).substring(0,4),10)+100); } if (n === 'p') { refreshYears(parseInt(($('#ytext')[0].innerText).substring(0,4),10)-100); } } function chMon(p) { //Change the month - p=previous month, n=next if (p === 'p') { dtu.setMonth(dtu.getMonth()-1); } else if (p === 'n') { dtu.setMonth(dtu.getMonth()+1); } refreshStuff(); } $(document).ready(function() { //Only do this stuff when the document's ready... Mousetrap.bind('left', function() { if(yearsShowing) { chYr('p'); } else { chMon('p'); } }); Mousetrap.bind('right', function() { if(yearsShowing) { chYr('n'); } else { chMon('n'); } }); Mousetrap.bind('up up down down left right left right b a enter', function() { alert('Konami code!'); }); Mousetrap.bind('esc', function() { refreshYears(parseInt($('#ytext')[0].innerText.substring(0,4),10)); showYears(); }); bindTouchStuff(); resizeStuff(); refreshStuff(); refreshYears(2001); reloadBubbles(); }); function reloadBubbles() { //remove all dots on the page var x = 1; $.each($('.dots'), function() { this.innerHTML = ""; this.id = 'dots'+x; x++; }); x=1; //create new dots for (var i=0; i&lt;datas.length; i++) { //runs once for every type of event. example: if there are two (e.g. "violin" and "homework") it would run twice for (x=1; x&lt;daysInMonth(dtu.getMonth()+1,dtu.getUTCFullYear())+1; x++) { //runs once for each day in that month var dated = (dtu.getMonth()+1).toString()+'/'+x.toString()+'/'+dtu.getUTCFullYear().toString(); //gets that day of the month; format mm/dd/yyyy (but if month or day is single char it does _not_ prefix a 0) if (typeof datas[i][dated] !== 'undefined') { //only runs if that day of the month has any of the current type of event $('#dots'+(x+dfb))[0].innerHTML += '&lt;a href="#detailsModal" data-toggle="modal" onclick="$(&amp;#39;#detailsModalLabel&amp;#39;)[0].innerText = &amp;#39;'+dated+' - '+datas[i].name+'&amp;#39;; $(&amp;#39;#detailsModalBody&amp;#39;)[0].innerText = &amp;#39;'+datas[i][dated]+'&amp;#39;"&gt;&lt;li class="'+datas[i].color+'"&gt;&lt;/li&gt;&lt;/a&gt; '; //adds a dot to that day. Each dot has a link which modifies, then opens a prefab BS modal containing details of that event //TODO: use the HTML5 history API to change the URL and let people link to an event. Make sure to cover a scenario in which that event doesn't exist } } } //ending for (x=1; x&lt;daysInMonth(dtu.getMonth()+1,dtu.getUTCFullYear())+1; x++) { //for each day in month $('#dots'+(x+dfb))[0].innerHTML = '&lt;ul&gt;' + $('#dots'+(x+dfb))[0].innerHTML + '&lt;/ul&gt;'; } } function bindTouchStuff() { console.log('Using Hammer') var hammer = new Hammer(document.getElementById("all")); hammer.ondragstart = function(ev) { if (yearsShowing) { if (ev.direction === "right") { chYr('p'); } if (ev.direction === "left") { chYr('n'); } } else { if (ev.direction === "right") { chMon('p'); } if (ev.direction === "left") { chMon('n'); } } }; hammer = new Hammer(document.getElementById("all")); hammer.ontransformstart = function(ev) { refreshYears(parseInt($('#ytext')[0].innerText.substring(0,4),10)); showYears(); }; } function daysInMonth(month,year) { return new Date(year, month, 0).getDate(); } function refreshStuff() { setTimeout(removeHighlight,10); } function removeHighlight() { $('#day'+highlighted).removeClass('today'); setTimeout(continueRefreshingStuff,10); } function continueRefreshingStuff() { $('#day'+highlighted).removeClass('today'); $('#daysmonth').addClass('zoom'); var fdom = new Date(dtu.getFullYear(), dtu.getMonth(), 1).getDay()+1; //finds first day of month dfb = 0; //days from beginning that month starts var mdtu = moment(dtu); $('#mtext')[0].innerText = moment.months[mdtu.month()]+' '+mdtu.year(); for (var i=1; i&lt;43; i++) { //43 not 42 and 1 not 0 because dates are not arrayish //for each of the 42 day cells document.getElementById('day'+i).childNodes[1].childNodes[0].innerText = ((i-fdom)+1); //labels days (with neg. #s, unfortunately) if ((i-fdom)+1&lt;1) { dfb++; //if there are days numbered 0 or less var x = daysInMonth(dtu.getMonth(),dtu.getUTCFullYear()); //days in previous month document.getElementById('day'+i).childNodes[1].childNodes[0].innerText = (x+((i-fdom)+1)); //renumber dates before start of month correctly } else if ((i-fdom)+1&gt;daysInMonth(dtu.getMonth()+1,dtu.getUTCFullYear())) { //if there are days numbered over the max. # of days in this month document.getElementById('day'+i).childNodes[1].childNodes[0].innerText = (((i-fdom)+1)-daysInMonth(dtu.getMonth()+1,dtu.getUTCFullYear())); //renumber dates after end of month correctly } } isHighlighted=false; if (mdtu.month() === new Date().getMonth()) { $('#day'+(new Date().getDate()+dfb)).addClass('today'); oldHighlighted = highlighted; highlighted = (new Date().getDate()+dfb); isHighlighted = true; } setTimeout(unZoom, 200); reloadBubbles(); } function unZoom() { if (!isHighlighted) $('#day'+oldHighlighted).removeClass('today'); $("#daysmonth").removeClass("zoom"); } function showYears() { $('#calendar')[0].style.display = "none"; $('#yearendar')[0].style.display = "block"; yearsShowing = true; } var yearOnClick = function () { if (go===true) { yearsShowing = false; dtu.setYear(parseInt(this.innerText,10)); refreshStuff(); $('#yearendar')[0].style.display = "none"; $('#calendar')[0].style.display = "block"; } }; function refreshYears_inner() { if (years.this.innerText !== undefined) { years.this.innerText = years.start+years.i; years.this.onclick=yearOnClick; years.i++; } } function refreshYears(start) { go = false; years.i = 0; for (var z=1; z&lt;11; z++) { years.start = start; years.this = this; $.each($('#tr'+z)[0].childNodes, refreshYears_inner); } $('#ytext')[0].innerText = start + '-' + (start+99); go=true; } $(window).resize(function() { resizeStuff(); }); function resizeStuff() { var eye=0; $.each($('.day'), function() { eye++; if ((eye/2).toString().indexOf('.') === -1) { this.setAttribute('style', 'width:'+($('#calheader')[0].clientWidth-7)/7+'px !important'); } else { this.setAttribute('style', 'width:'+($('#calheader')[0].clientWidth-7)/7+'px !important'); //6.985 } /*if ((eye/7).toString().indexOf('.') === -1) { this.setAttribute('style', 'width:'+((($('#calheader')[0].clientWidth-7)/6.985)+0.1)+'px !important'); } */ }); $.each($('.dayweek'), function() { this.setAttribute('style', 'width:'+($('#calheader')[0].clientWidth-6)/7+'px !important'); }); } window.onload=resizeStuff; </code></pre> <p>What could I have done better? Performance, readability, and maintainability wise.</p>
[]
[ { "body": "<p>Actually posting your code here should not require any additional comments. Everywhere you have the feeling for the need of the comment, you should check the method and variable names. Maybe even splitting a method might help to make the code more readable. (You obviously have a feeling for this at your own, so I won't post code here. But as a hint: rename all your abbreviations and don't use single letter variables )</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T04:12:47.897", "Id": "25118", "ParentId": "25110", "Score": "1" } }, { "body": "<p>I hate to be nitpicky but here goes.</p>\n\n<p><strong>Obviously the OP is a much better programmer today so I don't want to harp on being able to point these out. Everyone starts fresh somewhere and even I would hate to review my own old code from when I started out.</strong></p>\n\n<ul>\n<li><p>Since this is a calender module you should ideally make a <code>prototype</code> implementation. For e.g.</p>\n\n<pre><code>var Calender = function () {\n this.date = new Date();\n};\n\nCalender.prototype.date = null;\n\n/* Similarly dump dtu, dfb, go, etc. here. */\n...\n</code></pre></li>\n<li><p>Have more descriptive variable &amp; function names. For e.g.</p>\n\n<ul>\n<li><code>chYr</code> => <code>changeYear</code></li>\n<li><code>refreshStuff</code> => <code>refreshCalendar</code></li>\n<li><code>dtu</code> => <code>date</code> or <code>currentDate</code></li>\n<li><code>showYears</code> => <code>isYearsShowing</code></li>\n<li><code>highlighted</code> => <code>highlightedCellId</code>, and so on.</li>\n</ul></li>\n<li><p>Do not leave values <code>undefined</code> (<code>var go;</code>). Set it to <code>null</code>. You can always compare the value to <code>null</code>.</p></li>\n<li><p>Do not use keywords like <code>this</code> as variable names (<code>years.this = this;</code>).</p></li>\n<li><p>As far as possible avoid <strong>\"magic numbers\"</strong> in your code (<code>var z=1; z&lt;11; z++</code>). Set special values as named constants somewhere in your code and use those named constants in your logic.</p></li>\n<li><p>Remove <code>console.log</code> from production ready code.</p></li>\n<li><p>Reduce the number of calls to the <code>$</code> jquery function. For e.g</p>\n\n<ul>\n<li><p><code>$('#calendar')</code>, <code>$('#yearendar')</code>, <code>$('#calheader')</code> seem to be called frequently. If these elements do not change once they are set on the page then populate them into memory once and access from there.</p>\n\n<p><code>var $calender = $('#calender');</code></p></li>\n</ul></li>\n<li><p>Avoid using <code>window.onload</code>. Use <code>addEventListener</code> or the jQuery <code>.on</code> API instead.</p></li>\n<li><p>It may not be necessary to use both <code>window.onload</code> as well as <code>$(document).ready</code>. Using <code>$(document).ready</code> should be sufficient.</p></li>\n<li><p>In the function <code>resizeStuff</code> there is no need for the <code>if</code> condition <code>((eye/2).toString().indexOf('.') === -1)</code> within the <code>each</code> block for <code>$('.day')</code> as both branches set the <em>same</em> attribute.</p>\n\n<p><code>this.setAttribute('style', 'width:'+($('#calheader')[0].clientWidth-7)/7+'px !important');</code></p></li>\n</ul>\n\n<p>There could be more but I know this already may be too much to do. These suggestions would be the ideal way to keep your code maintainable, free from conflicts with other JS code/libraries and just optimized enough not to literally die on mobile devices.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T05:51:29.327", "Id": "25122", "ParentId": "25110", "Score": "4" } } ]
{ "AcceptedAnswerId": "25122", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T18:32:23.647", "Id": "25110", "Score": "1", "Tags": [ "javascript", "performance" ], "Title": "What could I have done better with this code from a calendar?" }
25110
<p>I was hoping I might get some feedback and ideas for improvement on this, particularly the <code>WebRouter</code> class.</p> <pre><code>#include &lt;native/native.h&gt; #include &lt;rapidjson/writer.h&gt; #include &lt;rapidjson/stringbuffer.h&gt; #include &lt;cppconn/driver.h&gt; #include &lt;cppconn/connection.h&gt; #include &lt;cppconn/statement.h&gt; #include &lt;cppconn/prepared_statement.h&gt; #include &lt;cppconn/resultset.h&gt; #include &lt;cppconn/exception.h&gt; #include &lt;cppconn/warning.h&gt; #include &lt;market_config.hpp&gt; using namespace native::http; namespace json = rapidjson; const std::string database(DATABASE); const std::string url(DBHOST); const std::string user(USER); const std::string password(PASSWORD); typedef std::shared_ptr&lt;sql::Connection&gt; SharedConnectionPtr; class ConnectionPool { public: ConnectionPool(uint32_t max_connections) { for (uint32_t i = 0; i &lt; max_connections; i++) { SharedConnectionPtr con = createConnection(); free_connections.push_back(con); } } SharedConnectionPtr getConnection() { SharedConnectionPtr con = *(free_connections.end() - 1); free_connections.pop_back(); return con; } void releaseConnection(SharedConnectionPtr con) { free_connections.push_back(con); } private: std::vector&lt;SharedConnectionPtr&gt; free_connections; SharedConnectionPtr createConnection() { try { sql::Driver *driver; driver = get_driver_instance(); auto con = std::shared_ptr&lt;sql::Connection&gt;(driver-&gt;connect(url, user, password)); return con; } catch (sql::SQLException) { std::cout &lt;&lt; "Failed to connecto to database. Exiting..." &lt;&lt; std::endl; exit(1); } } }; class WebRouter { public: WebRouter() { pool = new ConnectionPool(10); } void serve(request&amp; req, response&amp; res) { if ( req.url().path() == "/" ) { getIndex(req, res); } else if ( req.url().path() == "/history/AA" ) { getHistory(req, res); } else { res.set_status(404); res.set_header("Content-Type", "text/plain"); res.end("Not found."); } } private: ConnectionPool *pool; void getIndex(request&amp; req, response&amp; res) { res.set_status(200); res.set_header("Content-Type", "text/plain"); res.end("This is the index!"); } void getHistory(request&amp; req, response&amp; res) { SharedConnectionPtr con; sql::Statement *stmt; sql::ResultSet *result; json::StringBuffer buffer; json::Writer&lt;json::StringBuffer&gt; writer(buffer); con = pool-&gt;getConnection(); con-&gt;setSchema(DATABASE); stmt = con-&gt;createStatement(); result = stmt-&gt;executeQuery("select * from daily_history where symbol_id = 'AA';"); writer.StartArray(); while (result-&gt;next()) { writer.StartArray(); writer.Int(result-&gt;getInt(2)); // timestamp writer.Double(result-&gt;getDouble(3)); // open writer.Double(result-&gt;getDouble(4)); // high writer.Double(result-&gt;getDouble(5)); // low writer.Double(result-&gt;getDouble(6)); // close writer.Uint(result-&gt;getUInt(7)); // volume writer.EndArray(); } writer.EndArray(); delete result; delete stmt; pool-&gt;releaseConnection(con); res.set_status(200); res.set_header("Content-Type", "application/json"); res.end(buffer.GetString()); } }; int main() { http server; WebRouter *router = new WebRouter(); if(!server.listen("0.0.0.0", 8080, [&amp;](request&amp; req, response&amp; res) { router-&gt;serve(req, res); })) return 1; return native::run(); } </code></pre>
[]
[ { "body": "<p>I know this is a small app, but I would move the direct SQL calls into it's own class:</p>\n\n<p>From this:</p>\n\n<pre><code>sql::ResultSet *result;\nresult = stmt-&gt;executeQuery(\"select * from daily_history where symbol_id = 'AA';\");\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>DailyHistoryFactory *daily_history_factory;\ndaily_history_factory = new DailyHistoryFactory();\n\nsql::ResultSet *result;\nresult = daily_history_factory-&gt;all_daily_histories();\n</code></pre>\n\n<p>The factory could be responsible for connecting as well, possibly through subclassing of the Storage layer.</p>\n\n<p>I see a code smell as well: knowledge built into comments.</p>\n\n<pre><code>writer.Int(result-&gt;getInt(2)); // timestamp\nwriter.Double(result-&gt;getDouble(3)); // open\nwriter.Double(result-&gt;getDouble(4)); // high\nwriter.Double(result-&gt;getDouble(5)); // low\nwriter.Double(result-&gt;getDouble(6)); // close\nwriter.Uint(result-&gt;getUInt(7)); // volume\n</code></pre>\n\n<p>I would wrap the building of this array into a new class as well. You can have a build method inside that class:</p>\n\n<pre><code>class ResponseBuilder {\n public:\n json::StringBuffer build(sql::ResultSet result) {\n builder.add_timestamp(result); // Builder is an instance variable you can instantiate\n builder.add_open(result); // internally that does the string building.\n builder.add_high(result);\n builder.add_low(result);\n builder.add_close(result);\n builder.add_volume(result);\n return builder.GetString();\n }\n};\n</code></pre>\n\n<p>This way, you are capturing the purpose of those calls into the code itself. If you have to comment, the code might change and comments might not be updated. Better to build it into the code directly. Now it is easy to read.</p>\n\n<p>You can also store \"result\" inside the ResponseBuilder when you initialize it, so each instance method can access it without needing it passed in like I have here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T23:39:02.887", "Id": "25115", "ParentId": "25113", "Score": "1" } }, { "body": "<h3>First Impression</h3>\n<p>You are not using RAII (basically use your constructor/destructor to resource management).</p>\n<p>This leads to Rule of three (rule of five C++11). Your WebRouter class does not obey the rule of three. As a result it is very dangerous (thus must be fixed). Basically when your class contains an owned pointer you must implement (or disable) the &quot;copy constructor&quot;, &quot;assignment operator&quot; and destructor.</p>\n<h3>Details</h3>\n<p>Don't do this:</p>\n<pre><code>using namespace native::http;\n</code></pre>\n<p>See <a href=\"https://stackoverflow.com/q/1452721/14065\">here</a>. Same rules apply to other namespace not just std.</p>\n<p>This is good.</p>\n<pre><code>namespace json = rapidjson;\n</code></pre>\n<p>You should have used the same technique for <code>native::http</code>.</p>\n<p>Careful here.</p>\n<pre><code> SharedConnectionPtr getConnection() {\n SharedConnectionPtr con = *(free_connections.end() - 1);\n free_connections.pop_back();\n return con;\n }\n</code></pre>\n<p>If your connection pool is empty then the above is undefined behavior.<br />\nYou should be checking that there is an available member in the pool and take remedial action if there are non available.</p>\n<p>This is total fine:</p>\n<pre><code> std::vector&lt;SharedConnectionPtr&gt; free_connections;\n</code></pre>\n<p>But for this situation I would prefer to use <code>boost::ptr_vector&lt;sql::Connection&gt;</code>. I would put ownership of the connection with the class and only return references externally.</p>\n<p>Your WebRouter is not safe to use:</p>\n<pre><code>class WebRouter { \n ConnectionPool *pool;\n public:\n WebRouter() {\n pool = new ConnectionPool(10);\n }\n</code></pre>\n<p>If you do this:</p>\n<pre><code>{\n WebRouter a;\n WebRouter b(a);\n}\n// Your universe explodes in nasal dragons here.\n</code></pre>\n<p>This is because you do not define a copy constructor. The default (compiler generated) copy constructed does not work for &quot;Owned&quot; pointers because the default action is a shallow copy.</p>\n<p>Be very careful of RAW pointers.</p>\n<pre><code> sql::Statement *stmt;\n sql::ResultSet *result;\n</code></pre>\n<p>Any assignment to these variables is not exception safe. You will need to take extra precautions that no exceptions are thrown before the delete statements otherwise you will leak. As a result you should probably prefer to use a smart pointer (like you use above).</p>\n<pre><code> stmt = con-&gt;createStatement(); \n result = stmt-&gt;executeQuery(&quot;select * from daily_history where symbol_id = 'AA';&quot;);\n</code></pre>\n<p>You better make sure no statements from here throw!</p>\n<p>I dislike this.<br />\nYou are manually opening and closing things. You want to use C++ RAII to do this automatically if you can. This will prevent accidental programer mistakes.</p>\n<pre><code> writer.StartArray();\n while (result-&gt;next()) {\n writer.StartArray();\n writer.Int(result-&gt;getInt(2)); // timestamp\n writer.Double(result-&gt;getDouble(3)); // open\n writer.Double(result-&gt;getDouble(4)); // high\n writer.Double(result-&gt;getDouble(5)); // low\n writer.Double(result-&gt;getDouble(6)); // close\n writer.Uint(result-&gt;getUInt(7)); // volume\n writer.EndArray();\n }\n writer.EndArray();\n</code></pre>\n<p>Manual delete.</p>\n<pre><code> delete result;\n delete stmt;\n</code></pre>\n<p>Modern C++ see very few manual deletions. RAII allows the management of this to be done automatically.</p>\n<p>Manual management of a connection.</p>\n<pre><code> pool-&gt;releaseConnection(con);\n</code></pre>\n<p>You are manually doing something that should be automatic. Here you are not going to leak the connection. But if you forget then you are going to loose items from the pool and thus slowly make your pool less efficient.</p>\n<p>We are we using dynamically created objects here:</p>\n<pre><code> WebRouter *router = new WebRouter(); \n</code></pre>\n<p>Much simpler to to use automatic object.</p>\n<pre><code> WebRouter router;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T18:15:04.890", "Id": "38905", "Score": "0", "body": "Thank you! I wish I could choose more than one answer =(" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T04:30:23.470", "Id": "25120", "ParentId": "25113", "Score": "1" } } ]
{ "AcceptedAnswerId": "25115", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T22:24:38.247", "Id": "25113", "Score": "0", "Tags": [ "c++", "mysql", "json", "connection-pool" ], "Title": "JSON API in C++ with Node.native, RapidJSON, and MySQL" }
25113
<p>I have a 100page long .docx format document. I'm using a macro written in VBS to extract some information and then just generate a table from them. I iterate through the paragraphs and store the found strings in 3 separate arrays.</p> <p>However, the loop is unreasonably slow. It takes 3 min to complete on a relatively fast computer. Can you take a look at it and tell me what causes this slowness?</p> <pre><code>'TODO : Add checks, exception handling, dynamic user options, probes, style checks, and fix slowness. Sub genTable() Dim objDoc '''''''''''''''''''''Modify these'''''''''''''''' Dim ColumnName1, ColumnName2, ColumnName3, magicString ColumnName1 = "foo1" ColumnName2 = "foo2" ColumnName3 = "foo3" magicString = "ASD321: " ' we search for this string Set objDoc = ActiveDocument ' Because we run inside of word as macro '''''''''''''''''''''''''''''''''''''''''''''''''' Const MAX = 200 ' using fixed sized arrays, mod this if you'll have more than 200 entries. Dim vulnerabilityArr(MAX) ' initializing the arrays Dim severityArr(MAX) Dim paragraphArr(MAX) Dim counter ' will count the processed entries in this counter = 0 Dim currParagraph ' will be set in loop Dim tmpArray() As String ' for splitting For pIndex = 1 To objDoc.Paragraphs.Count ' THIS LOOP IS SLOW currParagraph = objDoc.Paragraphs(pIndex) currParagraph = Left(currParagraph, Len(currParagraph) - 1) 'remove junk character If InStr(1, currParagraph, magicString) &gt; 0 Then ' assuming this string is always present and the other two target data is near it tmpArray = Split(currParagraph) ' extract level currParagraph = objDoc.Paragraphs(pIndex - 1) 'assuming the previous paragraph is the vuln. name 'Storing the 3 extracted data vulnerabilityArr(counter) = currParagraph severityArr(counter) = tmpArray(1) paragraphArr(counter) = objDoc.Paragraphs(pIndex - 1).Range.ListFormat.ListString ' for some weird reason I cant use currParagraph here counter = counter + 1 ' adjusting index End If Next pIndex objDoc.Tables.Add objDoc.Paragraphs(objDoc.Paragraphs.Count).Range, counter, 3, True, True Set objTable = objDoc.Tables(objDoc.Tables.Count) 'select last table objTable.Cell(1, 1).Range.Text = ColumnName1 objTable.Cell(1, 2).Range.Text = ColumnName2 objTable.Cell(1, 3).Range.Text = ColumnName3 For RowIndex = 0 To counter objTable.Cell(RowIndex, 1).Range.Text = paragraphArr(RowIndex) objTable.Cell(RowIndex, 2).Range.Text = vulnerabilityArr(RowIndex) objTable.Cell(RowIndex, 3).Range.Text = severityArr(RowIndex) Next RowIndexy = RowIndex + 1 objTable.AutoFormat (25) End Sub </code></pre>
[]
[ { "body": "<p>Maybe I'm deeply wrong, but please test:</p>\n\n<p>-- Almost all your variables are of type Variant, even the ones which could be Long, like counter. Define each variable with the correct type (it will be faster), in the form: </p>\n\n<pre><code> Option Explicit\n Dim counter as Long\n Dim ColumnName1 as String, ColumnName2 as String\n</code></pre>\n\n<p>-- You dont really use <code>pIndex</code>. Try:</p>\n\n<pre><code>Dim currParagraph As Paragraph ' will be set in loop\nFor Each currParagraph In objDoc.Paragraphs ' THIS LOOP IS SLOW\n</code></pre>\n\n<p>-- I dont see why you make a copy of the paragraph only to 'remove junk character ?\n<em>for some weird reason I cant use currParagraph here</em>: I have always heard that this information is with this junk character stick</p>\n\n<p>All will:</p>\n\n<pre><code>'TODO : Add checks, exception handling, dynamic user options, probes, style checks, and fix slowness.\nOption Explicit\nSub genTable()\n\nDim objDoc\n\n'''''''''''''''''''''Modify these''''''''''''''''\nDim ColumnName1 As String, ColumnName2 As String, ColumnName3 As String, magicString As String\nColumnName1 = \"foo1\"\nColumnName2 = \"foo2\"\nColumnName3 = \"foo3\"\nmagicString = \"ASD321: \" ' we search for this string\n\nSet objDoc = ActiveDocument ' Because we run inside of word as macro\n''''''''''''''''''''''''''''''''''''''''''''''''''\n\nConst MAX = 200 ' using fixed sized arrays, mod this if you'll have more than 200 entries.\nDim vulnerabilityArr(MAX) As Paragraph ' initializing the arrays\nDim severityArr(MAX) As String\nDim paragraphArr(MAX) As String\n\nDim counter As Long ' will count the processed entries in this\ncounter = 0\n\nDim tmpArray() As String ' for splitting\nDim currParagraph As Paragraph, prevParagraph As Paragraph ' will be set in loop\nFor Each currParagraph In objDoc.Paragraphs ' THIS LOOP IS SLOW\n ' currParagraph = Left(currParagraph, Len(currParagraph) - 1) 'remove junk character\n If InStr(currParagraph, magicString) &gt; 0 Then ' assuming this string is always present and the other two target data is near it\n tmpArray = Split(currParagraph.Range.Text) ' extract level\n Set prevParagraph = currParagraph.Previous ' assuming the previous paragraph is the vuln. name\n\n 'Storing the 3 extracted data\n Set vulnerabilityArr(counter) = prevParagraph\n severityArr(counter) = tmpArray(1)\n paragraphArr(counter) = prevParagraph.Range.ListFormat.ListString ' for some weird reason I cant use currParagraph here\n\n counter = counter + 1 ' adjusting index\n End If\nNext currParagraph\n\nDim objTable As Table\nSet objTable = objDoc.Tables.Add(objDoc.Paragraphs(objDoc.Paragraphs.Count).Range, counter + 1, 3, True, True)\n 'Set objTable = objDoc.Tables(objDoc.Tables.Count) 'select last table\n\nobjTable.Cell(1, 1).Range.Text = ColumnName1\nobjTable.Cell(1, 2).Range.Text = ColumnName2\nobjTable.Cell(1, 3).Range.Text = ColumnName3\n\nDim RowIndex As Long, RowIndexy As Long\n\nFor RowIndex = 0 To counter - 1\n objTable.Cell(RowIndex + 2, 1).Range.Text = paragraphArr(RowIndex)\n objTable.Cell(RowIndex + 2, 2).Range.Text = vulnerabilityArr(RowIndex).Range.Text\n objTable.Cell(RowIndex + 2, 3).Range.Text = severityArr(RowIndex)\nNext\nRowIndexy = RowIndex + 1\n\nobjTable.AutoFormat (25)\n\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T09:58:38.283", "Id": "38881", "Score": "0", "body": "Thank you for your suggestions, I'll try it. Do you think it would be faster if I'ld run it externally as a vbs file, not from inside word? If that's even possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T10:31:32.347", "Id": "38882", "Score": "0", "body": "Im not sure how it could be possible, but think with VBA inside word will keep all simpler and faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T11:16:25.337", "Id": "38883", "Score": "1", "body": "Holly molly, it ran in 2 (!) seconds! Thanks a bunch! I wonder which change caused it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T11:41:00.923", "Id": "38887", "Score": "1", "body": "I edited, with some sintax corrections. Now it works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T11:55:32.800", "Id": "38889", "Score": "2", "body": "Well, one cause is the use of Variant (a variable declared whitohw a type) when you dont need. The other: dont make unnecesary copy of relatively big objects, like paragraphs." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T09:45:59.133", "Id": "25126", "ParentId": "25123", "Score": "7" } } ]
{ "AcceptedAnswerId": "25126", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T07:05:20.093", "Id": "25123", "Score": "7", "Tags": [ "performance", "vba", "vbscript", "ms-word" ], "Title": "Extracting data from a Word document is too slow" }
25123
<p>I've created simple try/catch macros that now I'd like to promote to wider use in my projects. I would have really liked to be able to do without global variables but I have not found any way to do it.</p> <p>Any suggestion for improvement? Any issue that I may have overlooked?</p> <pre><code> #include &lt;stdlib.h&gt; #include &lt;setjmp.h&gt; #define utl_trymax 16 #ifdef UTL_MAIN int utlErr = 0; int utl_jbn = 0; jmp_buf utl_jbv[utl_trymax]; #else extern int utlErr; extern int utl_jbn; extern jmp_buf utl_jbv[utl_trymax]; #endif #define utlTry for ( utlErr = -1 \ ; utlErr == -1 &amp;&amp; utl_jbn &lt; utl_trymax \ ; (utl_jbn&gt; 0 ? utl_jbn-- : 0 ) , \ ((utlErr &gt; 0)? utlThrow(utlErr) : 0), \ (utlErr = 0) ) \ if ((utlErr = setjmp(utl_jbv[utl_jbn++])) == 0 ) #define utlCatch(e) else if ((utlErr == (e)) &amp;&amp; ((utlErr = 0) == 0)) #define utlCatchAny else for ( ;utlErr &gt; 0; utlErr = 0) #define utlThrow(e) (utlErr=e, (utl_jbn &gt; 0 &amp;&amp; utlErr? \ longjmp(utl_jbv[utl_jbn-1], utlErr):\ exit(utlErr))) </code></pre> <p>The macros are to be used in this way:</p> <pre><code> utlTry { // Exceptions can be thrown here or in // any function called from here. ... utlThrow(EX_OUT_OF_MEM); } utlCatch(EX_OUT_OF_MEM) { ... } utlCatch(EX_DB_UNAVAILABLE) { ... } utlCatchAny { ... //optionally catch all other exceptions } </code></pre> <p>if there's no handler for an exception, the program exits.</p> <p>A simple example:</p> <pre><code>#include &lt;stdio.h&gt; #define UTL_MAIN #include "utltry.h" void functhrow(int e) { utlThrow(e); } int main(int argc, char *argv[]) { int k = 0; utlTry { functhrow(2); } utlCatch(1) { k = 1; } utlCatch(2) { k = 2; } printf("Caught: %d%s\n",k,(k==2)?" (as expected)":""); } </code></pre> <hr> <p>Here is another version I wrote to avoid the problems of having to use global variables. The price is to have to pass an extra argument to <code>try</code> and <code>throw</code>. I'd like to have comments on the code. The syntax is much closer to the C++ one</p> <pre><code> typedef struct utl_env_s { jmp_buf jb; struct utl_env_s *prev; int err; } utl_env_s, *tryenv; #define utl_lblx(x,l) x##l #define utl_lbl(x,l) utl_lblx(x,l) #define try(utl_env) \ do { struct utl_env_s utl_cur_env; int utlErr; \ utl_cur_env.err = 0; \ utl_cur_env.prev = utl_env; \ utl_env = &amp;utl_cur_env; \ for ( ; utl_cur_env.err &gt;= 0 \ ; (utl_env = utl_cur_env.prev) \ ? utl_env-&gt;err = utl_cur_env.err : 0 ) \ if (utl_cur_env.err &gt; 0) throw(utl_env,utl_cur_env.err); \ else if (!utl_env) break; \ else switch ((utl_cur_env.err = setjmp(utl_cur_env.jb))) {\ case 0 : #define catch(e) break; \ case e : utlErr = utl_cur_env.err; \ utl_cur_env.err = -1; \ #define catchall break; \ default : utlErr = utl_cur_env.err; \ utl_cur_env.err = -1; \ #define tryend } \ } while(0) #define throw(env,err) (env? longjmp(env-&gt;jb, err): exit(err)) </code></pre> <p>I really dislike the <code>tryend</code> part. I could get rid of it by forcing C99. Not sure if that would be the right thing to do ...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T19:57:35.257", "Id": "38909", "Score": "2", "body": "Why not use C++ instead of building your own?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T20:31:38.000", "Id": "38912", "Score": "0", "body": "@WilliamMorris I mostly do C programming. Even if I had the freedom to switch to C++, it wouldn't make much sense to do it just for having exceptions. On the other hand there are situation where try/catch simplfy the code a lot and I'm happy I can have them in C too. I'm just trying to be disciplined in what I use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T22:32:37.380", "Id": "38918", "Score": "0", "body": "One problem with setjmp/longjmp is leaking resources - such as open file descriptors and allocated memory. Perhaps you need a 'finally' block as somewhere to put cleanup. You might also look at P99 (http://p99.gforge.inria.fr/) which implements this type of behaviour and much else." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T04:51:58.857", "Id": "38922", "Score": "0", "body": "Thanks, I wasn't aware of P99. They seem to use setjmp/longjmp as well even if in a more convoluted way. Their `finally` clause doesn't seem to be executed if one throws an exception within CATCH (but I'll check again). Anyway, have you spotted a place in my code where there's a resource leaking? Or you just meant that, if one is not careful, using try/catch might lead to forgetting releasing acquired resources?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T13:11:48.570", "Id": "39040", "Score": "0", "body": "Not sure what this gives you. The same can be achieved just by using return statements. The real advantage of exceptions is automatic resource management and for that you need RAII or a garbage collector in addition." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T13:24:07.750", "Id": "39043", "Score": "0", "body": "@LokiAstari, yes the right way is to propagate the error through consistent use of functions returning errors code (see my comment to Lundin's reply). I might have been unlucky but I've never seen a project managing to consistently use this approach." } ]
[ { "body": "<p>One problem with this is resource leaks. It is not that your macros leak, but that when you use them, you'll leak. For example, suppose you call your <code>utlTry</code> in function <code>a()</code> that then calls function <code>b()</code> that allocates a resource (opens a file for example) and then calls function <code>c()</code> that does something with the resource. If <code>c()</code> fails and throws, the <code>longjmp</code> back to <code>a()</code> bypasses <code>b()</code> where the resource could be freed. There's no way round this problem and just 'being careful' is unlikely to be enough.</p>\n\n<p>Another problem is that the code doesn't look or behave like normal code. It looks as if I can add a statement between the try and the catch lines, but clearly I cannot. And there is no indication that the catch blocks are conditional. Perhaps this is nitpicking - if it is just you using the macros, I guess you'll get along fine.</p>\n\n<p>Talking of nitpicking, there are some small issues: </p>\n\n<ul>\n<li>you mix naming styles, with camel-case <code>utlErr</code> etc and separate words in <code>utl_jbn</code> etc</li>\n<li><code>utl_TRYMAX</code> might be expected to be <code>UTL_TRYMAX</code> and if that limit is exceeded, <code>utlTry</code> seems to skip its contained block.</li>\n</ul>\n\n<p>Overall, I'd say, don't do it. Error handling the long way can be a pain, but taking shortcuts like this is likely to be worse in the long run (especially if you share your code).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T19:44:50.787", "Id": "38981", "Score": "0", "body": "Thanks for the comments, William. I'll surely change the `utl_TRYMAX` it should have been `utl_trymax`. As for the `utl_xxxx' vs `utlAbcd', the convention is that first are for internal purpose only, while the lattere are supposed to be used by programmer. I should have said it in advance." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T18:07:49.383", "Id": "25187", "ParentId": "25124", "Score": "4" } }, { "body": "<p>I'm sorry for my bluntness, but this code is absolutely horrible and unsafe. To worry about global variables while using a mess of function-like macros, together with <code>setjmp</code>/<code>longjmp</code>, is kind of like worrying about the paint of your car while smoke is raising from the engine and the breaks are dead. </p>\n\n<p>Apart from that, trying to re-invent the C language is always a bad idea. Mainly because it confuses other C programmers.</p>\n\n<p>You can implement exception handling in much safer and more readable ways:</p>\n\n<pre><code>typedef enum\n{\n OK,\n ERR_THIS,\n ERR_THAT\n ...\n} err_t;\n\n\nerr_t func (void)\n{ \n if(something)\n return ERR_THIS;\n\n if(something_else)\n return ERR_THAT;\n\n return OK;\n}\n\nint main(int argc, char *argv[])\n{\n switch(func())\n {\n case OK:\n // code that should execute if no errors\n break;\n\n case ERR_THIS:\n // handle error\n break;\n\n case ERR_THAT;\n // handle error\n break;\n\n default: // equal to C++ catch(...)\n }\n}\n</code></pre>\n\n<p>And now you'll say \"this is not exception handling!\". Who cares. If you look at the generated machine code, this will generate exactly the same code as a C++ exception handling program. It will contain the same direct branches. The only difference is that the above program might contain less overhead and therefore execute quicker, with less memory usage.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T12:31:37.800", "Id": "39034", "Score": "0", "body": "Thanks for you comments, Lundin. Blunt feedback are exactly the reason I asked for a codereview. There would be little point otherwise :). That said, and just if you are interested, try to call some other function from func and assume there will be an error in that one. The point is that you need a way to propagate the error back to the first caller the cleanest way is to have all functions consitently returning an error code and build the rest around error code propagation. I confess I never managed to stay consistent with this style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T19:54:21.747", "Id": "39067", "Score": "0", "body": "@Remo.D In a real scenario, you'd typically not want the errors to \"fall all the way\" back to the first caller. You'd probably want to catch 'em in the middle function, then pass them on. For example if the call stack is `main -> add_to_queue -> linked_list_add_node`, then the caller is not really interested in \"Linked list exception, could not add node\". They want a \"queue full\" error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T07:05:08.680", "Id": "39099", "Score": "0", "body": "I'm not saying that the \"same error\" has to propagate back. In your example, `main` is interested in the fact that an error has occurred and you need a way to convey that message. Trust me, I've seen plenty of real scenarios where errors went unnoticed, program exited without releasing resources and so on. Exceptions are just a tool, I'm not advocating their use everywhere. There are cases where they come handy. I just wanted to have comments on my code, it was not my intention to start a debate on error handling (which, I believe, don't belong to \"Code Review\" exchange)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T23:35:48.943", "Id": "39375", "Score": "0", "body": "I love this answer and this is the strategy I typically use with my php code to avoid exceptions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T01:15:41.947", "Id": "400242", "Score": "0", "body": "Your statement _\"this will generate exactly the same code as a C++ exception handling program\"_ [is not remotely true](https://godbolt.org/z/jhfGlB). C++ generates code with no branching inside `main`, which is the key performance advantage of using exceptions - you only pay for them when they happen, unlike error codes which cost an extra branch at every call site." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T12:10:43.183", "Id": "25223", "ParentId": "25124", "Score": "2" } } ]
{ "AcceptedAnswerId": "25187", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T08:07:55.093", "Id": "25124", "Score": "3", "Tags": [ "c", "macros" ], "Title": "C try/catch macros" }
25124
<p>I was writing an answer in another thread and came across this challenge. I'm trying to have a generic class so that I can delegate the routine (and tiring) <code>Equals</code> and <code>GetHashCode</code> implementation to it (which should handle all that). With the code things will be clearer.</p> <p>Please note that I have no problem with performance as of now. But when writing a generic library for future use, I'm contemplating better designs. I'll include the bare minimum code required to drive the idea.</p> <p><strong>Approach 1</strong></p> <pre><code>public class Equater&lt;T&gt; : IEqualityComparer&lt;T&gt; { public IEnumerable&lt;Func&lt;T, object&gt;&gt; Keys { get; private set; } public Equater(params Func&lt;T, object&gt;[] keys) { Keys = keys; } public bool Equals(T x, T y) { ---- } public int GetHashCode(T obj) { ..... } } //an example usage public class Dao : IEquatable&lt;Dao&gt; { static Equater&lt;Dao&gt; equater = new Equater&lt;Dao&gt;(x =&gt; x.Id, x =&gt; x.Table); public bool Equals(Dao other) { return equater.Equals(this, other); } public override int GetHashCode() { return equater.GetHashCode(this); } } </code></pre> <p>This is great considering it <em>works for any number of properties</em>. But performance sucks, boxing I believe is the culprit. <strong>Runs in around 260 ms for about 100000 calls to <code>GetHashCode</code></strong>.</p> <p><strong>Approach 2</strong></p> <pre><code>public static class Equater&lt;T&gt; { public static Func&lt;T, T, bool&gt; equals; public static Func&lt;T, int&gt; getHashCode; public static void Set&lt;TKey1, TKey2&gt;(Func&lt;T, TKey1&gt; key1Selector, Func&lt;T, TKey2&gt; key2Selector) { equals = (x, y) =&gt; { ---- }; getHashCode = t =&gt; { .... }; } //other overloads of Set with varying type arguments } //an example usage public class Dao : IEquatable&lt;Dao&gt; { static Dao() { Equater&lt;Dao&gt;.Set(x =&gt; x.Id, x =&gt; x.Table); } public bool Equals(Dao other) { return Equater&lt;Dao&gt;.equals(this, other); } public override int GetHashCode() { return Equater&lt;Dao&gt;.getHashCode(this); } } </code></pre> <p><strong>Runs in around 100 - 110 ms this time</strong>.</p> <p><strong>Approach 3</strong></p> <pre><code>public abstract class Equater&lt;T&gt; : IEqualityComparer&lt;T&gt; { public static Equater&lt;T&gt; Create&lt;TKey&gt;(Func&lt;T, TKey&gt; keySelector) { return new Impl&lt;TKey&gt;(keySelector); } public static Equater&lt;T&gt; Create&lt;TKey1, Tkey2&gt;(Func&lt;T, TKey1&gt; key1Selector, Func&lt;T, Tkey2&gt; key2Selector) { return new Impl&lt;TKey1, Tkey2&gt;(key1Selector, key2Selector); } //etc. other overloads of Create with varying type arguments public abstract bool Equals(T x, T y); public abstract int GetHashCode(T obj); class Impl&lt;TKey&gt; : Equater&lt;T&gt; { readonly Func&lt;T, TKey&gt; keySelector; public Impl(Func&lt;T, TKey&gt; keySelector) { this.keySelector = keySelector; } public override bool Equals(T x, T y) { ---- } public override int GetHashCode(T obj) { .... } } class Impl&lt;TKey1, TKey2&gt; : Equater&lt;T&gt; { readonly Func&lt;T, TKey1&gt; key1Selector; readonly Func&lt;T, TKey2&gt; key2Selector; public Impl(Func&lt;T, TKey1&gt; key1Selector, Func&lt;T, TKey2&gt; key2Selector) { this.key1Selector = key1Selector; this.key2Selector = key2Selector; } public override bool Equals(T x, T y) { ---- } public override int GetHashCode(T obj) { .... } } } //an example usage public class Dao : IEquatable&lt;Dao&gt; { static Equater&lt;Dao&gt; equater = Equater&lt;Dao&gt;.Create(x =&gt; x.Id, x =&gt; x.Table); public bool Equals(Dao other) { return equater.Equals(this, other); } public override int GetHashCode() { return equater.GetHashCode(this); } } </code></pre> <p><strong>Approaches 80 - 90 ms</strong>. This is a lot verbose since I have to write a class for every additional type argument, but is the fastest.</p> <p>Can I implement it better?</p> <p>Please note that my question is not about performance <em>as such</em> (for that reason I've not included the critical <code>GetHashCode</code> part as my question is not about that). I'm trying to know if I can implement the above in a cooler and more efficient way. In other words its more about efficiency than performance.</p>
[]
[ { "body": "<p>You can reach maximum performance by generating specialized code at runtime using <code>Expression</code> trees. Instead of injecting <code>Func</code>s, inject <code>Expression&lt;Func&lt;...&gt;&gt;</code> s into your <code>Equater</code> class. Analyze what field they point to and build up the corresponding expressions for hashing and equality.</p>\n\n<p>That way you only have to execute one static field load and one delegate call per call to <code>Equals</code> or <code>GetHashCode</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T11:33:39.563", "Id": "38884", "Score": "0", "body": "Can you give a pointer? Or the bare minimum code to get me going? I did not understand this: `Analyze what field they point to and build up the corresponding expressions for hashing and equality.` Isn't that my 2nd approach is already doing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T11:37:14.430", "Id": "38885", "Score": "0", "body": "Your 2nd approach is combining delegates, not the expressions they were built from. It is really hard to give a short overview about expression trees. I suggest you read a little about them because that will be a more thorough information that I can offer here. Basically, expressions are a way to represent C# expressions at runtime in the form of an AST. That allows you to manipulate them and create new functions at runtime." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T11:39:45.953", "Id": "38886", "Score": "0", "body": "Do you have a good starter link to start with? A related question or so? Or some key words for google will do too.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T11:42:34.067", "Id": "38888", "Score": "1", "body": "Googling for \"c# expression trees\" I find some good stuff: http://msdn.microsoft.com/en-us/library/bb397951.aspx http://stackoverflow.com/questions/403088/practical-use-of-expression-trees http://stackoverflow.com/questions/683620/what-is-the-best-resource-for-learning-c-sharp-expression-trees-in-depth If you have specific questions about them I'll answer them on SO if I happen to see them." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T11:29:32.080", "Id": "25132", "ParentId": "25131", "Score": "3" } }, { "body": "<p>Yes, boxing is likely the culprit. To fix that, you need to type your <code>Func</code>s as in Example 3. Just make your <code>Equater</code> class better so it's not as verbose. Expression trees won't buy you anything here.</p>\n\n<pre><code>public class Equater&lt;T&gt;\n{\n private readonly List&lt;IEquaterFunc&lt;T&gt;&gt; _equaterFuncs = new List&lt;IEquaterFunc&lt;T&gt;&gt;();\n\n public bool Equals(T x, T y)\n {\n return _equaterFuncs.All(equaterFunc =&gt; equaterFunc.Equals(x, y));\n }\n\n public int GetHashCode(T obj)\n {\n //do something\n }\n\n public void AddEquaterFunc&lt;TProperty&gt;(Func&lt;T, TProperty&gt; equaterFunc)\n {\n _equaterFuncs.Add(new EquaterFunc&lt;T, TProperty&gt;(equaterFunc));\n }\n}\n\npublic interface IEquaterFunc&lt;T&gt;\n{\n bool Equals(T x, T y);\n int GetHashCode(T obj);\n}\n\npublic class EquaterFunc&lt;T, TProperty&gt; : IEquaterFunc&lt;T&gt;\n{\n private readonly Func&lt;T, TProperty&gt; _func;\n\n public EquaterFunc(Func&lt;T, TProperty&gt; func)\n {\n _func = func;\n }\n\n public bool Equals(T x, T y)\n {\n //use EqualityComparer&lt;TProperty&gt;.Default to avoid boxing\n return EqualityComparer&lt;TProperty&gt;.Default.Equals(_func(x), _func(y));\n }\n\n public int GetHashCode(T obj)\n {\n TProperty value = _func(obj);\n return ReferenceEquals(value, null) ? 0 : value.GetHashCode();\n }\n}\n\n//an example usage\npublic class Dao : IEquatable&lt;Dao&gt;\n{\n private static readonly Equater&lt;Dao&gt; Equater;\n\n static Dao()\n {\n Equater = new Equater&lt;Dao&gt;();\n Equater.AddEquaterFunc(x =&gt; x.Id);\n Equater.AddEquaterFunc(x =&gt; x.Table);\n }\n\n public bool Equals(Dao other)\n {\n return Equater.Equals(this, other);\n }\n\n public override int GetHashCode()\n {\n return Equater.GetHashCode(this);\n }\n\n public int Id { get; set; }\n public string Table { get; set; }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T15:25:26.960", "Id": "25142", "ParentId": "25131", "Score": "1" } }, { "body": "<p>I created a library a while ago that takes exactly the approach described by <a href=\"https://codereview.stackexchange.com/a/25132/46371\">usr</a>. Feel free to take a look at it: <a href=\"https://github.com/thedmi/Equ\" rel=\"nofollow noreferrer\">https://github.com/thedmi/Equ</a> . You can find the expression tree magic in the class <a href=\"https://github.com/thedmi/Equ/blob/master/Sources/Equ/EqualityFunctionGenerator.cs\" rel=\"nofollow noreferrer\">EqualityFunctionGenerator</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-15T12:37:55.073", "Id": "57084", "ParentId": "25131", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-15T22:44:31.577", "Id": "25131", "Score": "6", "Tags": [ "c#", "performance", "generics" ], "Title": "Generic wrapper for equality and hash implementation" }
25131
<p>I want to extend an app object with a widget that initializes itself immediately.</p> <p><em>Immediately-Invoked Function Expression:</em></p> <pre><code>var app = {}; (function() { app.widget = { init: function() { return true; } }; app.widget.init(); }()); </code></pre> <p><em>Immediately-Invoked Object Expression:</em></p> <pre><code>var app = {}; ({ init: function() { app.widget = this; return true; } }.init()); </code></pre> <p>Please take a look: <a href="http://jsperf.com/iife-vs-iioe" rel="nofollow">http://jsperf.com/iife-vs-iioe</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T11:55:33.300", "Id": "38890", "Score": "3", "body": "It's better if you actually put the code here. If jsPerf was down, this question won't have any future value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T15:55:32.343", "Id": "38899", "Score": "0", "body": "Quick tip: Change the first line in either example to `window.app = window.app || {};` (I'm guessing `app` is a global). That way, you'll avoid overwriting it if you or someone else defines it elsewhere (technically, you should do a full check for `typeof window.app === 'undefined'` but the default operator covers most cases and conveys the intention well)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T07:44:54.810", "Id": "38936", "Score": "0", "body": "@Flambino: You are right. window.app is the better way to handle conflicts and overwriting. In this example code I would like to clear out the basic idea between iife vs. iioe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T09:53:28.363", "Id": "38940", "Score": "0", "body": "@RonnySpringer Understood. I just pointed it out just in case. As for your actual question: I'd stick to using an IIFE, mostly because it is the most common, well-known pattern, and because you get an isolated context for your code (that context creation is probably partly why it's slower than the IIOE)" } ]
[ { "body": "<p>Code is not just about performance. You have to check for maintainability, scalability and readability as well.</p>\n\n<p>With regards to the way code is written, I'd favor the first method because it's the module pattern and is a common convention. The second one is too full of brackets and the object notation, though flexible, is nasty especially when you forget the commas.</p>\n\n<p>For extendability, I suggest you build a base set of helper functions to facilitate module loading and phase handling. Here are potential events that you might want to hook on events:</p>\n\n<ul>\n<li>when the DOM is ready (<code>DomContentLoaded</code>)</li>\n<li>when everything is loaded (<code>window.onload</code>)</li>\n<li>when the page is unloading (<code>window.onunload</code> and <code>onbeforeunload</code>)</li>\n<li>when the widget is loaded into the library</li>\n<li>when the widget is unloaded/removed</li>\n<li>when the widget is first run (<code>init</code>)</li>\n<li>and so on...</li>\n</ul>\n\n<p>Also, I suggest the following style of extension since:</p>\n\n<ul>\n<li>It creates a single local scope for your widget to operate and share. You have the so called \"private sandbox\".</li>\n<li>Objects are provided as an interface to attach stuff like public methods/properties, handlers and stuff. Whatever attached will be collected by your framework, sorted and executed accordingly.</li>\n<li>It's simple and readable!</li>\n</ul>\n\n<p>Here's a sample of a widget:</p>\n\n<pre><code>//assumung app is your framework namespace\napp.addWidget('WeatherWidget',function(handles,publicStuff){\n\n //your local scope\n var foo = 'bar';\n\n function baz(){console.log('bam');}\n\n //handles and public are your interfaces\n //in this example, handles will be used to collect your event handlers\n\n handles.init = function(){/*run on init*/};\n handles.documentReady = function{/*run on DOM ready*/};\n\n publicStuff.getBar = function(){return foo;}\n\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T12:37:55.960", "Id": "25136", "ParentId": "25133", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T11:53:22.463", "Id": "25133", "Score": "1", "Tags": [ "javascript", "performance" ], "Title": "Performance Test and Idea: Initialize a widget" }
25133
<p>I started this question to get people to grasp a little bit more on how to develop analog controls for android devices. But my code is a little outdated so if anyone knows how to implement it better please post your answer, as there are a lots of bugs in the code below as you'll see.</p> <p>Note: this is only if your app requires a custom built in analog controls. If you have a library that could implement it better then I suggest to use it. Also the analog controls developed here are mostly for use in landscape mode, but it can be altered to support portrait. Also be sure to check if your device supports multitouch (though if it has at least 800Mhz processor in 99% it does).</p> <p><img src="https://i.stack.imgur.com/7Isrn.png" alt="enter image description here"></p> <p>This is how your controls would optimally look like. If this is for a game then Move1 would be for walking forward and backward, move2 to for strafe left and right. Rotate1 for looking up and down and rotate2 for left and right.</p> <p>First thing you should do is get your device resolution in on create:</p> <pre><code> DisplayMetrics gettotalY = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(gettotalY); resolutiony= gettotaly.heightPixels; resolutionx= gettotaly.widthPixels; help1=(2*resolutiony)/3; help2=resolutionx/5; help3=(4*resolutionx)/5; </code></pre> <p>Help variables only position your screen analog controllers.</p> <p>This would be your touch listener:</p> <pre><code>public boolean onTouchEvent(MotionEvent me) { int pointerCount = me.getPointerCount(),i=0; int actionCode = me.getAction() &amp; MotionEvent.ACTION_MASK; while(i&lt;pointerCount) { int pointerId = me.getPointerId(i); i++; xpos = me.getX(pointerId); ypos = me.getY(pointerId); if(xpos&lt;help2 &amp;&amp; ypos&gt;help1) {float alo = resolutionx/10; float hej = (5*resolutiony)/6; alo=xpos-alo; hej=ypos-hej; hej=-(hej/((5*resolutiony)/6)); alo=alo/(resolutionx/10); move1=hej; move2=alo;} if(xpos&gt;help3 &amp;&amp; ypos&gt;help1) {float alo = (resolutionx*9)/10; float hej = (5*resolutiony)/6; alo=xpos-alo; hej=ypos-hej; hej=-(hej/((5*resolutiony)/6)); alo=alo/(resolutionx/10); rotate2=hej; rotate1=alo; } } if(me.getActionIndex()==0 &amp;&amp; actionCode == MotionEvent.ACTION_UP) {xpos = me.getX(me.getPointerId(0)); ypos = me.getY(me.getPointerId(0)); if(xpos&lt;help2 &amp;&amp; ypos&gt;help1) {move1=0; move2=0;} if(xpos&gt;help3 &amp;&amp; ypos&gt;help1) {rotate1=0; rotate2=0;} } if(me.getActionIndex()==1 &amp;&amp; actionCode == MotionEvent.ACTION_POINTER_UP) {xpos = me.getX(me.getPointerId(1)); ypos = me.getY(me.getPointerId(1)); if(xpos&lt;help2 &amp;&amp; ypos&gt;help1) {move1=0; move2=0;} if(xpos&gt;help3 &amp;&amp; ypos&gt;help1) {rotate1=0; rotate2=0;} } try { Thread.sleep(15); } catch (Exception e) { // No need for this... } return super.onTouchEvent(me); } </code></pre> <p>Since this is a multitouch example there a few things to learn from here. First we do a while loop to see where every finger on the screen is. If you expect to have only one finger at the screen then we probably wouldn't even need to make this loop, but since this is dual analog we need to check for at least two fingers.</p> <p>Now why would that be at least? Well you know when you are gaming, you put one thumb on the screen and then put the other and then you press the screen with your thumb again and then release the second thumb and by now the array that holds the information about only two fingers on the screen now holds the information about 5 fingers on the screen. This is why we need to check for all the fingers on the screen.</p> <p>This can get confusing I know, but the more you think about it the more it makes sense to you and you see that the device cannot really tell what you did with your finger when you lifted it up.</p> <p>Now this listener returns global variables move1,2, rotate1,2 either positive or negative, and from there on you can implement your dual analog controls without any more problems.</p> <p>However this is a question as this implementation is not flawless as it would seem. Most of the time everything works fine but when you leave the square with your thumb where the analog controller is variables do not return to 0. Does anyone know how to make this code better?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T11:56:13.840", "Id": "38891", "Score": "0", "body": "thanks, i did not even know about that site" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T12:25:27.597", "Id": "38892", "Score": "0", "body": "anyway `Thread.sleep` in `onTouchEvent` looks really bad ... maybe you could use some delta time ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T18:44:29.577", "Id": "38907", "Score": "0", "body": "i think thread sleep serves it's purpose here quite good" } ]
[ { "body": "<h3>Initial refactoring</h3>\n\n<p>Your code was hard to follow, so I applied a few mechanical transformations to clean it up first.</p>\n\n<p>Let's start by renaming a few variables.</p>\n\n<pre><code>void init() {\n DisplayMetrics screen = new DisplayMetrics();\n getWindowManager().getDefaultDisplay().getMetrics(screen);\n\n // \"resolution\" to me sounds like it should be in DPI. Rename!\n screenHeight = screen.heightPixels;\n screenWidth = screen.widthPixels;\n horizon = (2 * screenHeight) / 3;\n left = (1 * screenWidth) / 5;\n right = (4 * screenWidth) / 5;\n}\n</code></pre>\n\n<p>In <code>onTouchEvent()</code>, you have a weaselly <code>i=0</code>, followed two lines later by <code>while (i &lt; pointerCount)</code>, followed two lines later by <code>i++</code>. That's a for-loop! Also, why not rename <code>i</code> → <code>p</code> as in the example in the <a href=\"http://developer.android.com/reference/android/view/MotionEvent.html\" rel=\"nofollow noreferrer\">documentation</a>?</p>\n\n<pre><code>public boolean onTouchEvent(MotionEvent me) {\n int pointerCount = me.getPointerCount();\n for (int p = 0; p &lt; pointerCount; p++) {\n int pointerId = me.getPointerId(p);\n\n // Shouldn't xpos and ypos be local?\n xpos = me.getX(pointerId);\n ypos = me.getY(pointerId);\n\n if (xpos &lt; left &amp;&amp; ypos &gt; horizon) { // LHS control\n float alo = screenWidth /10;\n float hej = (5 * screenHeight) / 6;\n alo = xpos - alo;\n hej = ypos - hej;\n hej = -(hej / ((5 * screenHeight) / 6));\n alo = alo / (screenWidth / 10);\n move1 = hej;\n move2 = alo;\n } else if (xpos &gt; right &amp;&amp; ypos &gt; horizon) { // RHS control\n float alo = (screenWidth * 9) / 10;\n float hej = (5 * screenHeight) / 6;\n alo = xpos - alo;\n hej = ypos - hej;\n hej = -(hej / ((5 * screenHeight) / 6));\n alo = alo / (screenWidth / 10);\n rotate2 = hej;\n rotate1 = alo;\n }\n }\n\n int actionCode = me.getAction() &amp; MotionEvent.ACTION_MASK;\n if (me.getActionIndex() == 0 &amp;&amp; actionCode == MotionEvent.ACTION_UP)\n {\n xpos = me.getX(me.getPointerId(0));\n ypos = me.getY(me.getPointerId(0));\n if (xpos &lt; left &amp;&amp; ypos &gt; horizon) {\n move1 = move2 = 0;\n } else if (xpos &gt; right &amp;&amp; ypos &gt; horizon) {\n rotate1 = rotate2 = 0;\n }\n }\n if (me.getActionIndex() == 1 &amp;&amp; actionCode == MotionEvent.ACTION_POINTER_UP)\n {\n xpos = me.getX(me.getPointerId(1));\n ypos = me.getY(me.getPointerId(1));\n if (xpos &lt; left &amp;&amp; ypos &gt; horizon) {\n move1 = move2 = 0;\n } else if (xpos &gt; right &amp;&amp; ypos &gt; horizon) {\n rotate1 = rotate2 = 0;\n }\n }\n\n try {\n // FIXME: WHY IS THIS DELAY NEEDED???\n Thread.sleep(15);\n } catch (Exception e) {\n // No need for this...\n }\n\n return super.onTouchEvent(me);\n}\n</code></pre>\n\n<h3>Coordinate system</h3>\n\n<p>Let's focus on this snippet:</p>\n\n<pre><code>if (xpos &gt; right &amp;&amp; ypos &gt; horizon) { // RHS control\n float alo = (screenWidth * 9) / 10;\n float hej = (5 * screenHeight) / 6;\n alo = xpos - alo;\n hej = ypos - hej;\n hej = -(hej / ((5 * screenHeight) / 6));\n alo = alo / (screenWidth / 10);\n rotate2 = hej;\n rotate1 = alo;\n}\n</code></pre>\n\n<p>I've deduced the following diagram of your coordinate system:</p>\n\n<p><img src=\"https://i.stack.imgur.com/CBikr.png\" alt=\"Coordinate system\"></p>\n\n<p>There are bugs:</p>\n\n<ul>\n<li>In your drawing, the controls are circular or square. Your code has rectangular control zones, which are only square if the screen has a 5:3 width:height ratio.</li>\n<li><code>alo</code> ranges from 0.0 to 1.0 within each control zone which seems reasonable, but <code>hej</code> ranges from 0.0 to 0.2.</li>\n<li>If a pointer is dragged outside the control zone but not released, the event handler keeps updating <code>move1</code>, <code>move2</code>, <code>rotate1</code>, and <code>rotate2</code> to some possibly crazy values. (<code>alo</code> can have values from -8.0 to +8.0; <code>hej</code> can have values from -0.2 to +1.0.)</li>\n</ul>\n\n<p>My recommendations:</p>\n\n<ul>\n<li>If you want circular-looking controls, then specify each control zone as a center and a radius.</li>\n<li>If a pointer is dragged outside the control zone not not released, I think that a reasonable behaviour might be to report the orientation, but cap the magnitude of the reading at the control zone radius.</li>\n</ul>\n\n<h3>Pointer lifecycle</h3>\n\n<p>There is another bug: If the pointer is released outside the gray rectangles, then that control will continue on autopilot. I suspect that that is not what you intended.</p>\n\n<p>A pointer starts out with an <code>ACTION_DOWN</code>/<code>ACTION_POINTER_DOWN</code> action, followed by <code>ACTION_MOVE</code> actions, and ends with an <code>ACTION_UP</code>/<code>ACTION_POINTER_UP</code> action. You want two modes:</p>\n\n<ul>\n<li>For <em>down</em>, if the coordinates are within either control zone, note which control that pointer is associated with (using an instance variable).</li>\n<li>For <em>move</em>, update the coordinates of the control associated with the pointer, if it is associated with a control zone.</li>\n<li>For <em>up</em>, reset the readings of the control to 0, if the pointer is associated with a control zone.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-29T22:04:07.987", "Id": "45713", "ParentId": "25135", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T11:52:31.700", "Id": "25135", "Score": "3", "Tags": [ "java", "android" ], "Title": "Dual Analog Stick Controls" }
25135
<p>I'm using OpenGL to draw about 20 circles. Each circle has 2 lines, ~10 segments, and all of them have different colors and lengths. Frames per Second are around 4.</p> <p>How can I optimize this to run faster, with higher frame-rates? I am using Python 3 on Ubuntu.</p> <pre><code>class ScreenOpenGL(Screen): def __init__(self,layers,layers_lock): """ Инициализирует экран и запускает его, потом всю программу """ Screen.__init__(self,"OpenGL",layers,layers_lock) self.window = 0 self.quad = None self.keypress = [] print("Fuck") # self.infoScreen = ScreenCursesInfo() self.infoScreen = ScreenStandartInfo() GLUT.glutInit(sys.argv) GLUT.glutInitDisplayMode(GLUT.GLUT_RGBA | GLUT.GLUT_DOUBLE | GLUT.GLUT_ALPHA | GLUT.GLUT_DEPTH) GLUT.glutInitWindowSize(640, 480) GLUT.glutInitWindowPosition(400, 400) self.window = GLUT.glutCreateWindow(b"Project Evoluo alpha") GLUT.glutDisplayFunc(self._loop) # Функция, отвечающая за рисование GLUT.glutIdleFunc(self._loop) # При простое перерисовывать GLUT.glutReshapeFunc(self._resize) # изменяет размеры окна GLUT.glutKeyboardFunc(self._keyPressed) # Обрабатывает нажатия self._initGL(640, 480) field_params(640, 480) print("Fuck") def run(self): # для threading GLUT.glutMainLoop() def _initGL(self,Width,Height): GL.glShadeModel(GL.GL_SMOOTH); GL.glClearColor(0.0, 0.0, 0.0, 0.0) # This Will Clear The Background Color To Black GL.glClearDepth(1.0) # Enables Clearing Of The Depth Buffer GL.glDepthFunc(GL.GL_LESS) # The Type Of Depth Test To Do GL.glHint(GL.GL_LINE_SMOOTH_HINT, GL.GL_NICEST) GL.glEnable(GL.GL_BLEND); # Enable Blending GL.glLineWidth(1.); GL.glDisable(GL.GL_LINE_SMOOTH) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); self.width = Width self.height = Height self.quad = GLU.gluNewQuadric() GLU.gluQuadricNormals(self.quad, GLU.GLU_SMOOTH) GLU.gluQuadricTexture(self.quad, GL.GL_TRUE) def _resize(self,Width,Height): if Height == 0: Height = 1 self.width = Width self.height = Height field_params(Width,Height) GL.glViewport(0, 0, Width, Height) # Reset The Current Viewport And Perspective Transformation GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glOrtho(0.0,Width,0.0,Height,-1.0,1.0) GL.glMatrixMode(GL.GL_MODELVIEW) # Select The Modelview Matrix GL.glLoadIdentity() def update(self): GLUT.glutSwapBuffers() def clear(self): GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) GL.glLoadIdentity() # Reset The View def write(self,pos,str): pass def __del__(self): del(self.infoScreen) GLUT.glutDestroyWindow(self.window) self._end() # sys.exit() def getch(self): if self.keypress != []: # print return self.keypress.pop(-1)[0] else: return None def _keyPressed(self,*args): if args != None: self.keypress.append(args) print(self.keypress) def _draw_prepare(self): del(self._layers) self._layers = [] for layer in layers: if layer.__class__ == LayerObjects: self._layers.append([layer.type,copy.deepcopy(layer.get_objs()),copy.copy(layer._attacked)]) def draw_eyes(self,vis,r_max,dphi): for x in range(0,7): GLU.gluPartialDisk(self.quad, 1, vis[x][0] * r_max, 5, 3, - ((x - 3) * 15 + 7.5 + dphi / pi * 180) + 90, 15) def draw_sensitivity(self,sens,r_max,dphi): for x in range(0,5): GLU.gluPartialDisk(self.quad, 1, sens[x] * r_max, 5, 3, - (52.5 + (x+1) * 51 + dphi / pi * 180) + 90, 51) pass def draw_obj(self,obj,_id,pos,circle,lines,attacked): # Кружок GL.glLoadIdentity() GL.glTranslatef(pos[0]-1,pos[1]-1,0) red,green,blue = obj.color # берём цвет GL.glColor3f(red,green,blue) GLU.gluDisk(self.quad,*circle) #Глазки GL.glColor3f(1-red,1-green,1-blue) try: eyes = obj.eyes except NameError: pass else: self.draw_eyes(obj.eyes.eyes,obj.radius * k_screen,obj.pos[1]) # Прикосновения GL.glColor3f(1,0,0) try: sensitivity = obj.sensitivity except NameError: pass else: self.draw_sensitivity(obj.sensitivity._sens,obj.radius * k_screen,obj.pos[1]) # Полосочки GL.glBegin(GL.GL_LINES) for color,x,y in lines: GL.glColor3f(*color) GL.glVertex3f(0,0,0) GL.glVertex3f(x,y,0) GL.glEnd() def draw(self,layer): global width,height if layer[0] == "Layer Objects": attacked = layer[2] for obj in layer[1]: #Стрелочки-направления pos = [int(x) for x in obj.get_pos_screen()] positions = [pos,] radius_scr = obj.radius * k_screen att = Vector(radius_scr * (1 +obj._attack_range*obj._attack), obj.pos[1], isPolar = True ) speed = obj.speed[0] * k_screen * 5 if pos[0] &lt; radius_scr: positions.append([pos[0] + self.width,pos[1]]) if pos[0] + radius_scr &gt; self.width: positions.append([pos[0] - self.width,pos[1]]) if pos[1] &lt; radius_scr: positions.append([pos[0],pos[1] + self.height]) if pos[1] + radius_scr &gt; self.height: positions.append([pos[0],pos[1] - self.height]) for ps in positions: self.draw_obj(obj,obj._id, ps , [0,obj.radius*k_screen,20,1], [ [ (1,0,0) , att.x, att.y ], [ (0,0,1) , speed.x, speed.y] ] , attacked) self.infoScreen.draw() </code></pre> <p>Function code that draws:</p> <pre><code> def _draw_prepare(self): """ Копирует из глобальной переменной всё, что ей нужно """ self._layers = copy.deepcopy(layers) def _loop(self): global tick if (self.ch == b'q') or (self.ch == b'\xb1') or (self.ch == 27) or (self.ch == 113): isEnd = True self.__del__() del(self) return 0 elif (self.ch == b's'): self._is_draw = not self._is_draw print("changed to %d" %self._is_draw) else: if (self.last_tick != tick) and (self._is_draw): self.layers_lock.acquire(1) self._draw_prepare() self.layers_lock.release() self.last_tick = tick # рисует сцену return self._main() def _main(self): global tick self.clear() if self._is_draw: for layer in self._layers: self.draw(layer) self.update() self.ch = self.getch() </code></pre> <p>And on <a href="https://github.com/ktulhy-kun/project_evoluo/blob/master/evoluo.py#L213" rel="nofollow">GitHub</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T13:43:29.247", "Id": "38962", "Score": "1", "body": "First, we're a code review...not here to fix code. Having said that, your code does not follow *any* style-rules. Sometimes there are spaces between operators, sometimes there are not, sometimes there are spaces after a comma, sometimes not...sometimes there are English comments, sometimes they're Russian(?)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-03T20:39:03.650", "Id": "105992", "Score": "0", "body": "A bad algorithm is not a broken algorithm. Voted to leave open. Further more, all facets of the code are up for review, not the performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-04T12:22:20.063", "Id": "106115", "Score": "0", "body": "This post [was mentioned on meta](http://meta.codereview.stackexchange.com/q/2206/41243)." } ]
[ { "body": "<p>Not really sure why this line is neccesary.</p>\n\n<pre><code>print(\"Fuck\")\n</code></pre>\n\n<p>Unless <code>\"Fuck\"</code> is Russian for something, this should be removed.</p>\n\n<p>In addition, using <code>%</code> for string formatting is deprecated. One should be using <a href=\"https://docs.python.org/3/library/string.html#string.Formatter.format\"><code>str.format</code></a> instead. <code>str.format</code> supports normal, positional, and named parameters. Here's an example:</p>\n\n<pre><code># str.format without positional or named parameters\nprint(\"{} {}\".format(\"Hello\", \"world\"))\n\n# str.format with positional parameters\nprint(\"{1} {0}\".format(\"world\", \"Hello\"))\n\n# str.format with named parameters\nprint(\"{word1} {word2}\".format(word1=\"Hello\", word2=\"world\"))\n</code></pre>\n\n<p>I also noticed that you're mixing English and Russian comments. I'd recommend sticking to one language or the other.</p>\n\n<p>In the class <code>ScreenOpenGL</code> you have a \"private\" method named <code>_initGL</code>. Is there any reason why the contents of this method can't just be part of <code>__init__</code>?</p>\n\n<p>You also don't need parentheses around Boolean conditions. For example, <code>(self.last_tick != tick)</code> would become <code>self.last_tick != tick</code>. </p>\n\n<p>Finally, I noticed that you're mixing a lot of naming styles. Variables and functions should be <code>snake_case</code>, and classes should be <code>PascalCase</code>. If a variable is a constant (un-changing value), it should be in <code>UPPER_SNAKE_CASE</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-24T07:13:20.560", "Id": "179249", "Score": "1", "body": "So, \"print(\"Fuck\")\" used for debug :)\nOther comment's -- thank, but this code was written a long ago, and most of things I already know. Thank anyway!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-15T22:50:25.440", "Id": "97067", "ParentId": "25138", "Score": "7" } } ]
{ "AcceptedAnswerId": "97067", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T13:37:05.810", "Id": "25138", "Score": "5", "Tags": [ "python", "performance", "python-3.x", "linux", "opengl" ], "Title": "Accelerate OpenGL 2D on Python3" }
25138
<p>In a new project I am creating for my work, I am creating a fairly large ASP.NET web API. The API will be in a separate Visual Studio solution that also contains all of my business logic, database interactions, and <code>Model</code> classes.</p> <p>In the test application I am creating (which is ASP.NET MVC4), I want to be able to hit an API URL I defined from the control and cast the return JSON to a <code>Model</code> class. The reason behind this is that I want to take advantage of strongly typing my views to a <code>Model</code>. This is all still in a proof of concept stage, so I have not done any performance testing on it, but I am curious if what I am doing is a good practice, or if I am crazy for even going down this route. </p> <p>Here is the code on the client controller:</p> <pre><code>public class HomeController : Controller { protected string dashboardUrlBase = "http://localhost/webapi/api/StudentDashboard/"; public ActionResult Index() //This view is strongly typed against User { //testing against Joe Bob string adSAMName = "jBob"; WebClient client = new WebClient(); string url = dashboardUrlBase + "GetUserRecord?userName=" + adSAMName; //'User' is a Model class that I have defined. User result = JsonConvert.DeserializeObject&lt;User&gt;(client.DownloadString(url)); return View(result); } . . . } </code></pre> <p>If I choose to go this route, another thing to note is I am loading several partial views in this page (as I will also do in subsequent pages). The partial views are loaded via an <code>$.ajax</code> call that hits this controller and does basically the same thing as the code above:</p> <ol> <li>Instantiate a new <code>WebClient</code></li> <li>Define the URL to hit</li> <li>Deserialize the result and cast it to a <code>Model</code> Class</li> </ol> <p>So it is possible (and likely) I could be performing the same actions 4-5 times for a single page. </p> <p>Is there a better method to do this that will:</p> <ol> <li>Let me keep strongly typed views</li> <li>Do my work on the server rather than on the client (this is just a preference since I can write C# faster than I can write JavaScript)</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T15:48:02.030", "Id": "60531", "Score": "0", "body": "This method will probably help your cause: http://i-skool.co.uk/net/re-usable-webapi-request-wrapper/ Let's you call an API route and return the delegated object." } ]
[ { "body": "<p>All the controlers are regular classes with methods.</p>\n\n<p>Assuming your API controller <code>StudentDashboard</code> has a <code>Get(string name)</code> verb method, you can do this:</p>\n\n<pre><code>public ActionResult Index() //This view is strongly typed against User\n{\n //testing against Joe Bob\n string adSAMName = \"jBob\";\n var apiController = new StudentDashboardController(); //or whatever other API controller returns your data\n var result = apiController.Get(adSAMName);\n return View(result);\n}\n</code></pre>\n\n<p>This should give you strong typing.\nYou can also instantiate and use 'regular' MVC controllers too.</p>\n\n<p>[EDIT]</p>\n\n<p>Per comment, it's even better if you delegate the controller creation to the framework</p>\n\n<pre><code>ControllerBuilder.GetControllerFactory().CreateController(Request.RequestContext, controllerName);\n</code></pre>\n\n<p>You can either set the string or extract it from the type if you want stronger typing.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.controllerbuilder%28v=vs.108%29.aspx\" rel=\"nofollow\">Reference MSDN</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T20:47:16.890", "Id": "38914", "Score": "2", "body": "I think I would consider using the framework to make the controller as that way and DI will be sorted for you i.e. ControllerBuilder.Current.GetControllerFactory().CreateController(Request.RequestContext, controllerName)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T06:47:59.067", "Id": "38932", "Score": "0", "body": "@dreza Very good point, I'll include that possibility." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T19:44:41.273", "Id": "25150", "ParentId": "25141", "Score": "3" } }, { "body": "<h2>Testing?</h2>\n\n<p>Then create a simple unit test and test your API controller or your business layer classes directly.\nIf you want to create an integration test or need a cleaner solution in production code read further.</p>\n\n<h2>Wrapping the API calls</h2>\n\n<p>This is just a disposable wrapper around the WebClient which can be easily reused.</p>\n\n<pre><code>public abstract class WebClientWrapperBase : IDisposable\n{\n private readonly string _baseUrl;\n private Lazy&lt;WebClient&gt; _lazyClient;\n\n protected WebClientWrapperBase(string baseUrl)\n {\n _baseUrl = baseUrl.Trim('/');\n _lazyClient = new Lazy&lt;WebClient&gt;(() =&gt; new WebClient());\n }\n\n protected WebClient Client()\n {\n if (_lazyClient == null)\n {\n throw new ObjectDisposedException(\"WebClient has been disposed\");\n }\n\n return _lazyClient.Value;\n }\n\n protected T Execute&lt;T&gt;(string urlSegment)\n {\n return JsonConvert.DeserializeObject&lt;T&gt;(Client().DownloadString(_baseUrl + '/' + urlSegment.TrimStart('/')));\n }\n\n ~WebClientWrapperBase()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(false);\n GC.SuppressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (_lazyClient != null)\n {\n if (disposing)\n {\n if (_lazyClient.IsValueCreated)\n {\n _lazyClient.Value.Dispose();\n _lazyClient = null;\n }\n }\n\n // There are no unmanaged resources to release, but\n // if we add them, they need to be released here.\n }\n }\n}\n</code></pre>\n\n<p>Creating a \"strongly typed proxy\":</p>\n\n<pre><code>class StudentDashboardClient : WebClientWrapperBase\n{\n public StudentDashboardClient()\n : base(\"http://localhost/webapi/api/StudentDashboard/\")\n {\n //just for compatibility\n }\n\n public StudentDashboardClient(string baseUrl)\n : base(baseUrl)\n {\n }\n\n public User GetUserRecord(string userName)\n {\n return Execute&lt;User&gt;(\"GetUserRecord?userName=\" + userName);\n }\n}\n</code></pre>\n\n<p>And then passing to your controllers where it's needed:</p>\n\n<pre><code>public class HomeController : Controller\n{\n private readonly StudentDashboardClient _studentDashboardClient;\n\n public HomeController(StudentDashboardClient studentDashboardClient)\n {\n _studentDashboardClient = studentDashboardClient;\n }\n\n public ActionResult Index()\n {\n return View(_studentDashboardClient.GetUserRecord(\"jBob\"));\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing)\n {\n _studentDashboardClient.Dispose();\n }\n base.Dispose(disposing);\n }\n}\n</code></pre>\n\n<p>Note that the controller now have a parameterless constructor so you will need a solution to instantiate controllers this way for example a DI framework with MVC support like Ninject.</p>\n\n<p>What you gain? Cleaner code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T20:50:31.280", "Id": "38915", "Score": "0", "body": "I quite like that wrapper. Simple but does the job that the OP seems to want" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-23T03:18:34.873", "Id": "158592", "Score": "0", "body": "Does this wrapper takes care of POSTs as well?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T19:59:27.180", "Id": "25151", "ParentId": "25141", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T14:45:36.390", "Id": "25141", "Score": "18", "Tags": [ "c#", "performance", "asp.net", "web-services" ], "Title": "Consuming an ASP.NET Web API call in an MVC controller" }
25141
<p>I am brand new to dictionaries and coding and am hoping to get some suggestions on how I should structure my dictionary. </p> <p>I have a collector number which has meters connected to them. Each of the meters have a meter number and a ert number and would like to store both the meter and ert number. There will be a list of meter reading timestamps and values for each of the meters. Also, I would like to be able to select the values by either the ert number or meter number. I have attached the current structure I have for the dictionary but was wondering if this was the best way to format the dictionary. Someone had suggested objects but I have never worked with objects before.</p> <pre><code>{ Dictionary&lt;Int32, Dictionary&lt;string, Meter&gt;&gt; dictionary = new Dictionary&lt;int, Dictionary&lt;string, Meter&gt;&gt;(); if (!dictionary.ContainsKey(objectID)) { dictionary.Add(objectID, new Dictionary&lt;string, Meter&gt;()); } Meter meter = new Meter(); meter.ertNumber = "9480:1"; meter.meterNumber = "fsadfa"; meter.Reading = new Dictionary&lt;Int32, double&gt;(); meter.Reading.Add(0, 6); dictionary[objectID].Add("Test", meter); } class Meter { public String ertNumber { get; set; } public String meterNumber { get; set; } public Dictionary&lt;Int32, double&gt; Reading { get; set; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T17:30:39.950", "Id": "38900", "Score": "5", "body": "Dictionaries are fast (O(1)) but not handy if you need to find items by more than one 'key'. If the lists will not be large you'd be better of just using a list of objects (classes) using `Linq` to find items. I also think that is what that someone meant by 'objects'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T18:44:44.817", "Id": "38908", "Score": "0", "body": "That makes sense. I have been thinking about it and I really do not need the objectID and only need either the ert or meter number to reference. The function of the dictionary is to be able to add every meter numbers value at a desired index. I think I will be able to create a dictionary that can use the Meter Number as the key then the value is another dictionary that will have keys from 0-however long the list is and the value as the meter value." } ]
[ { "body": "<p>If you have a collection of <code>Meter</code>s and you want to be able to find the ONE based on a property, this is how I would do it:</p>\n\n<p>Create a <code>List</code> of <code>Meter</code>s, say <code>l</code>..</p>\n\n<pre><code>List&lt;Meter&gt; l = new List&lt;Meter&gt;();\n</code></pre>\n\n<p>Then implement Extension methods like so..</p>\n\n<pre><code>public static class MeterExt\n{\n public static Meter GetByErm(this List&lt;Meter&gt; l, String sErm)\n {\n Meter r = l.Find(s =&gt; s.ertNumber == sErm);\n\n return r;\n }\n\n public static Meter Get(this List&lt;Meter&gt; l, String sMeter)\n {\n Meter r = l.Find(s =&gt; s.meterNumber == sMeter);\n\n return r;\n }\n}\n</code></pre>\n\n<p>Then you can find your meter like so..</p>\n\n<pre><code>Meter m = l.Get(\"fsadfa\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T19:12:49.400", "Id": "25149", "ParentId": "25143", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T16:44:58.397", "Id": "25143", "Score": "0", "Tags": [ "c#", "hash-map" ], "Title": "Dictionary Structure" }
25143
<p>I'm working on a piece of code for calculating all the possible combinations of numbers that sum to <em>n</em>. For example:</p> <pre><code>sum_combination(3) = [ [1,1,1], [1,2], [3] ] </code></pre> <p>So my ruby code is this:</p> <pre><code>class Integer SUM_COMBINATION = { 1 =&gt; [[1]], 2 =&gt; [[1,1],[2]], 3 =&gt; [[1,1,1],[1,2],[3]] } def sum_combination SUM_COMBINATION[self] ||= ( (self-1).downto((self/2.0).ceil).map do |n| n.sum_combination.map { |c| (c+[self-n]).sort } end.flatten(1).uniq + [[self]] ) end end </code></pre> <p>The code works, but it's insanely slow for numbers above 50.</p>
[]
[ { "body": "<p>Unless you need the entire set of combinations immediately, you could use <a href=\"http://ruby-doc.org/core-2.0/Enumerable.html#method-i-lazy\" rel=\"nofollow\">a <code>lazy</code> enumerator</a>, which just gets the next item in the set when asked.</p>\n\n<p>This requires using Ruby 2.0, as it was only recently implemented.</p>\n\n<p>Here's a great article about it <a href=\"http://patshaughnessy.net/2013/4/3/ruby-2-0-works-hard-so-you-can-be-lazy\" rel=\"nofollow\">iterating over an infinite range</a>.</p>\n\n<p>If using Ruby 2.0 isn't an option, then you're screwed. Your problem is inherently exponentially more costly as the value of <code>n</code> increases. Unlike <a href=\"http://projecteuler.net/problem=31\" rel=\"nofollow\">the coin/money problem</a> where the number of possible coins (8) never increases, in the problem you're proposing <strong>both</strong> the number of output combinations <strong>and</strong> the number of integers that can go into making them increases infinitely as you increase the value of <code>n</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T21:11:06.197", "Id": "39069", "Score": "0", "body": "I don't think the number of unique combinations ([1, 1, 2] and [2, 1, 1] being treated as non-unique) may not grow exponentially, but the number of possible arrangements of integers may (where the previous example is taken as two possible combinations instead of one) - it's an interesting question. If, in the process of calculating all possible unique combinations you have to calculate the non-unique ones as well, that's a ton of wasted time. In that scenario most of the time spent would be wasted. Maybe there's a simple away to avoid this duplication." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T09:31:34.773", "Id": "39169", "Score": "1", "body": "If we take permutations instead of combinations indeed we have exponential cases (2^(N-1)). But there is no need to do that, check my answer, you simply have to pass down what's the maximum value you are allowed to subtract in that branch." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T20:25:42.523", "Id": "25153", "ParentId": "25148", "Score": "2" } }, { "body": "<p>I don't have a specific solution for you yet, but I can point you in the right direction.</p>\n\n<p>I threw your code into irb and ran it through <a href=\"http://ruby-prof.rubyforge.org/\" rel=\"nofollow\">RubyProf</a>. RubyProf will tell you where the bottlenecks in your code are and help you optimize it.</p>\n\n<p>I copied your code into IRB, then ran the following script:</p>\n\n<pre><code>require 'ruby-prof'\n\nresult = RubyProf.profile do\n 20.sum_combination\nend\n\nprinter = RubyProf::FlatPrinter.new(result)\nprinter.print(STDOUT)\n</code></pre>\n\n<p>The output is:</p>\n\n<pre><code> %self total self wait child calls name\n 37.03 0.160 0.096 0.000 0.064 15390 Array#hash\n 24.57 0.064 0.064 0.000 0.000 104648 Kernel#hash\n 12.37 0.055 0.032 0.000 0.023 11754 Array#eql?\n 8.71 0.023 0.023 0.000 0.000 36146 Numeric#eql?\n 6.74 0.233 0.018 0.000 0.216 17 Array#uniq\n 6.31 0.026 0.016 0.000 0.009 98 Array#map\n 3.59 0.009 0.009 0.000 0.000 7695 Array#sort\n 0.16 0.000 0.000 0.000 0.000 636 Fixnum#==\n 0.15 0.000 0.000 0.000 0.000 17 Array#flatten\n 0.04 0.260 0.000 0.000 0.260 1 Object#irb_binding\n 0.02 0.260 0.000 0.000 0.260 99 *Integer#sum_combination\n 0.01 0.000 0.000 0.000 0.000 17 Float#ceil\n 0.01 0.000 0.000 0.000 0.000 17 Hash#[]=\n 0.01 0.000 0.000 0.000 0.000 17 Fixnum#/\n 0.01 0.200 0.000 0.000 0.200 34 *Integer#downto\n 0.00 0.200 0.000 0.000 0.200 17 *Enumerator#each\n 0.00 0.200 0.000 0.000 0.200 17 *Enumerable#map\n</code></pre>\n\n<p>As you can see, the vast majority of your time is spent in #hash and #eql?, which are called by sort, uniq, and possibly flatten. That suggests that finding ways to avoid uniquifying the data until you've completed the algorithm would be much more efficient.</p>\n\n<p>If you can refactor your code to avoid calling sort, flatten, and uniq on every run, that would speed things up significantly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T20:33:14.373", "Id": "38913", "Score": "0", "body": "Really good catch, didn't know of this gem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T10:59:31.270", "Id": "38941", "Score": "0", "body": "I am not sure profiling is very useful to analyze an algorithm. I mean, the most efficient implementation could have a similar profile for all we know, these are only relative times. In general algorithms require a more mathematical approach to see what's going on. Though indeed is some cases it may give a hint where the problem lies." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T20:30:22.770", "Id": "25154", "ParentId": "25148", "Score": "2" } }, { "body": "<p>Notes:</p>\n\n<ul>\n<li>Using <code>uniq</code> in a combinatorics problem is most likely a code smell. It means that you are generating more elements that you need (waste of space and time) and later you have to remove them (waste of more time).</li>\n<li>The natural way seems to be passing down which is the maximum subtraction value allowed, that way you won't repeat values in different orders. </li>\n<li>I wouldn't extend <code>Integer</code> for a method like this, it does not seem a general enough abstraction.</li>\n<li>Note that <code>map</code> + <code>flatten(1)</code> -> <code>flat_map</code>. </li>\n</ul>\n\n<p>I'd write (also in functional style, as your code):</p>\n\n<pre><code>module Combinatorics\n def self.sets_with_sum(value, max = value)\n if value == 0\n [[]]\n else\n 1.upto(max).flat_map do |n|\n sets_with_sum(value - n, [value, n].min).map do |ns|\n [n] + ns\n end\n end\n end \n end\nend\n\np Combinatorics.sets_with_sum(4)\np Combinatorics.sets_with_sum(50).size\n</code></pre>\n\n<p>Even though I don't memoize anything, the performance is acceptable:</p>\n\n<pre><code>$ time ruby sum-combination.rb\n[[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]\n204226\n\nreal 0m8.416s\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T22:03:14.527", "Id": "25203", "ParentId": "25148", "Score": "5" } } ]
{ "AcceptedAnswerId": "25203", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T18:45:55.793", "Id": "25148", "Score": "5", "Tags": [ "ruby", "combinatorics" ], "Title": "Optimizing sum_combination_for(n) code" }
25148
<p>I've got this method, and it's quite a big method. I look at it, and I feel... dirty. I feel that it's doing too much, and that there might be a better way to accomplish what I'm trying to.</p> <pre><code>/// &lt;summary&gt; /// Calculates daily project drilling hours /// &lt;/summary&gt; /// &lt;param name="daily"&gt;Bool: True for daily, false for total project&lt;/param&gt; /// &lt;param name="timeFrame"&gt;Bool: True for specific time frame, false for whole day &lt;/param&gt; /// &lt;returns&gt;Double: Drilling hours for time frame&lt;/returns&gt; public double CalculateDrillingHours(bool daily = false, bool timeFrame = false) { Logger.Info("Calculating Drilling Hours"); var query = "SELECT timestamp FROM myDatabase WHERE measured_dist = bit_loc AND rop &gt; 0"; query = BuildQuery(query, daily, timeFrame); var tempList = ExecuteQuery(query); // The user needs to know if there was no data for the time frame chosen var noData = new Exception("There was no data for the selected time frame. Please select another. (Drilling Hours)"); if (tempList.Count &lt; 1) { throw noData; } if(!daily) { TotalProjectDrillingHours = Convert.ToDouble(Math.Round(TimeCalculations(ConvertStringListToDateTimeList(tempList)).TotalHours, 2, MidpointRounding.AwayFromZero)); Logger.Info("Total Drilling Hours calculated"); return TotalProjectDrillingHours; } DailyDrillingHours = Convert.ToDouble(Math.Round(TimeCalculations(ConvertStringListToDateTimeList(tempList)).TotalHours, 2, MidpointRounding.AwayFromZero)); Logger.Info("Daily Drilling Hours calculated"); return DailyDrillingHours; } </code></pre> <p>This method returns 1 of 2 items: Either Daily Drilling Hours, or Total Project Drilling Hours. This was originally two methods, but I combined them because a lot of the code was being duplicated, and it made sense at the time (about 6 months ago). But now, looking at it, I'd like to improve this. Is there a better way? </p> <p>Yes, I know about parameterized queries. I've already incorporated those in the final query, which would look something like this:</p> <pre><code>query = "SELECT timestamp FROM myDatabase WHERE measured_dist = bit_loc AND rop &gt; 0 AND date = @Date AND timestamp BETWEEN @StartTime AND @EndTime"; </code></pre>
[]
[ { "body": "<p>Without going too far I've simplified your method. I'll leave the bigger stuff to someone who is more familiar with the content. I haven't touched correctness and/or functionality.\nYou should also have some try/catch around the query stuff and the conversions.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Calculates daily project drilling hours\n/// &lt;/summary&gt;\n/// &lt;param name=\"daily\"&gt;Bool: True for daily, false for total project&lt;/param&gt;\n/// &lt;param name=\"timeFrame\"&gt;Bool: True for specific time frame, false for whole day &lt;/param&gt;\n/// &lt;returns&gt;Double: Drilling hours for time frame&lt;/returns&gt;\npublic double CalculateDrillingHours(bool daily = false, bool timeFrame = false)\n{\n Logger.Info(\"Calculating Drilling Hours\");\n\n string queryString = \"SELECT timestamp FROM myDatabase WHERE measured_dist = bit_loc AND rop &gt; 0\";\n var query = BuildQuery(queryString, daily, timeFrame);\n var queryResults = ExecuteQuery(query);\n\n // The user needs to know if there was no data for the time frame chosen\n if (queryResults.Count &lt; 1)\n {\n throw new Exception(\"There was no data for the selected time frame. Please select another. (Drilling Hours)\");;\n }\n\n var drillingHours = Convert.ToDouble(Math.Round(TimeCalculations(ConvertStringListToDateTimeList(queryResults )).TotalHours, 2, MidpointRounding.AwayFromZero));\n\n Logger.Info((daily ? \"Daily\" : \"Total\") + \" Drilling Hours calculated\");\n\n return drillingHours;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T22:03:03.080", "Id": "25156", "ParentId": "25155", "Score": "3" } }, { "body": "<p>I think your method is doing too much. Any time you have two possible measures returned, you have to be thinking code smell. When code is duplicated, instead of combining the methods into one method, refactor the duplicated code into separate methods. There are also too many concerns in the method.</p>\n\n<p>Personally, I would extract out the data retrieval into its own class/methods, ideally with an interface to you can inject mocks and fakes for unit testing. I like the repository pattern for this, keeps things simple, and a lot of people know about it, so maintenance is fairly easy.</p>\n\n<p>Seems the only way the measures differ is in the query. I would create two methods <code>CalculateDailyDrillingHours</code> and <code>CalculateTotalDrillingHours</code>. These two methods would call a thirds method, passing in the start and end times as required. The third method would then call the repository, and calculate the hours.</p>\n\n<pre><code>public double CalculateDailyDrillingHours()\n{\n return CalculateDrillingHoursForDateRange(/*dateStartTime*/, /*dateEndTime*/);\n}\n\npublic double CalculateTotalDrillingHours()\n{\n return CalculateDrillingHoursForDateRange(/*dateStartTime*/, /*dateEndTime*/);\n}\n\nprivate double CalculateDrillingHoursForDateRange(DateTime startAt, DateTime, endAt)\n{\n var drillHourList = _repository.GetDrillTimesBasedOnDate(startAt, endAt);\n\n return Convert.ToDouble(\n Math.Round(\n TimeCalculations(ConvertStringListToDateTimeList(tempList)).TotalHours, \n 2, \n MidpointRounding.AwayFromZero));\n}\n</code></pre>\n\n<p>I would go one step further and movethe calucation of hours to its own method, and give it a descriptive name, this will further clear up the intent of the above code.</p>\n\n<pre><code>public double ConvertTimestampsToHours(IEnumerable&lt;/*class*/&gt; timestamps)\n{\n return Convert.ToDouble(\n Math.Round(\n TimeCalculations(ConvertStringListToDateTimeList(tempList)).TotalHours, \n 2, \n MidpointRounding.AwayFromZero));\n}\n\nprivate double CalculateDrillingHoursForDateRange(DateTime startAt, DateTime, endAt)\n{\n var drillHourList = _repository.GetDrillTimesBasedOnDate(startAt, endAt);\n\n return ConvertTimestampsToHours(drillHourList);\n}\n</code></pre>\n\n<p>You can add logging as required.</p>\n\n<p>One other thing:</p>\n\n<p>Instead of doing <code>if (tempList.Count &lt; 1)</code>, do <code>if (!tempList.Any())</code>, it makes the code a little more clear.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T22:21:45.953", "Id": "25157", "ParentId": "25155", "Score": "1" } }, { "body": "<p>I would consider first splitting the method into smaller methods as other people have mentioned. The only suggestion for now is I might suggest changing your bool daily to a enumeration. This in theory means it might be easier to add a Hourly,Monthly etc reporting option. Although this is only slightly better in my opinion and I'm sure there are better approaches (maybe using interfaces?).</p>\n\n<p>Something like this as an exercise in splitting things out into various methods keeping most of your code but just re-arranging it slightly.</p>\n\n<pre><code>public double CalculateDrillingHours(DrillingPeriod period = DrillingPeriod.Daily, bool timeFrame = false)\n{\n Logger.Info(\"Calculating Drilling Hours\");\n var tempList = GetDrillingTimes(period, timeFrame);\n\n var drillingHours = CalculateDrillingHours(tempList);\n SetDrillingTimes(period, drillingHours);\n\n return drillingHours;\n}\n\nprivate void SetDrillingTimes(DrillingPeriod period, double drillingHours)\n{\n switch (period)\n {\n case DrillingPeriod.Daily:\n Logger.Info(\"Total Drilling Hours calculated\"); \n DailyDrillingHours = drillingHours;\n break;\n case DrillingPeriod.Total:\n Logger.Info(\"Daily Drilling Hours calculated\");\n TotalProjectDrillingHours = drillingHours;\n break;\n default:\n throw new NotImplementedException(\"Drilling period not supported\");\n }\n}\n\nprivate List&lt;DateTime&gt; GetDrillingTimes(DrillingPeriod period, bool timeFrame)\n{\n var query = \"SELECT timestamp FROM myDatabase WHERE measured_dist = bit_loc AND rop &gt; 0\";\n\n var daily = period == DrillingPeriod.Daily;\n query = BuildQuery(query, daily, timeFrame);\n\n var tempList = ExecuteQuery(query);\n\n if (tempList.Any())\n {\n return tempList;\n }\n\n // I would look at possibly using a custom exception here i.e. NoDataException\n throw new NoDataException(\"There was no data for the selected time frame. Please select another. (Drilling Hours)\");\n} \n\nprivate double CalculateDrillingHours(List&lt;DateTime&gt; projectHours)\n{\n return Convert.ToDouble(Math.Round(TimeCalculations(ConvertStringListToDateTimeList(projectHours)).TotalHours, 2, MidpointRounding.AwayFromZero));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T07:42:59.590", "Id": "38935", "Score": "0", "body": "In `SetDrillingTimes` it looks like you have the wrong code in each switch `DrillingPeriod.Daily` is dealing with totals?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T08:07:30.830", "Id": "38938", "Score": "0", "body": "@TrevorPilley so I do. Cheers" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T20:06:15.470", "Id": "38982", "Score": "0", "body": "Thank you. This is the approach I'm going to take. I'm attempting to have this work for the entire class, and not just this particular method. Hopefully, worth the effort." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T20:12:44.087", "Id": "38983", "Score": "0", "body": "@CL4PTR4P no problem. Always plenty of ways to skin a cat, but glad this approach helped you." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T22:44:22.860", "Id": "25158", "ParentId": "25155", "Score": "5" } } ]
{ "AcceptedAnswerId": "25158", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-16T21:42:18.350", "Id": "25155", "Score": "6", "Tags": [ "c#" ], "Title": "Calculating daily project drilling hours" }
25155
<p>Thanks for looking it over. I'm still pretty new to programming. I thought this would be a good exercise in addition to making the Project Euler fraction problems easier</p> <pre><code>import java.math.BigInteger; final class BigFraction extends Number{ private BigInteger numerator; private BigInteger denominator; public final static BigFraction ZERO = new BigFraction(BigInteger.ZERO); public BigFraction(String numerator, String denominator, boolean reduce){ this(new BigInteger(numerator), new BigInteger(denominator)); if(reduce) this.reduce(); } public BigFraction(long numerator, long denominator){ this(BigInteger.valueOf(numerator), BigInteger.valueOf(denominator)); } public BigFraction(String numerator, String denominator){ this(new BigInteger(numerator), new BigInteger(denominator)); } public BigFraction(BigInteger numerator, BigInteger denominator){ if(denominator.signum() == 0) throw new IllegalArgumentException("Denominator can't be zero"); if(numerator.signum() == 0){ denominator = BigInteger.ONE; } if(denominator.signum() == -1){ numerator = numerator.multiply( BigInteger.valueOf(-1 )); denominator = denominator.multiply( BigInteger.valueOf(-1 )); } this.numerator = numerator; this.denominator= denominator; } public void reduce(){ if( ! this.numerator.equals(BigInteger.ZERO) ){ BigInteger GCF = (GCF(this.numerator, this.denominator)).abs(); this.numerator = this.numerator.divide(GCF); this.denominator = this.denominator.divide(GCF); } } public BigFraction(BigInteger numerator){ this.numerator = numerator; this.denominator = BigInteger.ONE; } public static BigFraction valueOf(long numerator, long denominator){ return new BigFraction(BigInteger.valueOf(numerator), BigInteger.valueOf(denominator)); } public static BigFraction valueOf(long numerator){ return new BigFraction(BigInteger.valueOf(numerator)); } public BigFraction multiply(BigFraction frac){ BigInteger newNumerator = this.getNumerator().multiply( frac.getNumerator() ); BigInteger newDenominator = this.getDenominator().multiply( frac.getDenominator() ); return new BigFraction(newNumerator, newDenominator); } public BigFraction divide(BigFraction frac){ return this.multiply(new BigFraction(frac.getDenominator(), frac.getNumerator()) ); } public BigFraction add(BigFraction frac){ BigInteger LCM = LCM(frac); BigInteger fracNum = ( LCM.divide( frac.getDenominator() )).multiply( frac.getNumerator() ); BigInteger thisNum = ( LCM.divide( this.getDenominator() )).multiply( this.getNumerator() ); return new BigFraction( thisNum.add(fracNum), LCM ); } public BigFraction subtract(BigFraction frac){ BigInteger LCM = LCM(frac); BigInteger fracNum = (LCM.divide( frac.getDenominator() )).multiply( frac.getNumerator() ); BigInteger thisNum = (LCM.divide( this.getDenominator() )).multiply( this.getNumerator() ); return new BigFraction(thisNum.subtract( fracNum), LCM); } public String toString(){ return this.getNumerator()+"/"+this.getDenominator(); } public BigInteger getNumerator(){ return this.numerator; } public BigInteger getDenominator(){ return this.denominator; } @Override public int intValue() { return (int) this.doubleValue(); } @Override public long longValue() { return (long) this.doubleValue(); } @Override public float floatValue() { return (float) this.doubleValue(); } @Override public double doubleValue() { return (this.numerator).doubleValue() / (this.denominator).doubleValue(); } public boolean equals(BigFraction frac){ return this.compareTo(frac) == 0; } public int compareTo(BigFraction frac){ BigInteger t = this.getNumerator().multiply( frac.getDenominator() ); BigInteger f = frac.getNumerator().multiply( this.getDenominator() ); int result = 0; if(t.max(f).equals(t)) return 1; if(f.max(t).equals(f)) return -1; return result; } public BigInteger LCM(BigFraction frac){ return (frac.getDenominator().multiply( this.getDenominator()).abs()).divide( GCF(frac.getDenominator(), this.getDenominator() ) ) ; } public boolean isReduced(){ BigInteger tempDenominator = numerator.min(denominator); BigInteger tempNumerator = numerator.max(denominator); BigInteger remainder = tempDenominator.mod( tempNumerator ); while(! remainder.equals(BigInteger.ZERO)){ remainder = tempDenominator.mod( tempNumerator ); tempDenominator = tempNumerator; tempNumerator = remainder; } return tempDenominator.equals(BigInteger.ONE); } private BigInteger GCF(BigInteger numerator, BigInteger denominator){ BigInteger tempDenominator = numerator.min(denominator); BigInteger tempNumerator = numerator.max(denominator); numerator = tempNumerator; denominator = tempDenominator; BigInteger remainder = denominator.mod( numerator ); while(! remainder.equals(BigInteger.ZERO)){ remainder = denominator.mod( numerator ); denominator = numerator; numerator = remainder; } return denominator; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T07:10:01.737", "Id": "38934", "Score": "4", "body": "Can you specify what is slow? All operations?" } ]
[ { "body": "<p>You should use <code>BigInteger.gcd()</code> instead of <code>GCF()</code>, also in <code>isReduced()</code>. Don't use <code>compareTo</code> in <code>equals</code>: If your fractions are <em>always</em> in reduced form, you can just compare numerators and denominators. In <code>compareTo</code>, you could test some special cases to avoid multiplication, e.g. <code>a/b &gt; c/d</code> if <code>a &gt; c</code> and <code>b &lt;= d</code> (for <code>a,b,c,d &gt; 0</code>).</p>\n\n<p>I think for multiplication <code>a/b * c/d</code>, it could be faster to reduce <code>a</code> and <code>d</code>, as well as <code>b</code> and <code>c</code>, instead of doing the reduction after the multiplication.</p>\n\n<p>There is a <a href=\"http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/fraction/BigFraction.html\" rel=\"nofollow\">BigFraction class in Apache Commons</a>, maybe you can get some inspiration there...</p>\n\n<p>BTW, method and variable names should be lower-case.</p>\n\n<p><strong>[Update]</strong></p>\n\n<p>I think you should always reduce fractions. This allows you to use shortcuts (e.g. in <code>equals</code> and <code>compareTo</code>), and also faster calculations. If fractions are always reduced, you can compare numerators and denominators in <code>equals</code> (instead of calling <code>compareTo</code>). Further, for multiplication you can reduce before you multiply:</p>\n\n<pre><code>public BigFraction multiply(BigFraction frac){\n BigInteger gcd1 = this.getNumerator().gcd(frac.getDenominator());\n BigInteger num1 = this.getNumerator().divide(gcd1); \n BigInteger den1 = frac.getDenominator().divide(gcd1); \n\n BigInteger gcd2 = frac.getNumerator().gcd(this.getDenominator());\n BigInteger num2 = frac.getNumerator().divide(gcd2); \n BigInteger den2 = this.getDenominator().divide(gcd2); \n\n BigInteger newNumerator = num1.multiply(num2);\n BigInteger newDenominator = den1.multiply(den2);\n return new BigFraction(newNumerator, newDenominator); //already reduced\n}\n</code></pre>\n\n<p>I'm not sure this is faster, but it's worth a try.</p>\n\n<p>Concerning lower-case variable and method names I thought about things like <code>BigInteger LCM = LCM(frac);</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T08:42:27.750", "Id": "38939", "Score": "0", "body": "Thank you for your input. I had no idea about the BigInteger.gcd(). Weird thing to miss, I must have looked the BigInteger doc over 100 times. I only caps the final variables, isn't that according to convention? I'm not sure I understand the second half of your comments, would you mind clarifying? Also, it isn't always in reduced form. The reduce() function has to be called in order to reduce it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T22:47:21.020", "Id": "39304", "Score": "0", "body": "@Josh, I would suggest (and it appears that Landei may have suggested) that you always reduce, at the end of every method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-14T07:47:26.837", "Id": "133763", "Score": "0", "body": "@Josh According to the convention, only constants are all uppercase, which means only `static final` fields which never change their content (primitives and `String`s never do, a `byte[]` may or may not change). I [gave it a try](http://codereview.stackexchange.com/q/73571/14363), too (and the reduction gets always done). I haven't yet benchmark it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T07:50:16.710", "Id": "25164", "ParentId": "25160", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T06:34:50.403", "Id": "25160", "Score": "3", "Tags": [ "java" ], "Title": "I made a BigFraction class in Java. It's a bit slow" }
25160
<p>I have read some articles discussing about why static is bad, some of them refering static as not-testable, non-mockable, has state (non-stateless) and everything else.</p> <p>However I have encountered some cases where I am forced to use static implementation, such as:</p> <ul> <li>During using HttpContext.Current in Asp.Net, as well as Session</li> <li>The HttpContext and Session sometimes contains configurations, which is needed to do some validations</li> <li>Accessing some static objects in framework or third-party component</li> <li>Maybe there are other situation where I don't yet encountered</li> </ul> <p>Up until now I have handle those static methods using custom adapters (correct me if I misuse the term adapter here, or maybe it is better for provider), such as:</p> <pre><code>public class ConfigurationAdapter : IConfigurationAdapter { public string CurrentUsername { get { return HttpContext.Current.User.Identity.Name; } } } </code></pre> <p>Then the consumer will use the adapter like:</p> <pre><code>public class ConfigurationConsumer : IConfigurationConsumer { public ConfigurationConsumer(IConfigurationAdapter adapter) { _adapter = adapter; } private readonly IConfigurationAdapter _adapter; public void DoSomething() { string userName = _adapter.CurrentUsername; } } </code></pre> <p>I believe that this way I can get the benefits:</p> <ul> <li>The adapter can be replaced by other implementation</li> <li>The adapter can be mocked</li> <li>The consumer does not directly dependent on HttpContext</li> </ul> <p>However due to inexperienced in design, I am still wondering about:</p> <ul> <li>Does this kind of implementation can really decouple the consumer with the static object?</li> <li>Will it provide any problem in the future?</li> <li>Is there any better design or pattern than this?</li> </ul> <p>In this case I want to make sure that my application is testable, maintainable dan extendable. I believe performance is not effecting too much here, so it can be ignored.</p> <p>Any kind of thoughts will be appreciated</p>
[]
[ { "body": "<p>I see no problem in such wrappers except they are kinda cumbersome to write. They provide a good way to decouple your code not only from static objects, but from the all the objects you cannot mock too (for example, sealed classes from 3rd party libraries). I use that kind of adapters myself and have little problem with them. It is important to have these classes as simple as possible (so that you don't need to test them) and only expose properties and methods you realy need.</p>\n\n<p><strong>Update:</strong> ctrucza suggests using a service locator in his answer. While it's a good solution when your class has many dependencies which leads to many constructor parameters, it makes unit-testing your class a little harder. </p>\n\n<p>If you add some new dependency into your class and resolve it with some generic service locator's method then your code (including unit tests and production code) will compile just fine. You only realize that something is wrong when your working unit-tests will suddenly fail with null reference exception, or some other resolution exception your service locator provides. The constructor injection, on the other hand, gives you a clear knowledge of what dependencies a class using and if you miss some constructor parameter in your tests, the compiler will tell you. </p>\n\n<p>One more thing. If you have a dozen dependencies in your class, may be the design of the class is wrong and refactoring is needed. I think that's really good indicator, which will be hidden if you are using a service locator pattern.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T12:36:01.243", "Id": "39035", "Score": "0", "body": "Thank you for sharing your experience. Looks like it is the good way to do it anyway." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T11:22:08.513", "Id": "25167", "ParentId": "25161", "Score": "6" } }, { "body": "<p>The only problem with this otherwise nice and simple approach is when you have many classes which need the adapters: you will have to pass the IConfigurationAdapter to each of them.</p>\n\n<p>If this starts to be a problem I usually try to move towards a ServiceLocator:</p>\n\n<pre><code>public class Configuration \n{ \n public static IConfigurationAdapter CurrentConfiguration { get; set; }\n}\n</code></pre>\n\n<p>and use it like this:</p>\n\n<pre><code>public class ConfigurationConsumer\n{\n public ConfigurationConsumer()\n {\n _adapter = Configuration.CurrentConfiguration;\n }\n private readonly IConfigurationAdapter _adapter;\n\n public void DoSomething()\n {\n string userName = _adapter.CurrentUsername;\n }\n}\n</code></pre>\n\n<p>or like this:</p>\n\n<pre><code>public class ConfigurationConsumer\n{\n public void DoSomething()\n {\n IConfigurationAdapter _adapter = Configuration.CurrentConfiguration;\n string userName = _adapter.CurrentUsername;\n }\n}\n</code></pre>\n\n<p>(Sometimes I miss global variables :)</p>\n\n<p>For a good discussion of injection vs. service locator see Martin Fowler's article here: <a href=\"http://martinfowler.com/articles/injection.html\" rel=\"nofollow\">http://martinfowler.com/articles/injection.html</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T21:28:49.367", "Id": "39071", "Score": "1", "body": "This is a horrible suggestion. If you are going to assign it in the constructor, why not just inject it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T21:39:14.423", "Id": "39072", "Score": "0", "body": "Although I agree Jeff, I guess ctrucza is suggesting that when a class A uses Class B which uses Class C which in turn needs to know about the current config by doing DI you will need to pass it through all the various levels even though Class B does not need to know about it?? I think that's the theory of the answer anyway" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T23:02:05.523", "Id": "39083", "Score": "0", "body": "Not really, `Class C` should be created with `CurrentConfig` injected into it. `Class C` should then be injected into `Class B`, which is in turn injected into `Class A`. Therefore, A and B do not know about `CurrentConfig`. My main objection was the use of statics in a object oriented environment. They take way everything that is good about objects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T05:40:32.443", "Id": "39095", "Score": "1", "body": "You can think of my proposal as a poor mans' service locator, an alternative to dependency injection. A thorough discussion of the topic can be found here: http://martinfowler.com/articles/injection.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T06:14:12.340", "Id": "39097", "Score": "0", "body": "@ctrucza, you realy should have mentioned service locator and provide a link to Martin Fowler's blog in your answer, because the suggestion to use a static parameter is not very good indeed. It makes your code hard to test and increase coupling. I am sure you know about that, but some unexperienced readers may use this solution in their project only to regret about it later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T06:22:46.290", "Id": "39098", "Score": "0", "body": "@Andrei Zubov: Good point about including the article in the answer (updated). I somehow fail to see how a static service locator would make the code harder to test or increase coupling (compared to the dependency injection). Care to elaborate?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T09:12:47.693", "Id": "39110", "Score": "0", "body": "I don't think this is a bad practice as well. It can 'magically' encapsulate the configuration into the wrapper, so in the later the developer (component user) will not need to matter with it again. But it sometimes can be abused though. +1 anyway" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T20:08:35.127", "Id": "25238", "ParentId": "25161", "Score": "2" } } ]
{ "AcceptedAnswerId": "25167", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T07:13:20.580", "Id": "25161", "Score": "6", "Tags": [ "c#", "design-patterns", "static" ], "Title": "Handle static objects using custom adapter" }
25161
<p>I have the following CRC 16 code. Is it possible to improve the performance of the code with unsafe constructs? My knowledge about pointer arithmetic is rather limited.</p> <pre><code>public enum Crc16Mode : ushort { Standard = 0xA001, CcittKermit = 0x8408 } public class Crc16Ccitt { static ushort[] table = new ushort[256]; public ushort ComputeChecksum(params byte[] bytes) { ushort crc = 0; for (int i = 0; i &lt; bytes.Length; ++i) { byte index = (byte)(crc ^ bytes[i]); crc = (ushort)((crc &gt;&gt; 8) ^ table[index]); } return crc; } public Crc16Ccitt(Crc16Mode mode) { ushort polynomial = (ushort)mode; ushort value; ushort temp; for (ushort i = 0; i &lt; table.Length; ++i) { value = 0; temp = i; for (byte j = 0; j &lt; 8; ++j) { if (((value ^ temp) &amp; 0x0001) != 0) { value = (ushort)((value &gt;&gt; 1) ^ polynomial); } else { value &gt;&gt;= 1; } temp &gt;&gt;= 1; } table[i] = value; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T14:20:10.557", "Id": "38963", "Score": "3", "body": "Is the performance of this code problematic? `ComputeChecksum` looks rock-solid as you can get. The only other improvement I can see is to remove the constructor and replace with an already-computed table such as this solution: http://stackoverflow.com/a/5074468/3312" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T08:44:30.253", "Id": "39014", "Score": "0", "body": "Thanks. Thats one improvement i will do. I am just curious if there would be any major performance gain when using \"unsafe features\". Also for learning about this subject by example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T10:45:36.337", "Id": "39027", "Score": "2", "body": "One obvious issue is that your code is incorrect. You have one static table, but there are two kinds of CRC calculator you can instantiate. If you instantiate instances of both of them, your program becomes incorrect." } ]
[ { "body": "<p>Your code looks pretty good except for the <code>static table</code>. More about that later.</p>\n\n<p>Unsafe code has a few things that can make code go faster, like pointers to arrays and arrays on the stack.</p>\n\n<p>A pointer to array would make code only faster if the code is iterating through that array. <code>ComputeChecksum</code> does iterate trough <code>data</code>, so yes, this part could become a little bit faster. We are talking about microseconds.</p>\n\n<p>You are also iterating through an the table array inside the constructor. So creation of this table could also become a littel bit faster.</p>\n\n<p>Personally: I would not use unsafe code in your case.</p>\n\n<p><strong>About the static</strong></p>\n\n<p>You have a static table, but when you create a new instance of <code>Crc16Ccitt</code> it will recalculate all the (same) values. (Talking about performance loss!) If you have two instances of <code>Crc16Ccitt</code> with different polynomials, then one of your instances will calculate it CRC's wrong, because they both share the same table (since it is static).</p>\n\n<p>How to solve this in a faster and safer way?</p>\n\n<p>Use a static! (Huh?) Yes, a static but another one:</p>\n\n<p><code>static private readonly Dictionary&lt;Crc16Mode, ushort[]&gt; _tables;</code> This will store all calculated tables.</p>\n\n<p>In your class use a local field: <code>ushort[] _table;</code> This one will hold the (already) calculated table. If the table was not calculated, it will be calculated and stored inside <code>_tables</code>.</p>\n\n<p>You also use this mechanism to store hard coded calcaulated tables, as Jesse suggests. In that case you would assign your hard code table to the dictionary inside a static constructor.</p>\n\n<p>Your code could become like this:</p>\n\n<pre><code>public enum Crc16Mode : ushort { Standard = 0xA001, CcittKermit = 0x8408 }\n\npublic class Crc16Ccitt\n{\n #region Static members\n\n static private readonly Dictionary&lt;Crc16Mode, ushort[]&gt; _tables = new Dictionary&lt;Crc16Mode, ushort[]&gt;();\n\n static private ushort[] GetTable(Crc16Mode mode)\n {\n lock (_tables)\n {\n ushort[] table;\n if (_tables.TryGetValue(mode, out table))\n return table;\n\n ushort polynomial = (ushort)mode;\n for (ushort i = 0; i &lt; table.Length; ++i)\n {\n ushort value = 0;\n ushort temp = i;\n for (byte j = 0; j &lt; 8; ++j)\n {\n if (((value ^ temp) &amp; 0x0001) != 0)\n value = (ushort)((value &gt;&gt; 1) ^ polynomial);\n else\n value &gt;&gt;= 1;\n temp &gt;&gt;= 1;\n }\n table[i] = value;\n }\n _tables[mode] = table;\n return table;\n }\n }\n\n #endregion\n\n private readonly ushort[] _table = new ushort[256];\n\n public Crc16Ccitt(Crc16Mode mode)\n {\n _table = GetTable(mode);\n }\n\n public ushort ComputeChecksum(params byte[] bytes)\n {\n ushort crc = 0;\n for (int i = 0; i &lt; bytes.Length; ++i)\n {\n byte index = (byte)(crc ^ bytes[i]);\n crc = (ushort)((crc &gt;&gt; 8) ^ _table[index]);\n }\n return crc;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-30T08:03:15.580", "Id": "25646", "ParentId": "25165", "Score": "3" } }, { "body": "<p>Here is what I tried to do</p>\n\n<pre><code>public ushort ComputeChecksumUnsafe(params byte[] bytes)\n{\n ushort crc = 0;\n unsafe\n {\n int len = bytes.Length;\n fixed (byte* pb = bytes)\n {\n fixed (ushort* tab = table)\n {\n for (int i = 0; i &lt; len; ++i)\n {\n byte index = (byte)(crc ^ pb[i]);\n crc = (ushort)((crc &gt;&gt; 8) ^ tab[index]);\n }\n }\n }\n }\n return crc;\n}\n</code></pre>\n\n<p>Unfortunately, even with 100Mbytes data the performance is still the same with safe version. I just post this FYI.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-03T05:56:14.310", "Id": "25756", "ParentId": "25165", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T09:02:39.447", "Id": "25165", "Score": "2", "Tags": [ "c#", "performance" ], "Title": "CRC 16 code with \"unsafe features\"" }
25165
<p>I have to create a modularized program that can find out the diameter, circumference, and area of a circle's radius. I'm sure many of you can notice I kind of winged this from a example given from my teacher. Instead of people pointing out the fact that I coded this wrong, could you please give me reasons for what I should do so I can better understand this concept?</p> <pre><code>import math def main(): Radius = 0 Diameter = 0 Circumference = 0 Area = 0 Radius = GetRadius(Radius) Diameter = SetDiameter(Radius, Diameter) Circumference = SetCircumference(Radius, Circumference) Area = SetArea(Radius, Area) ShowResults(Radius, Diameter, Circumference, Area) def GetRadius(myradius): myradius = float(str(input("Enter your radius: "))) return myradius def SetDiameter(myradius, mydiameter): mydiameter = myradius * 2 return mydiameter def SetCircumference(myradius, mycircumference): PIE = 3.14159 mycircumference = 2 * PIE * myradius return mycircumference def SetArea(myradius, myarea): PIE = 3.14159 myarea = PIE * myradius * myradius return myarea def ShowResults(Radius, Diameter, Circumference, Area): print("The Diameter is",mydiameter) print("The Circumference is",mycircumference) print("The Area is",myarea) main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T12:02:30.047", "Id": "38945", "Score": "0", "body": "Have you learned about Classes? This would be a great example in using one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T07:51:11.587", "Id": "39104", "Score": "0", "body": "Those \"setters\" make no sense: you pass a variable, set it inside the function and return it? that's not gonna work." } ]
[ { "body": "<p>Many little comments here to make things simpler,shorter,more pythonic :</p>\n\n<ul>\n<li><p><a href=\"http://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables\" rel=\"nofollow\">PEP 0008</a> gives some coding guidelines for python. Among other things, it gives a naming convention. Also, you don't need the \"my\" prefix everywhere.</p></li>\n<li><p>You can use <code>math.pi</code> instead of repeating our own definition of pi everywhere. (Isn't it the reason why your import math in the first place)</p></li>\n<li><p>Most of your function just need to return a value and updating the parameter probably shouldn't be their responsability.</p></li>\n<li><p>Most of the variables are not really required.</p></li>\n<li><p>there's no point to define a main function in your case.</p></li>\n</ul>\n\n<p>After taking these comments into accounts, your code looks like this :</p>\n\n<pre><code>import math\n\ndef get_radius_from_user():\n return float(input(\"Enter your radius: \"))\n\ndef get_diameter(radius):\n return radius * 2\n\ndef get_circumference(radius):\n return 2 * math.pi * radius\n\ndef get_area(radius):\n return math.pi * radius * radius\n\ndef show_results(radius):\n print(\"The Diameter is\",get_diameter(radius))\n print(\"The Circumference is\",get_circumference(radius))\n print(\"The Area is\",get_area(radius))\n\nshow_results(get_radius_from_user())\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T13:27:21.190", "Id": "38958", "Score": "1", "body": "Thanks for your review! In `get_radius_from_user()`, is there any reason you're converting a string to a string before converting it to a `float`? Also, you could write `radius ** 2` instead of `radius * radius` but that's subjective." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T15:09:53.910", "Id": "38964", "Score": "0", "body": "For the conversion, I just reused the original code without thinking too much about it as I'm not too sure to understand what was intended.\nYour comment about `radius**2` is valid too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T16:42:26.853", "Id": "38969", "Score": "1", "body": "`float(str(input(...)))` → `float(raw_input(...))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T16:54:14.533", "Id": "38973", "Score": "0", "body": "I've edited my answer. Thanks guys for the comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-07T05:33:11.953", "Id": "92377", "Score": "0", "body": "A comma should be followed by a space, according to PEP8." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T12:31:45.423", "Id": "25171", "ParentId": "25166", "Score": "6" } }, { "body": "<p>Once you've learned about classes you could create a <code>Circle</code> object which when initiated performs all possible conversions, so that its properties - diameter, radius, area and circumference - can all be accessed without having to write anything else.</p>\n\n<p>The conversion functions can be stored as a dictionary of <code>lambda</code>s.</p>\n\n<pre><code>import math\nclass Circle:\n conversions = {\n ('diameter', 'radius'): lambda d: d / 2.0,\n ('radius', 'area'): lambda r: math.pi * r ** 2,\n ('radius', 'diameter'): lambda r: r * 2.0,\n ('radius', 'circumference'): lambda r: math.pi * r * 2,\n ('area', 'radius'): lambda a: (a / math.pi) ** .5,\n ('circumference', 'radius'): lambda c: c / (math.pi * 2)\n }\n\n def _set(self, property, value):\n \"\"\" Set a property and recursively make all possible \n conversions based on that property \"\"\" \n setattr(self, property, value)\n for (fro, to), conversion in self.conversions.items():\n if fro == property and getattr(self, to, None) is None:\n self._set(to, conversion(getattr(self, fro)))\n\n def __init__(self, **kwargs):\n self._set(*kwargs.items()[0])\n\nmy_circle = Circle(radius = 5)\nprint my_circle.area\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-07T20:09:09.133", "Id": "52720", "ParentId": "25166", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T09:30:14.287", "Id": "25166", "Score": "2", "Tags": [ "python" ], "Title": "Modularized program to find circumference, diameter, and area from a circle's radius" }
25166
<p>I'm using the following pattern to pool D3D objects globally in my application. Is it a good idea (alternatives)? Is it thread-safe?</p> <pre><code>CComPtr&lt;ID3D11Texture2D&gt; create_texture(const D3D11_TEXTURE2D_DESC&amp; desc) { static concurrent_unordered_map&lt;D3D11_TEXTURE2D_DESC, concurrenct_vector&lt;CComPtr&lt;ID3D11Texture2D&gt;&gt; d3d_texture2d_desc_hash, d3d_texture2d_desc_equal_to&gt; pools; auto&amp; pool = pools[desc]; auto it = std::find_if(pool.begin(), pool.end(), [](const CComPtr&lt;ID3D11Texture2D&gt;&amp; texture) { assert(texture); IUnknown* unknown = texture; auto ref_count = unknown.AddRef(); if(ref_count != 2) unknown-&gt;Release(); // Only release if we don't want ownership. return ref_count == 2; }); CComPtr&lt;ID3D11Texture2D&gt; texture; if(it != pool.end()) { texture = *it; // Take ownership. IUnknown* unknown = texture; // Release the extra ref-count once we have taken ownership. #ifndef _DEBUG unknown-&gt;Release(); #else assert(unknown-&gt;Release() == 2); #endif } else { HR(get_default_device()-&gt;CreateTexture2D(&amp;desc, nullptr, &amp;texture)); pool.push_back(texture); } assert(texture); return texture; } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T12:06:26.980", "Id": "25169", "Score": "2", "Tags": [ "c++", "c++11", "thread-safety", "memory-management", "com" ], "Title": "D3D COM Object Pooling" }
25169
<p>I have written the below code which generates all possible permutations with repetitions of a string.</p> <p>I want to make this program shorter and much faster, but I don't know how to do that.</p> <pre><code>Imports System.Text Public Class Form1 Private blkRpt As Integer Private perm As Double Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim textlen As Double = TextBox1.Text.Length Dim rtb As Double = TextBox2.Text perm = textlen ^ rtb permutate() End Sub Private Sub permutate() For a As Integer = 0 To 1 Step 0 Dim s As String = TextBox1.Text Dim len As Integer = TextBox2.Text Dim r As New Random Dim sb As New StringBuilder For i As Integer = 1 To len Dim idx As Integer = r.Next(0, s.Length) sb.Append(s.Substring(idx, 1)) Next Dim sring As String = sb.ToString If RichTextBox1.Text.Contains(sb.ToString) Then blkRpt = blkRpt + 1 Else RichTextBox1.AppendText(sring &amp; vbNewLine) End If Dim s1 As String = TextBox1.Text Dim len1 As Integer = TextBox2.Text Dim r1 As New Random Dim sb1 As New StringBuilder For i As Integer = 1 To len1 Dim idx1 As Integer = r1.Next(0, s1.Length) sb1.Append(s1.Substring(idx1, 1)) Next Dim sring1 As String = sb1.ToString If RichTextBox1.Text.Contains(sb1.ToString) Then blkRpt = blkRpt + 1 Else RichTextBox1.AppendText(sring1 &amp; vbNewLine) End If Dim s2 As String = TextBox1.Text Dim len2 As Integer = TextBox2.Text Dim r2 As New Random Dim sb2 As New StringBuilder For i As Integer = 1 To len2 Dim idx2 As Integer = r2.Next(0, s2.Length) sb2.Append(s2.Substring(idx2, 1)) Next Dim sring2 As String = sb2.ToString If RichTextBox1.Text.Contains(sb2.ToString) Then blkRpt = blkRpt + 1 Else RichTextBox1.AppendText(sring2 &amp; vbNewLine) End If Dim s21 As String = TextBox1.Text Dim len21 As Integer = TextBox2.Text Dim r21 As New Random Dim sb21 As New StringBuilder For i As Integer = 1 To len1 Dim idx21 As Integer = r21.Next(0, s2.Length) sb2.Append(s2.Substring(idx21, 1)) Next Dim sring21 As String = sb21.ToString If RichTextBox1.Text.Contains(sb21.ToString) Then blkRpt = blkRpt + 1 Else RichTextBox1.AppendText(sring21 &amp; vbNewLine) End If If RichTextBox1.Lines.Length - 1 &gt;= perm Then Exit For End If Label6.Text = blkRpt.ToString Label5.Text = RichTextBox1.Lines.Length - 1 &amp; "/" &amp; perm Next End Sub End Class </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T08:56:54.583", "Id": "38946", "Score": "1", "body": "Please use Option Strict....implicit conversions (like `Dim rtb As Double = TextBox2.Text`) are dangerous. What is `TextBox2.Text` has \"The first and the last\" in it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T09:05:26.220", "Id": "38947", "Score": "0", "body": "Have you run this code? Your outer for loop has `Step 0` - which means the loop will never increment - you have an infinite loop. You're using random to get (I think) a random element of the string...but you could easily get the same element multiple times. Those are just two things that jump out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T09:06:17.053", "Id": "38948", "Score": "1", "body": "Take a look at this SO question - [Listing all permutations of a string/integer](http://stackoverflow.com/a/756083/745969). Goes into a good deal of detail on how to do this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T10:54:10.897", "Id": "38949", "Score": "0", "body": "I have ran this code, It will continue to loop until it generated all the possible combination" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T10:55:34.650", "Id": "38950", "Score": "0", "body": "Every output in Richtextbox1 is unique. Look at \n `richtextbox1.text.contains(sb.ToString)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T21:16:32.690", "Id": "38951", "Score": "0", "body": "I see the `Exit For` now...personally I try to avoid breaking out of for loops like that (use a While loop instead) if possible. Recursion is your friend in a scenario like this. Have you had a chance to look at the link I posted?" } ]
[ { "body": "<p>I'm not going to rewrite this code right now, but I can highlight a few points:</p>\n\n<ol>\n<li>Naming. \n<ul>\n<li>Identifiers should have a <strong>meaningful</strong> name.</li>\n<li><strong>Disemvoweling</strong> is evil.</li>\n<li>Adding a <code>1</code> after an identically-named variable is bad.</li>\n<li>Adding a <code>2</code> after an identically-named variable is terrible.</li>\n<li>Adding <code>21</code> instead of a <code>3</code> after an identically-named variable is careless.</li>\n<li>If you <em>think</em> you need the same variable 3 times in one function, something's not right. Right? I think Tim's comment on your original post has a huge golden clue on that matter.</li>\n</ul></li>\n<li>UI is for presentation. Logic that isn't <em>presentation logic</em> shouldn't need to know there's a UI involved.\n<ul>\n<li>Decoupling your logic from the UI helps making your code <strong>testable</strong>.</li>\n<li>Learn to pass <strong>parameters</strong> into your functions.</li>\n<li>Knowing exactly what's involved is very hard to tell, we need to puzzle out the whole thing just to figure out what <code>RichTextBox1</code> is supposed to contain; your naming isn't helping.</li>\n</ul></li>\n<li>Implicit string-to-numeric conversion is ugly and bug-prone, <strong>especially with user input</strong>.\n<ul>\n<li>Assume the user is a 3 year old that could click anywhere and enter <em>anything</em> in any TextBox.</li>\n</ul></li>\n<li>You have many, many, <strong>many</strong> things to worry about before you can think of improving performance.\n<ul>\n<li>Using <code>Random</code> isn't making it any faster. I don't think <code>Random</code> is warranted here.</li>\n<li>Access the UI <strong>once</strong> to <em>get</em> the values you need, <strong>once</strong> to <em>write</em> the values you've computed; pass the values as parameters (I said that before, I'll say it again - here, done).</li>\n<li>It's not the job of a permutation function to access the UI. Ever. Take values in (<em>as parameters</em>), do your thing, spit out a result (as a <em>return value</em>).</li>\n<li><code>perm</code> (bad name) shouldn't be an <em>instance variable</em>. Not even a parameter. It's only meaningful within the <code>permutate</code> function: that's where it belongs.</li>\n</ul></li>\n</ol>\n\n<p>That's all folks! I might edit this post later with actual code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T03:41:03.037", "Id": "57495", "Score": "2", "body": "+1 good points about the naming, UI, and testing. It does all tie into what I know about interfacing and good, testable coding." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T18:20:10.337", "Id": "35192", "ParentId": "25170", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T08:48:27.413", "Id": "25170", "Score": "2", "Tags": [ "vb.net", "combinatorics", "performance" ], "Title": "Generating permutations with repetitions of string" }
25170
<p>I have several calculus to do in my ruby app. My code is currently working but I find it very ugly.</p> <pre><code>@guestreviews = GuestReview.where(:reviewed_id =&gt; @user.id) @hostreviews = HostReview.where(:reviewed_id =&gt; @user.id) @hospitalityrate = 0 @foodrate = 0 @placerate = 0 @hostreviews.try(:each) do | rate | @hospitalityrate += rate.people_rate @foodrate += rate.food_rate @placerate += rate.place_rate end @hospitalityrate = (@hospitalityrate / @hostreviews.size).round @foodrate = (@foodrate / @hostreviews.size).round @placerate = (@placerate / @hostreviews.size).round @averagerate = ((@hospitalityrate + @foodrate + @placerate) / @hostreviews.size).round </code></pre> <p>Any idea how to make it still readable but less ugly ?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T16:39:02.403", "Id": "38968", "Score": "0", "body": "why are all of these instance variables? why not use some local variables?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T03:59:09.960", "Id": "39092", "Score": "0", "body": "You're misusing `try`. `@hostreviews` is guaranteed to be an array of 0 or more items, it *will* respond to `each`. Don't use `try` here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T09:27:38.420", "Id": "39111", "Score": "0", "body": "@meagar I don't use try anymore, but hostreviews can also be nil." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T13:16:20.513", "Id": "39117", "Score": "0", "body": "@bl0b No, it can't be `nil`. `where` will always return a chainable scope which responds to `each`, which will behave like an array of 0 or more elements. In the code you've posted, it's impossible for `@hostreviews` to be `nil` by the time it reaches the `each` statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T13:48:47.763", "Id": "39120", "Score": "0", "body": "@meagar You're right. I juste checked my code and I don't use the .each anymore and it wasn't nil but an empty array.\nThank you" } ]
[ { "body": "<p>It's actually easier to do this in the database layer. It's exceedingly good at these kinds of things.</p>\n\n<pre><code>@guest_reviews = GuestReview.where(:reviewed_id =&gt; @user.id)\n@host_reviews = HostReview.where(:reviewed_id =&gt; @user.id)\n\n@hospitality_rate = @guest_reviews.average('people_rate')\n@food_rate = @guest_reviews.average('food_rate')\n@place_rate = @guest_reviews.average('place_rate')\n\n@average_rate = [@hospitality_rate, @food_rate, @place_rate].inject(:+).to_f / @host_reviews.count\n</code></pre>\n\n<p>It'll result in more database queries, but overall it's more efficient.</p>\n\n<p>I've left out the <code>round()</code> call on the <code>@average_rate</code> only because that seems like a presentation concern to me. Let the controller figure out the average (decimals and all), and let the view decide how to round and display it.</p>\n\n<p>You could also add a <code>has_many :guest_reviews, :foreign_key =&gt; \"reviewed_id\"</code> to the <code>User</code> model, so you can just call <code>@user.guest_reviews.average(...)</code>. Same for <code>host_reviews</code></p>\n\n<p>If you do that, you could also consider simply moving the calculations to the <code>User</code> model, so you don't need to do it all in the controller. And perhaps you could cache the results on the user record and only recalculate when reviews are added/deleted/changed. Assuming this happens less often than the averages being displayed, it'll speed up things a bit.</p>\n\n<p>Lastly, (and this is just small stuff) I'd probably rename some of the variables. I.e. call it <code>@food_rate_average</code> instead of <code>@food_rate</code> in order to a) indicate that it's an average, and b) so it's not confused with the database column of the same name.<br>\nSimilarly, I'd call the first average <code>people_rate_average</code> rather than <code>hospitality_rate</code>; the column is called <code>people_rate</code> so it's probably best to keep it consistent with that name (or rename the database column, if \"hospitality\" is a more fitting name)</p>\n\n<p><em>(Edit: Actually, it's more natural to prefix the <code>average_</code> rather than suffixing it, i.e. <code>average_food_rate</code>, <code>average_rate</code>, etc.)</em></p>\n\n<p>In the code above, I've also underscored the names, just to keep things consistent with general Rails/Ruby conventions (<code>FooBar</code> → <code>foo_bar</code>).</p>\n\n<hr>\n\n<p>Edit: Just for fun, you could go fully meta (though it's probably more confusing than anything - the above is much more readable)</p>\n\n<pre><code>@guest_reviews = GuestReview.where(:reviewed_id =&gt; @user.id)\n@host_reviews = HostReview.where(:reviewed_id =&gt; @user.id)\n\n@average_rate = %w(people_rate food_rate place_rate).map { |column|\n instance_variable_set(:\"@average_#{column}\", @guest_reviews.average(column))\n}.inject(:+).to_f / @host_reviews.count\n</code></pre>\n\n<p>That'll set <code>@average_people_rate</code>, <code>@average_food_rate</code> and so on</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T15:14:29.737", "Id": "38965", "Score": "0", "body": "I would give 1000 upvote if I could. That's such a good answer !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T00:48:55.567", "Id": "39006", "Score": "0", "body": "@bl0b Thanks. I had added a few more notes here and there if you're interested" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T15:47:13.887", "Id": "39058", "Score": "0", "body": "Thanks. I was actually using the foreign key system, no idea why I wasn't using it. Thanks for the reminder.\n\nAlso, I won't cache the result right now because we don't have enough user/visitor yet to worry about it(sadly) but I'll keep it in mind.\nI'll change my variables name, you're right it makes more sense with the way you said it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T14:54:28.963", "Id": "25174", "ParentId": "25172", "Score": "5" } } ]
{ "AcceptedAnswerId": "25174", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T13:41:07.730", "Id": "25172", "Score": "3", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Math Calculus in ruby" }
25172
<pre><code>/** * takes a list of componentIDs to load, relative to componentRoot * returns a promise to the map of (ComponentID -&gt; componentCfg) */ function asyncLoadComponents (componentRoot, components) { var componentCfgs = {}; function asyncLoadComponentCfg(component) { var url = _.sprintf("%s/%s", componentRoot, component); var promise = util.getJSON(url); promise.done(function(data) { componentCfgs[component] = data; }); return promise; } var promises = _.map(components, asyncLoadComponentCfg); var flattenedPromise = $.when.apply(null, promises); var componentCfgPromise = flattenedPromise.pipe(function() { // componentCfgs is loaded now return $.Deferred().resolve(componentCfgs).promise(); }); return componentCfgPromise; } var locale = 'en-US'; var componentRoot = '/api/components'; var components = ['facets', 'header', 'DocumentList']; function buildDocumentListPage(locale, componentCfgs) { /* code goes here */ } $.when(asyncLoadComponents(componentRoot, components)).done(function(componentCfgs) { buildDocumentListPage(locale, componentCfgs) }); </code></pre>
[]
[ { "body": "<p>Here's <a href=\"http://jsfiddle.net/UgdNA/1/\" rel=\"nofollow\">a sample in jsFiddle</a>, with some values and functions mocked-up to use jsFiddle API.</p>\n\n<p>Here's the actual code, with notes in the comments:</p>\n\n<pre><code>//personally, I like comma separated variables preferrably the \n//\"comma-before style\". But it's personal preference.\n\n//JS \"hoists\" up variable and function declarations higher in the scope.\n//To avoid unexpected behaviour, and so that they are easier to find,\n//we move them to the top of their scopes\nvar locale = 'en-US'\n , componentRoot = '/api/components'\n , components = ['facets', 'header', 'DocumentList']\n ;\n\nfunction buildDocumentListPage(locale, componentCfgs) {}\n\n//load our components\nfunction asyncLoadComponents(componentRoot, components) {\n\n //our configuration collector\n var componentCfgs = {}\n\n //we create a promises array by mapping each value to a function\n , promises = _.map(components, function (component) {\n\n //we use the promise of a getJSON request (Assuming this is jQuery).\n //since you just concatenated the url values, we can just concatenate with +\n return util.getJSON(componentRoot+'/'+component).done(function (data) {\n\n //when getJSON resolves, we put the data in the collector\n componentCfgs[component] = data\n });\n });\n\n //as of jQuery 1.8, pipe is deprecated in favor of then. However, then\n //is designed to act like pipe, and instead of resolving with the value\n //we return the value instead\n return $.when.apply(null, promises).then(function () {\n return componentCfgs;\n })\n}\n\n//we model the function to return a promise that we'll listen to instead\n//of having a $.when here. That way, we'll deal with less code and promises\nasyncLoadComponents(componentRoot,components).done(function(componentCfgs) {\n\n //here, all configs have loaded and stored to componentCfgs\n buildDocumentListPage(locale, componentCfgs);\n});\n</code></pre>\n\n<p>Packed code looks like this, tons shorter:</p>\n\n<pre><code>var locale = 'en-US',\n componentRoot = '/api/components',\n components = ['facets', 'header', 'DocumentList'];\n\nfunction buildDocumentListPage(locale, componentCfgs) {}\n\nfunction asyncLoadComponents(componentRoot, components) {\n var componentCfgs = {}, promises = _.map(components, function (component) {\n return util.getJSON(componentRoot + '/' + component).done(function (data) {\n componentCfgs[component] = data\n })\n });\n return $.when.apply(null, promises).then(function () {\n return componentCfgs\n })\n}\n\nasyncLoadComponents(componentRoot, components).done(function (componentCfgs) {\n buildDocumentListPage(locale, componentCfgs)\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T16:36:33.087", "Id": "25177", "ParentId": "25173", "Score": "1" } }, { "body": "<p>i have fully generalized thanks to Joseph's help. So this could parallelize and sequence by key arbitrary async things, like say a database query to load objects by ID.</p>\n\n<p>library code:</p>\n\n<pre><code>/**\n * perform multiple requests in parallel, returning a Promise[Map[Key, Response]]\n * @fBuildUrl function that can build a URL from a key\n * @fAsyncRequest function of one argument that returns a promise\n * @keys the things to load, that fBuildUrl can build a URL from\n *\n * use case: takes a list of componentIDs to load, relative to componentRoot\n * returns a promise to the map of (ComponentID -&gt; componentCfg)\n */\nexports.asyncParallel = function (fBuildUrl, fAsyncRequest, keys) {\n\n var responses = {};\n var asyncLoadOne = function (key) {\n var url = fBuildUrl(key);\n return fAsyncRequest(url).done(function(data) {\n responses[key] = data;\n });\n };\n\n var promises = _.map(keys, asyncLoadOne);\n return $.when.apply(null, promises).then(function() {\n return responses;\n });\n};\n</code></pre>\n\n<p>application code:</p>\n\n<pre><code>var components = ['tmfFacets', 'tmfHeader', 'tmfDocumentList'];\n\nfunction buildUrl (key) {\n return componentRoot + \"/\" + key;\n}\n\nutil.asyncParallel(buildUrl, util.getJSON, components).done(function(componentConfigs) {\n window.page = new DocListPage(locale, componentConfigs, DocListPageRouter);\n});\n</code></pre>\n\n<p>can we do even better, or is this it?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T18:53:32.433", "Id": "38978", "Score": "1", "body": "`util.asyncParallel` already returns a promise, you can chain `done` directly. Using `$.when` to judge it's return is redundant." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T17:48:42.477", "Id": "25184", "ParentId": "25173", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T14:53:29.787", "Id": "25173", "Score": "1", "Tags": [ "javascript", "functional-programming", "asynchronous", "underscore.js", "monads" ], "Title": "functional javascript - how could I generalize this code that correlates parallel async requests with their results?" }
25173
<p>Could this be better factored as a reduce?</p> <pre><code>/** * recursively build a nested Backbone.Model or Backbone.Collection * from a deep JSON structure. * * undefined for regex values */ exports.modelify = function modelify (data) { if (_.isArray(data)) { return new Backbone.Collection(_.map(data, modelify)); } else if (_.isObject(data) &amp;&amp; !_.isDate(data)) { var m = util.mapo(data, function(val, key) { return [key, modelify(val)]; }); return new Backbone.Model(m); } else { // data is a primitive or a date return data; } } var mapo = exports.mapo = _.compose(_.object, _.map); </code></pre>
[]
[ { "body": "<p>Looks quite nice to me, the only thing I would change is the flow, you do not need the <code>else if</code> and <code>else</code> after a <code>return</code>. I think the function is easier on the eyes and shorter if you take <code>return</code> into account.</p>\n\n<pre><code>exports.modelify = function modelify (data) {\n\n if (_.isArray(data)) {\n return new Backbone.Collection(_.map(data, modelify));\n }\n\n if (_.isObject(data) &amp;&amp; !_.isDate(data)) {\n\n var m = util.mapo(data, function(val, key) {\n return [key, modelify(val)];\n });\n\n return new Backbone.Model(m);\n }\n // data must be a primitive or a date\n return data;\n}\n\nvar mapo = exports.mapo = _.compose(_.object, _.map);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T14:00:28.623", "Id": "37589", "ParentId": "25175", "Score": "2" } }, { "body": "<p>It can indeed be factored as a reduce, but I don't know if the result is \"better\".</p>\n\n<p>So, to anyone who still has this problem so long after the question was asked, and god knows I hated Backbone for the lack of data tree-spanning <code>Model</code> and <code>Collection</code> classes, here is the <code>treeReduce</code> function, analogous to <code>Array.prototype.reduceRight</code> but for trees, first written in a simple fashion:</p>\n\n<p>Assuming that each tree object has a <code>value</code> property (of type <code>a</code> which may be anything) and a <code>children</code> property which is an array of child tree objects,</p>\n\n<p>Assuming that <code>f :: a -&gt; [b] -&gt; b</code> in Haskell notation (i.e. to an element of type <code>a</code> and an array of elements of type <code>b</code>, <code>f</code> associates another <code>b</code>-typed element),</p>\n\n<p>Assuming that <code>ini</code> has type <code>[b]</code>,</p>\n\n<pre><code>function treeReduce(tree, f, ini)\n{\n // If we're at a leaf, use 'ini'\n if (tree.children.length === 0) {\n return f(tree.value, ini);\n }\n\n // Else, recursion!\n return f(tree.value, children.map(function (child) {\n return treeReduce(child, f, ini);\n }));\n}\n</code></pre>\n\n<p>For your problem, we have to adapt <code>treeReduce</code> to use <code>_.map</code> and to not assume that the tree has the <code>value</code> and <code>children</code> properties, etc:</p>\n\n<pre><code>// Using this, we can customize the way to get the value and children of a tree\n// in our treeReduce function\nfunction treeReduceFactory(getValue, getChildren)\n{\n return function customTreeReduce(tree, f, ini)\n {\n var children = getChildren(tree);\n if (children.length === 0) {\n return f(getRoot(tree), ini);\n }\n\n return f(getValue(tree), _.map(children, function (child) {\n return customTreeReduce(child, f, ini);\n }));\n };\n}\n\n// Our treeReduce is defined like this:\nvar treeReduceForBackbone = treeReduceFactory(\n // There really is no such thing as getting the 'value' of the current node\n // in our case\n function (data) {\n return data;\n },\n\n // How to get the \"children\" of something that can be an array or an object?\n function (data) {\n // If data is an array then it is itself its own children (??!)\n if (_.isArray(data)) {\n return data;\n }\n // If it's an object then its children are in the values\n if (_.isObject(data) &amp;&amp; !_.isDate(data)) {\n return _.map(data, function (val, key) { return [key, val]; });\n }\n // If it's neither of those, it doesn't have children\n return [];\n }\n);\n\n// Finally, we define 'modelify', and indeed it looks somewhat more elegant\nexports.modelify = function (data) {\n return treeReduceForBackbone(\n data,\n\n function (data, modelifiedDataArray) {\n if (_.isArray(data)) {\n return new Backbone.Collection(modelifiedDataArray);\n }\n if (_.isObject(data) &amp;&amp; !_.isDate(data)) {\n return new Backbone.Model(_.object(modelifiedDataArray));\n }\n return data;\n },\n\n []\n );\n};\n</code></pre>\n\n<p>And this is where we realize that because our data tree does not have a coherent interface throughout (different ways to get the children depending on the type of the node in the tree, object or array), we end up repeating checks in the node children getter and in the <code>f</code> function. This could obviously be fixed with yet another modification to <code>treeReduce</code>, but sincerely at this point I like your initial solution better.</p>\n\n<p>To note, though: an iterative version of your function, as opposed to recursive, <a href=\"http://jsperf.com/treereduce-iterative-vs-recursive\" rel=\"nofollow\">would certainly be faster</a>, and may counterbalance the lack of readability factor in your choice of implementation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-22T19:02:35.037", "Id": "74538", "ParentId": "25175", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T15:02:53.763", "Id": "25175", "Score": "5", "Tags": [ "javascript", "functional-programming", "recursion", "underscore.js" ], "Title": "Recursively walking a tree to build up a new one" }
25175
<p>I wonder if someone could give me some pointers to my PHPmailer Process file and see if they find any misstakes or things that I have missed in the validation/sanitation of the data. Any input would be most wellcome! </p> <pre><code>&lt;?php //includes require_once('func/mail/mailcon/config-info.php'); require_once('include/class.phpmailer.php'); //Sanitazion and cleanup. if ($_SERVER['REQUEST_METHOD'] == 'POST') { $entries = array(); $errors = array(); // Escape and extract all the post values foreach ($_POST as $key =&gt; $value) { $entries[$key] = sanitize($value); } // Get a set of variable variables for easier use foreach ($entries as $key =&gt; $value) { ${$key} = $value; } //validation //contact_Name if (empty($contact_Name)) { $errors['contact_Name'] = 'Detta fält måste fyllas i.'; } elseif (mb_strlen($contact_Name, 'UTF-8') &gt; 50) { $errors['contact_Name'] = 'Detta namn är för långt, får inte vara över 50 tecken.'; } //contact_Foretag. if (mb_strlen($contact_Foretag, 'UTF-8') &gt; 50) { $errors['contact_Foretag'] = 'Detta företagsnamn är för långt, får inte vara över 50 tecken'; } //contact_Email if (empty($contact_Email)) { $errors['contact_Email'] = 'Detta fält måste fyllas i.'; } elseif (!(filter_var($contact_Email, FILTER_VALIDATE_EMAIL))) { $errors['contact_Email'] = 'Fyll i en giltig E-post address.'; } //contact_Subject if (empty($contact_Subject)) { $errors['contact_Subject'] = 'Detta fält måste fyllas i.'; } elseif (mb_strlen($contact_Subject, 'UTF-8') &gt; 50) { $errors['contact_Subject'] = 'Detta ämne är för långt, får inte vara över 50 tecken.'; } //contact_Message if (empty($contact_Message)) { $errors['contact_Message'] = 'Detta fält måste fyllas i.'; } elseif (mb_strlen($contact_Message, 'UTF-8') &gt; 5000) { $errors['contact_Message'] = 'Detta meddeoande är för långt, får inte vara över 5000 tecken.'; } //If no errors if (empty($errors)) { $formOK = true; $mail = new PHPMailer(true); try { $mail-&gt;IsSMTP(); $mail-&gt;SMTPDebug = 0; $mail-&gt;SMTPAuth = true; $mail-&gt;SMTPSecure = "ssl"; $mail-&gt;Host = MAIL_HOST; $mail-&gt;Port = MAIL_PORT; $mail-&gt;Username = MAIL_USER; $mail-&gt;Password = MAIL_PASS; $mail-&gt;SetFrom($contact_Email, $contact_Name); $mail-&gt;Subject = "$contact_Subject"; $mail-&gt;Body = "Your received the following message from $contact_Mame ($contact_Foretag) &lt;$contact_Email&gt;:\r\n\r\n$contact_Message"; $mail-&gt;AddAddress(MAIL_ADDR); $mail-&gt;Send(); } catch (PHPMailerException $e) { header("HTTP/1.1 500 Internal Server Error"); echo "Exception occurred: ".$e-&gt;errorMessage(); exit(); } } else { $formOK = false; } //if this is not an ajax request if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp; strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){ session_start(); $return_data = array( 'formOK' =&gt; $formOK, 'errors' =&gt; $errors, 'entries' =&gt; $entries ); $_SESSION['return_data'] = $return_data; header('Location: ' . BASE_URL); exit(); } } //First else { header('Location: ' . BASE_URL); exit(); } </code></pre>
[]
[ { "body": "<p>and welcome to CodeReview!</p>\n\n<p>Here's a few things:</p>\n\n<ul>\n<li>You have a lot of pointless comments \n<ul>\n<li>(\"includes\": The includes are the next line. We see them; no need to tell us.)</li>\n</ul></li>\n<li>Indent block content.\n<ul>\n<li>Whenever you enter an if block, indent it.</li>\n<li>Same for while/for/functions/classes/methods/etc</li>\n</ul></li>\n<li>Your variable-variable loop is equivalent to <code>extract</code>.</li>\n<li><code>extract</code> tends to be a bad idea (the <a href=\"http://php.net/manual/en/function.extract.php\" rel=\"nofollow\">manual</a> has various warnings) \n<ul>\n<li>It pollutes the scope</li>\n<li>You no longer know what variables are and are not defined unless you strictly control what is inside of the array (which you don't for $_POST)</li>\n<li>Users can clobber <em>your</em> values, meaning there are certain security implications.</li>\n<li>Can be mitigated with options to extract, but still a problem</li>\n<li>In short, there are a few situations where extract is convenient and a decent idea; this is not one of them.</li>\n<li>use <code>$_POST[...]</code> or <code>$entries[...]</code> directly.</li>\n</ul></li>\n<li>Variable variables are also a bad idea.\n<ul>\n<li>Variable variables scream \"What I really need is an array!\"</li>\n<li>You already have an array :)</li>\n</ul></li>\n<li>Don't sanitize content until you're actually ready to put it into the context for which you're sanitizing it.\n<ul>\n<li>For example, &amp; is a special character in HTML (in some contexts). DBs do not care about it. Nor do plain text emails. Or email subjects. Or... infinite things.</li>\n<li>Rule of thumb: sanitize at the last possible moment.</li>\n<li>You can also take the raw value and process it, but you can't always do the reverse.</li>\n</ul></li>\n<li>Be careful with empty() on strings\n<ul>\n<li>empty($var) === (isset($var) &amp;&amp; $var)</li>\n<li>Implicit bool rules are <em>very</em> odd in PHP though. In particular, the string \"0\" can get you.</li>\n<li>I doubt <code>0</code> should be a valid email content, but just throwing it out there in case it gets you in the future.</li>\n</ul></li>\n<li>Invert your conditions and you'll see that you can bail early:\n<ul>\n<li>if (...) { /* huge block <em>/ } else { /</em> redirect <em>/ exit; }</li>\n<li>Instead you could do if (!...) { /</em> redirect */ exit; }</li>\n<li>Now your entire file doesn't have to be indented one step.</li>\n<li>This is similar to the concept of returning early, though it tends to be less applicable to files (redirection is one of the few justified uses of <code>exit</code> in web site PHP)</li>\n</ul></li>\n<li>You have a typo of <code>$contact_Mame</code> rather than <code>$contact_Name</code> in your email content</li>\n<li>Be careful with 500 errors. IE has a minimum length limit where if your response is less than some number of bytes, IE 'helpfully' replaces your content with its own.\n<ul>\n<li>Also, I'm torn on how I feel about this being a 500 response. It's not really an internal error so much as just an exception.</li>\n<li>Internal errors implies a major mess up to me like Apache is pissed off, or a E_FATAL PHP error.</li>\n</ul></li>\n<li>You should probably log the email failing to send. You could just use something like <code>trigger_error</code> if you want to go the simple route.</li>\n<li><code>$formOK</code> is gaurenteed to be <code>$formOK === empty($errors)</code>. This means you could just use <code>empty($errors)</code> in it's place.</li>\n<li>I tend to use only strict equalities with strings these days. If you're comparing something to a string, you're sure 99.9% of the time that it's a string. If you're sure it should be a string, might as well use a strict check.\n<ul>\n<li>There are situations where loose string comparisons are still quite handy though.</li>\n</ul></li>\n<li>I would use a GET or POST variable to signify AJAX rather than checking a header.\n<ul>\n<li>Headers can be spoofed.</li>\n<li>Testing becomes easier.</li>\n<li>No potential browser/JS library compatibility issues</li>\n</ul></li>\n<li><code>$mail-&gt;Subject = \"$contact_Subject\";</code> is (functionally) equivalent to <code>$mail-&gt;Subject = (string) $contact_Subject;</code>\n<ul>\n<li>You know it's already a string, so no need for the cast.</li>\n<li>Just do <code>$mail-&gt;Subject = $contact_Subject</code>.</li>\n<li>Also, I wouldn't use <code>\"$var\"</code> as a cast. I would stick with explict casts (<code>(string) $var</code>).</li>\n</ul></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T21:49:18.923", "Id": "38999", "Score": "0", "body": "This is an awsome answer! Thx @Corbin" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T19:53:54.157", "Id": "39294", "Score": "0", "body": "Corbin I looked at your answer and did as you suggested, but the one thing I still don´t get is \" would use a GET or POST variable to signify AJAX rather than checking a heade\" could you elaborate on it a bit?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T19:38:57.997", "Id": "25191", "ParentId": "25182", "Score": "2" } } ]
{ "AcceptedAnswerId": "25191", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T13:19:49.777", "Id": "25182", "Score": "4", "Tags": [ "php" ], "Title": "PHPmailer sanitazion/validation a second oppinion." }
25182
<p>I'm trying to teach myself javascript and HTML5, (just beginning), and for some practice with canvas I am trying to turn <a href="http://www.stefan.gr/dhammachart-bigger.gif" rel="nofollow">this chart</a> into an interactive chart on canvas, whereby clicking on a word opens up some of the tree below, and so on. I can't post images of what it does as I'm too new here, sorry.</p> <p>The thing is, the code I have done is all working as I want it to (yay!), but it's already pretty long, and to map the rest of the chart (I've only done a small part of it so far) it's going to be War and Peace in javascript. So I was wondering if anyone could take a look at my code and tell me how to make it briefer?</p> <p>I've googled, and looked in my books on javascript, and nothing jumps out at me. I am also going to try and do it with SVG for practice with that, and suspect it may be more efficient, but as I specifically want to learn javascript+canvas I really want to get this way working well also. Thanks in advance for any help.</p> <p>Edit to add: I tried putting functions inside functions e.g. calling BDS() where I wanted to write that out, rather than copying the code, but that simply caused it not to do any of the stuff after it.</p> <p>Here is my code:</p> <pre><code>onload = BDS; var called = false; function BDS() { var c = document.getElementById("canvas"); var ctx = c.getContext("2d"); ctx.font = "bold 48px Arial"; ctx.fillStyle = "#F63"; ctx.textAlign = "center"; var B = "Buddha "; var D = "Dhamma "; var S = "Sangha"; ctx.fillText(B + D + S, 500, 100); } function q(event) { event = event || window.event; var canvas = document.getElementById("canvas"), x = event.pageX - canvas.offsetLeft, y = event.pageY - canvas.offsetTop; //alert(x + ' ' + y); if (x &lt; 295 &amp;&amp; x &gt; 120 &amp;&amp; y &gt; 60 &amp;&amp; y &lt; 110){ called = false; buddha(); } if (x &lt; 600 &amp;&amp; x &gt; 400 &amp;&amp; y &gt; 60 &amp;&amp; y &lt; 110) { called = true; dhamma(); } if (x &lt; 880 &amp;&amp; x &gt; 710 &amp;&amp; y &gt; 60 &amp;&amp; y &lt; 110) { called = false; sangha(); } if (called === true &amp;&amp; x &lt; 330 &amp;&amp; x &gt; 140 &amp;&amp; y &gt; 260 &amp;&amp; y &lt;300) { alert("yay"); } } function buddha() { var c = document.getElementById("canvas"); var ctx = c.getContext("2d"); ctx.clearRect(0, 0, 1000, 750); ctx.beginPath(); ctx.moveTo(185, 120); ctx.lineTo(500, 250); ctx.strokeStyle = "#FCF"; ctx.lineWidth = 5; ctx.stroke(); ctx.font = "bold 48px Arial"; ctx.fillStyle = "#F63"; ctx.textAlign = "center"; var B = "Buddha "; var D = "Dhamma "; var S = "Sangha"; ctx.fillText(B + D + S, 500, 100); ctx.font = "bold 40px Arial"; ctx.fillStyle = "#0C0"; ctx.textAlign = "center"; ctx.fillText("Accomplished", 500, 300); ctx.font = "bold 40px Arial"; ctx.fillStyle = "#0C0"; ctx.textAlign = "center"; ctx.fillText("Fully Enlightened", 500, 350); ctx.font = "bold 40px Arial"; ctx.fillStyle = "#0C0"; ctx.textAlign = "center"; ctx.fillText("Perfect in True Knowledge and Conduct", 500, 400); ctx.font = "bold 40px Arial"; ctx.fillStyle = "#0C0"; ctx.textAlign = "center"; ctx.fillText("Sublime", 500, 450); ctx.font = "bold 40px Arial"; ctx.fillStyle = "#0C0"; ctx.textAlign = "center"; ctx.fillText("Knower of Worlds", 500, 500); ctx.font = "bold 40px Arial"; ctx.fillStyle = "#0C0"; ctx.textAlign = "center"; ctx.fillText("Incomparable Leader of Persons to be Tamed", 500, 550); ctx.font = "bold 40px Arial"; ctx.fillStyle = "#0C0"; ctx.textAlign = "center"; ctx.fillText("Teacher of Gods and Humans", 500, 600); ctx.font = "bold 40px Arial"; ctx.fillStyle = "#0C0"; ctx.textAlign = "center"; ctx.fillText("Blessed", 500, 650); } function sangha(){ var c = document.getElementById("canvas"); var ctx = c.getContext("2d"); ctx.clearRect(0, 0, 1000, 750); ctx.beginPath(); ctx.moveTo(800, 120); ctx.lineTo(270, 250); ctx.strokeStyle = "#FCF"; ctx.lineWidth = 5; ctx.stroke(); ctx.moveTo(840, 120); ctx.lineTo(680, 250); ctx.strokeStyle = "#FCF"; ctx.lineWidth = 5; ctx.stroke(); ctx.font = "bold 48px Arial"; ctx.fillStyle = "#F63"; ctx.textAlign = "center"; var B = "Buddha "; var D = "Dhamma "; var S = "Sangha"; ctx.fillText(B + D + S, 500, 100); ctx.font = "bold 40px Arial"; ctx.fillStyle = "#0C0"; ctx.textAlign = "right"; ctx.fillText("Monastic Sangha ", 500, 300); ctx.font = "bold 36px Arial"; ctx.fillStyle = "#FCF"; ctx.textAlign = "right"; ctx.fillText("Nuns ", 500, 350); ctx.font = "bold 36px Arial"; ctx.fillStyle = "#FCF"; ctx.textAlign = "right"; ctx.fillText("Monks ", 500, 400); ctx.font = "bold 36px Arial"; ctx.fillStyle = "#FCF"; ctx.textAlign = "right"; ctx.fillText("Novice Nuns ", 500, 450); ctx.font = "bold 36px Arial"; ctx.fillStyle = "#FCF"; ctx.textAlign = "right"; ctx.fillText("Novice Monks ", 500, 500); ctx.font = "bold 40px Arial"; ctx.fillStyle = "#0C0"; ctx.textAlign = "left"; ctx.fillText(" Noble Sangha", 500, 300); ctx.font = "bold 36px Arial"; ctx.fillStyle = "#FCF"; ctx.textAlign = "left"; ctx.fillText(" Arahants", 500, 350); ctx.font = "bold 36px Arial"; ctx.fillStyle = "#FCF"; ctx.textAlign = "left"; ctx.fillText(" Non-Returners", 500, 400); ctx.font = "bold 36px Arial"; ctx.fillStyle = "#FCF"; ctx.textAlign = "left"; ctx.fillText(" Once-Returners", 500, 450); ctx.font = "bold 36px Arial"; ctx.fillStyle = "#FCF"; ctx.textAlign = "left"; ctx.fillText(" Stream-Enterers", 500, 500); } function dhamma() { var c = document.getElementById("canvas"); var ctx = c.getContext("2d"); ctx.clearRect(0, 0, 1000, 750); ctx.beginPath(); ctx.moveTo(500, 120); ctx.lineTo(235, 250); ctx.strokeStyle = "#FCF"; ctx.lineWidth = 5; ctx.stroke(); ctx.moveTo(505, 120); ctx.lineTo(420, 250); ctx.strokeStyle = "#FCF"; ctx.lineWidth = 5; ctx.stroke(); ctx.moveTo(510, 120); ctx.lineTo(620, 250); ctx.strokeStyle = "#FCF"; ctx.lineWidth = 5; ctx.stroke(); ctx.moveTo(515, 120); ctx.lineTo(805, 250); ctx.strokeStyle = "#FCF"; ctx.lineWidth = 5; ctx.stroke(); ctx.font = "bold 48px Arial"; ctx.fillStyle = "#F63"; ctx.textAlign = "center"; var B = "Buddha "; var D = "Dhamma "; var S = "Sangha"; ctx.fillText(B + D + S, 500, 100); ctx.font = "bold 40px Arial"; ctx.fillStyle = "#09F"; ctx.textAlign = "center"; ctx.fillText("Suffering Origin Cessation Path", 500, 300); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T18:56:34.597", "Id": "38979", "Score": "0", "body": "I highly suggest you use a framework rather than tackling this head on with raw JS." } ]
[ { "body": "<p><a href=\"http://canvasquery.com/\" rel=\"nofollow\">Canvas Query</a> will be very helpful. Once you load it you will be able to chain methods as follows:</p>\n\n<pre><code>ctx.font = \"bold 40px Arial\";\nctx.fillStyle = \"#0C0\";\nctx.textAlign = \"center\";\nctx.fillText(\"Fully Enlightened\", 500, 350);\n</code></pre>\n\n<p>can be shortened to:</p>\n\n<pre><code>cq('#canvas');\ncq().textAlign('center').font('bold 48px Arial').fillStyle('#F63').fillText\"Fully Enlightened\", 500, 350);\n</code></pre>\n\n<p>You have some other areas of improvement as well. First of all, your code will be easier to review if you fix up your indentation and make your function names more informative than <code>BDS</code> and <code>q</code>.</p>\n\n<p>Now...you never call <code>q</code> in your code snippet, so it is unclear what event is the trigger...please post the full script if possible so it is more clear what you are trying to accomplish.</p>\n\n<p>Anyway, you can abstract a lot of your code using the <a href=\"http://c2.com/cgi/wiki?OnceAndOnlyOnce\" rel=\"nofollow\">OnceAndOnlyOnce</a> principle. Take for example that you initialize all three functions in a similar way:</p>\n\n<pre><code>var c = document.getElementById(\"canvas\");\nvar ctx = c.getContext(\"2d\");\nctx.clearRect(0, 0, 1000, 750);\n\nctx.font = \"bold 48px Arial\";\nctx.fillStyle = \"#F63\";\nctx.textAlign = \"center\";\nvar B = \"Buddha \";\nvar D = \"Dhamma \";\nvar S = \"Sangha\";\nctx.fillText(B + D + S, 500, 100);\n</code></pre>\n\n<p>despite the fact that <strong>the exact same code</strong> is contained in your BDS method. I'm not sure why you feel it is necessary to clear the canvas after each method is called... Anyway I would rename <code>BDS</code> to <code>setup</code> and just call it from inside the <code>buddha</code>, etc. functions if you feel this clearing of the canvas is necessary. Also you are caching variables you don't reuse. You could change the above to:</p>\n\n<pre><code>var text = ['Buddha', 'Dhamma', 'Sangha'].join(' '); // Whitespace not preserved...\ncq().textAlign('center').font('bold 48px Arial').fillStyle('#F63').fillText(text, 500, 100);\n</code></pre>\n\n<p>Another abstraction you can make is that you do something similar to the following all over your code: </p>\n\n<pre><code>ctx.font = \"bold 40px Arial\";\nctx.fillStyle = \"#0C0\";\nctx.textAlign = \"center\";\nctx.fillText(\"Accomplished\", 500, 300);\n</code></pre>\n\n<p>Abstract it!</p>\n\n<pre><code>function label(text, x, y, styleClass){\n if( typeof styleClass != 'undefined'){\n cq().textAlign(styleClass.textAlign)\n .font(styleClass.font)\n .fillStyle(styleClass.fillStyle);\n }\n cq().fillText(text, x, y);\n}\n</code></pre>\n\n<p>This function can actually be further reduced to:</p>\n\n<pre><code>function label(text, x, y, styleClass){\n if( typeof styleClass != 'undefined'){\n cq().set(styleClass);\n }\n cq().fillText(text, x, y);\n}\n</code></pre>\n\n<p>Now you can do:</p>\n\n<pre><code>var style1 = {font: \"bold 40px Arial\", textAlign: \"center\", fillStyle: \"#0C0\"};\n\nsetup();\nfunction buddha() {\n cq().beginPath().moveTo(185, 120).lineTo(500, 250).strokeStyle(\"#FCF\").lineWidth(5).stroke();\n\n label(\"Accomplished\", 500, 300, style1);\n label(\"Fully Enlightened\", 500, 350);\n label(\"Perfect in True Knowledge and Conduct\", 500, 400);\n label(\"Sublime\", 500, 450);\n label(\"Knower of Worlds\", 500, 500);\n label(\"Incomparable Leader of Persons to be Tamed\", 500, 550);\n label(\"Teacher of Gods and Humans\", 500, 600);\n label(\"Blessed\", 500, 650);\n}\n</code></pre>\n\n<p>Note that you only need to pass in a style object if you are changing the style. You could perform a similar abstraction with your lines:</p>\n\n<pre><code>function edge(x1, y1, x2, y2, lineStyle){\n if (typeof lineStyle != 'undefined'){\n cq().set(lineStyle);\n }\n cq().beginPath().moveTo(x1, y1).lineTo(x2, y2).stroke();\n}\n\nlineStyle = {strokeStyle: \"#FCF\", lineWidth: 5};\nedge(185, 120, 500, 250, lineStyle);\n</code></pre>\n\n<p>Now your complete code should look like:</p>\n\n<pre><code>onload = setup;\n\nfunction setup() {\n cq('#canvas');\n var text = ['Buddha', 'Dhamma', 'Sangha'].join(' ');\n cq().textAlign('center').font('bold 48px Arial').fillStyle('#F63').fillText(text, 500, 100);\n buddha();\n dhamma();\n sangha();\n}\n\nfunction label(text, x, y, styleClass){\n if( typeof styleClass != 'undefined'){\n cq().textAlign(styleClass.textAlign)\n .font(styleClass.font)\n .fillStyle(styleClass.fillStyle);\n }\n cq().fillText(text, x, y);\n}\n\nfunction edge(x1, y1, x2, y2, lineStyle){\n if (typeof lineStyle != 'undefined'){\n cq().strokeStyle(lineStyle.strokeStyle)\n .lineWidth(lineStyle.lineWidth);\n }\n cq().beginPath().moveTo(x1, y1).lineTo(x2, y2).stroke();\n}\n\nvar edgeStyle = {strokeStyle: \"#FCF\", lineWidth: 5};\nvar labelStyles = {\n Buddha: {font: \"bold 40px Arial\", textAlign: \"center\", fillStyle: \"#0C0\"},\n Sangha: {font: \"bold 36px Arial\", textAlign: \"right\", fillStyle: \"#FCF\"},\n Dhamma: {font: \"bold 40px Arial\", textAlign: \"center\", fillStyle: \"#0C0\"}\n};\n\nfunction buddha() {\n edge(185, 120, 500, 250, edgeStyle);\n label(\"Accomplished\", 500, 300, labelStyles.Buddha);\n label(\"Fully Enlightened\", 500, 350);\n label(\"Perfect in True Knowledge and Conduct\", 500, 400);\n label(\"Sublime\", 500, 450);\n label(\"Knower of Worlds\", 500, 500);\n label(\"Incomparable Leader of Persons to be Tamed\", 500, 550);\n label(\"Teacher of Gods and Humans\", 500, 600);\n label(\"Blessed\", 500, 650);\n}\n\nfunction sangha(){\n edge(800, 120, 270, 250, edgeStyle);\n edge(840, 120, 680, 250);\n label(\"Monastic Sangha \", 500, 300, labelStyles.Sangha);\n label(\"Nuns \", 500, 350);\n label(\"Monks \", 500, 400);\n label(\"Novice Nuns \", 500, 450);\n label(\" Noble Sangha\", 500, 300);\n label(\" Arahants\", 500, 350);\n label(\" Non-Returners\", 500, 400);\n label(\" Once-Returners\", 500, 450);\n label(\" Stream-Enterers\", 500, 500);\n}\n\nfunction dhamma() {\n edge(500, 120, 235, 250, edgeStyle);\n edge(505, 120, 420, 250);\n edge(510, 120, 620, 250);\n edge(515, 120, 805, 250);\n label(\"Suffering Origin Cessation Path\", 500, 300);\n}\n</code></pre>\n\n<p>You just trimmed your code from 231 lines down to 69!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T13:46:16.117", "Id": "39045", "Score": "0", "body": "Thank you! The function q() is called in the html to make the mouseclick thing work: onclick=q(event). The indentation is less of a mess in ecplise than it looks in my post. I'll go back now and make my names make more sense, and start condensing stuff like you've suggested. Many many thanks for taking the time to go through it so thoroughly :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T21:10:43.573", "Id": "25201", "ParentId": "25185", "Score": "1" } }, { "body": "<p>I have this problem as well. I like to keep my code short and clean. If I don't, I usually end of abandoning a project because it gets too long and messy.\nWhat I do is condense actions that are carried out many times on the canvas.</p>\n\n<p>Example:</p>\n\n<pre><code>// drawing a bunch of rectangles to canvas the old way.\n\ncanvas.save();\ncanvas.fillStyle = \"red\";\ncanvas.fillRect(50, 50, 100, 100);\ncanvas.restore();\ncanvas.save();\ncanvas.fillStyle = \"blue\";\ncanvas.fillRect(0, 0, 100, 100);\ncanvas.restore();\n// etc....\n\n//instead create a function for making simple rectangles\n\nfunction drawRect(x, y, width, height, color) {\n canvas.save();\n canvas.fillStyle = color;\n canvas.fillRect(x, y, width, height);\n canvas.restore();\n};\n\n//now i can call this function whenever i need a rectangle\n//also you can use rgb(red, green, blue) in place of named colors.\n\ndrawRect(0, 0, 50, 60, \"yellow\");\ndrawRect(50, 50, 100, 200, \"red\");\ndrawRect(0, 50, 200, 300, rgb(120, 40, 200));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-09T19:17:24.340", "Id": "27204", "ParentId": "25185", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T17:55:03.617", "Id": "25185", "Score": "2", "Tags": [ "javascript", "html5", "canvas" ], "Title": "Javascript canvas interactive chart - how to make my code shorter" }
25185
<p>How can I improve this code?</p> <p>Also available from git://github.com/edescourtis/actor.git .</p> <p>Actor.java</p> <pre><code>package com.benbria.actor; public interface Actor&lt;T&gt; extends Runnable { public abstract void send(T msg) throws InterruptedException; public abstract void stop() throws InterruptedException; } </code></pre> <p>ActorListener.java</p> <pre><code>package com.benbria.actor; public interface ActorListener&lt;T&gt; { void start(Actor&lt;T&gt; actor); void stop(Actor&lt;T&gt; actor); void exception(Actor&lt;T&gt; actor, Exception ex); } </code></pre> <p>Behaviour.java</p> <pre><code>package com.benbria.actor; public interface Behaviour&lt;T&gt; { void receive(Actor&lt;T&gt; self, T msg); } </code></pre> <p>ThreadActor.java</p> <pre><code>package com.benbria.actor; import java.util.Comparator; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.PriorityBlockingQueue; import com.benbria.actor.listeners.NullActorListener; /** * @author Eric des Courtis * */ public final class ThreadActor&lt;T&gt; implements Runnable, Actor&lt;T&gt; { private final BlockingQueue&lt;StopOrT&lt;T&gt;&gt; queue; private final Behaviour&lt;T&gt; behaviour; private final ActorListener&lt;T&gt; listener; public static &lt;T&gt; Actor&lt;T&gt; create(Behaviour&lt;T&gt; behaviour, ActorListener&lt;T&gt; listener) { return new ThreadActor&lt;T&gt;(behaviour, listener); } public static &lt;T&gt; Actor&lt;T&gt; create(Behaviour&lt;T&gt; behaviour) { return create(behaviour, new NullActorListener&lt;T&gt;()); } public static &lt;T&gt; Actor&lt;T&gt; spawn(Behaviour&lt;T&gt; behaviour, ActorListener&lt;T&gt; listener){ Actor&lt;T&gt; a = create(behaviour, listener); new Thread(a).start(); return a; } public static &lt;T&gt; Actor&lt;T&gt; spawn(Behaviour&lt;T&gt; behaviour) { return spawn(behaviour, new NullActorListener&lt;T&gt;()); } public static &lt;T&gt; Actor&lt;T&gt; createWithPriorityQueue(Behaviour&lt;T&gt; behaviour, ActorListener&lt;T&gt; listener, final Comparator&lt;T&gt; comparator) { return new ThreadActor&lt;T&gt;(behaviour, listener, new PriorityBlockingQueue&lt;StopOrT&lt;T&gt;&gt;(10, new Comparator&lt;StopOrT&lt;T&gt;&gt;() { @Override public int compare(StopOrT&lt;T&gt; o1, StopOrT&lt;T&gt; o2) { if(o1.isStop()) return -1; if(o2.isStop()) return 1; return comparator.compare(o1.getT(), o2.getT()); } })); } public static &lt;T&gt; Actor&lt;T&gt; createWithPriorityQueue(Behaviour&lt;T&gt; behaviour, Comparator&lt;T&gt; comparator) { return createWithPriorityQueue(behaviour, new NullActorListener&lt;T&gt;(), comparator); } public static &lt;T&gt; Actor&lt;T&gt; spawnWithPriorityQueue(Behaviour&lt;T&gt; behaviour, ActorListener&lt;T&gt; listener, Comparator&lt;T&gt; comparator){ Actor&lt;T&gt; a = createWithPriorityQueue(behaviour, listener, comparator); new Thread(a).start(); return a; } public static &lt;T&gt; Actor&lt;T&gt; spawnWithPriorityQueue(Behaviour&lt;T&gt; behaviour, Comparator&lt;T&gt; comparator) { return spawnWithPriorityQueue(behaviour, new NullActorListener&lt;T&gt;(), comparator); } private ThreadActor(Behaviour&lt;T&gt; behaviour, ActorListener&lt;T&gt; listener, BlockingQueue&lt;StopOrT&lt;T&gt;&gt; queue) { this.listener = listener; this.behaviour = behaviour; this.queue = queue; } private ThreadActor(Behaviour&lt;T&gt; behaviour, ActorListener&lt;T&gt; listener) { this(behaviour, listener, new LinkedBlockingQueue&lt;StopOrT&lt;T&gt;&gt;()); } private ThreadActor(Behaviour&lt;T&gt; behaviour) { this(behaviour, new NullActorListener&lt;T&gt;()); } public void run() { listener.start(this); try { while(true) { StopOrT&lt;T&gt; stopOrMsg = queue.take(); if(stopOrMsg.isT()){ behaviour.receive(this, stopOrMsg.getT()); }else{ break; } } listener.stop(this); } catch (Exception ex) { listener.exception(this, ex); } } @Override public void send(T msg) throws InterruptedException { queue.put(StopOrT.newT(msg)); } @Override public void stop() throws InterruptedException { StopOrT&lt;T&gt; stop = StopOrT.newStop(); queue.put(stop); } private static class StopOrT&lt;T&gt; { private final T t; private StopOrT(T t) { this.t = t; } public boolean isStop() { return t == null; } public boolean isT() { return t != null; } public T getT() { if (t == null) throw new RuntimeException("not T"); return t; } public static &lt;T&gt; StopOrT&lt;T&gt; newStop() { return new StopOrT&lt;T&gt;(null); } public static &lt;T&gt; StopOrT&lt;T&gt; newT(T t) { return new StopOrT&lt;T&gt;(t); } } } </code></pre> <p>NullActorListener.java</p> <pre><code>package com.benbria.actor.listeners; import com.benbria.actor.Actor; import com.benbria.actor.ActorListener; public class NullActorListener&lt;T&gt; implements ActorListener&lt;T&gt; { public NullActorListener() { } @Override public void start(Actor&lt;T&gt; actor) { } @Override public void stop(Actor&lt;T&gt; actor) { } @Override public void exception(Actor&lt;T&gt; actor, Exception ex) { } } </code></pre> <p>NullBehaviour.java</p> <pre><code>package com.benbria.actor.behaviours; import com.benbria.actor.Actor; import com.benbria.actor.Behaviour; public final class NullBehaviour&lt;T&gt; implements Behaviour&lt;T&gt; { @Override public void receive(Actor&lt;T&gt; self, T msg) { } } </code></pre> <p>ThreadActorTests.java</p> <pre><code>/** * */ package com.benbria.actor.tests; import static org.junit.Assert.*; import org.junit.Test; import com.benbria.actor.Actor; import com.benbria.actor.ActorListener; import com.benbria.actor.Behaviour; import com.benbria.actor.ThreadActor; import com.benbria.actor.behaviours.NullBehaviour; /** * @author Eric des Courtis * */ public class ThreadActorTests { class StartStopExceptionCheckingActorListener implements ActorListener&lt;String&gt; { private boolean started = false; private boolean stopped = false; private boolean exception = false; @Override public void start(Actor&lt;String&gt; actor) { setStarted(); } @Override public void stop(Actor&lt;String&gt; actor) { setStopped(); } @Override public void exception(Actor&lt;String&gt; actor, Exception ex) { setException(); } public boolean isStarted() { return started; } public void setStarted() { this.started = true; } public boolean isStopped() { return stopped; } public void setStopped() { this.stopped = true; } public boolean isException() { return exception; } public void setException() { this.exception = true; } }; @Test public void testStartStopException(){ StartStopExceptionCheckingActorListener checkListener = new StartStopExceptionCheckingActorListener(); Actor&lt;String&gt; a = ThreadActor.spawn(new NullBehaviour&lt;String&gt;(), checkListener); try { a.stop(); Thread.sleep(1000); } catch (InterruptedException e) { } assertTrue(checkListener.isStarted()); assertTrue(checkListener.isStopped()); assertFalse(checkListener.isException()); } class ExceptionGeneratingBehaviour implements Behaviour&lt;String&gt; { @Override public void receive(Actor&lt;String&gt; self, String msg) { throw new RuntimeException("evil"); } } @Test public void testException() { StartStopExceptionCheckingActorListener checkListener = new StartStopExceptionCheckingActorListener(); Actor&lt;String&gt; a = ThreadActor.spawn(new ExceptionGeneratingBehaviour(), checkListener); try { a.send("hello"); Thread.sleep(1000); a.stop(); } catch (InterruptedException e) { } assertTrue(checkListener.isException()); } class ReceivedMessageCheckingBehaviour implements Behaviour&lt;String&gt; { private String msg; @Override public void receive(Actor&lt;String&gt; self, String msg) { this.msg = msg; } public String getMsg() { return msg; } } @Test public void testSend() { ReceivedMessageCheckingBehaviour behaviour = new ReceivedMessageCheckingBehaviour(); Actor&lt;String&gt; a = ThreadActor.spawn(behaviour); try { a.send("testing"); Thread.sleep(1000); a.stop(); } catch (InterruptedException e) { } assertEquals("testing", behaviour.getMsg()); } } </code></pre> <p>LoggingBehaviour.java</p> <pre><code>package com.benbria.actor.behaviours; import java.util.logging.Logger; import com.benbria.actor.Actor; import com.benbria.actor.Behaviour; public final class LoggingBehaviour&lt;T&gt; implements Behaviour&lt;T&gt; { private final static Logger logger = Logger.getLogger(LoggingBehaviour.class.getName()); @Override public void receive(Actor&lt;T&gt; self, T msg) { logger.info(self + ": " + msg); } } </code></pre> <p>LoggingActorListener.java</p> <pre><code>package com.benbria.actor.listeners; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.logging.Logger; import com.benbria.actor.Actor; import com.benbria.actor.ActorListener; public class LoggingActorListener&lt;T&gt; implements ActorListener&lt;T&gt; { private static final Logger logger = Logger.getLogger(LoggingActorListener.class.getName()); public LoggingActorListener() { } @Override public void start(Actor&lt;T&gt; actor) { logger.info(actor + ": started"); } @Override public void stop(Actor&lt;T&gt; actor) { logger.info(actor + ": stopped"); } @Override public void exception(Actor&lt;T&gt; actor, Exception ex) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ex.printStackTrace(new PrintStream(baos, true)); logger.severe(actor + ": " + baos.toString()); } } </code></pre> <p>BroadcastBehaviour.java</p> <pre><code>package com.benbria.actor.behaviours; import java.util.LinkedList; import java.util.List; import com.benbria.actor.Actor; import com.benbria.actor.Behaviour; public class BroadcastBehaviour&lt;T&gt; implements Behaviour&lt;T&gt; { private List&lt;Behaviour&lt;T&gt;&gt; behaviourList = new LinkedList&lt;Behaviour&lt;T&gt;&gt;(); public BroadcastBehaviour(List&lt;Behaviour&lt;T&gt;&gt; behaviourList) { this.behaviourList.addAll(behaviourList); } @Override public void receive(Actor&lt;T&gt; self, T msg) { for(Behaviour&lt;T&gt; behaviour: behaviourList){ behaviour.receive(self, msg); } } } </code></pre> <p>BroadcastActorListener.java</p> <pre><code>package com.benbria.actor.listeners; import java.util.LinkedList; import java.util.List; import com.benbria.actor.Actor; import com.benbria.actor.ActorListener; public class BroadcastActorListener&lt;T&gt; implements ActorListener&lt;T&gt; { private final List&lt;ActorListener&lt;T&gt;&gt; listeners = new LinkedList&lt;ActorListener&lt;T&gt;&gt;(); public BroadcastActorListener(List&lt;ActorListener&lt;T&gt;&gt; listeners) { this.listeners.addAll(listeners); } @Override public void start(Actor&lt;T&gt; actor) { for(ActorListener&lt;T&gt; listener: listeners) { listener.start(actor); } } @Override public void stop(Actor&lt;T&gt; actor) { for(ActorListener&lt;T&gt; listener: listeners) { listener.stop(actor); } } @Override public void exception(Actor&lt;T&gt; actor, Exception ex) { for(ActorListener&lt;T&gt; listener: listeners) { listener.exception(actor, ex); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T21:56:49.697", "Id": "39001", "Score": "0", "body": "Very nice! What about an factory to create the actor?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T21:57:51.483", "Id": "39002", "Score": "0", "body": "Not sure if it's worth doing. Anyone else have input on this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T09:04:19.700", "Id": "39109", "Score": "0", "body": "ThreadActor is a factory (having static create() methods)." } ]
[ { "body": "<ol>\n<li><p>No need for Actor to extend Runnable</p></li>\n<li><p>NullActorListener is redundant: MultiplexedActorListener with empty list of listeners behaves the same way. Having MultiplexedActorListener as a default listener, no need for the ThreadActor constructors with ActorListener parameters - one can just add listeners after ThreadActor creation.</p></li>\n<li><p>Multiplexer is a wrong term, you meant demultiplexer, see Wikipedia</p></li>\n<li><p>Parameter Actor self in Behaviour.receive() can be dropped. The case when Behaviour really needs access to its own actor is rare, and can be implemented with passing Actor to Behaviour implementation constructor.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T18:48:09.803", "Id": "39141", "Score": "1", "body": "3. You are right that Multiplexer is the wrong term but come to think of it Demultiplexer isn't either. I changed it to Broadcast instead. 4. The parameter cannot be dropped because the actor needs to be able to tell others about itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T18:52:51.653", "Id": "39142", "Score": "1", "body": "1. Actor needs to extend Runnable because in some containers where threads are managed you must create the thread on your own and register it with the container. If the actor does not implements Runnable this is not possible. 2. I simply don't agree that they are equivalent. The meaning is lost if the name is changed regardless if they produce the same output." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T09:06:26.757", "Id": "25259", "ParentId": "25188", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T18:41:49.907", "Id": "25188", "Score": "5", "Tags": [ "java", "design-patterns", "multithreading", "thread-safety", "actor" ], "Title": "Review of simple Java Actor library" }
25188
<p>I wrote a small ducktaped VBA script which pings servers every 15 mins or so. If a server's status is anything other than "Alive", the server and timestamp is written to another worksheet called "Log". </p> <pre><code>Sub Countup() Dim CountDown As Date CountDown = Now + TimeValue("00:00:01") Application.OnTime CountDown, "Auto_Open" End Sub Sub Auto_Open() Dim count As Range Set count = Worksheets("Servers").Range("A1:A1") count.Value = count.Value - TimeSerial(0, 0, 1) If count &lt;= 0 Then count = Worksheets("Servers").Range("C1:C1") Call GetComputerToPing Call Countup Exit Sub End If Call Countup End Sub Public Sub addDataToTable(ByVal strTableName As String, ByVal strData As String, ByVal Col As Integer) Dim lLastRow As Long Dim iHeader As Integer With ActiveSheet.ListObjects(strTableName) 'find the last row of the list lLastRow = ActiveSheet.ListObjects(strTableName).ListRows.count 'shift from an extra row if list has header If .Sort.Header = xlYes Then iHeader = 1 Else iHeader = 0 End If End With 'add the data a row after the end of the list ActiveSheet.Cells(lLastRow + 1 + iHeader, Col).Value = strData End Sub 'Requires references to Microsoft Scripting Runtime and Windows Script Host Object Model. 'Set these in Tools - References in VB Editor. Function sPing(sHost) As String On Error Resume Next sHost = Trim(sHost) Dim ipaddress As String Dim computername As String Dim Model As String Dim memory As Long Dim oPing As Object, oRetStatus As Object Set oPing = GetObject("winmgmts:{impersonationLevel=impersonate}") Set oPing = oPing.execquery("select * from win32_pingstatus where address ='" &amp; sHost &amp; "'") For Each oRetStatus In oPing If IsNull(oRetStatus.statuscode) Then sPing = "Dead" ElseIf oRetStatus.statuscode = 11010 Then sPing = "Request Timed Out" ElseIf oRetStatus.statuscode = 11013 Then sPing = "Destination Host Unreachable" Else sPing = "Alive" End If Next Set oPing = Nothing Set oRetStatus = Nothing End Function Sub GetComputerToPing() Application.DisplayAlerts = False 'On Error Resume Next Dim applicationobject As Object Dim i As Integer i = 3 'row to start checking servers from Do Until Cells(i, 1) = "" 'If Cells(i, 1) &lt;&gt; "" Then 'If Cells(i, 2) = "Request Timed Out" Or Cells(i, 2) = "" Or Cells(i, 2) = "Dead" Then Cells(i, 2) = sPing(Cells(i, 1)) Cells(i, 3) = Now() 'log it to Log If Cells(i, 2).Value &lt;&gt; "Alive" Then Call copytest(i) End If 'End If 'End If i = i + 1 Loop Set applicationobject = Nothing End Sub Function findlast_Row() As Long Dim ws As Worksheet Set ws = ThisWorkbook.Sheets("Log") With ws findlast_Row = .Range("A" &amp; .Rows.count).End(xlUp).Row End With End Function Sub copytest(ByVal intRow As Integer) 'screens for last row in log sheet iLastRow = findlast_Row() + 1 Worksheets("Log").Range("A" &amp; CStr(iLastRow) &amp; ":E" &amp; CStr(iLastRow)).Value = Worksheets("Servers").Range("A" &amp; CStr(intRow) &amp; ":E" &amp; CStr(intRow)).Value End Sub </code></pre> <p>Is there another way (or better way) to do the countdown timer?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T08:53:54.247", "Id": "39019", "Score": "1", "body": "And what was your question again?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T15:27:47.813", "Id": "39057", "Score": "0", "body": "Is there another way (or better way) to do the countdown timer?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T09:15:37.263", "Id": "39168", "Score": "0", "body": "Ok. That's clearer. I personaly don't see another way but let's see if anyone has a great idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T00:51:06.453", "Id": "57467", "Score": "1", "body": "I think it's \"duct tape\", not \"duck tape\"... poor ducks!" } ]
[ { "body": "<p>Using <code>Application.OnTime</code> is a <strong>very neat</strong> way of implementing your timer, but I have a hard time figuring out how \"<em>pings servers every 15 mins or so</em>\" translates to <code>Now + TimeValue(\"00:00:01\")</code>. Note that since VBA is single-threaded, <em>OnTime</em> doesn't mean your code will run <em>at that specific time</em>, rather that when Excel isn't busy doing something else, it will queue your method for synchronous execution, like any other event handler code.</p>\n\n<p>That said, your naming and access modifiers lack consistency (I guess that's what you meant with \"duct-taped\"?).</p>\n\n<h3>Observations</h3>\n\n<ul>\n<li>You're using <code>ListObject.ListRows.Count</code>, but you're puzzling your way into adding a new row - why aren't you using <code>ListObject.ListRows.Add()</code> which returns the added row?</li>\n<li>In <code>sPing</code> function (awful name), I would refactor this <code>ElseIf</code> construct into some <code>Private Function GetPingResult(StatusCode As Long) As String</code>, and <strong>assign the function's return value once</strong>; also you made the <em>default value</em> \"Alive\" - if there's an error code you haven't accounted for, <strong>your function returns \"Alive\" which is possibly wrong.</strong></li>\n</ul>\n\n<h3>Nitpicks</h3>\n\n<ul>\n<li>This is VBA - stick to <em>PascalCasing</em> for all identifiers. It will make your code read consistently with the language itself.</li>\n<li>The default access modifier for <code>Sub</code> and <code>Function</code> is <code>Public</code> - thus, <strong>either specify it or leave it out</strong>, but don't do <em>both</em>. If the unspecified ones are supposed to be <code>Private</code>, be explicit about it.</li>\n<li>The language's convention for <strong>underscores in procedure names</strong>, is only for methods that implement interface methods (e.g. event handlers). Avoid it.</li>\n<li>Worse than Hungarian notation (<code>strTableName As String</code>), is <strong>inconsistent</strong> Hungarian notation, especially in the <strong>same method signature</strong> (why isn't it <code>iCol As Integer</code> then?). Avoid it (Hungarian notation, that is!).</li>\n</ul>\n\n<p>I know this is an incomplete review, but I think you have enough meat here anyway.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T01:22:55.150", "Id": "35461", "ParentId": "25189", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T19:07:00.597", "Id": "25189", "Score": "7", "Tags": [ "optimization", "vba", "timer", "excel" ], "Title": "How to make this ping test with timer more efficient?" }
25189
<p>I have a C# program that I would like to have reviewed. I am new to programming and want to know how it could be improved. It is a Windows Forms project that generates a PDF using the iTextSharp dll. I have tried to leave off the repetitive parts (multiple textboxes, etc) as well as the part that uses iTextSharp.</p> <pre><code>namespace InvoiceGenerator { public partial class InvoiceGenerator : Form { List&lt;string&gt; state = new List&lt;string&gt;(); public InvoiceGenerator() { InitializeComponent(); string[] states = new string[] { "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" }; comboBoxState.Items.AddRange(states); } private void InvoiceGenerator_Load(object sender, EventArgs e) { maskedTextBoxDate.Text = DateTime.Today.ToString("MM/dd/yyyy"); maskedTextBoxDate.ValidatingType = typeof(System.DateTime); lblTotalPrice.Text = "$0.00"; } public static bool IsFileLocked(FileInfo file) { FileStream stream = null; try { stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); } catch (IOException) { return true; } finally { if (stream != null) stream.Close(); } return false; } private void btnGenerate_Click(object sender, EventArgs e) { FillForm(); maskedTextBoxDate.Text = DateTime.Today.ToString("MM/dd/yyyy"); txtName.Text = ""; txtAddress.Text = ""; txtCity.Text = ""; comboBoxState.SelectedIndex = -1; txtZipCode.Text = ""; txtAttn.Text = ""; checkBoxFull.Checked = false; checkBoxFirst.Checked = false; checkBoxNext.Enabled = false; lblTotalPrice.Text = ""; textBox1.Text = ""; } private void FillForm() { string pdfTemplate = @"\\server\files\Invoice_Generator\invoice.pdf"; string newFile = @"\\server\files\Invoice_Generator\completed_invoice.pdf"; FileInfo fileStatus = new FileInfo(newFile); if (IsFileLocked(fileStatus)) { MessageBox.Show("An invoice is currently open and needs to be closed before another one can be created.", "File currently in use.", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { //iTextSharp code Process.Start(newFile); } } private void checkBoxFull_CheckedChanged(object sender, EventArgs e) { if (checkBoxFull.Checked) { lblFullPrice.Text = "$1,000.00"; numericUpDownFull.Enabled = true; } else { lblFullPrice.Text = ""; lblTotalFull.Text = ""; numericUpDownFull.Value = 0; numericUpDownFull.Enabled = false; } } string invoiceFull = String.Empty; private void numericUpDownFull_ValueChanged(object sender, EventArgs e) { if (numericUpDownFull.Value == 0) { lblTotalFull.Text = ""; decimal total = (((decimal)numericUpDownFull.Value * 1000) + ((decimal)numericUpDownFirst.Value * 65) + ((decimal)numericUpDownNext.Value * 40)); lblTotalPrice.Text = total.ToString("C"); invoiceFull = ""; } else { decimal Value = numericUpDownFull.Value; if (numericUpDownFull.Value &gt; 0) { Value = Value * 1000; string Label = Value.ToString("C"); lblTotalFull.Text = Label; decimal total = (((decimal)numericUpDownFull.Value * 1000) + ((decimal)numericUpDownFirst.Value * 65) + ((decimal)numericUpDownNext.Value * 40)); lblTotalPrice.Text = total.ToString("C"); invoiceFull = numericUpDownFull.Value.ToString(); } } } private void maskedTextBoxDate_TypeValidationCompleted(object sender, TypeValidationEventArgs e) { if (!e.IsValidInput) { MessageBox.Show("Please enter a valid date.", "Invalid Date"); maskedTextBoxDate.Text = DateTime.Today.ToString("MM/dd/yyyy"); maskedTextBoxDate.Focus(); } else { //Now that the type has passed basic type validation, enforce more specific type rules. DateTime userDate = (DateTime)e.ReturnValue; if (userDate &gt; DateTime.Now) { MessageBox.Show("Please enter a valid date.", "Invalid Date"); maskedTextBoxDate.Text = DateTime.Today.ToString("MM/dd/yyyy"); maskedTextBoxDate.Focus(); } else { DateTime beginTime = new DateTime(1900, 1, 1); if (userDate &lt; beginTime) { MessageBox.Show("Please enter a valid date.", "Invalid Date"); maskedTextBoxDate.Text = DateTime.Today.ToString("MM/dd/yyyy"); maskedTextBoxDate.Focus(); } } } } private void TextEntry(object sender, KeyPressEventArgs e) { if (!char.IsLetter(e.KeyChar) &amp;&amp; !char.IsWhiteSpace(e.KeyChar) &amp;&amp; !char.IsControl(e.KeyChar)) { e.Handled = true; } } private void txtName_KeyPress(object sender, KeyPressEventArgs e) { TextEntry(txtName, e); } string invoiceName = String.Empty; private void txtName_TextChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtName.Text)) { invoiceName = txtName.Text; } } } } </code></pre>
[]
[ { "body": "<ol>\n<li>Moving the states list to some sort of data store (could be a text / xml file, or database) is preferable; this way you won't have to re-compile if you want to use your application in countries other than the US. </li>\n<li>(A positive point) I see that <code>IsFileLocked</code> is copied from a SO answer about file locking. using proven and tested code (i.e from a good source online) is a very good practice. however, why is this method public? </li>\n<li>In <code>FillForm</code>, if the file is locked, you can just <code>return</code> from the function after displaying the message to the user; there's no need for the <code>else</code> clause.<br>\nPersonally, I always advocate verification at the beginning, and returning immediately if it fails. This saves levels of nesting. (this comment also applies to <code>checkBoxFull_CheckedChanged</code> and <code>numericUpDownFull_ValueChanged</code> and <code>maskedTextBoxDate_TypeValidationCompleted</code>) </li>\n<li>Is <code>invoiceFull</code> a class member? if so, I would recommend naming it as such (either with a <code>_</code> or <code>m_</code> prefix). It's also recommended to declare all members at the top of the class.<br>\nAlso, I fail to see where it's used. </li>\n<li>If <code>numericUpDownFull.Value == 0</code> , then <code>total</code> will also will always be 0. no need to calculate it. </li>\n<li>The member <code>invoiceName</code> is never used for reading...</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T20:16:04.167", "Id": "38984", "Score": "0", "body": "thanks. as for # 2:because that is how I found it off of SO. Didn't think to make it private since I'm not calling it from elsewhere. #3:If I don't have an else statement the code for the pdf creation will try to run and I'll get an error since the pdf file is open. #4:invoiceFull is just a string variable that I use in the pdf creation (iTextSharp) part( pdfFormFields.SetField(\"QtyFull\", invoiceFull);. #5:good point! #6: its used in the pdf creation part." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T21:55:04.920", "Id": "39000", "Score": "0", "body": "#2- if you're not using it from anywhere else- it should be private. #3- please note I suggested you return from the function; therefore no further code would be executed. #4- my suggestions for naming and regioning still stand, though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T19:46:46.010", "Id": "25192", "ParentId": "25190", "Score": "3" } }, { "body": "<p>(This is in addition to the review from sJhonny.)</p>\n\n<p>These three lines are repeated three times in <code>maskedTextBoxDate_TypeValidationCompleted</code>:</p>\n\n<pre><code>MessageBox.Show(\"Please enter a valid date.\", \"Invalid Date\");\nmaskedTextBoxDate.Text = DateTime.Today.ToString(\"MM/dd/yyyy\");\nmaskedTextBoxDate.Focus();\n</code></pre>\n\n<p>Instead of copy-pasting them, move them to a separate method and call that.</p>\n\n<p>The same is true for this:</p>\n\n<pre><code>decimal total = (((decimal)numericUpDownFull.Value * 1000) \n + ((decimal)numericUpDownFirst.Value * 65)\n + ((decimal)numericUpDownNext.Value * 40));\nlblTotalPrice.Text = total.ToString(\"C\");\n</code></pre>\n\n<p>Repeated at least twice. Imagine you need to change this logic: now you need to do it in two places instead of one.</p>\n\n<hr>\n\n<p>I'm not a fan of this:</p>\n\n<pre><code>if (!e.IsValidInput)\n{}\nelse\n{}\n</code></pre>\n\n<p>I prefer a \"positive check\":</p>\n\n<pre><code>if (e.IsValidInput)\n{}\nelse\n{}\n</code></pre>\n\n<hr>\n\n<p>Note that local variables should be camelCase:</p>\n\n<p>decimal Value = numericUpDownFull.Value;\nstring Label = Value.ToString(\"C\");</p>\n\n<p>Moreover, \"Value\" is not good enough a name, ditto \"Label\". I don't see any need for \"Label\" anyway, since it is only used once: <code>lblTotalFull.Text = Label;</code>.</p>\n\n<hr>\n\n<p>I note that several of your fields don't have an explicit access modifier:</p>\n\n<pre><code>List&lt;string&gt; state = new List&lt;string&gt;();\nstring invoiceFull = String.Empty;\nstring invoiceName = String.Empty;\n</code></pre>\n\n<p>I'd always set those explicitly.</p>\n\n<hr>\n\n<p>Most importantly though I'd urge you to <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow\">separate your business logic from your display</a>. IMHO assignments to e.g. <code>lblTotalFull.Text</code> should probably be encapsulated into a method; perhaps the business logic could be moved to a separate class even. Same for the iTextSharp code in <code>FillForm()</code> (is that even a correct name for the functionality of that method?): move that to a separate class, along with the <code>IsFileLocked</code> method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-30T09:05:21.160", "Id": "75216", "ParentId": "25190", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T19:10:56.187", "Id": "25190", "Score": "3", "Tags": [ "c#", "beginner", "winforms" ], "Title": "Windows form that generates invoices" }
25190
<p>I have written an algorithm to find the largest palindrome under a given number, but I am sure my code loses efficiency by creating new arrays in every pass. I am currently learning about efficiency so I have the following question: Can anyone suggest a more efficient (faster) approach and explain why this approach is more efficient? </p> <pre><code>int number = 0; int palindrome = 0; for (int i = 1; i &lt; 999999; i++) { number = i; string s = number.ToString(); char[] charArray = s.ToCharArray(); char[] charArrayReversed = new char[charArray.Length]; Array.Copy(charArray, charArrayReversed, charArray.Length); Array.Reverse(charArrayReversed); bool isEqual = Enumerable.SequenceEqual(charArray, charArrayReversed); if (isEqual) palindrome = number; } Console.Write(palindrome); Console.ReadLine(); </code></pre>
[]
[ { "body": "<p>I'm sure there are other ways to improve it but here are a few quick points: </p>\n\n<ol>\n<li>Start from the end and work your way back, that way once you've found one palindrome you're done!</li>\n<li>You only have to check half of the digits for equality.</li>\n<li>We can shave off some time by avoiding <code>Array.Copy</code> / <code>Array.Reverse</code></li>\n</ol>\n\n<p>Something like this:</p>\n\n<pre><code>var limit = ?\nfor (int i = limit; i &gt; 0; i--)\n{\n number = i;\n string s = number.ToString();\n char[] charArray = s.ToCharArray();\n\n bool isEqual = true;\n int halfLength = charArray.Length / 2; // will skip the middle digit\n int max = charArray.Length - 1;\n for(int j = 0; j &lt; halfLength; j++)\n {\n if(charArray [j] != charArray[max - j])\n {\n isEqual = false;\n break;\n }\n }\n\n if (isEqual)\n {\n palindrome = number;\n break; // stop evaluating here\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-05T03:48:02.017", "Id": "39981", "Score": "0", "body": "I also thought of working my way back from the top. On 8 digits MAX limit it took about a second as compared to 40 seconds with the original algo in the question!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-05T03:49:20.507", "Id": "39982", "Score": "0", "body": "also start the FOR loop with (i=limit-1) or else 999999 will show up as the palindrome itself!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T20:55:46.127", "Id": "25195", "ParentId": "25193", "Score": "5" } }, { "body": "<p>Take the first half of the digits then add the reverse (keeping the middle in mind for odd length values). Then check if this new value is smaller than the original. If so, we are done.<br>\nThis is because the most significant digits are necessary for making the number as large as possible.</p>\n\n<p>If the number we created is too large, we need to make it a bit smaller. To do this we'd like to shrink the middle if we can, since that's where we'll find the least significant digits. This has to account for the fact that if there is a single middle digit (odd length) it doesn't get mirrored, so in that case the code doesn't copy the entire half.</p>\n\n<pre><code>string Palindrome(string largest)\n{ \n int len = largest.Length;\n\n //Special case. This is the only case where the number of digits in the result is different.\n if (IsPowerOf10(Int32.Parse(largest)))\n {\n return new String('9', len - 1);\n }\n\n //This will keep the middle digit if it's odd lengthed.\n string firstHalf = largest.Substring(0, (len + 1) / 2);\n //This will drop the middle digit if it's odd lengthed, so that it's not repeated.\n string secondHalf = Reverse(firstHalf.Substring(0, len / 2));\n\n if (firstHalf + secondHalf &gt; largest) //string concat then compare, not int operations.\n {\n firstHalf = (Int32.Parse(firstHalf) - 1).ToString();\n }\n\n return firstHalf + Reverse(firstHalf.Substring(0, len / 2);\n}\n\npublic static string Reverse(string s)\n{\n char[] charArray = s.ToCharArray();\n Array.Reverse(charArray);\n return new string(charArray);\n}\n\npublic static bool IsPowerOf10(int i)\n{\n i = i * 10; //for the case when i == 1\n while(i &gt; 10) //keeping it above 10 will avoid things like 11/10 == 1 leading to wrong results.\n {\n i = i/10;\n }\n\n return i == 10;\n}\n</code></pre>\n\n<p>Don't know if this compiles.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T20:58:04.757", "Id": "25196", "ParentId": "25193", "Score": "5" } }, { "body": "<p>There is no need to do it by brute-force approach, or even reduced version of brute-force. We can just cut the max value to half, handle odd and even digits logic and all special cases then it's done.</p>\n\n<pre><code>private static int MakePalindrome(int left, int? cen)\n{\n string right = new string(left.ToString().Reverse().ToArray());\n string cenStr = cen.HasValue ? cen.ToString() : string.Empty;\n return int.Parse(left.ToString() + cenStr + right);\n}\n\nprivate static int MaxPalindrome(int maxValue)\n{\n string digits = maxValue.ToString();\n if (digits.Length == 1) return maxValue;\n bool hasCen = digits.Length % 2 &gt; 0;\n int left = int.Parse(digits.Substring(0, digits.Length / 2));\n int oLeft = left;\n int? cen = hasCen ? int.Parse(digits.Substring(digits.Length / 2, 1)) : (int?) null;\n int result = MakePalindrome(left, cen);\n if (result &gt; maxValue)\n {\n if (hasCen)\n {\n cen--;\n if (cen &lt; 0)\n {\n cen = 9;\n left--;\n }\n }\n else\n {\n left--;\n }\n\n if (left == 0 || left.ToString().Length &lt; oLeft.ToString().Length)\n {\n result = int.Parse(new string('9', digits.Length - 1));\n }\n else\n {\n result = MakePalindrome(left, cen);\n }\n }\n return result;\n}\n</code></pre>\n\n<p>Here is the code to test my logic:</p>\n\n<pre><code> int lastPalindrome = 0;\n for (int i = 0; i &lt; 10000; i++)\n {\n int newPalindrome = MaxPalindrome(i);\n if (lastPalindrome == 0) lastPalindrome = newPalindrome;\n Console.WriteLine(\"{0}/{1}\", i, newPalindrome);\n if (lastPalindrome != newPalindrome)\n {\n if (i != newPalindrome) {\n Console.WriteLine(\"***{0}/{1}\", i, newPalindrome); \n throw new InvalidProgramException(\"Incorrect palindrome\");\n }\n lastPalindrome = newPalindrome;\n }\n }\n</code></pre>\n\n<p>You can run it here: <a href=\"http://ideone.com/StCw4u\" rel=\"nofollow\">http://ideone.com/StCw4u</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T10:27:20.687", "Id": "25484", "ParentId": "25193", "Score": "0" } }, { "body": "<p>Try this</p>\n\n<pre><code> int number = 0;\n int palindrome = 0;\n\n for (int i = 99999998; i &gt;0 ; i--)\n {\n number = i;\n string s = number.ToString();\n char[] charArray = s.ToCharArray();\n char[] charArrayReversed = new char[charArray.Length];\n Array.Copy(charArray, charArrayReversed, charArray.Length);\n\n Array.Reverse(charArrayReversed);\n bool isEqual = Enumerable.SequenceEqual(charArray, charArrayReversed);\n if (isEqual)\n {\n palindrome = number;\n break;\n }\n }\n\n\n Console.Write(palindrome);\n Console.ReadLine();\n</code></pre>\n\n<p>more than technical optimization I have done some logical optimization. Run the loop in reverse and break at the first palindrome!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-05T03:51:34.877", "Id": "25826", "ParentId": "25193", "Score": "1" } } ]
{ "AcceptedAnswerId": "25196", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T20:34:16.463", "Id": "25193", "Score": "6", "Tags": [ "c#", "performance", "palindrome" ], "Title": "Largest Palindrome efficiency" }
25193
<p>This is my first attempt with a basic text adventure game, and I was wondering if there was a way to make it more efficient (or any other things I could add to make the game better). It isn't totally finished yet, but if there is a way to make it better, please post in the comments.</p> <pre><code>#lets me use the exit function import sys #Lets me use the time function import time #Want to play loop #asks for name name = raw_input('What is your name, adventurer? ') print 'Nice to meet you, '+name+'. Are you ready for your adventure?' while True: ready = raw_input('y/n ') if ready == 'y': print 'Good, let us start our great adventure!' break elif ready == 'n': print 'That is a real shame...' time.sleep(1) print 'Exiting program in 5 seconds:' time.sleep(1) print '5' time.sleep(1) print '4' time.sleep(1) print '3' time.sleep(1) print '2' time.sleep(1) print '1' time.sleep(1) sys.exit('Exiting Game...') break else: print 'That is not a valid answer... Try again' time.sleep(2) #First level loop while True: print 'You awaken on the ground of a great forest. You can see two possible things to do, enter the cabin to your left, or wander through the woods.' print ' ' print 'Where do you want to go?' FirstDecision = raw_input('cabin/woods ') #Cabin option if FirstDecision == 'cabin': print 'You approach the door to the cabin, luckily it is unlocked.' Cnt = raw_input('Enter &lt; to continue') print 'You open the door and walk through, only to hear a dry and shaky voice say:' print '\"Get out.\"' Cnt = raw_input('Enter &lt; to continue') print 'What do you do?' FirstCabin = raw_input('leave/fight ') if FirstCabin == 'leave': print 'As you run out the door, the voice shoots and kills you.' Cnt = raw_input('Enter &lt; to continue') print ' ' FirstRetry = raw_input('Try again? (y/n)') if FirstRetry == 'y': print 'Restarting back at checkpoint...' time.sleep(2) elif FirstRetry == 'n': print 'That\'s a shame...' time.sleep(1) print 'Exiting program in 5 seconds:' time.sleep(1) print '5' time.sleep(1) print '4' time.sleep(1) print '3' time.sleep(1) print '2' time.sleep(1) print '1' time.sleep(1) sys.exit('Exiting Game...') break elif FirstCabin == 'fight': print 'You turn to where the voice came from and you bluntly say \"No.\"`` </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T22:07:47.220", "Id": "39003", "Score": "0", "body": "`while True: ready = raw_input('y/n ')` : if I'm not wrong and if the indentation is not wrong, this would loop forever." } ]
[ { "body": "<p>A couple things. First of all, you should abstract the function that exits the game:</p>\n\n<pre><code>def exitGame():\n print 'That\\'s a shame...'\n print 'Exiting program in 5 seconds:'\n for i in range(5):\n time.sleep(1)\n print(i+1)\n sys.exit('Exiting Game...')\n</code></pre>\n\n<p>Second, I would probably push Cabins, retries, etc. into arrays.</p>\n\n<pre><code>DECISIONS = []\nCABINS = []\nCONTINUES = []\n</code></pre>\n\n<p>Third, I would define the first level as a function so you can do the gracefully exit:</p>\n\n<pre><code>EXIT_MESSAGE = 'Exiting Game...'\n#First level loop\nwhile True:\n try: firstLevel()\n except SystemExit as e:\n print(str(e))\n break\n</code></pre>\n\n<p>One last thing. Use print as a function and not a statement. And maybe it's personal preference, but I find string formatting strongly preferable:</p>\n\n<pre><code>print('Nice to meet you, %s. Are you ready for your adventure?' % name)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T01:14:24.243", "Id": "39007", "Score": "2", "body": "nitpick: those are lists not arrays" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T14:22:34.753", "Id": "39047", "Score": "0", "body": "Array is a general term for the type of data structure. I used lists above but you could use many other types of array depending on your needs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T14:31:04.290", "Id": "39050", "Score": "1", "body": "You could argue that, and that's why its just a nitpick. Typically in python arrays refer to fixed-size arrays from either the `array` module or numpy." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T00:02:12.777", "Id": "25206", "ParentId": "25194", "Score": "3" } }, { "body": "<p>One thing that stuck out to me is line 38 of your code is 158 characters long:</p>\n\n<pre><code>print 'You awaken on the ground of a great forest. You can see two possible things to do, enter the cabin to your left, or wander through the woods.'\n</code></pre>\n\n<p>Below are the first two sentences of the \"Maximum Line Length\" section in <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a>:</p>\n\n<blockquote>\n <p>Limit all lines to a maximum of 79 characters.</p>\n \n <p>For flowing long blocks of text with fewer structural restrictions\n (docstrings or comments), the line length should be limited to 72\n characters.</p>\n</blockquote>\n\n<p>To break line 38 into shorter lines in your source, you can store it in a variable inside parenthesis:</p>\n\n<pre><code>s1 = ('You awaken on the ground of a great forest. '\n 'You can see two possible things to do, enter '\n 'the cabin to your left, or wander through the woods.')\n</code></pre>\n\n<p>Note that with the above, the output will still be one continuous line of text without line breaks. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T00:32:33.610", "Id": "30471", "ParentId": "25194", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T20:46:55.353", "Id": "25194", "Score": "3", "Tags": [ "python" ], "Title": "Is there a better way to code this text adventure game?" }
25194
<p>**Note: I might put this on Code Golf too, but first I'd like to get this code reviewed.</p> <p>So there's this programming contest my school will be holding soon, which is about solving problems in the shortest (writing) time possible. I want to participate, but I discovered that I suck with puzzles. So today I begun doing a few example problems from past competitions.</p> <p><strong>Problem Description</strong></p> <p>A genome is a sequence of characters (A,C,G or T). Sometimes, many genomes share the same sequence of characters:</p> <ol> <li>ACCC <strong>GTT</strong></li> <li>A <strong>GTT</strong> AAC</li> </ol> <p>Given a set of genomes, you will have to find the size of the largest character sequence that is repeated in all given genomes.</p> <p><strong>Input</strong></p> <p>The first line is an integer, which just tells you the number of genomes you will be given. The next lines are the genome strings themselves (one per line).</p> <p>Example:</p> <pre><code>2 ACGGGCGTCGTCCCCGTCGTCGTATC CTCGTCGTCCCCGTCGTCGTGTC </code></pre> <p><strong>Output</strong></p> <p>Integer representing the size of the largest character sequence you found in all given genomes.</p> <p>Example (based on previous input):</p> <pre><code>18 </code></pre> <p><strong>My Analysis</strong></p> <p>Not gonna lie: I'm not good with clever math voodoo. I just decided to create all possible sequences and then grab the largest from that is found in all genomes. The key to that was using <code>std::string::find()</code>, which I guess is not the brightest idea ever.</p> <p><strong>My Solution</strong> <em>You may notice that my variables and such are in Spanish. Yeah.</em></p> <pre><code>#include &lt;iostream&gt; #include &lt;deque&gt; using namespace std; int main() { // Read data int cantidad; cin &gt;&gt; cantidad; // Number of genomes deque&lt;string&gt; genomas; // Deque of genomes string menorString; // Smallest genome for (int i = 0; i &lt; cantidad; ++i) { string in; cin &gt;&gt; in; // Read a genome genomas.push_back(in); // Send to deque // Check if this is the smallest genome so far if (i == 0) { menorString = in; }else { if (in.length() &lt; menorString.length()){ menorString = in; } } } // Create all possible sequences deque&lt;string&gt; sequences; // Deque for sequences unsigned long size = menorString.length(); // We will use the smallest genome found for (int a = 0; a &lt; size; ++a) { // For each char in this genome... // We begin building a sequence using this char. string temp = string(1,menorString.at(a)); // And store the sequence sequences.push_back(temp); for (int b = a + 1; b &lt; size; ++b) { // For each character AFTER this character... // We append it to our current sequence... temp.append(1,menorString.at(b)); // And store it. sequences.push_back(temp); } } // Now time to find the largest sequence found in ALL genomes. string largestSequence; for (int i = 0; i &lt; sequences.size(); ++i) { // For each sequence... bool genomas_ok = true; for (int g = 0; g &lt; genomas.size() &amp;&amp; genomas_ok; ++g) { // We check all genomes... string genoma = genomas[g]; // We search for the sequence to be within the genome if (genoma.find(sequences[i]) == string::npos) { // Sequence not found in genome. Discard this sequence. genomas_ok = false; } } if (genomas_ok) { // All genomes do have this sequence! // Check if is the largest one we got so far... if (i == 0) { largestSequence = sequences[i]; }else{ if (sequences[i].size() &gt; largestSequence.size()) { largestSequence = sequences[i]; } } } } // Print size of largest genome. cout &lt;&lt; largestSequence.size(); return 0; } </code></pre> <p><strong>Does it work?</strong></p> <p>Well, it <em>seems</em> to work. It works for the example given above, and with a few of my own tests.</p> <p><strong>What I need</strong></p> <p>This code looks pretty large. Not good for a speed contest (I suppose). Can you help me figure out improvements for this? Namely, improvements that make the code smaller - not necessarily about efficiency (but it is appreciated as well!).</p> <p>I suppose that commenting almost every line is not good for a contest either. Haha...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T17:48:28.887", "Id": "61237", "Score": "1", "body": "This question appears to be off-topic because it is about code golfing, that is not what we do here on code review." } ]
[ { "body": "<p>The book programming perls has one of the most clever implemenations to find the longest repeated substring. He sorts an array of pointers to the substrings. This would be the place that I would start for an implementation.</p>\n\n<pre><code>/* From 'Programming Pearls' by Jon Bentley */\n/* longdup.c -- Print longest string duplicated M times */\n\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdio.h&gt;\n\nint pstrcmp(char **p, char **q)\n{ return strcmp(*p, *q); }\n\nint comlen(char *p, char *q)\n{ int i = 0;\n while (*p &amp;&amp; (*p++ == *q++))\n i++;\n return i;\n}\n\n#define M 1\n#define MAXN 5000000\nchar c[MAXN], *a[MAXN];\n\nint main()\n{ int i, ch, n = 0, maxi, maxlen = -1;\n while ((ch = getchar()) != EOF) {\n a[n] = &amp;c[n];\n c[n++] = ch;\n }\n c[n] = 0;\n qsort(a, n, sizeof(char *), pstrcmp);\n for (i = 0; i &lt; n-M; i++)\n if (comlen(a[i], a[i+M]) &gt; maxlen) {\n maxlen = comlen(a[i], a[i+M]);\n maxi = i;\n }\n printf(\"%.*s\\n\", maxlen, a[maxi]);\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-04T02:19:11.373", "Id": "25791", "ParentId": "25197", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T20:58:13.120", "Id": "25197", "Score": "2", "Tags": [ "c++", "contest-problem" ], "Title": "Largest sequence found in all strings" }
25197
<p>I'm currently working my way through the questions on Project Euler and I am on question 5. Is this the best possible solution? Any suggestions welcomed!</p> <pre><code> List&lt;int&gt; divisors = new List&lt;int&gt;{ 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; int n = 1; while (true) { n++; foreach (int d in divisors) { if (n % d != 0) { break; } if (d==20) { Console.Write(n); Console.ReadLine(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T21:32:18.423", "Id": "38992", "Score": "0", "body": "Thanks for the suggestion. Do you know order would that would give?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T21:32:56.753", "Id": "38994", "Score": "0", "body": "Not sure what you mean? Order of what? If you mean Big-O complexity, it would be O(n), whereas your current algorithm is probably O(n!)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T21:40:43.507", "Id": "38998", "Score": "1", "body": "@phcoding what mellamokb mean is multiply all the prime factors of each number you will get your answer [2,3,4,5,6] 2*3*5*2=60" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T00:15:41.317", "Id": "39004", "Score": "0", "body": "@mellamokbtheWise i doubt original algorithm is N! ,i think it is N*M ( Assumning is N is output Number and M is 1-20) then worst case scenario is N*M right ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T04:14:53.137", "Id": "39008", "Score": "1", "body": "I was using `n` to refer to the number of input divisors (in this case `20`). Worst case scenario is that all of your divisors share no common factors, and so you would have to loop 1 by 1 all the way to `n!` before you found the answer. It isn't a good idea to use the \"output number\" in the algorithm complexity because it obscures the real complexity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T21:27:32.670", "Id": "39011", "Score": "0", "body": "Why are you not checking 11 ? i think your list of divisor should include 11" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T13:20:48.550", "Id": "39042", "Score": "0", "body": "@mellamokb agreed" } ]
[ { "body": "<p>The most optimal solution would be to calculate the <a href=\"http://en.wikipedia.org/wiki/Least_common_multiple\">LCM</a> of 1 to 20 directly using the standard <a href=\"http://en.wikipedia.org/wiki/Euclidean_algorithm\">Euclidean algorithm</a>.</p>\n\n<pre><code>// calculate GCD using Euclidean algorithm\npublic long GCD(long a, long b) {\n if (b == 0)\n return a;\n else\n return GCD(b, a % b);\n}\n\n// calculate LCM using simple formula based on GCD\npublic long LCM(long a, long b) {\n var gcd = GCD(a, b);\n return a * b / gcd;\n}\n\n// iteratively calculate LCM of 1 through 20\npublic static void Main(string args[]) {\n long result = 1;\n\n // loop through each value 1 to 20, and LCM with previous result\n for (long n = 2; n &lt;= 20; n++) {\n result = LCM(result, n);\n }\n\n // print out the result\n Console.WriteLine(result);\n}\n</code></pre>\n\n<p>In terms of complexity, this algorithm is roughly <code>O(n)</code> for small <code>n</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T00:48:15.590", "Id": "39005", "Score": "0", "body": "this is cool !!! awesome" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T22:14:05.440", "Id": "25204", "ParentId": "25200", "Score": "6" } } ]
{ "AcceptedAnswerId": "25204", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T21:09:29.127", "Id": "25200", "Score": "5", "Tags": [ "c#", "project-euler" ], "Title": "smallest number divisible by all numbers from 1 to 20? Project Euler question 5" }
25200
<p>The requirements:</p> <ul> <li>Work inside <strong>.htaccess</strong> (preferably via <code>mod_rewrite</code>)</li> <li><strong>Redirect</strong> requests from <code>/any/directory/index.php</code> to <code>/any/directory/</code></li> <li>Make sure that <code>/index.php-with-stupid-stuff-here</code> <strong>does not</strong> get rewritten</li> <li>Add <strong>trailing slash</strong> to directories, <code>/another/directory</code> becomes <code>/another/directory/</code></li> </ul> <p>Also note that:</p> <ul> <li>The ideal scenario would be to use <strong>manual 301 redirects</strong>, but this is a case where there are far too many directories to do that for individually.</li> <li><strong>Internal linking</strong> is clean (always goes to the right place), so this is a just-in-case solution. (But others who find this question might be in a different situation.)</li> </ul> <p><a href="https://codereview.stackexchange.com/users/8108/daverandom">DaveRandom</a> helped me revise my solution, resulting in…</p> <pre><code>RewriteEngine On RewriteCond %{THE_REQUEST} (?:/[^/]*)*/index\.php[?#\ ] RewriteRule .* %{REQUEST_URI}/../ [L,R=301] </code></pre> <blockquote> <p>The basic idea behind it is that by using <code>%{THE_REQUEST}</code> in a <code>RewriteCond</code> you are looking at the actual URI requested by the user before any file system mappings, alias, other rewrite rules etc. were applied.</p> <p>This is important, because if you just look at the request-URI in a <code>RewriteRule</code> you will almost definitely end up in a redirect loop.</p> </blockquote> <p>Questions:</p> <ul> <li>Is that solid, correct code?</li> <li>Anything else that should be added, or taken into account?</li> <li>Or, considering best practices, is there a better way entirely?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T16:32:38.433", "Id": "473953", "Score": "0", "body": "Looking for nearly the exact same thing. Any success?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-11T20:21:37.170", "Id": "475099", "Score": "0", "body": "@ArtGeigel, I ended up using that code. I don't remember the outcome though. Does it work for you?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T15:14:00.240", "Id": "475166", "Score": "1", "body": "I ended up figuring out my problem that initially prompted me to land on this page looking for answers. In my situation there was a parent directory housing an abandoned Wordpress installation (that I had completely forgotten about!) with a custom .htaccess that was conflicting with things I was trying to do in a sub-directory. Once I removed that then things worked fine for my needs. Others who have come to this page searching Google for similar answers consider looking above the directory you’re working with and carve out exceptions in parent .htaccess files for your folder." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-14T20:37:04.290", "Id": "475481", "Score": "0", "body": "@ArtGeigel, thanks for sharing! Consider writing an answer to this if you think it's helpful! I can upvote and mark it" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-17T22:50:14.230", "Id": "25205", "Score": "3", "Tags": [ "regex", "file-system", ".htaccess" ], "Title": "Automatically redirect /index.php files to their URL directory with .htaccess" }
25205
<p>I've coded following two methods to combine images that are HTTP POSTed to the server:</p> <pre><code>// Crops two squares out of two separate images // And then combines them into single image that's returned as byte[] private byte[] combineImages(HttpPostedFileBase[] itemPayload) { try { using (var ms = new MemoryStream()) using (var bitmap = new Bitmap(800, 400, PixelFormat.Format24bppRgb)) using (var img1 = Image.FromStream(itemPayload[0].InputStream)) using (var img2 = Image.FromStream(itemPayload[1].InputStream)) using (var g = Graphics.FromImage(bitmap)) { RectangleF img1Params = getCropParams(img1); g.DrawImage(img1, new RectangleF(0, 0, 400, 400), img1Params, GraphicsUnit.Pixel); RectangleF img2Params = getCropParams(img2); g.DrawImage(img2, new RectangleF(400, 0, 400, 400), img2Params, GraphicsUnit.Pixel); var encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 90L); bitmap.Save(ms, ImageCodecInfo.GetImageDecoders().Single(codec =&gt; codec.FormatID == ImageFormat.Jpeg.Guid), encoderParameters); return ms.ToArray(); } } catch (Exception ex) { return new byte[0]; } } private RectangleF getCropParams(Image img) { var rect = new RectangleF(); if (img.Width &gt; img.Height) { rect.X = (img.Width / 2) - (img.Height / 2); rect.Width = (img.Width / 2) + (img.Height / 2) - rect.X; rect.Y = 0; rect.Height = img.Height; } else { rect.X = 0; rect.Width = img.Width; rect.Y = (img.Height / 2) - (img.Width / 2); rect.Height = (img.Height / 2) + (img.Width / 2) - rect.Y; } return rect; } </code></pre> <p>It produces results I expect, but I was curious if my implementation could be improved. I am specifically interested in three things:</p> <ol> <li>Do you see any potential memory leaks?</li> <li>Do you think code will be performing well when it comes to scalability</li> <li>Is there a component like <a href="http://imageresizing.net/" rel="nofollow">ImageResizer</a> that can do this?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T13:40:18.017", "Id": "39044", "Score": "2", "body": "Instead of `return new byte[0]`, I'd have a class-level field `private static readonly byte[] emptyImage = new byte[0]` and then just `return emptyImage`. You may also want to do similarly with your `encoderParameters` so it isn't created on each call as it seems to be invariant." } ]
[ { "body": "<p>Expanding on my comment above, I'd also follow Microsoft's naming guidelines and have the method names be <code>PascalCase</code>d. Plus, I'm not a huge fan of mutable <code>structs</code>, preferring to initialize them via provided constructors. So I came up with the following:</p>\n\n<pre><code>public static class ImageCombiner\n{\n private static readonly EncoderParameters encoderParameters = new EncoderParameters(1);\n\n private static readonly RectangleF sizeLocation1 = new RectangleF(0.0F, 0.0F, 400.0F, 400.0F);\n\n private static readonly RectangleF sizeLocation2 = new RectangleF(400.0F, 0.0F, 400.0F, 400.0F);\n\n private static readonly ImageCodecInfo jpgDecoder = ImageCodecInfo.GetImageDecoders().Single(codec =&gt; codec.FormatID == ImageFormat.Jpeg.Guid);\n\n private static readonly byte[] emptyImage = new byte[0];\n\n static ImageCombiner()\n {\n encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 90L);\n }\n\n // Crops two squares out of two separate images\n // And then combines them into single image that's returned as byte[]\n public static byte[] CombineImages(IList&lt;HttpPostedFileBase&gt; itemPayload)\n {\n try\n {\n using (var ms = new MemoryStream())\n using (var bitmap = new Bitmap(800, 400, PixelFormat.Format24bppRgb))\n using (var img1 = Image.FromStream(itemPayload[0].InputStream))\n using (var img2 = Image.FromStream(itemPayload[1].InputStream))\n using (var g = Graphics.FromImage(bitmap))\n {\n g.DrawImage(img1, sizeLocation1, GetCropParams(img1), GraphicsUnit.Pixel);\n g.DrawImage(img2, sizeLocation2, GetCropParams(img2), GraphicsUnit.Pixel);\n bitmap.Save(ms, jpgDecoder, encoderParameters);\n return ms.ToArray();\n }\n }\n catch\n {\n return emptyImage;\n }\n }\n\n private static RectangleF GetCropParams(Image img)\n {\n return img.Width &gt; img.Height\n ? new RectangleF(\n (img.Width / 2) - (img.Height / 2),\n 0.0F,\n 2 * (img.Height / 2),\n img.Height)\n : new RectangleF(\n 0.0F,\n (img.Height / 2) - (img.Width / 2),\n img.Width,\n 2 * (img.Width / 2));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T01:49:16.840", "Id": "39157", "Score": "0", "body": "You could do away with the extra calculations. `((img.Width / 2) + (img.Height / 2)) - ((img.Width / 2) - (img.Height / 2))` is equal to `img.Height`.\n\nSimilarly `((img.Height / 2) + (img.Width / 2)) - ((img.Height / 2) - (img.Width / 2))` equals `img.Width`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T15:01:34.053", "Id": "40487", "Score": "0", "body": "@TanzeelKazi while you are correct the calculations can be simplified, what you say they can be simplified to is somewhat off. For instance, an image with an odd `Width` or `Height` will wind up rounding down when said and done. I have edited my answer to show a simplified calculation that is accurate." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T13:55:10.803", "Id": "25226", "ParentId": "25211", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T05:46:12.520", "Id": "25211", "Score": "2", "Tags": [ "c#", "asp.net", "asp.net-mvc-4" ], "Title": "Cropping and combining two images on server" }
25211
<p>Sometimes, I need to read two integer parameters in a single input line, separated by a whitespace.</p> <p>I have these two functions that seem to do the job just fine:</p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;deque&gt; // Splits a string by its whitespaces and returns a deque with each item. deque&lt;string&gt; split(string original) { deque&lt;string&gt; result; string buffer; stringstream stream(original); while (stream &gt;&gt; buffer) { result.push_back(buffer); } return result; } // Reads two integer parameters from a single line, separated by a whitespace void getTwiceInput(int &amp;a,int &amp;b) { string input; getline(cin,input); deque&lt;string&gt; deck = split(input); stringstream ss; ss &lt;&lt; deck[0]; ss &gt;&gt; a; ss.clear(); ss &lt;&lt; deck[1]; ss &gt;&gt; b; } </code></pre> <p>So in my program I do this call:</p> <pre><code>int x,y; getTwiceInput(x, y); </code></pre> <p>Is there an easier way to achieve this? It is a bit tiring having to type all of that just to achieve this for every programming challenge given.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T09:03:57.387", "Id": "39021", "Score": "0", "body": "If you're always reading two values from a line, consider using `std::pair` instead of `std::deque`. In fact, why do you even use `std::deque`? Use just `std::vector`, it's generally more efficient except cases where you have to insert values in random position, especially in front." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T09:37:58.497", "Id": "39023", "Score": "0", "body": "@Archie: Haha, yeah XD. I'm too used to deque." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T17:16:39.573", "Id": "39131", "Score": "2", "body": "Why not: `std::cin >> x >> y;`" } ]
[ { "body": "<p>I can think of two more ways of doing it.</p>\n\n<p><strong>1. Using iostream iterators</strong>. (Following code is from <a href=\"http://www.cplusplus.com/reference/iterator/istream_iterator/\" rel=\"nofollow\">here</a>)</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;iterator&gt;\nusing namespace std;\n\nint main () {\n double value1, value2;\n cout &lt;&lt; \"Please, insert two values: \";\n\n istream_iterator&lt;double&gt; eos; // end-of-stream iterator\n istream_iterator&lt;double&gt; iit (cin); // stdin iterator\n\n if (iit!=eos) value1=*iit;\n\n iit++;\n if (iit!=eos) value2=*iit;\n\n cout &lt;&lt; value1 &lt;&lt; \"*\" &lt;&lt; value2 &lt;&lt; \"=\" &lt;&lt; (value1*value2) &lt;&lt; endl;\n\n return 0;\n}\n</code></pre>\n\n<p><strong>2. Converting string to int using atoi()</strong> rest everything will be same.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T09:05:54.363", "Id": "39022", "Score": "0", "body": "Streams are nice, but using `atoi()` is not a good idea. Better use `std::stoi()` if your compiler handles C++11 Standard." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T08:09:37.177", "Id": "25213", "ParentId": "25212", "Score": "3" } }, { "body": "<p>I would recommend to use <code>std::stringstream</code> for split. Here is how I think this function would look like:</p>\n\n<pre><code>#include &lt;sstream&gt;\n#include &lt;vector&gt;\n#include &lt;iterator&gt;\n\ntemplate&lt;typename T&gt;\nstd::vector&lt;T&gt; split(const std::string&amp; line) {\n std::istringstream is(line);\n return std::vector&lt;T&gt;(std::istream_iterator&lt;T&gt;(is), std::istream_iterator&lt;T&gt;());\n}\n</code></pre>\n\n<p>And here is how to use it:</p>\n\n<pre><code>std::string line = \"1.2 3.4 5.6e7\";\nstd::vector&lt;double&gt; vec = split&lt;double&gt;(line);\n</code></pre>\n\n<p>This method is more general and can split more than two elements as well as parse them to any type provided as template parameter, as long as it is “readable” by <code>operator&gt;&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T19:17:58.643", "Id": "39066", "Score": "0", "body": "Would `std::assign` be better than `std::copy` ?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T09:17:23.813", "Id": "25216", "ParentId": "25212", "Score": "3" } }, { "body": "<p>Sorry, what is the problem with:</p>\n\n<pre><code> cin &gt;&gt; x &gt;&gt; y; \n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>void getTwiceInput(int &amp;a,int &amp;b) {\n string input;\n getline(cin,input);\n stringstream ss(input);\n ss &gt;&gt; a &gt;&gt; b;\n}\n</code></pre>\n\n<p>?? \nHere maybe you need to detect format errors (no mummers or only one per line, or more than two..) But your code dont do that anyway.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T10:40:44.193", "Id": "25219", "ParentId": "25212", "Score": "3" } } ]
{ "AcceptedAnswerId": "25216", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T07:13:57.050", "Id": "25212", "Score": "2", "Tags": [ "c++" ], "Title": "Input reading: two values (separated by whitespace) per line" }
25212
<p>I made a reference-counting smart pointer class. My aim is to make a "minimal" but "general purpose" smart pointer class with proper documentation. This is basically for educational purposes.</p> <p>I would like to have comments regarding exception handling, code clarity, comments, ease of use of API, etc. And, also comment if the code is of "industrial level".</p> <pre><code>#ifndef SMARTPTR_HPP #define SMARTPTR_HPP #include &lt;algorithm&gt; namespace smartptrnamespace { // // Basic reference counting smart pointer (no overloaded Bool magic, etc). // Ownership of memory on heap is shared amongst objects of this // class (shared ownership) i.e., no new object of T type is created // by this class. // Objects of this class are: // 1. nothrow-copy-assignable // 2. nothrow-copy-constructible // 3. nothrow-destructible, if T is nothrow-destructible // 4. suitable for storage in a STL container like List, Deque etc. // Strong exception guarantee // // Sample Usage: // SmartPtr&lt;T&gt; sPtr1 (new T); // sPtr1 refers to object of T type // SmartPtr&lt;T&gt; sPtr2; // sPtr2 refers to no object // if (!sPtr2.isAssigned ()) // SmartPtr::isAssigned() returns false if no reference is being held // cout &lt;&lt; "sPtr2 is not holding any reference" &lt;&lt; endl; // sPtr2 = new T; // make a new oject of T and pass ownership to sPtr // template&lt;class T&gt; class SmartPtr { public: // create a new object which is not // refering to any object on heap. // no-throw guarantee explicit SmartPtr () : m_pT (NULL), m_pRefCount (NULL) { } // new object will point to a memory location on heap given by 'pObj' // Strong exception guarantee explicit SmartPtr (T *pObj) : m_pT (pObj), m_pRefCount (NULL) { try { m_pRefCount = new int; } catch (...) { checkedDelete (m_pT); throw; } *m_pRefCount = 1; } // new object will refer to same memory on heap as 'rObj' // no-throw guarantee SmartPtr (const SmartPtr&lt;T&gt; &amp;rObj) : m_pT(rObj.m_pT), m_pRefCount(rObj.m_pRefCount) { if (m_pRefCount != NULL) (*m_pRefCount)++; } // make 'rObj' and 'this' will refer to same object on heap // no-throw guarantee SmartPtr&amp; operator= (const SmartPtr&lt;T&gt; &amp;rObj) { // uses copy-and-swap idiom this_type(rObj).swap(*this); return *this; } // assign this smart pointer to another object on heap // Strong exception guarantee SmartPtr&amp; operator= (T *pTObj) { // try and setup memory for reference counter int *pNewRefCount; try { pNewRefCount = new int; } catch (...) { delete pTObj; throw; } // stop referring to previous object updateCountAndTriggerDelete (); // start referring to new object m_pRefCount = pNewRefCount; *m_pRefCount = 1; m_pT = pTObj; return *this; } // no-throw guarantee ~SmartPtr () { updateCountAndTriggerDelete (); } // returns true if this object is holding a reference // to an object on heap // no-throw guarantee bool isAssigned() { return !(m_pT == NULL); } // no-throw guarantee T* operator-&gt;() { return m_pT; } // no-throw guarantee T&amp; operator*() { return *m_pT; } private: // make sure we dont delete a incomplete type pointer // no-throw guarantee template &lt;class S&gt; void checkedDelete (S* pSObj) { typedef char type_must_be_complete[ sizeof(S)? 1: -1 ]; (void) sizeof(type_must_be_complete); delete pSObj; } // count the references and delete it if this is last reference // no-throw guarantee void updateCountAndTriggerDelete () { if (m_pRefCount != NULL) { (*m_pRefCount)--; // if this is last reference delete the memory if (*m_pRefCount == 0) { checkedDelete (m_pRefCount); checkedDelete (m_pT); } } } // swap the pointer values of 'rObj' with values of 'this' // no-throw guarantee void swap (SmartPtr&lt;T&gt; &amp;rObj) { std::swap (m_pT, rObj.m_pT); std::swap (m_pRefCount, rObj.m_pRefCount); } // pointer to memory location of object T *m_pT; // pointer to memory location where 'reference' count of // object pointed to by m_pT is kept int *m_pRefCount; typedef SmartPtr&lt;T&gt; this_type; }; } // namespace smartptrnamespace #endif // SMARTPTR_HPP </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T08:40:45.383", "Id": "39012", "Score": "1", "body": "I'm not sure... but it seems your copy operators don't handle self assignment (cf. Effective C++ item 11)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T08:42:42.263", "Id": "39013", "Score": "2", "body": "I would also add an exception throw if someone try to dereference a NULL smart pointer. In my opinion it would be useful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T08:45:54.510", "Id": "39015", "Score": "2", "body": "I would rename `updateCountAndTriggerDelete` to `decreaseCountAndTriggerDelete`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T08:46:57.653", "Id": "39016", "Score": "1", "body": "Also, your smart pointer is not thread-safe." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T08:48:11.470", "Id": "39017", "Score": "1", "body": "After a delete, you should immediately put the pointer to NULL, even if you don't use it anymore. It's a good practice that may save you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T08:52:05.973", "Id": "39018", "Score": "1", "body": "While I'm totally fine with it (cf. http://www.joelonsoftware.com/articles/Wrong.html) you use some kind of hungarian notation (`m_p*`) and there are a lot of zealots out there that would frown at your code just for that. Safer to use `refCount_` if you want to ensure a good impression." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T08:54:19.267", "Id": "39020", "Score": "2", "body": "You can add `const` in a lot of places : params, `isAssigned()`. That would make your code more robust and able to work in more situation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T14:26:39.833", "Id": "39048", "Score": "0", "body": "why not `shared_ptr`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T14:26:57.223", "Id": "39049", "Score": "1", "body": "@Offirmo, `m_` is not a hungarian notation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T18:15:15.757", "Id": "39063", "Score": "0", "body": "@Offirmo: Thank you very much for review. I could not indent my reply for all your comments in this tiny box... please see answers below for my reply. Thanks again :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T18:43:27.347", "Id": "39064", "Score": "1", "body": "@Abyx: this is just a self-education endeavor. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T07:50:29.153", "Id": "39103", "Score": "0", "body": "@Abyx in my experience, a lot of zealot people get mad as soon as they see something like `m_` or `pXyz`. Those persons are often bosses that can fire you or lead coders that can evict you. Safety first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T08:21:22.783", "Id": "39105", "Score": "1", "body": "@Offirmo, why do you mix `m_` and `p` prefixes? `m_` is a reliable replacement for `this->`, while `p` is just a hungarian notation" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T09:36:48.977", "Id": "39112", "Score": "0", "body": "@Abyx _I_ do not mix. Colleagues in my previous jobs and influent coders on the net do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T17:11:17.943", "Id": "39128", "Score": "1", "body": "@Offirmo: Your comments should be an answer. 1) Self copy is covered correctly. 2) Setting a pointer to NULL is a bad idea. It hides more problems then it solves. This is actually considered bad practice in C++ (though good practice in C)." } ]
[ { "body": "<p>A few non-expert comments: </p>\n\n<ul>\n<li><p>I would prefer the private vars to be at the top of the class - to avoid the immediate need to scroll to the bottom.</p></li>\n<li><p>Is there and advantage in making <code>m_pRefCount</code> a pointer to <code>int</code> instead of a simple <code>int</code>?</p></li>\n<li><p>Why would you need to use <code>checkedDelete</code> to delete a pointer to <code>int</code> that you created yourself? If you don't use <code>checkedDelete</code> for your local <code>int</code>, then the function can take template type T not a new class S. Is there not a better way to check for an incomplete type? And (showing my ignorance) is it necessary? </p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T22:22:31.870", "Id": "39075", "Score": "4", "body": "It has to be a pointer or otherwise how would multiple instances of the class access the same int? `SharedPtr b = a;` `b` needs to increment `a`'s counter too. In this case, it's simple to just go inside of a and increment it, but in other cases (such as when `a` falls out of scope, but `b` doesn't) simple manipulation like that isn't possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T08:24:19.653", "Id": "39106", "Score": "0", "body": "in c++, we usually put public members at the top." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T17:14:11.253", "Id": "39129", "Score": "3", "body": "@Abyx: Don't agree with that. I would also have put the private member variables at the top to aid in readability. I would put the private member functions at the bottom." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T18:09:17.357", "Id": "39135", "Score": "0", "body": "@LokiAstari better readability for people who use you class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T20:28:35.037", "Id": "39144", "Score": "3", "body": "@Abyx: For people that maintain the class. The most important users." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T21:40:24.587", "Id": "25240", "ParentId": "25214", "Score": "1" } }, { "body": "<ol>\n<li><p>API should resemble API of existing shared pointers, like <code>std::(tr1::)shared_ptr</code>. They have widely known well-designed API and there is no need to invent something new without a good reason.</p></li>\n<li><p>Pointer should have an <code>operator bool</code>, instead of <code>isAssigned</code> and it should be <code>const</code>.<br>\nIn C++ it will be <code>explicit operator bool() const</code>, in C++03 - safe-bool idiom.</p></li>\n<li><p>Those try-catch blocks are awful. You should write <code>unique_ptr</code> first, and use it to temporally own the object:</p>\n\n<pre><code>explicit SmartPtr (T *pObj) : m_pT(pObj), m_pRefCount()\n{\n unique_ptr&lt;T&gt; temp(pObj);\n m_pRefCount = new int(1);\n temp.release();\n}\n</code></pre></li>\n<li><p>Assignment operator can take argument by value:</p>\n\n<pre><code>void operator= (SmartPtr&lt;T&gt; rObj) { swap(rObj); }\n</code></pre></li>\n<li><p>Both copy ctor an assignment operator should be templates to allow code like</p>\n\n<pre><code>struct Derived : Base {...}; \nSmartPtr&lt;Derived&gt; d = ...;\nSmartPtr&lt;Base&gt; b = d;\n</code></pre></li>\n<li><p><code>operator= (T *pTObj)</code> should use <code>SmartPtr (T *pObj)</code> ctor and dtor</p>\n\n<pre><code>void operator= (T *pTObj) { SmartPtr&lt;T&gt;(pTObj).swap(*this); }\n</code></pre></li>\n<li><p><code>SmartPtr&lt;T&gt;(NULL)</code> is broken.</p></li>\n<li><p>You can write <code>typedef SmartPtr this_type;</code> (without <code>&lt;T&gt;</code>)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T08:59:44.257", "Id": "25258", "ParentId": "25214", "Score": "0" } }, { "body": "<p>1-- Why not <code>nullptr</code> in place of <code>NULL</code> ?</p>\n\n<p>2-- Personally I like <code>if (m_pRefCount)</code> more that <code>if (m_pRefCount != NULL)</code></p>\n\n<p>3-- In your <code>SmartPtr&amp; operator= (T *pTObj)</code> you <code>delete pTObj;</code> but in your <code>explicit SmartPtr (T *pObj)</code> you <code>checkedDelete (m_pT);</code> Why this inconsistence?</p>\n\n<p>4-- Implementing manually <code>SmartPtr&amp; operator= (const SmartPtr&lt;T&gt; &amp;rObj)</code> could be a litter more efficient, but I find very good your use of the copy-swap: it allow not to duplicate code. Why not use it for;</p>\n\n<pre><code> SmartPtr&amp; operator= (T *pTObj)\n {\n If (pTObj== m_pT) return *this; // this may be a litter better.\n // uses copy-and-swap idiom\n this_type(pTObj).swap(*this); // temporary SmartPtr get deleted, and m_pRefCount decreased (after swap: for the old value).\n return *this;\n }\n</code></pre>\n\n<p>In this case the only place where <code>updateCountAndTriggerDelete ();</code> will be called is the destructor, and you could move it entirely code there, with seems more natural for me. That also mean that you will don’t need to zeroes any deleted pointer.</p>\n\n<pre><code>~SmartPtr ()\n{\n if ( ! m_pRefCount) return;\n\n if ( 0== --(*m_pRefCount ) ) // :-) if this is last reference delete the memory\n {\n delete m_pRefCount;\n checkedDelete (m_pT);\n }\n}\n</code></pre>\n\n<p>5-- Also (from your answer to comments) this <a href=\"http://ideone.com/fGt5YA\" rel=\"nofollow\"><code>SmartPtr&amp; operator= (T *pTObj)</code> is not used during initialization</a>:</p>\n\n<pre><code>T *oldPtr = new T();\n\nSmartPtr&lt;T&gt; sPtr = oldPtr; // will not compile. Here you have: SmartPtr sPtr ( oldPtr); but you declared this constructor explicit.\nThe use of this will be:\nSmartPtr&lt;T&gt; sPtr;\nsPtr = oldPtr; \nsPtr = oldPtr; // second time you have a problem if not insert the If (pTObj== m_pT). But this may be OK.\n</code></pre>\n\n<p><a href=\"http://ideone.com/MVzIsS\" rel=\"nofollow\">The construction <code>T a=b;</code> is a short for <code>T a(b);</code></a> and the <code>operator=()</code> is only used to assign a value to an already constructed object, and not to construct a new object and initialize it.</p>\n\n<p>6-- As others said, add <code>const</code> where possible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T18:10:34.173", "Id": "39136", "Score": "0", "body": "obviously it's C++03 code, that's why no `nullptr`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T11:05:43.570", "Id": "25261", "ParentId": "25214", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "15", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T08:21:23.893", "Id": "25214", "Score": "3", "Tags": [ "c++", "pointers" ], "Title": "Reference-counting smart pointer class" }
25214
<p>I'm implementing a simple <a href="http://msdn.microsoft.com/en-us/library/65zzykke%28v=vs.80%29.aspx" rel="nofollow">iterator in C#</a> over an xml document, in order to process an xml document in as much a streaming manner as possible. For this reason, I'm using an <a href="http://msdn.microsoft.com/en-us/library/b8a5e1s5.aspx" rel="nofollow">XmlReader</a> variable in a <code>while</code> loop.</p> <p>This iterator must either return each first-level child elements, depending upon the name of the root tag. Otherwise, it should return the single root element as a whole.</p> <p>In order to return an xml element, I have a choice of using <a href="http://msdn.microsoft.com/en-us/library/system.xml.linq.xnode.readfrom.aspx" rel="nofollow">XNode.ReadFrom()</a> or <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.readouterxml.aspx" rel="nofollow">XmlReader.ReadOuterXml()</a>. Both of which perform an additionnal read on the <a href="http://msdn.microsoft.com/en-us/library/b8a5e1s5.aspx" rel="nofollow">XmlReader</a> variable. Therefore, I must find a way to prevent reading past interesting data in the underlying xml.</p> <p>The first draft I came up with had a <code>goto</code> statement that I now would like to avoid, without sacrificing readability. Here is the code:</p> <pre><code> public IEnumerable&lt;XElement&gt; Elements() { while (reader_.Read()) { next_element: switch (reader_.NodeType) { case XmlNodeType.Element: { // This is a composite document // skip to first-level elements if (reader_.LocalName.StartsWith("CompositeDocument")) { RootNamespace = reader_.NamespaceURI; IsComposite = true; continue; } var element = XNode.ReadFrom(reader_) as XElement; System.Diagnostics.Debug.Assert(element != null); yield return element; goto next_element; } break; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: case XmlNodeType.EntityReference: case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: case XmlNodeType.DocumentType: case XmlNodeType.Comment: case XmlNodeType.EndElement: break; } } } </code></pre> <p>A first attempt to remove the <code>goto</code> statement, involves using two embedded loops, and a boolean flag indicating whether to stay in the inner loop or break back to the outer loop. I feel this makes the code less readable. Here is the code: </p> <pre><code> public IEnumerable&lt;XElement&gt; Elements() { while (reader_.Read()) { var inner_loop = true; while (inner_loop) { switch (reader_.NodeType) { case XmlNodeType.Element: { // this is a composite document // skip to first-level elements if (reader_.LocalName.StartsWith("CompositeDocument")) { RootNamespace = reader_.NamespaceURI; IsComposite = true; inner_loop = false; } else { var element = XNode.ReadFrom(reader_) as XElement; System.Diagnostics.Debug.Assert(element != null); yield return element; inner_loop = true; } } break; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: case XmlNodeType.EntityReference: case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: case XmlNodeType.DocumentType: case XmlNodeType.Comment: case XmlNodeType.EndElement: inner_loop = false; break; } } } } </code></pre> <p>The reason I'm inclined to keed the goto statement is that, in iterators, the <code>yield</code> statement is already akin to a <code>goto</code> statement, albeit to the next line of code.</p> <p>Please, can anyone suggest how to best rewrite this code snippet ?</p>
[]
[ { "body": "<p>Could you do it with a boolean and short circuiting your while loop condition?</p>\n\n<pre><code>...\n var isElement = false;\n while (isElement || reader_.Read())\n {\n isElement = false;\n switch (reader_.NodeType)\n {\n case XmlNodeType.Element:\n {\n // This is a composite document\n // skip to first-level elements\n if (reader_.LocalName.StartsWith(\"CompositeDocument\"))\n {\n RootNamespace = reader_.NamespaceURI;\n IsComposite = true;\n continue;\n }\n\n var element = XNode.ReadFrom(reader_) as XElement;\n System.Diagnostics.Debug.Assert(element != null);\n yield return element;\n isElement = true;\n }\n break;\n...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T11:15:30.690", "Id": "39029", "Score": "0", "body": "This must have been one of my 'Doh !' moments..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T12:28:44.363", "Id": "39033", "Score": "0", "body": "It brings up an interesting point. Some people would argue that the goto version is cleaner / easier to read. I don't think I'm one of those people though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T10:48:29.497", "Id": "25220", "ParentId": "25217", "Score": "2" } } ]
{ "AcceptedAnswerId": "25220", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T09:48:57.100", "Id": "25217", "Score": "2", "Tags": [ "c#", "iterator" ], "Title": "How to remove goto statement from iterator" }
25217
<p>I've been writing a node.js web crawler, to get it running, I've found myself having to string together really rather a lot of different NPM modules.</p> <p>I've done my best to keep the code DRY and well designed, but unfortunately, it's turned into a bit of a tangled mess, and in places I feel like I'm forced to use global variables to communicate between different functions, and that makes me very uncomfortable.</p> <p>I'd really appreciate advice on how to structure this program more sensibly. Since I've spent hours trying to refactor it, and I've hit a plateau that my limited skills can't get me over. I can tell this is bad, but not how to improve it.</p> <pre><code>/* Modules */ //Load all imported modules var Crawler = require("crawler").Crawler; var Redis = require("redis"); var _ = require("underscore"); var url = require("url"); var express =require("express"); var app = express(); var httpServer = require('http').createServer(app); var io = require('socket.io').listen(httpServer); var robots = require('robots'); //Define inline - i.e. custom - modules function CreateDataStore(storePort, storeUrl, passwd) { var client; //create the redis client client = Redis.createClient(storePort, storeUrl); //Set client password and create logging function for on connect event. client.auth(passwd, function(err, msg) { if (err) { console.log("redis-error: " + err); } console.log("redis: " + msg); console.log("redis: Connected"); }); function createSiteUpdater(site) { var testResults = {}; function CreateUpdaterFunction(redisKey, redisCommand) { /*This function creates a property on the dataStore object that regularly updates itself with state of that key on the redis server. These keys can then later be queried by the view layer to see the state of the crawl. It requires two arguments, redisKey (string) which is the key that we're queriying in the database, and redisCommand (string) which is the name of the function on the client object which runs the query. This should just be the name of the redis command you want to use */ var updaterFunction = function() { if (typeof redisKey === "string" &amp;&amp; typeof redisCommand === "string") { client[redisCommand](redisKey, function(err, res) { testResults[redisKey] = res; }); } }; setInterval(updaterFunction, 500); // set regular pulse updating the variable } if (site) site = url.parse(site).hostname+":"; console.log("Site post-parse is", site); for (var i = 0; i &lt; analyticsPackages.length; i++) { CreateUpdaterFunction(site + "has" + analyticsPackages[i].name, "smembers"); CreateUpdaterFunction(site + "no" + analyticsPackages[i].name, "smembers"); CreateUpdaterFunction(site + "crawledPages", "smembers"); console.log("Test Results Object Created for ", site, ":", analyticsPackages[i].name, testResults); } return testResults; } //exports return { "redisClient": client, "dataObject": createSiteUpdater("") }; } function testForAnalytics(urlToTest, $, siteBeingTested) { var analyticsTestCases = []; //Constructor function for the functions which test for different analytics products function GenerateAnalyticsTest(testSelector, testName) { return function() { var foundAnalyticsPlatform = false; if ($(testSelector).length &gt; 0) foundAnalyticsPlatform = true; return { "FoundCode": foundAnalyticsPlatform, "PlatformName": testName }; }; } //create the different analytics test cases and store them in an array for (var i = 0; i &lt; analyticsPackages.length; i++) { analyticsTestCases.push(GenerateAnalyticsTest(analyticsPackages[i].test, analyticsPackages[i].name)); } //create the function which runs the different analytics tests function runTest(testCase) { var testObject = testCase(); if (testObject.FoundCode) { client.sadd(siteBeingTested + ":has" + testObject.PlatformName, urlToTest) } if (!testObject.FoundCode) { client.sadd(siteBeingTested + ":no" + testObject.PlatformName, urlToTest) } } //run the testing function for every test in the test cases array. for (var j = 0; j &lt; analyticsTestCases.length; j++) { runTest(analyticsTestCases[j]); } } function runCrawler(urlToTest) { //Find the local robots.txt and parse it. var changingUrl = url.parse(urlToTest); client.sadd("sitesCrawled",changingUrl.hostname); changingUrl.pathname = "/robots.txt"; var robotsTxtUrl = url.format(changingUrl); console.log(robotsTxtUrl); var robotsParser = new robots.RobotsParser( robotsTxtUrl, 'Mozilla/5.0 (compatible; RobotTxtBot/1.0)', after_parse); //Once the robots text has been parsed, set up the crawler. function after_parse(parser, success) { console.log("Robots.txt loaded"); if (success) { console.log("Robots.txt Parsed Successfully"); } //Set up Crawler's item fetched callback. This callback is where all the actual business logic goes. function runOnPageCrawled(error, responseBuffer, $) { //Log any crawl errors if (error) { console.log("Page Crawl Error: " + error); } // Do something with the data in responseBuffer var thisPage = url.parse(responseBuffer.uri); console.log("Crawled Page: ",thisPage.href); testResults.currentlyCrawling = thisPage.href; //Payload testForAnalytics(thisPage.href, $, thisPage.hostname); //Admin to be done before we quit client.sadd("crawledPages", thisPage.href); //add this url to the list of pages we've crawled //add next pages to crawl queue $("body a").each(function(index, a) { // For each anchor tag in the body var thisLink = url.parse(a.href); //parse the link into a url if (success) { //if we have successfully parsed a robots.txt, if (thisLink.hostname === thisPage.hostname &amp;&amp; parser.canFetchSync("*", thisLink.href)) { //check if we can crawl this link tagCrawler.queue(thisLink.href); //add the link to the crawl queue } } else { //if there is no robots.txt, then assume we can crawl this link if (thisLink.hostname === thisPage.hostname) { tagCrawler.queue(thisLink.href); //add the link to the crawl queue } } }); } //Create a crawler instance to crawl this site var tagCrawler = new Crawler({ "forceUTF8": true, "callback": runOnPageCrawled, "skipDuplicates": true }); tagCrawler.queue(urlToTest); } } /* Configuration */ var analyticsPackages = []; // this object is read by the analytics test module and the datastore creation module. var Omniture = { "name": "Omniture", "test": "script:contains('s_code=s.t')" }; analyticsPackages.push(Omniture); var GoogleAnalytics = { "name": "GoogleAnalytics", "test": "script:contains('.google-analytics.com/ga.js')" }; analyticsPackages.push(GoogleAnalytics); /* Initialisation */ //Initialise Crawler object and Redis connection var dataStore = CreateDataStore(6379, "redis.myDomain.com", "myRedisPassword"); console.log("Data Store initialised = ", dataStore); var client = dataStore.redisClient; //this object is the redis client, and will be called to query redis; console.log("Redis client initialised"); var testResults = dataStore.dataObject; //this object holds the current results of the scan, and is passed to the client. console.log("Test Results Object initialised = ", testResults); //Set up Express.js http server //This is only used to serve the static site content app.enable('trust proxy'); app.use(express.static(__dirname + '/static')); app.use(app.router); //Configure and initialise Socket.io //Almost all user modifiable functions of the app are controlled via the socket.io handler. io.enable('browser client minification'); // send minified client io.enable('browser client etag'); // apply etag caching logic based on version number io.enable('browser client gzip'); // gzip the file io.set('log level', 1); // reduce logging io.sockets.on('connection', function(socket) { socket.emit('message',testResults); socket.on('datarequest', function(res) { console.log("Received Update Request From Client"); socket.emit('message', testResults); }); socket.once("startCrawl",function(res){ console.log("Recieved Crawl request for",res); if(_.isString(res) &amp;&amp; res === "http:/myDomain.com"){ //temporary validation to prevent client side misuse; runCrawler(res); } }); }); /* Activation */ //Actually run the crawler webserver and sockets httpServer.listen(process.env.PORT || 5000); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T10:20:10.303", "Id": "39025", "Score": "2", "body": "It seems to me there could be at least 3 different files: a data store, an analytics tester, and a crawler. I'm pretty sure the socket handling could be in another file too." } ]
[ { "body": "<p>Isaacs, node.js current maintainer, recently wrote node.js' philosophy in this blog post: <a href=\"http://blog.izs.me/post/48281998870/unix-philosophy-and-node-js\" rel=\"nofollow\">http://blog.izs.me/post/48281998870/unix-philosophy-and-node-js</a></p>\n\n<blockquote>\n <p>In Node, the basic building block that people share and interact with is not a binary on the command line, but rather a module loaded in by require().</p>\n</blockquote>\n\n<p>Use files. Use modules. Don't let your files grow. 100 lines is already too much.</p>\n\n<p>Clearly, in your code, there is at least 3 entities that could be separated in their own module:</p>\n\n<ul>\n<li>A data store</li>\n<li>An analytics tester</li>\n<li>A crawler</li>\n<li>Eventually, a socket handler</li>\n</ul>\n\n<p>I'd understand that you want to keep it all in a module, but you should at least split it up into different files, and use <code>require()</code> to your heart's content.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T15:47:39.747", "Id": "39123", "Score": "0", "body": "I've literally just read that blog post an hour ago, but failed to mentally apply it to my own code base. +1 for insight." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T20:35:10.837", "Id": "39146", "Score": "0", "body": "@Racheet Just from a quick look, your code can be even more split up. Your redis client in the data store could be in another file too. The robots.txt parser could be in another file. Etc, etc. You just refactor till you feel satisfied :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T14:12:06.273", "Id": "25265", "ParentId": "25218", "Score": "2" } } ]
{ "AcceptedAnswerId": "25265", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T10:09:42.550", "Id": "25218", "Score": "3", "Tags": [ "javascript", "node.js", "web-scraping" ], "Title": "Node.js web crawler" }
25218
<p>I wrote the following to create an animation which collapses a navigation bar, load new content for it and expands it again. Meanwhile, the rest of the page content fades out, loads and fades in again.</p> <p>It works and looks good, and is even timed well. But my code is one hell of a mess. How could I have done better?</p> <pre><code>$(function() { var newHash = "", $NavmainContent = $("#contentNavigationWrapper"), $mainContent = $(".contentWrapper"), $first = $('#currentSection'), $second = $('#project-tools'), $third = $('#project-pagetools'), $fourth = $('#cp'), $pageWrap = $("#page-wrap"), baseHeight = 0, $el; $pageWrap.height($pageWrap.height()); baseHeight = $pageWrap.height() - $NavmainContent.height(); $("nav").delegate("a", "click", function() { _link = $(this).attr("href"); history.pushState(null, null, _link); loadContent(_link); return false; }); function loadContent(href){ $mainContent .find("#guts") .fadeOut(1000, function() { $mainContent.hide().load(href + " #guts", function() { $mainContent.fadeIn(1000); }); }); $NavmainContent .find('#inner-cn') .find("#project-pagetools,#project-tools,#cp,#currentSection") .animate({ 'width': '0' },800); setTimeout(function(){ $first.load(href + " #currentSection span"); $second.load(href + " #project-tools li"); $third.load(href + " #project-pagetools li"); $fourth.load(href + " #cp span"); },900); setTimeout(function(){ var l = $("#project-tools li").length ; l = 100 / l ; l = l + '%'; $("#project-tools li").css({ 'width': l }); $NavmainContent .find("#project-pagetools,#project-tools") .animate({ 'width': '15%' },800); $NavmainContent .find("#currentSection") .animate({ 'width': '10%' },800); $NavmainContent .find("#cp") .animate({ 'width': '55%' },800); },1100); } }); </code></pre>
[]
[ { "body": "<p>Here are some quite general pointers on your code. If you put up a fiddle with everything working, I might be able to play around and re-write this for you. But anyways, I've included my comments directly into the code to provide some context:</p>\n\n<pre><code>$(function() {//Is this what wraps your entire code, or just this part of it?\n var newHash = \"\",\n $NavmainContent = $(\"#contentNavigationWrapper\"),\n $mainContent = $(\".contentWrapper\"),\n $first = $('#currentSection'),\n $second = $('#project-tools'),\n $third = $('#project-pagetools'),\n $fourth = $('#cp'),\n $pageWrap = $(\"#page-wrap\"),\n baseHeight = 0,\n $el; //You define \"el\" but don't use it anywhere.\n\n $pageWrap.height($pageWrap.height()); //Da fuck? I don't get this lol. You set the height of the element to its own height?\n baseHeight = $pageWrap.height() - $NavmainContent.height(); //I would just include a pageWrapHeight variable since you use often.\n\n $(\"nav\").delegate(\"a\", \"click\", function() { //.delegate is deprecated since 1.7, use .on() instead: $(\"nav\").on(\"click\", \"a\", callback(){});\n _link = $(this).attr(\"href\");\n history.pushState(null, null, _link);\n loadContent(_link);\n return false; //Here you can just e.preventDefault(); instead. Don't forget to pass the \"e\" for event into the callback.\n });\n\n function loadContent(href){\n\n $mainContent\n .find(\"#guts\")\n .fadeOut(1000, function() {\n $mainContent.hide().load(href + \" #guts\", function() {\n $mainContent.fadeIn(1000);\n });\n });\n\n $NavmainContent\n .find('#inner-cn')\n .find(\"#project-pagetools,#project-tools,#cp,#currentSection\")\n .animate({\n 'width': '0'\n },800);\n\n //The method \".load()\" calls the method \".ajax()\", passing in the stuff you put there.\n //Why not save a few function calls and just use the .ajax() method directly?\n\n //Instead of using this timeout, you should check out ajax a little more.\n //You'll find that it has a nice little thing called Deffered already built into the ajax method.\n //Also jQuery has a queue which you can manipulate the order of stuff that happens etc., animation in particular.\n setTimeout(function(){\n $first.load(href + \" #currentSection span\");\n $second.load(href + \" #project-tools li\");\n $third.load(href + \" #project-pagetools li\");\n $fourth.load(href + \" #cp span\");\n },900);\n\n //Same thing here.\n //You could do this all with a deffered promise.\n //Also worth checking out is Pub/Sub\n //Basically when set up, you can publish, \"Hey I'm done doing this stuff\" to another part of your JS that is \"subscribed\" to that,\n //and continue with your other stuff only when that gets published.\n setTimeout(function(){\n\n var l = $(\"#project-tools li\").length; //I don't personally like using single character variable names.\n //That can be a nightmare to come back to in the future if you have to make changes or include new functionality.\n //But then again that's just me. Don't shoot yourself over that.\n\n l = 100 / l ;\n l = l + '%';\n $(\"#project-tools li\").css({\n 'width': l\n });\n\n $NavmainContent\n .find(\"#project-pagetools,#project-tools\")\n .animate({\n 'width': '15%'\n },800);\n\n $NavmainContent\n .find(\"#currentSection\")\n .animate({\n 'width': '10%'\n },800);\n\n $NavmainContent\n .find(\"#cp\")\n .animate({\n 'width': '55%'\n },800);\n },1100);\n }\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T14:42:29.043", "Id": "39054", "Score": "0", "body": "Thank you very much! I will provide a fiddle where the problems you mentioned above will be fixed later this evening, when i am finally home :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T14:35:53.607", "Id": "25229", "ParentId": "25224", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T12:40:23.277", "Id": "25224", "Score": "2", "Tags": [ "javascript", "performance", "jquery", "animation" ], "Title": "Animation for collapsing/expanding a navigation bar" }
25224
<p>I have been attempting the questions at Project Euler and I am trying to find the sum of Primes under two million (question 10)</p> <blockquote> <p>The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.</p> <p>Find the sum of all the primes below two million.</p> </blockquote> <p>Here is my attempt which does work, but I would like to know if there is any way to improve this code. Any suggestions welcomed!</p> <pre><code>class SumOfPrimes { static void Main(string[] args) { Primes primes = new Primes(2000000); long sum = 0; foreach(int p in primes.list_of_primes){ sum += p; } Console.WriteLine(sum); Console.ReadLine(); } } class Primes { public HashSet&lt;int&gt; all_numbers = new HashSet&lt;int&gt;(); public HashSet&lt;int&gt; list_of_primes = new HashSet&lt;int&gt;(); public HashSet&lt;int&gt; list_of_nonprimes = new HashSet&lt;int&gt;(); public Primes(int n) { all_numbers = new HashSet&lt;int&gt;(Enumerable.Range(1, n)); for (int i = 2; i &lt; Math.Sqrt(n) + 1; i++) { for (int j = 3; j &lt;= n / i; j++) list_of_nonprimes.Add(i * j); } list_of_primes = new HashSet&lt;int&gt;(all_numbers.Except(list_of_nonprimes)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T14:37:49.160", "Id": "39051", "Score": "1", "body": "just want to let you know - after you solve your project euler question . you can see the problem list and a PDF document in general a link to PDF document explains the best way to do the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T14:39:25.417", "Id": "39052", "Score": "0", "body": "Yes I know but they are more interested in the mathematical methods whereas I am looking for specific feedback on code optimisation and efficiency, a topic not covered there at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T05:34:42.777", "Id": "39320", "Score": "0", "body": "`Math.Sqrt(n)` and `n/i` in the for loop should be made local variables instead so it got calculated once. Now it got executed unnecessarily in every single iteration." } ]
[ { "body": "<p>One slight improvement you can do is </p>\n\n<p>All Prime numbers could be represented this format</p>\n\n<p>2,3,4,5 and</p>\n\n<p>6,7,8,9,10,11 or 12,13,14,15,16,17 or 18,19,20,21,22,23</p>\n\n<p>6k,6K+1 ,6k+2,6K+3,6k+4,6k+5</p>\n\n<p>so only prime number possible is </p>\n\n<p>6k+1 and 6k+5 </p>\n\n<p>So you can step your for loop by 6</p>\n\n<p>this is copied form Wikipedia\n<a href=\"http://en.wikipedia.org/wiki/Primality_test\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Primality_test</a></p>\n\n<blockquote>\n <p>The algorithm can be improved further by observing that all primes are\n of the form 6k ± 1, with the exception of 2 and 3. This is because all\n integers can be expressed as (6k + i) for some integer k and for i =\n −1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3\n divides (6k + 3). So a more efficient method is to test if n is\n divisible by 2 or 3, then to check through all the numbers of form 6k\n ± 1 . This is 3 times as fast as testing all m.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T14:41:53.757", "Id": "39053", "Score": "0", "body": "Thanks for the suggestion this is a good point. However, this idea is implicit in the code I have used above. As a sieve is used, in the first step and second step all multiples of 2 and 3 are added to the list of non-primes. This is equivalent to the idea of removing all numbers of the form 6k+2,6k+3,6k+4 and 6k." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T14:24:07.290", "Id": "25228", "ParentId": "25225", "Score": "1" } }, { "body": "<p>Some other things that you can try, short of trying a totally different algorithm:</p>\n\n<ul>\n<li><p>rename <code>all_numbers</code> to <code>prime_candidates</code> and remove composite numbers from it. (<code>list_of_nonprimes.Add(i * j);</code> -> <code>prime_candidates.Remove(i*j)</code>. Avoiding the <code>Except</code> at the end. </p></li>\n<li><p>You can also hold which numbers are non primes in an array of <code>bool</code>s and lose all the <code>HashSet</code>s. Changing:</p>\n\n<pre><code>list_of_nonprimes.Add(i * j)\n</code></pre>\n\n<p>to </p>\n\n<pre><code>nonprimes[i*j] = true;\n</code></pre>\n\n<p>Thus avoiding a bunch of hash lookups. After the loops sum up any <code>n</code> s.t. <code>nonprime[n]==false</code></p></li>\n<li><p>You can also use a <code>BitArray</code> instead of a <code>bool</code> array. Because it is more space efficient it <em>might</em> reduce cache misses.</p></li>\n</ul>\n\n<p>Of course, you can only be sure if any of these actually makes any improvement after you try.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T06:27:30.033", "Id": "25256", "ParentId": "25225", "Score": "2" } }, { "body": "<p>If you implement <code>@abuzittin gillifirca</code>'s suggestion of preparing the known prime candidate list as you go, another important improvement at an algorithm level would be to only sieve on primes or prime candidates. When you are looping <code>i</code> and <code>j</code> for applying the sieve, it is redundant to check for composite multiples (like <code>6</code>), because those numbers would already have been sieved out by smaller <code>i</code> or <code>j</code>.</p>\n\n<p>In other words, instead of looping <code>1</code> by <code>1</code> for values of <code>i</code> and <code>j</code>, loop through the contents of known prime candidates for both and you will skip a lot of unnecessary sieve checks. This should also make your process exponentially faster for large primes because larger and larger primes are further and further apart, so you are saving more wasted time in checking composite multiples.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T12:25:42.137", "Id": "25264", "ParentId": "25225", "Score": "1" } }, { "body": "<p>I'll focus on making loop quicker.</p>\n\n<pre><code>int ilimit = Math.Sqrt(n) + 1;\nfor (int i = 2; i &lt; ilimit; i++)\n{\n int jlimit = n / i\n for (int j = 3, sum = i * 3; j &lt;= jlimit; j++) {\n list_of_nonprimes.Add(sum);\n sum += i;\n }\n}\n</code></pre>\n\n<p>I made the loop ending expression more efficient, and replaced <code>i*j</code> with addition ,which is cheaper. The <code>list_of_nonprimes</code> should be modified accordingly to the accepted answer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T05:47:08.353", "Id": "25358", "ParentId": "25225", "Score": "0" } } ]
{ "AcceptedAnswerId": "25256", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T13:46:25.233", "Id": "25225", "Score": "4", "Tags": [ "c#", "primes", "project-euler" ], "Title": "Sum of primes less than 2,000,000" }
25225
<p>This is one of the slightly trickier Project Euler Questions I have seen (Question 27)</p> <pre><code>Considering quadratics of the form: n² + an + b, where |a| &lt; 1000 and |b| &lt; 1000 where |n| is the modulus/absolute value of n e.g. |11| = 11 and |−4| = 4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. </code></pre> <p>Here is my code let me know if this is good coding practice. Thanks.</p> <pre><code>class QuadraticPrimes { static void Main(string[] args) { int max = 1000; Primes primes = new Primes(max); int n = 0; int m = 0; int a = -999; int b = -999; for (int i = -999; i &lt; 1000; i++) { for (int j = -999; j &lt; 1000; j++) { while (true) { m++; if(primes.list_of_primes.Contains(quadratic(i, j, m)) == false) break; } if (n &lt; m) { n = m; a = i; b = j; } m = 0; } } Console.WriteLine("a:" + a + ", b:" + b + ", n:"+n); Console.ReadLine(); } public static int quadratic(int a, int b, int n) { return n*n + a*n + b; } } class Primes { public HashSet&lt;int&gt; all_numbers = new HashSet&lt;int&gt;(); public HashSet&lt;int&gt; list_of_primes = new HashSet&lt;int&gt;(); public HashSet&lt;int&gt; list_of_nonprimes = new HashSet&lt;int&gt;(); public Primes(int n) { all_numbers = new HashSet&lt;int&gt;(Enumerable.Range(1, n)); for (int i = 2; i &lt; Math.Sqrt(n) + 1; i++) { for (int j = 3; j &lt;= n / i; j++) list_of_nonprimes.Add(i * j); } list_of_primes = new HashSet&lt;int&gt;(all_numbers.Except(list_of_nonprimes)); } } </code></pre>
[]
[ { "body": "<p>Pre-computing a large list containing numbers you may or may not use isn't always a good idea. I tested it and it turns out to be much slower. </p>\n\n<hr>\n\n<p>Things I would change about your code:</p>\n\n<ol>\n<li><p>I'd remove the classes, this is a trivial problem that can be solved with a few methods, follow the KISS principle and keep it simple.</p></li>\n<li><p>I'm not a fan of your while loop. It can be recreated as:<br>\n<code>int m = 0;<br>\n while (primes.list_of_primes.Contains(quadratic(i, j, m++));</code><br>\nWhich avoids break;. While we're at it, in my version I use a for loop so that the m++ is cleaner and we are sure it's happening after the fact.</p></li>\n<li><p>You don't need to initialize <code>a</code> or <code>b</code> to -999, it makes things messier and doesn't provide any value.</p></li>\n</ol>\n\n<hr>\n\n<p>Here's how I would do it, breaking things apart into methods with their own purposes. I also used a slightly more efficient IsPrime, but it's nothing special.</p>\n\n<pre><code> static int FindMaxCoeff()\n {\n int maxConsec = 0;\n int maxCoeff = 0;\n for (int a = -999; a &lt; 1000; a++)\n {\n for (int b = -999; b &lt; 1000; b++)\n {\n int currentConsec = FindMaxConsecutive(a, b);\n if (currentConsec &gt; maxConsec)\n {\n maxConsec = currentConsec;\n maxCoeff = a * b;\n }\n }\n }\n\n return maxCoeff;\n }\n\n static int FindMaxConsecutive(int a, int b)\n {\n int n = 0;\n\n for (n = 0; IsPrime(n * n + a * n + b); n++) ;\n\n return n;\n }\n\n static bool IsPrime(int n)\n {\n n = Math.Abs(n);\n if (n == 1 || n == 2 || n == 3)\n {\n return true;\n }\n\n if (n % 2 == 0 || n % 3 == 0)\n {\n return false;\n }\n\n for (int x = 6; x - 1 &lt;= Math.Sqrt(n); x += 6)\n {\n if (n % (x - 1) == 0 || n % (x + 1) == 0)\n {\n return false;\n }\n }\n\n return true;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T23:17:21.677", "Id": "39084", "Score": "0", "body": "Keep in mind there are many math tricks to optimize this solution, but they aren't strictly coding best practices." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T00:03:44.043", "Id": "39088", "Score": "0", "body": "Thanks for your solution, however I have a question about efficiency. You call the line `for (n = 0; IsPrime(n * n + a * n + b); n++) ;` meaning that you are going through your prime checking algorithm for the number `n * n + a * n + b` for each pair `(a,b)`, `n` times (depending on how many consecutive primes occur. Whereas if you just create a list you avoid repeatedly computing the values. Unless I am unaware of some sort of efficiency work done by the virtual machine for the method `bool IsPrime(int n)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T02:37:06.747", "Id": "39090", "Score": "0", "body": "The work done to calculate IsPrime the necessary amount of times is less than the work required to create the list and then access it repeatedly. Try it out yourself with the Stopwatch class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T02:59:39.450", "Id": "39091", "Score": "0", "body": "Surely it depends on the size of your list? I set `max = 1000000` but `max = 1000` would have worked perfectly too (changed code to reflect this). I didn't time it but it gave the result in an instant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T17:14:28.510", "Id": "39130", "Score": "0", "body": "Try it out yourself http://pastebin.com/TRPxKcUq" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T18:29:31.157", "Id": "39140", "Score": "0", "body": "hahaha it turns out yours is indeed faster with the max=1000, I forgot to reset the timer in between runs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T22:54:06.750", "Id": "39151", "Score": "0", "body": "Seeings as it runs in a couple of seconds the time difference is negligible." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T23:13:17.873", "Id": "25245", "ParentId": "25227", "Score": "2" } } ]
{ "AcceptedAnswerId": "25245", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T14:19:49.940", "Id": "25227", "Score": "4", "Tags": [ "c#", "primes", "project-euler" ], "Title": "Quadratic Primes" }
25227
<p>I'm totally hooked on CodeEval, and one of the problems on there caught my attention. Here it is, copied from <a href="https://www.codeeval.com/open_challenges/75/" rel="nofollow">here</a>:</p> <p>Challenge Description:</p> <p>Flavius Josephus was a famous Jewish historian of the first century, at the time of the destruction of the Second Temple. According to legend, during the Jewish-Roman war he was trapped in a cave with a group of soldiers surrounded by Romans. Preferring death to capture, the Jews decided to form a circle and, proceeding around it, to kill every j'th person remaining until no one was left. Josephus found the safe spot in the circle and thus stayed alive.Write a program that returns a list of n people, numbered from 0 to n-1, in the order in which they are executed. Input sample:</p> <p>Your program should accept as its first argument a path to a filename. Each line in this file contains two comma separated positive integers n and m , where n is the number of people and every m'th person will be executed. e.g.</p> <pre><code>10,3 5,2 </code></pre> <p>Output sample:</p> <p>Print out the list of n people(space delimited) in the order in which they will be executed. e.g.</p> <pre><code>2 5 8 1 6 0 7 4 9 3 1 3 0 4 2 </code></pre> <p>Here's my solution in JavaScript, which succeeded in all test cases:</p> <pre><code>var fs = require("fs"); //object for reading in a file fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) { if (line != "") { var lineSplit = line.split(","); var maxNum = parseInt(lineSplit[0], 10); //the number of people in the circle (n) var spacer = parseInt(lineSplit[1], 10); //Every m'th person is executed var counter = spacer - 1; //We're working with a zero-based array, so decrement accordingly var people = []; var deadPeople = []; for (var i = 0; i &lt; maxNum; i++) { var person = []; person = new Array(i.toString(), 1); people[i] = person; //a new person is added with a status of 1 (alive) } while(deadPeople.length &lt; maxNum){ people[counter][1] = 0; //sadness deadPeople.push(people[counter][0]); counter += spacer; while(people.length &gt; 0 &amp;&amp; counter &gt;= people.length){ counter = counter - people.length; regroup(people); } } console.log(deadPeople.join(" ")); } }); function regroup(arr) { arr.forEach(function(element, index, array) { if (element[1] === 0) { array.splice(index, 1); } }); } </code></pre> <p>All comments are welcome, but I'm especially interested in efficiency.</p>
[]
[ { "body": "<ol>\n<li><p>You can easily find the next death-index with the modulus operation: <code>next = (current + space) % totalStillAlive</code> . No need for fancy loops (see end of answer).</p></li>\n<li><p>Instead of making an array of arrays (btw, don't create js arrays with <code>new Array</code>, use the array literal <code>[]</code>), simply store an array of original indexes, and splice from that on each around until there are no more people left.</p></li>\n<li><p>The way you're extracting the data is awkward, specifically the <code>spacer</code> definition - why not define it right off the bat as <code>parseInt(...) - 1</code> ?</p></li>\n<li><p>It's probably not very important with this input size, but the synchronous line reading is frowned upon; you should use the asynchronous versions unless there's a reason not to.</p></li>\n<li><p><code>if (line != \"\")</code> can just be <code>if (line)</code></p></li>\n<li><p>With #1 you don't need <code>regroup</code>, but your <code>forEach</code> loop is an implementation <code>filter</code> (<a href=\"https://developer.mozilla.org/en/docs/JavaScript/Reference/Global_Objects/Array/filter\">docs</a>)</p></li>\n</ol>\n\n<p>(as a continuation of #2:</p>\n\n<pre><code>var person = [];\nperson = new Array(i.toString(), 1);\n</code></pre>\n\n<p>I don't get what went through your mind at the time, but why not just <code>people[i] = [i, 1]</code> ?)</p>\n\n<p>So, your main algorithm can be simplified to 1 nice loop instead of 3 (discounting the instantiation loop):</p>\n\n<pre><code>function josephus (n, interval) {\n var people = [],\n deaths = [];\n for (var i = 0; i &lt; n; i += 1) {\n people[i] = i;\n }\n\n var idx = 0,\n len = people.length;\n while (len = people.length) {\n idx = (idx + interval) % len;\n deaths.push(people[idx]);\n people.splice(idx, 1);\n }\n\n return deaths;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T15:19:54.043", "Id": "25232", "ParentId": "25230", "Score": "9" } }, { "body": "<pre><code>function josephus(n, interval) {\n return (n &gt; 1 ? (josephus(n - 1, interval) + interval - 1)%n + 1 : 1)\n}\n</code></pre>\n\n<p>It iterates n times.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-10-30T04:21:20.523", "Id": "273430", "Score": "0", "body": "The problem with this is that you can easily run into recursion limits with fairly low numbers (mid thousands). It may be better to switch to an iterative approach. ``var f=1; for(let i=1;i<=n;i++) f= (f+k-1)%i+1;return f;``" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T19:11:41.327", "Id": "26585", "ParentId": "25230", "Score": "3" } }, { "body": "<p>It's simpler to write an iterative solution.</p>\n\n<p>A recurrence relation is required to rotate/calculate new positions after each execution, but we can use a <em>queue</em> to take care of the positions.</p>\n\n<p>Like this:</p>\n\n<pre><code>function josIterative(n, k) {\nlet queue = [];\nfor (let i = 1; i &lt;= n; i++) queue.push(i);\n\nlet deathOrder = [];\n\nwhile (queue.length !== 1) {\n for (let skip = 1; skip &lt; k; skip++) queue.push(queue.shift());\n deathOrder.push(queue.shift());\n}\n\nconsole.log(\"Death order is \" + deathOrder.join(\" \"));\nreturn queue[0]; //survivor\n}\n\nconsole.log(josIterative(7, 3) + \" is survivor\");\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T13:48:19.070", "Id": "466033", "Score": "1", "body": "Your answer should provide a more in-depth explanation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T13:34:51.100", "Id": "237638", "ParentId": "25230", "Score": "1" } } ]
{ "AcceptedAnswerId": "25232", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T14:40:51.117", "Id": "25230", "Score": "4", "Tags": [ "javascript" ], "Title": "The Josephus problem in JavaScript" }
25230
<p>I've developed my own class in ASP.NET project to access MySQL and make queries and scalars, and read the results from it.</p> <p>I want you to review my class and tell me where I've made a mistake.</p> <p>Here are some questions that are important for me:</p> <ul> <li>Do I use a reference correctly for the connector class of MySQL in methods?</li> <li>Is it correct to make it NON-static class as it is? For the GC, memory reasons?</li> <li>Do I need to add some events, delegate for the autoclose for the MySQL connection, or is there no need in it, because out of scope it will be auto freed from memory?</li> </ul> <p></p> <pre><code>public class MySQLGear { private const string connStr = "Server = localhost; Database = self; Uid = someuser; Pwd = 1234;"; public MySqlConnection CreateConnection() { MySqlConnection connMysql = new MySqlConnection(connStr); connMysql.Open(); if (connMysql.State == ConnectionState.Open) { return connMysql; } else return null; } public MySqlDataReader GetReader(ref MySqlConnection connMysql, string queryMysql) { MySqlCommand cmdMysql = new MySqlCommand(queryMysql, connMysql); MySqlDataReader readerMysql = cmdMysql.ExecuteReader(); return readerMysql; } public int MakeQuery(ref MySqlConnection connMysql, string queryMysql) { MySqlCommand cmdMysql = new MySqlCommand(queryMysql, connMysql); int result = cmdMysql.ExecuteNonQuery(); return result; } public object MakeScalar(ref MySqlConnection connMysql, string queryMysql) { MySqlCommand cmdMysql = new MySqlCommand(queryMysql, connMysql); object result = cmdMysql.ExecuteScalar(); return result; } } </code></pre>
[]
[ { "body": "<h2>Question #1</h2>\n\n<p>No. You do not need to ref the connection object in your methods' parameters - think object oriented way not class oriented.</p>\n\n<h2>Question #2</h2>\n\n<p>The only way is to make this as a non static class. Avoid always statics when the current problem contains some kind of state management like a MySQL connection.</p>\n\n<h2>Question #3</h2>\n\n<p>No you don't but you should implement the IDisposable interface and apply the correct disposable pattern.</p>\n\n<pre><code>public class MySQLGear : IDisposable\n{\n private readonly MySqlConnection _connection;\n\n public MySQLGear(string connectionString)\n {\n _connection = new MySqlConnection(connectionString);\n }\n\n protected MySqlConnection Connection()\n {\n if (_connection == null)\n {\n throw new ObjectDisposedException(\"The underlying connection has been closed\");\n }\n\n if (_connection.State != ConnectionState.Open)\n {\n _connection.Open();\n }\n\n return _connection;\n }\n\n public MySqlDataReader GetReader(string queryMysql)\n {\n using (var cmdMysql = new MySqlCommand(queryMysql, Connection()))\n {\n return cmdMysql.ExecuteReader();\n }\n }\n\n public int MakeQuery(string queryMysql)\n {\n using (var cmdMysql = new MySqlCommand(queryMysql, Connection()))\n {\n return cmdMysql.ExecuteNonQuery();\n }\n }\n\n public object MakeScalar(string queryMysql)\n {\n using (var cmdMysql = new MySqlCommand(queryMysql, Connection()))\n {\n return cmdMysql.ExecuteScalar();\n }\n }\n\n ~MySQLGear()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (_connection != null)\n {\n if (_connection.State != ConnectionState.Closed) \n {\n _connection.Dispose();\n }\n _connection = null;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T18:53:46.393", "Id": "39065", "Score": "2", "body": "Answer to #1 is that ref keyword is redundant because objects/classes are Reference Types http://msdn.microsoft.com/en-ca/library/490f96s2(v=vs.71).aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T17:29:52.150", "Id": "39132", "Score": "1", "body": "You should also put the MySqlCommands in using statements, as IDbCommand extends IDisposable." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T17:01:16.817", "Id": "25234", "ParentId": "25231", "Score": "4" } }, { "body": "<p>It's a bad practice to keep an open connection. I'd advice you to store a connection string and open connection each time within a using block. </p>\n\n<p>Something like this (just change to mysql funcs):</p>\n\n<pre><code>public class OleDbGear\n{\n private readonly string _connectionString;\n\n /// &lt;summary&gt;\n /// Default constructor.\n /// &lt;/summary&gt;\n /// &lt;param name=\"connString\"&gt;Connection string.&lt;/param&gt;\n public OleDbGear(string connSrting)\n {\n _connectionString = connString;\n }\n\n /// &lt;summary&gt;\n /// Returns open connection.\n /// &lt;/summary&gt;\n private OleDbConnection GetOpenConnection()\n {\n var dbConnection = new OleDbConnection(_connectionString);\n dbConnection.Open();\n return dbConnection;\n }\n\n private T Execute &lt;T&gt;(string query, Action&lt;OleDbCommand&gt; paramsSetup, Func&lt;OleDbCommand, T&gt; func)\n {\n using (OleDbConnection connection = GetOpenConnection())\n using (var cmd = new OleDbCommand(query, connection))\n {\n if (paramsSetup != null)\n paramsSetup(cmd);\n return func(cmd);\n }\n }\n\n public int ExecuteNonQuery(string query, Action&lt;OleDbCommand&gt; paramsSetup = null)\n {\n return Execute(query, paramsSetup, cmd =&gt; cmd.ExecuteNonQuery());\n }\n\n public object ExecuteSclar(string query, Action&lt;OleDbCommand&gt; paramsSetup = null)\n {\n return Execute(query, paramsSetup, cmd =&gt; cmd.ExecuteScalar());\n }\n\n public T ExecuteReader &lt;T&gt;(string query, Func&lt;OleDbDataReader, T&gt; converter, Action&lt;OleDbCommand&gt; paramsSetup = null)\n {\n return Execute(query, paramsSetup, cmd =&gt;\n {\n using (OleDbDataReader reader = cmd.ExecuteReader())\n {\n if (reader == null)\n throw new Exception(\"DB error\");\n return converter(reader);\n }\n });\n }\n}\n</code></pre>\n\n<p>Wrapping all in <code>using</code> blocks ensures correct disposing of all resources. <code>Action&lt;OleDbCommand&gt; paramsSetup</code> helps you to provide parameters of your query (no injection). <code>Func&lt;OleDbDataReader, T&gt; converter</code> just converts reader object into usable result.</p>\n\n<p>You also could consider creating a sup method:</p>\n\n<pre><code> public IEnumerable&lt;T&gt; ExecuteAndReadToEnd &lt;T&gt;(string query, Func&lt;OleDbDataReader, T&gt; lineReader, Action&lt;OleDbCommand&gt; paramsSetup = null)\n {\n return ExecuteReader(query, reader =&gt;\n {\n var results = new List&lt;T&gt;();\n while (reader.Read())\n results.Add(lineReader(reader));\n return results;\n }, \n paramsSetup);\n }\n</code></pre>\n\n<p>as in most cases you are going to read all lines.</p>\n\n<p>Usage example (suppose Instance is your reference to a db):</p>\n\n<pre><code>...\n public IEnumerable&lt;string&gt; GetAllPurchases(int customerId)\n {\n var query = \"SELECT Purchase FROM Purchases WHERE CustomerId=@id\";\n return Instance.ExecuteAndReadToEnd(query, reader =&gt; reader.GetString(0),\n cmd =&gt; cmd.Parameters.AddWithValue(\"@id\", customerId));\n }\n</code></pre>\n\n<p>Good luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T17:28:15.007", "Id": "39214", "Score": "0", "body": "There are definitely scenarios where you need to keep a connection open because opening the connection every time does add lots of overhead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-06T08:32:20.023", "Id": "98986", "Score": "0", "body": "@banging I typically agree, however opening the connection does not necessarily add a-lot of overhead if the underlying provider uses connection pooling." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T21:41:49.920", "Id": "25275", "ParentId": "25231", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T15:04:16.617", "Id": "25231", "Score": "3", "Tags": [ "c#", "mysql", "asp.net", "classes" ], "Title": "Accessing MySQL to make queries and scalars" }
25231
<p>I am trying to get a tuple of <code>date</code> (or <code>datetime</code>) objects over the last <code>N</code> months.</p> <p>My thought was to use the <code>dateutil</code> package with something like this:</p> <pre><code>def last_n_months(n=12, ending=None): """Return a list of tuples of the first/last day of the month for the last N months """ from datetime import date from dateutil.rrule import rrule, MONTHLY from dateutil.relativedelta import relativedelta if not ending: ending = date.today() # set the ending date to the last day of the month ending = ending + relativedelta(months=+1, days=-ending.day) # starting is the first day of the month N months ago starting = ending - relativedelta(months=n, day=1) months = list(rrule(MONTHLY, bymonthday=(1, -1), dtstart=starting, until=ending)) # we return pairs of dates like this: (1st day of month, last day of month) months = zip(months[::2], months[1::2]) return months </code></pre> <p>Example usage:</p> <pre><code> &gt;&gt;&gt; from datetime import date, timedelta # get last two months as a degenerate example &gt;&gt;&gt; l2n = last_n_months(2, ending=date(2012, 01, 01)) &gt;&gt;&gt; map(lambda x: [x[0].year, x[0].month, x[0].day], l2n) [[2011, 11, 1], [2011, 12, 1], [2012, 1, 1]] &gt;&gt;&gt; map(lambda x: [x[1].year, x[1].month, x[1].day], l2n) [[2011, 11, 30], [2011, 12, 31], [2012, 1, 31]] &gt;&gt;&gt; l24n = last_n_months(24, ending=date(2012,03,16)) &gt;&gt;&gt; len(l24n) # inclusive of current month 25 # every tuple starts with the first day of the month &gt;&gt;&gt; all(x[0].day == 1 for x in l24n) True # every tuple ends with the last day of the month &gt;&gt;&gt; all((x[1] +timedelta(days=1)).month != x[1].month for x in l24n) True # every tuple is the same month &gt;&gt;&gt; all(x[0].month == x[1].month for x in l24n) True </code></pre> <p>I am posting it here to see if anyone has a better solution than this (and perhaps see if this yields some off-by-one sort of error that I haven't thought of).</p> <p>Is there a simpler or faster solution than this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-20T01:50:57.113", "Id": "119705", "Score": "0", "body": "Unless I'm missing something, you can probably adapt the itermonthdates() function from the calendar module in the python standard library:\nhttps://docs.python.org/2/library/calendar.html\nNo?" } ]
[ { "body": "<pre><code>def last_n_months(n=12, ending=None):\n \"\"\"Return a list of tuples of the first/last day of the month\n for the last N months \n \"\"\"\n from datetime import date\n from dateutil.rrule import rrule, MONTHLY\n from dateutil.relativedelta import relativedelta\n</code></pre>\n\n<p>It is better to import outside of the function. Typically imports go at the top of the file.</p>\n\n<pre><code> if not ending:\n</code></pre>\n\n<p>You should check for none like: <code>if ending is not None:</code> just to be explicit about what you are checking for.</p>\n\n<pre><code> ending = date.today()\n\n # set the ending date to the last day of the month\n ending = ending + relativedelta(months=+1, days=-ending.day)\n</code></pre>\n\n<p>Modifying <code>ending</code> rubs me the wrong way. </p>\n\n<pre><code> # starting is the first day of the month N months ago\n starting = ending - relativedelta(months=n, day=1)\n\n months = list(rrule(MONTHLY, bymonthday=(1, -1), dtstart=starting,\n until=ending))\n\n # we return pairs of dates like this: (1st day of month, last day of month)\n months = zip(months[::2], months[1::2])\n\n return months\n</code></pre>\n\n<p>You can combine these two lines</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T20:26:09.450", "Id": "39068", "Score": "0", "body": "Thanks Winston, much appreciated. Quick question with respect to the imports, is the preference to import outside the function a preference or functional? From a PEP? Always preferable where there are no circular dependencies? Or is there a concern about cluttering the namespace? Just curious - I'd be very grateful if anyone were to post a link to a discussion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T21:17:18.657", "Id": "39070", "Score": "1", "body": "@BrianM.Hunt, PEP 8 says to put all imports at the top. See here for some discussion of it: http://stackoverflow.com/questions/477096/python-import-coding-style" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T22:08:40.913", "Id": "39074", "Score": "0", "body": "Thanks for the discussion thread. A quote I thought interesting in one of the upvoted answers \"As you can see, it can be more efficient to import the module in the function\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T22:45:59.150", "Id": "39076", "Score": "0", "body": "@BrianM.Hunt, yes but that only applies if you are calling the function a lot. In your case it doesn't, because you only use any of those imports a few times." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T20:11:26.720", "Id": "25239", "ParentId": "25233", "Score": "2" } } ]
{ "AcceptedAnswerId": "25239", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T15:09:12.853", "Id": "25233", "Score": "2", "Tags": [ "python", "datetime" ], "Title": "Get tuple of the first and last days of the last N months" }
25233
<p>I have a selector that pulls in all anchor tags that start with the <code>#</code> symbol. I am trying to add a <code>:not</code> selector of some form for elements that have a <code>data</code> attribute. I know I could do the following...</p> <pre><code>$('a[href^="#"]:not([data-known])') </code></pre> <p>But the problem is that I don't know what the <code>data</code> attribute will be called. I have resorted to doing the following. </p> <pre><code>$('a[href^="#"]').click(function(event){ if($.isEmptyObject($(this).data())){ //custom code here } }); </code></pre> <p>Is there a way to avoid the <code>if</code> statement and add the <code>:not</code> to the original selector? Is there a better way of doing this period? </p> <p>Here is a <a href="http://jsfiddle.net/bplumb/RXKS8/" rel="nofollow">FIDDLE</a> I have been playing in.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T22:46:56.107", "Id": "62780", "Score": "0", "body": "I think your best approach would be using [jQuery.hasData()](http://api.jquery.com/jQuery.hasData/) (even though you will still use an if statement)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T22:49:11.380", "Id": "62781", "Score": "0", "body": "Why is that the best approach? I'd argue against it, since it [anyhow calls `isEmptyObject` under the hood](http://james.padolsey.com/jquery/#v=1.7.2&fn=jQuery.hasData), but with a lot of extra code that's not needed in this case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T22:52:14.017", "Id": "62782", "Score": "0", "body": "Because of the ease of usefulness; even though you make a good point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T22:52:21.923", "Id": "62783", "Score": "0", "body": "Actually, `hasData` simply won't work at all. `hasData` only checks for data that has been set via `.data()`. It doesn't automatically pull in the HTML5 `data-*` attributes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T22:58:58.717", "Id": "62784", "Score": "0", "body": "[Here's a fiddle](http://jsfiddle.net/5BKVb/) demonstrating my point above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T23:01:53.517", "Id": "62785", "Score": "0", "body": "That is completely true, thank you Joseph." } ]
[ { "body": "<p>Very good question. I'm pretty sure this can't be done within the selector.</p>\n\n<p>However, instead of checking the <code>data</code> every time it's clicked, <code>filter</code> the collection before applying the event listener:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>$('a[href^=\"#\"]').filter(function () {\n return $.isEmptyObject( $(this).data() );\n}).click(function (event) {\n // Your code here...\n});\n</code></pre>\n\n<hr>\n\n<p>If you don't care about IE, you can check the <a href=\"https://developer.mozilla.org/en-US/docs/DOM/element.dataset\" rel=\"nofollow\"><code>dataset</code></a> property directly, which is <em>much</em> faster and much more reliable, since <code>$(this).data()</code> also contains any arbitrary data that might have been set (possibly by a plugin):</p>\n\n<pre><code>$('a[href^=\"#\"]').filter(function () {\n return $.isEmptyObject( this.dataset );\n})\n</code></pre>\n\n<hr>\n\n<p>If you find that you have to do this a lot, you can abstract it into a custom filter, which you can then use in your selectors:</p>\n\n<pre><code>jQuery.expr[':']['has-data'] = function (el) {\n return ! $.isEmptyObject( $(el).data() );\n // If you don't care about IE:\n // return ! $.isEmptyObject( el.dataset );\n};\n</code></pre>\n\n<p>Then just use it throughout your code:</p>\n\n<pre><code>$('a[href^=\"#\"]:not(:has-data)').click(function (event) {\n // Your code here...\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T23:01:27.667", "Id": "39081", "Score": "0", "body": "This is great! This solves the main issue I was facing with it having to call `$.isEmptyObject()` on every click." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T22:44:51.267", "Id": "25243", "ParentId": "25241", "Score": "4" } } ]
{ "AcceptedAnswerId": "25243", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T21:42:16.057", "Id": "25241", "Score": "5", "Tags": [ "javascript", "jquery", "html5" ], "Title": "Do not select elements that contain data attributes" }
25241
<p>I need to add quotes to each word in a string. Here is something that works but it looks ugly to me; </p> <pre><code>"this is a test".split.to_s.delete("[],") </code></pre> <p>produces</p> <pre><code>"\"this\" \"is\" \"a\" \"test\"" </code></pre> <p>split adds the quotes, to_s turns the array back to a string, then the delete removes the array stuff. The downside is the case where the data includes <code>[]</code> or <code>,</code></p> <p>I welcome your responses! </p>
[]
[ { "body": "<p>Here's the \"naïve\" way to go</p>\n\n<pre><code>\"this is a test\".split.map { |word| \"\\\"#{word}\\\"\" }.join(\" \")\n</code></pre>\n\n<p>But a better way is to use a regular expression, since those are made specifically for string manipulation/substitution</p>\n\n<pre><code>\"this is a test\".gsub(/\\S+/, '\"\\0\"')\n</code></pre>\n\n<p>The expression matches 1 or more (the <code>+</code>) non-whitespace characters (the <code>\\S</code>) in a row, and replaces the match with the same string (the <code>\\0</code>) but surrounded by quotes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T12:30:23.277", "Id": "39116", "Score": "0", "body": "I knew there was an elegant \"Ruby\" way to do this!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T13:34:23.440", "Id": "39119", "Score": "0", "body": "@SteveO7 Well, it's not terribly specific to Ruby; tons of languages and tools support regular expressions because they're so useful. Syntaxes and APIs vary slightly, but the gist is the same. E.g. the here's the pretty much same using the `sed` *nix command: `echo 'this is a test' | sed 's/[^ ]*/\"&\"/g'` → `\"this\" \"is\" \"a\" \"test\"`. Point is, regexps are neat :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T23:38:15.260", "Id": "25246", "ParentId": "25242", "Score": "3" } } ]
{ "AcceptedAnswerId": "25246", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T22:41:52.697", "Id": "25242", "Score": "0", "Tags": [ "ruby" ], "Title": "Suggestions for Ruby string parsing" }
25242
<p>I wanted to store some dictionary data (key/value pairs of strings) in C, and decided to use a trie.</p> <p>I found what looks like a good implementation <a href="http://simplestcodings.blogspot.com/2012/11/trie-implementation-in-c.html" rel="nofollow">here</a>, along with some nice notes.</p> <p>In this implementation, each node in the trie is a trie itself. Each node has <code>next</code>, <code>prev</code>, <code>child</code>, and <code>parent</code> properties, pointing to other nodes or <code>NULL</code>.</p> <p>I've modified the code as follows:</p> <ul> <li><p>Node values are of type <code>void *</code> instead of type <code>int</code>.</p></li> <li><p>Keys are kept in alphabetical order as new nodes are added. This isn't much trouble, since tries to a lot of the work naturally. This should improve search time, since you can stop looking for a character once you find a character in the same position with a greater value. </p> <p>This might slow down adding new keys, except that adding new keys involves searching for existing keys, so adding sorted keys could possibly be faster in some cases.</p></li> <li><p>Added a "dump" function.</p></li> <li><p>Formatted and refactored.</p></li> </ul> <hr> <h2>Public functions for manipulating tries</h2> <ul> <li><code>Trie_create()</code> creates a new trie and returns a pointer to it.</li> <li><code>Trie_dump()</code> dumps all keys and values in the trie to <code>stdout</code>.</li> <li><code>Trie_get()</code> gets the value at a given key.</li> <li><code>Trie_put()</code> puts a value in the given key.</li> <li><code>Trie_remove()</code> removes the given key from the trie.</li> </ul> <hr> <h2><code>trie.h</code></h2> <pre><code>typedef struct Trie_t Trie; Trie *Trie_create(); const char *Trie_get(Trie *root, const char *key); void Trie_put(Trie *root, const char *key, void *data); void Trie_remove(Trie *root, const char *key); void Trie_dump(Trie *t); </code></pre> <hr> <h2><code>trie.c</code></h2> <pre><code>#include &lt;stdio.h&gt; #include "trie.h" #include &lt;stdlib.h&gt; struct Trie_t { char key; void *value; Trie *next; Trie *prev; Trie *child; Trie *parent; Trie *marker; }; Trie *Trie_createNode(const char key, void *data) { Trie *t = NULL; t = (Trie *)malloc(sizeof(Trie)); if (!t) { printf("Malloc failed\n"); return t; } t-&gt;key = key; t-&gt;value = data; t-&gt;next = NULL; t-&gt;child = NULL; t-&gt;parent = NULL; t-&gt;prev = NULL; t-&gt;marker = NULL; return t; } void Trie_unlink(Trie *t) { if (t-&gt;next) t-&gt;next-&gt;prev = t-&gt;prev; if (t-&gt;prev) t-&gt;prev-&gt;next = t-&gt;next; else if (t-&gt;parent) t-&gt;parent-&gt;child = t-&gt;next; t-&gt;prev = 0; t-&gt;next = 0; t-&gt;parent = 0; } void Trie_insertAfter(Trie *oldTrie, Trie *newTrie) { Trie_unlink(newTrie); newTrie-&gt;parent = oldTrie-&gt;parent; newTrie-&gt;next = oldTrie-&gt;next; newTrie-&gt;prev = oldTrie; if (newTrie-&gt;next) newTrie-&gt;next-&gt;prev = newTrie; oldTrie-&gt;next = newTrie; } void Trie_insertBefore(Trie *oldTrie, Trie *newTrie) { Trie_insertAfter(oldTrie, newTrie); Trie_insertAfter(newTrie, oldTrie); } Trie *Trie_search(Trie *root, const char *key) { while (1) { Trie *t; int match = 0; for (t = root; t &amp;&amp; t-&gt;key &lt;= *key; t = t-&gt;next) { if (t-&gt;key == *key) { match = 1; break; } } if (!match) return NULL; if (*key == '\0') return t; root = t-&gt;child; key++; } } void Trie_putPart(Trie *root, const char *key, void *data){ Trie *t; for (t = root; *key; t = t-&gt;child) { t-&gt;child = Trie_createNode(*key, NULL); t-&gt;child-&gt;parent = t; key++; } t-&gt;child = Trie_createNode('\0', data); t-&gt;child-&gt;parent = t; } void Trie_put(Trie *root, const char *key, void *data) { Trie *t = NULL; Trie *current = NULL; Trie *tmp = NULL; if (!root) return; t = root-&gt;child; current = Trie_search(t, key); if (current) { current-&gt;value = data; return; } if (!t) { Trie_putPart(root, key, data); return; } while (*key != '\0') { if (*key != t-&gt;key) break; key++; t = t-&gt;child; } while (t-&gt;next &amp;&amp; (t-&gt;key &lt; *key)) { if (*key == t-&gt;next-&gt;key) { key++; Trie_put(t-&gt;next, key, data); return; } t = t-&gt;next; } tmp = Trie_createNode(*key, NULL); if (t-&gt;key &gt; tmp-&gt;key) { Trie_insertBefore(t, tmp); } else { Trie_insertAfter(t, tmp); } key++; Trie_putPart(tmp, key, data); return; } void Trie_remove(Trie *root, const char *key) { Trie *t = NULL; if (!root || !key) return; for (t = Trie_search(root-&gt;child, key); t; t = t-&gt;parent) { if (t-&gt;prev || t-&gt;next) { Trie_unlink(t); free(t); return; } } } Trie *Trie_create() { return Trie_createNode('\0', 0); } void *Trie_getRaw(Trie *root, const char *key) { Trie *t = Trie_search(root-&gt;child, key); return t ? t-&gt;value : 0; } const char *Trie_get(Trie *root, const char *key) { return Trie_getRaw(root, key); } void Trie_dumpf(Trie *root, const char * keysep, const char * valsep) { Trie *t = root; Trie *tmp; while (t) { if (t-&gt;value) { tmp = root; while (tmp) { printf("%c", tmp-&gt;key); tmp = tmp-&gt;marker; } printf("%s%s%s", keysep, (char *)t-&gt;value, valsep); while (t &amp;&amp; !t-&gt;next) t = t-&gt;parent; if (t) t = t-&gt;next; if (t &amp;&amp; t-&gt;parent) t-&gt;parent-&gt;marker = t; } else { t = t-&gt;child; t-&gt;parent-&gt;marker = t; } } } void Trie_dump(Trie *t) { Trie_dumpf(t, ": ", "\n"); } </code></pre> <hr> <h2><code>example.c</code></h2> <pre><code>int main() { Trie *t = Trie_create(); Trie_put(t, "name", "Testman"); Trie_put(t, "address", "123 main st"); Trie_put(t, "max-y", "200"); Trie_put(t, "max-z", "300"); Trie_put(t, "country", "USA"); Trie_put(t, "city", "Nowhere"); Trie_put(t, "max-x", "100"); Trie_remove(t, "max-y"); Trie_remove(t, "badkey"); Trie_dump(t); printf("max xyz = %s,%s,%s\n", Trie_get(t, "max-x"), Trie_get(t, "max-y"), Trie_get(t, "max-z")); return 0; } </code></pre> <blockquote> <p><strong>output</strong></p> <p>address: 123 main st<br> city: Nowhere<br> country: USA<br> max-x: 100<br> max-z: 300<br> name: Testman<br> max xyz = 100,(null),300</p> </blockquote> <hr> <h2>Questions</h2> <p>Some things I'm wondering about:</p> <ul> <li><p>In the original code, <code>TrieAdd</code> and <code>TrieRemove</code> take a pointer to a pointer to a trie, instead of a pointer to a trie. I couldn't see any reason for doing this, so I changed it. Is this alright? What reason could the author have had for doing this?</p></li> <li><p>I hacked up <code>Trie_remove</code> pretty badly. I was confused about this code at first, but I think I understand it now. Stilll, if anyone wants to comment on this, I'm interested. Eventually I want to write <code>Trie_destroy()</code> to complement <code>Trie_create()</code>.</p></li> <li><p>Any thoughts on the sorting approach and any potential cost/benefit in terms of performance? Should I consider doing a binary search to improve search time even further?</p></li> <li><p>Tries want void pointers as data, but in practice I'm giving them strings. I did this to keep things flexible in case I want to store complex data later. Is this too weird? </p></li> <li><p>Is there any redundancy to eliminate or obvious enhancements that should be made?</p></li> <li><p>Any new bugs I created that weren't in the original code?</p></li> <li><p>Any old bugs I overlooked that are still in my code?</p></li> <li><p>Any comments on <code>Trie_dump</code>?</p></li> </ul> <hr> <h2>Original code</h2> <p>Varun Gupta's <a href="http://simplestcodings.blogspot.com/2012/11/trie-implementation-in-c.html" rel="nofollow">trie implementation in c</a>, included here for reference.</p> <pre><code>/*trie.h*/ typedef int trieVal_t; typedef struct trieNode { char key; trieVal_t value; struct trieNode *next; struct trieNode *prev; struct trieNode *children; struct trieNode *parent; } trieNode_t; trieNode_t* TrieSearch(trieNode_t *root, const char *key); /*trie.c*/ #include &lt;stdio.h&gt; #include "trie.h" #include &lt;stdlib.h&gt; #define DEBUG trieNode_t *TrieCreateNode(char key, int data) { trieNode_t *node = NULL; node = (trieNode_t *)malloc(sizeof(trieNode_t)); if(NULL == node) { printf("Malloc failed\n"); return node; } node-&gt;key = key; node-&gt;next = NULL; node-&gt;children = NULL; node-&gt;value = data; node-&gt;parent= NULL; node-&gt;prev= NULL; return node; } void TrieAdd(trieNode_t **root, char *key, int data) { trieNode_t *pTrav = NULL; if(NULL == *root) { printf("NULL tree\n"); return; } #ifdef DEBUG printf("\nInserting key %s: \n",key); #endif pTrav = (*root)-&gt;children; if(TrieSearch(pTrav, key)) { printf("Duplicate!\n"); return; } if(pTrav == NULL) { /*First Node*/ for(pTrav = *root; *key; pTrav = pTrav-&gt;children) { pTrav-&gt;children = TrieCreateNode(*key, 0xffffffff); pTrav-&gt;children-&gt;parent = pTrav; #ifdef DEBUG printf("Inserting: %c\n",pTrav-&gt;children-&gt;key); #endif key++; } pTrav-&gt;children = TrieCreateNode('\0', data); pTrav-&gt;children-&gt;parent = pTrav; #ifdef DEBUG printf("Inserting: %c\n",pTrav-&gt;children-&gt;key); #endif return; } while(*key != '\0') { if(*key == pTrav-&gt;key) { key++; #ifdef DEBUG printf("Traversing child: %c\n",pTrav-&gt;children-&gt;key); #endif pTrav = pTrav-&gt;children; } else break; } while(pTrav-&gt;next) { if(*key == pTrav-&gt;next-&gt;key) { key++; TrieAdd(&amp;(pTrav-&gt;next), key, data); return; } pTrav = pTrav-&gt;next; } pTrav-&gt;next = TrieCreateNode(*key, 0xffffffff); pTrav-&gt;next-&gt;parent = pTrav-&gt;parent; pTrav-&gt;next-&gt;prev = pTrav; #ifdef DEBUG printf("Inserting %c as neighbour of %c \n",pTrav-&gt;next-&gt;key, pTrav-&gt;key); #endif key++; for(pTrav = pTrav-&gt;next; *key; pTrav = pTrav-&gt;children) { pTrav-&gt;children = TrieCreateNode(*key, 0xffffffff); pTrav-&gt;children-&gt;parent = pTrav; #ifdef DEBUG printf("Inserting: %c\n",pTrav-&gt;children-&gt;key); #endif key++; } pTrav-&gt;children = TrieCreateNode('\0', data); pTrav-&gt;children-&gt;parent = pTrav; #ifdef DEBUG printf("Inserting: %c\n",pTrav-&gt;children-&gt;key); #endif return; } trieNode_t* TrieSearch(trieNode_t *root, const char *key) { trieNode_t *level = root; trieNode_t *pPtr = NULL; int lvl=0; while(1) { trieNode_t *found = NULL; trieNode_t *curr; for (curr = level; curr != NULL; curr = curr-&gt;next) { if (curr-&gt;key == *key) { found = curr; lvl++; break; } } if (found == NULL) return NULL; if (*key == '\0') { pPtr = curr; return pPtr; } level = found-&gt;children; key++; } } void TrieRemove(trieNode_t **root, char *key) { trieNode_t *tPtr = NULL; trieNode_t *tmp = NULL; if(NULL == *root || NULL == key) return; tPtr = TrieSearch((*root)-&gt;children, key); if(NULL == tPtr) { printf("Key not found in trie\n"); return; } while(1) { if( tPtr-&gt;prev &amp;&amp; tPtr-&gt;next) { tmp = tPtr; tPtr-&gt;next-&gt;prev = tPtr-&gt;prev; tPtr-&gt;prev-&gt;next = tPtr-&gt;next; free(tmp); break; } else if(tPtr-&gt;prev &amp;&amp; !(tPtr-&gt;next)) { tmp = tPtr; tPtr-&gt;prev-&gt;next = NULL; free(tmp); break; } else if(!(tPtr-&gt;prev) &amp;&amp; tPtr-&gt;next) { tmp = tPtr; tPtr-&gt;parent-&gt;children = tPtr-&gt;next; free(tmp); break; } else { tmp = tPtr; tPtr = tPtr-&gt;parent; free(tmp); } } } </code></pre>
[]
[ { "body": "<p>If I look at the Wikipedia page on Trie, <a href=\"https://en.wikipedia.org/wiki/Trie\" rel=\"nofollow\">https://en.wikipedia.org/wiki/Trie</a> I see that each node has one parent and an arbitrary number of children; if the key is a char the limit would be 255 children (or maybe less if you restrict yourself to printable chars). Yet your <code>Trie</code> structure has a very different arrangement. As your structure doesn't match my naive expectation, and you have no comments indicating how the tree is actually arranged I didn't review the functionality of the code, but instead just picked as few nits:</p>\n\n<ul>\n<li>put standard headers before your own</li>\n<li>start functions with the <code>{</code> in the first column (some tools rely on this - or used to anyway)</li>\n<li>make local functions static. And static functions don't need the <code>Trie_</code> prefix.</li>\n<li>use const in function parameters and variables wherever possible</li>\n<li>the <code>key</code> parameter to <code>Trie_createNode</code> need not be <code>const</code> (although it does no harm)</li>\n<li>use of braces on single-line conditions etc is generally preferred (although noisy)</li>\n<li>use <code>perror</code> to print error messages (eg <code>perror(\"malloc\");</code>)</li>\n<li><p>don't cast malloc. eg. this</p>\n\n<pre><code>Trie *t = NULL;\nt = (Trie *)malloc(sizeof(Trie));\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>Trie *t = malloc(sizeof(Trie)); /* or malloc(sizeof *t) */\n</code></pre></li>\n<li><p>nested loops are best avoided. For example in <code>Trie_search</code>, the for-loop could be extracted to a function (eg <code>find_key</code>).</p></li>\n<li><p>the <code>while(1)</code> in <code>Trie_search</code> would be better as a for-loop</p>\n\n<pre><code>Trie *Trie_search(const Trie *root, const char *key)\n{\n for (const Trie *t = root;\n (t = find_key(t, *key)) != NULL; ++key, t = t-&gt;child) {\n\n if (*key == '\\0') {\n return t;\n }\n }\n return NULL;\n}\n</code></pre>\n\n<p>Note that this loop (and your original) allow the search to start even if <code>key</code> is an empty string. I also get the impression that the '\\0' is entered as a node in the tree, which seems very odd, but maybe I misunderstood the code.</p></li>\n<li><p>the two while loops in <code>Trie_put</code> could probably be extracted into functions</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T00:30:18.287", "Id": "39156", "Score": "0", "body": "Thanks, your comments are very helpful, I'll update my answer in a bit with changes and an explanation of the children thing (but yes, the `\\0` is entered... only the `\\0` entries have values. Each node's key is a single character)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T06:26:59.800", "Id": "39322", "Score": "0", "body": "Sorry for the late followup on this. I created another trie question [here](http://codereview.stackexchange.com/questions/25359/simple-trie-implementation-in-javascript), partly to try to explain the children thing. I'll probably end up rewriting this to be more like that code eventually." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T23:25:07.900", "Id": "25282", "ParentId": "25248", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T01:34:07.963", "Id": "25248", "Score": "1", "Tags": [ "c", "linked-list", "hash-map", "trie" ], "Title": "Sorted trie implementation in C" }
25248
<p>It would be a huge help if you could tell me ways to make my code run smoother and if I could add more code to my program to make my program more unique.</p> <p>Panelball class: </p> <pre><code>import java.awt.*; import java.awt.event.KeyEvent; import javax.swing.*; public class Panelball extends JPanel implements Runnable { private static final long serialVersionUID = 1L; private int ballX = 10, ballY = 100, ply1X=10, ply1Y=100, ply2X=230, ply2Y=100; Thread string; int right=5; int left= -5; int up=5; int down= -5; int width, height; int contPlay1=0, contPlay2=0; boolean player1FlagArr,player1FlagAba, player2FlagArr, player2FlagAba; boolean playin, gameOver; public Panelball(){ playin=true; string=new Thread(this); string.start(); } public void paintComponent(Graphics gc){ setOpaque(false); super.paintComponent(gc); gc.setColor(Color.black); gc.fillOval(ballX, ballY, 8,8); gc.fillRect(ply1X, ply1Y, 10, 25); gc.fillRect(ply2X, ply2Y, 10, 25); gc.drawString("Score1: "+contPlay1, 25, 10); gc.drawString("Score2: "+contPlay2, 150, 10); if(gameOver) gc.drawString("Game Over", 100, 125); } public void drawball (int nx, int ny) { ballX= nx; ballY= ny; this.width=this.getWidth(); this.height=this.getHeight(); repaint(); } public void keyPressed(KeyEvent evt) { switch(evt.getKeyCode()) { case KeyEvent.VK_W : player1FlagArr = true; break; case KeyEvent.VK_S : player1FlagAba = true; break; case KeyEvent.VK_UP: player2FlagArr=true; break; case KeyEvent.VK_DOWN: player2FlagAba=true; break; } } public void keyReleased(KeyEvent evt) { switch(evt.getKeyCode()) { case KeyEvent.VK_W : player1FlagArr = false; break; case KeyEvent.VK_S : player1FlagAba = false; break; case KeyEvent.VK_UP: player2FlagArr=false; break; case KeyEvent.VK_DOWN: player2FlagAba=false; break; } } public void moverPlayer1() { if (player1FlagArr == true &amp;&amp; ply1Y &gt;= 0) ply1Y += down; if (player1FlagAba == true &amp;&amp; ply1Y &lt;= (this.getHeight()-25)) ply1Y += up; drawPlayer1(ply1X, ply1Y); } public void moverPlayer2() { if (player2FlagArr == true &amp;&amp; ply2Y &gt;= 0) ply2Y += down; if (player2FlagAba == true &amp;&amp; ply2Y &lt;= (this.getHeight()-25)) ply2Y += up; drawPlayer2(ply2X, ply2Y); } public void drawPlayer1(int x, int y){ this.ply1X=x; this.ply1Y=y; repaint(); } public void drawPlayer2(int x, int y){ this.ply2X=x; this.ply2Y=y; repaint(); } public void run() { boolean lftrgt=false; boolean updwn=false; while(true){ if(playin){ if (lftrgt) { ballX += right; if (ballX &gt;= (width - 8)) lftrgt= false; } else { ballX += left; if ( ballX &lt;= 0) lftrgt = true; } if (updwn) { ballY += up; if (ballY &gt;= (height - 8)) updwn= false; } else { ballY += down; if ( ballY &lt;= 0) updwn = true; } drawball(ballX, ballY); try { Thread.sleep(50); } catch(InterruptedException ex) { } moverPlayer1(); moverPlayer2(); if (ballX &gt;= (width - 8)) contPlay1++; if ( ballX == 0) contPlay2++; if(contPlay1==6 || contPlay2==6){ playin=false; gameOver=true; } if(ballX==ply1X+10 &amp;&amp; ballY&gt;=ply1Y &amp;&amp; ballY&lt;=(ply1Y+25)) lftrgt=true; if(ballX==(ply2X-5) &amp;&amp; ballY&gt;=ply2Y &amp;&amp; ballY&lt;=(ply2Y+25)) lftrgt=false; } } } } </code></pre> <p>Main Class:</p> <pre><code>import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Main extends JFrame { private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private Panelball panel = null; private Panelball getPanel() { if (panel == null) { panel = new Panelball(); } return panel; } public Main() { super(); initialize(); this.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { formKeyPressed(evt); } public void keyReleased(KeyEvent evt) { formKeyReleased(evt); } }); } private void formKeyPressed(KeyEvent evt) { panel.keyPressed(evt); } private void formKeyReleased(KeyEvent evt) { panel.keyReleased(evt); } private void initialize() { this.setResizable(false); this.setBounds(new Rectangle(312, 184, 250, 250)); this.setMinimumSize(new Dimension(250, 250)); this.setMaximumSize(new Dimension(250, 250)); this.setContentPane(getJContentPane()); this.setTitle("Pong"); } private JPanel getJContentPane() { if (jContentPane == null) { jContentPane = new JPanel(); jContentPane.setLayout(new BorderLayout()); jContentPane.add(getPanel(), BorderLayout.CENTER); } return jContentPane; } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Main thisClass = new Main(); thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); thisClass.setVisible(true); } }); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T10:08:42.273", "Id": "39171", "Score": "1", "body": "Especially on a site like *.stackexchange.com, where we're not reviewing code in a desktop IDE, I'd suggest removing extra newlines from your code, and indenting with a limited number of **spaces**, not tabs. The formatting of this code hurts its readability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-04T21:22:48.943", "Id": "372426", "Score": "0", "body": "It's too late now, but if you do another GUI Java project you should use JavaFX instead of Swing. Swing is kind of deprecated. It's also quite messy." } ]
[ { "body": "<p>\"Uniqueness\" should not be your goal (except you copied it completely from somebody else ;) ) In general you should aim for removing stuff and still let it work as expected and not adding unnecessary stuff. Do you have test, that is something you should add always?</p>\n\n<p>Some hints:</p>\n\n<ul>\n<li>make your fields private instead of default</li>\n<li>don't use abbreviation, or use them in a consistent way (ply1.. vs. player1..., Aba?) </li>\n<li>why is your Thread called string? playin?</li>\n<li>Did you notice that you duplicate some code for Player 1 and 2? Maybe it's a good idea to create a player class? </li>\n<li>If you have player objects a ball object would also be nice. You could encapsulate the drawing and movement. Beside better readability, it would also be easier to write a test for the object movements.</li>\n<li>If you want to restart your game later you could also put the remaining variables in a game class. So you could move your whole logic out of the panel, which main purpose should be only displaying stuff and not more.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T06:24:52.727", "Id": "25255", "ParentId": "25249", "Score": "5" } } ]
{ "AcceptedAnswerId": "25255", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-04-19T02:42:20.520", "Id": "25249", "Score": "2", "Tags": [ "java", "strings", "array", "game", "homework" ], "Title": "High School Java Class: Pong Project External Reviewer" }
25249
<p>I have a repository abstract class that encapsulates pretty much all of the CRUD functionality:</p> <pre><code>public abstract class DataRepository&lt;T&gt; : IRepository&lt;T&gt; where T : class { public DataContext Context { get; private set; } public TransactionScope Transaction { get; private set; } /// &lt;summary&gt; /// A &lt;see cref="bool"/&gt; function that compares the keys for fetching a single item, for example: /// return item1.Id == item2.Id (as an anonymous delegate). /// &lt;/summary&gt; public Func&lt;T, T, bool&gt; KeyCompare { get; private set; } /// &lt;summary&gt; /// Creates a new data repository. /// &lt;/summary&gt; /// &lt;param name="context"&gt;&lt;/param&gt; /// &lt;param name="scope"&gt;&lt;/param&gt; /// &lt;param name="keyCompare"&gt; /// A &lt;see cref="bool"/&gt; function that compares the keys for fetching a single item, for example: /// return item1.Id == item2.Id (as an anonymous delegate). /// &lt;/param&gt; public DataRepository(DataContext context, TransactionScope scope, Func&lt;T, T, bool&gt; keyCompare) { Context = context; Transaction = scope; KeyCompare = keyCompare; } public virtual T Item(T item) { return Items().SingleOrDefault(e =&gt; KeyCompare(e, item)); } public virtual IEnumerable&lt;T&gt; Items() { return DataTable.AsEnumerable(); } protected virtual Table&lt;T&gt; DataTable { get { return Context.GetTable&lt;T&gt;(); } } /// &lt;summary&gt; /// A method that updates the non-key fields of an existing entity with those of specified &lt;see cref="item"/&gt;. /// Called by the &lt;see cref="Save"/&gt; method. /// &lt;/summary&gt; /// &lt;param name="existing"&gt;The existing record to update.&lt;/param&gt; /// &lt;param name="item"&gt;A &lt;see cref="T"/&gt; object containing the values to update &lt;see cref="existing"/&gt; object with.&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; protected abstract void UpdateExisting(T existing, T item); /// &lt;summary&gt; /// A method that updates an existing item or creates a new one, as needed. /// &lt;/summary&gt; /// &lt;param name="item"&gt;The entity containing the values to be saved.&lt;/param&gt; public virtual void Save(T item) { var existing = Item(item); if (existing != null) { UpdateExisting(existing, item); } else { DataTable.InsertOnSubmit(item); } Context.SubmitChanges(); } /// &lt;summary&gt; /// A method that saves all specified items (creates new, updates existing). /// &lt;/summary&gt; /// &lt;param name="items"&gt;The entities to be saved.&lt;/param&gt; public virtual void Save(IEnumerable&lt;T&gt; items) { foreach (var item in items) { Save(item); } } /// &lt;summary&gt; /// A method that deletes specified item. /// &lt;/summary&gt; /// &lt;param name="item"&gt;&lt;/param&gt; public virtual void Delete(T item) { var existing = Item(item); if (existing != null) { DataTable.DeleteOnSubmit(existing); } Context.SubmitChanges(); } public virtual void Delete(IEnumerable&lt;T&gt; items) { var selection = Items().Where(e =&gt; items.Any(item =&gt; KeyCompare(e, item))); DataTable.DeleteAllOnSubmit(selection); Context.SubmitChanges(); } } </code></pre> <p>The <code>KeyCompare</code> property is used like this in the derived classes, so that the base class knows how to isolate a single item in the repository (not all "entities" have a "Id" property, and some keys span multiple columns - this solution attempts to resolve that particular point):</p> <pre><code>public AuthInfoRepository(DataContext context, TransactionScope scope) : base(context, scope, (item1, item2) =&gt; { return item1.Id == item2.Id;}) { } </code></pre> <p>This KeyCompare property is really the cornerstone that allows the derived classes to merely implement the UpdateExisting method, like this:</p> <pre><code>protected override void UpdateExisting(AuthInfo existing, AuthInfo item) { existing.AuthId = item.AuthId; existing.ActiveDirectoryGroup = item.ActiveDirectoryGroup; } </code></pre> <p>The rest (actual CRUD) is all handled by the base class. With this abstract repository I have been implementing the concrete ones in minutes if not seconds, writing only the code that is specific to each implementation. Finest DRY I've ever written.</p> <p>The DataRepository deals with SQL Server, so I needed yet another implementation for mocking, which I've called ListRepository and does pretty much exactly the same thing (except Context and Transaction properties both return null). I think the constructor's signature is all I need to post here:</p> <pre><code>public ListRepository(IEnumerable&lt;T&gt; items, Func&lt;T, T, bool&gt; keyCompare) </code></pre> <p>So for testing, I can bind <code>IReporitory&lt;T&gt;</code> to this <code>ListRepository</code> while production code binds to <code>DataRepository</code>:</p> <pre><code>Bind&lt;IRepository&lt;AuthInfo&gt;&gt;().To&lt;ListRepository&lt;AuthInfo&gt;&gt;() .WithConstructorArgument("items", _mockAuthInfo) .WithConstructorArgument("keyCompare", (Func&lt;AuthInfo, AuthInfo, bool&gt;)((item1, item2) =&gt; item1.Id == item2.Id)); </code></pre> <p>While this is all great (just about to start unit testing it), there are a couple points that I'd still like to address:</p> <ul> <li>Should I externalize the calls to <code>Context.SubmitChanges()</code>? I don't like that the method gets called at every iteration, both when saving and when deleting multiple items.</li> <li>While this is certainly great DRY, I'm worried the virtual methods violate YAGNI - I don't see me overriding any of those in any implmentation in the near future. Then the class doesn't need to be abstract and could still provide a virtual implementation of <code>UpdateExisting</code>, but that would make implementing the class less obvious than the abstract method. Where's the line drawn?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T19:38:23.513", "Id": "39195", "Score": "0", "body": "Made `Delete(IEnumerable<T> items)` a virtual method in `RepositoryBase`, just like `Save(IEnumerable<T> items)` is." } ]
[ { "body": "<h2>Repositories for</h2>\n\n<ul>\n<li>Add objects</li>\n<li>Remove objects</li>\n<li>Query objects (no named queries like GetById)</li>\n</ul>\n\n<p>Repositories may not know about anything their context or transaction scope (and they can't be saved directly) these are different story which can be told by an UnitOfWork instance:</p>\n\n<pre><code>class UnitOfWork : IDisposable\n{\n public void Dispose() {} // Rollback\n public void Commit() {}\n}\n</code></pre>\n\n<h2>Table</h2>\n\n<p>The Table property ends up with a leaky abstraction and not all repository need a concrete table.</p>\n\n<h2>KeyCompare</h2>\n\n<p>Nice idea but it will not work as expected becouse it's a <code>Func&lt;&gt;</code> and it can not be translated for example into a SQL query. You should return an <code>Expression&lt;Func&lt;&gt;&gt;</code> and you can apply that as a simple method call no need other expression becouse it will not be translated and maybe you will end up with an exception:</p>\n\n<pre><code>.SingleOrDefault(KeyCompare);\n</code></pre>\n\n<h2>AsEnumerable()</h2>\n\n<pre><code>public virtual IEnumerable&lt;T&gt; Items()\n {\n return DataTable.AsEnumerable();\n }\n</code></pre>\n\n<p>Imagine a reporitory with 20 billion entities which are stored in a SQL database. What will the above expression mean: download all entities and then query them somehow. Avoid calling the .AsEnumerable an similar methods (.ToArray()) before the final query statement.</p>\n\n<h2>Items()</h2>\n\n<p>God why? The reporitory should represent what you tried with this method but not an IEnumerable&lt;T&gt; but an IQueryable&lt;T&gt; so a repository must implement this interface. But in this way you cold only query your entities but not add/remove them. Need other methods in a common interface but before creating our own check out the IObjectSet&lt;T&gt; interface from the framework it's perfect for a repository.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T13:27:09.460", "Id": "39118", "Score": "0", "body": "Great answer, I'm reworking the interface right now - seeing everything that's online about repositories I was actually striving to avoid exposing `IQueryable` (yielding stuff like this *Table* property and *Items* method) but now I see that the *unit of work* likes IQueryable very much and shouldn't pass on its *TransactionScope* down the repos. This answer has sorted out lots of things, thanks a lot!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T19:27:41.660", "Id": "39194", "Score": "0", "body": "found a way to get `KeyCompare` to work with LinqToSQL, would you mind taking a look at the reworked code (updated the question)? Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T21:20:52.620", "Id": "39199", "Score": "0", "body": "@PeterKiss, see my edits (once they're approved) for two ways to get the generic's brackets to be displayed properly." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T05:04:32.200", "Id": "25252", "ParentId": "25250", "Score": "4" } } ]
{ "AcceptedAnswerId": "25252", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T02:57:38.547", "Id": "25250", "Score": "4", "Tags": [ "c#", "design-patterns" ], "Title": "Abstract repository implementation" }
25250
<p>I'm working on an algorithm to solve the <a href="http://en.wikipedia.org/wiki/24_Game" rel="nofollow">24-challenge game</a>. The basic idea is to combine positive integers using arithmetic operators to produce an expression that evaluates to exactly 24. For instance, <code>(9 - 3) * (2 + 2) = 24</code>. My current implementation is functional (delivers responses in less than 15 seconds) with seven or fewer inputs. I think there is plenty room for optimization - especially when trying to consider every order-of-operations to apply to a permutation of the inputs. I have included my code below. Any tips/tricks/suggestions much appreciated!</p> <pre><code># usage: # irb&gt; Solver.solve(8, 8, 3, 3) require 'set' class Solver def initialize(nums) @nums = nums @arity = nums.size @ops = initialize_functions @op_orders = op_orders(@ops.keys, @arity - 1) @solutions = Set.new @SOLUTION = 24.0 @MAX_SOLUTIONS = 10 @TOLERANCE = 0.000001 end def solve # iterate over all unique permutations of given numbers @nums.permutation.to_a.uniq do |ordered_nums| # iterate over all permutations of the operators @op_orders.each do |ops| procs = ops.map{|op_name| @ops[op_name][:proc]} symbols = ops.map{|op_name| @ops[op_name][:symbol]} # iterate over all possible orders of operations (0...ops.size).entries.permutation do |order_of_ops| ordered_nums_copy = ordered_nums.clone root = nil order_of_ops.each do |op_index| proc = procs[op_index] sym = symbols[op_index] tree = BinaryTree.new(proc, sym, ordered_nums_copy[op_index], ordered_nums_copy[op_index + 1]) old_ref1, ordered_nums_copy[op_index] = ordered_nums_copy[op_index], tree old_ref2, ordered_nums_copy[op_index + 1] = ordered_nums_copy[op_index + 1], tree ordered_nums_copy.each_with_index do |ref, index| if (ref.is_a? BinaryTree) &amp;&amp; [old_ref1, old_ref2].include?(ref) ordered_nums_copy[index] = tree end end root = tree end answer = root.calc if is_solution?(answer) # puts "solution: #{root}" @solutions &lt;&lt; root.to_s if @solutions.size &gt;= @MAX_SOLUTIONS return @solutions end end end end end return @solutions end private def initialize_functions add = Proc.new{|n, m| n + m} subtract = Proc.new{|n, m| n - m} multiply = Proc.new{|n, m| n * m} divide = Proc.new{|n, m| n.to_f / m} exponent = Proc.new{|n, m| n ** m} return { add: { proc: add, symbol: '+' }, subtract: { proc: subtract, symbol: '-' }, multiply: { proc: multiply, symbol: '*' }, divide: { proc: divide, symbol: '/' } # exponent: { # proc: exponent, # symbol: '^' # } } end def is_solution?(solution) return (@SOLUTION - solution.to_f).abs &lt; @TOLERANCE rescue false end def op_orders(ops, num_to_choose) results = [] radix = ops.size min = 0 max = ((ops.size - 1).to_s * num_to_choose).to_i(radix) (min..max).each do |num| results &lt;&lt; ("0" * num_to_choose + num.to_s(radix)).slice(num_to_choose * -1, num_to_choose).split('').map{|i| ops[i.to_i]} end return results end def self.solve(*nums) Solver.new(nums).solve end end class BinaryTree attr_accessor :left, :right, :proc, :sym def initialize(proc = nil, sym = nil, left = nil, right = nil) self.proc, self.sym, self.left, self.right = proc, sym, left, right end def calc left_operand = (left.is_a? BinaryTree) ? left.calc : left.to_f right_operand = (right.is_a? BinaryTree) ? right.calc : right.to_f return proc.call(left_operand, right_operand) end def to_s return "(#{left.to_s} #{sym} #{right.to_s})" end end </code></pre>
[]
[ { "body": "<pre><code> @SOLUTION = 24.0\n @MAX_SOLUTIONS = 10\n @TOLERANCE = 0.000001\n</code></pre>\n\n<p>I guess those uppercase names are used to denote constants, you can also use class constants for that.</p>\n\n<pre><code> # iterate over all unique permutations of given numbers\n @nums.permutation.to_a.uniq do |ordered_nums|\n</code></pre>\n\n<p>A \"unique permutation\" is a \"combination\", you have a <a href=\"http://ruby-doc.org/core-2.0/Array.html#method-i-combination\" rel=\"nofollow\">method</a> for that.</p>\n\n<pre><code> ordered_nums_copy = ordered_nums.clone\n root = nil\n order_of_ops.each do |op_index|\n</code></pre>\n\n<p>An advice: when dealing when mathematical/logic problems, use <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">functional programming</a>. No clones, eachs, <code>&lt;&lt;</code>, <code>update</code>', all that imperative stuff. Define <em>what</em> values are instead of <em>how</em> you calculate them. Strive for declarative programming.</p>\n\n<pre><code> add = Proc.new{|n, m| n + m}\n subtract = Proc.new{|n, m| n - m}\n multiply = Proc.new{|n, m| n * m}\n divide = Proc.new{|n, m| n.to_f / m}\n exponent = Proc.new{|n, m| n ** m}\n</code></pre>\n\n<p>Those procs are unnecessary, use the symbol and <code>send</code> when needed. By the way, is this to_f correct? I though the game allowed only integer division.</p>\n\n<pre><code> return {\n</code></pre>\n\n<p>It's not idiomatic to use <code>return</code> for the last expression of a block/method.</p>\n\n<pre><code>def is_solution?(solution)\n return (@SOLUTION - solution.to_f).abs &lt; @TOLERANCE\nrescue\n false\nend\n</code></pre>\n\n<p>That's not good practice, exceptions are used for excepcional situations, not to get out of algorithms. Note that lazy enumerators are a nice way to isolate the generation of solutions of the filtering/stopping condition. But in any case you must deal with it in another way.</p>\n\n<p>By the way, this is very similar to the numbers round of <a href=\"http://en.wikipedia.org/wiki/Countdown_%28game_show%29#Numbers_round\" rel=\"nofollow\">Countdown</a>, isn't it? By that name you surely will find implementations in Ruby and other languages. Some time ago I wrote <a href=\"https://code.google.com/p/tokland/source/browse/trunk/functional/presentation/src/cifras/cifras5.rb?r=687\" rel=\"nofollow\">this one</a> (now I'd change some things, but it may server as inspiration).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T20:54:33.497", "Id": "25312", "ParentId": "25251", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T03:31:23.457", "Id": "25251", "Score": "2", "Tags": [ "algorithm", "ruby" ], "Title": "General case of the 24-challenge problem" }
25251
<p>I have created a proof of concept jQuery based flow diagram based upon kayen's answer to <a href="https://stackoverflow.com/questions/7540149/click-through-yes-no-questions-from-opml-one-at-a-time">this post</a>.</p> <p>This diagram shows the flow diagram that I am seeking to create in jQuery:</p> <p><a href="https://i.stack.imgur.com/ZMtU4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZMtU4.jpg" alt="enter image description here"></a></p> <p>I also wanted to make the UI as clean as possible, so I have set it that only the current question is displayed as the users works their way through the various questions.</p> <p>The user can also go back to the last question at any time before they are given an answer.</p> <p>The code will be used on a website.</p> <p>As my code is long, I have set it out in full in my <a href="https://docs.google.com/file/d/0BxwgpyQEOuRdUm83QVNWWUdPTVk/edit?usp=sharing" rel="nofollow noreferrer">jsFiddle</a>. The basic structure is:</p> <p><strong>HTML:</strong></p> <pre><code>&lt;!—question 2--&gt; &lt;fieldset id="question2" style="display:none;"&gt; &lt;legend&gt;question 2&lt;/legend&gt; &lt;ul&gt; &lt;li&gt; &lt;label for=""&gt; &lt;input type="radio" name="question2" value="Yes" id="rdYes" /&gt;Yes&lt;/label&gt; &lt;/li&gt; &lt;li&gt; &lt;label for=""&gt; &lt;input type="radio" name="question2" value="No" id="rdNo" /&gt;No&lt;/label&gt; &lt;/li&gt; &lt;li&gt; &lt;input type="button" value="Back to last question" id="back2-1" /&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/fieldset&gt; </code></pre> <p><strong>jQuery:</strong></p> <pre><code>//Test for question 2 jQuery("input[name=question2]").change(function () { if ($(this).val() == "Yes") { jQuery("#question2A").show(); jQuery("#question2").hide(); } else { jQuery("#question3").show(); jQuery("#question2").hide(); } }); //Back button to question 1 from 2 jQuery("#back2-1").click(function () { jQuery("#q1").show(); jQuery("input:radio").attr("checked", false); jQuery("#question2").hide(); }); </code></pre> <p>It works, but as this is my first project it would really help me and others learning code, if someone could confirm:</p> <ol> <li><p>Is there a more efficient way to code this in jQuery?</p></li> <li><p>Would it be better to code it in another language, i.e. to avoid problems with older browsers?</p></li> </ol>
[]
[ { "body": "<p>You can simplify the javascript to be something as given below by adding some properties to the markup.</p>\n\n<pre><code>jQuery(function () {\n\n jQuery('input:radio[name^=\"question\"]').change(function(){\n var $this = $(this);\n\n $this.closest('.question-container').hide();\n $('#' + $this.data('target')).show();\n });\n});\n</code></pre>\n\n<p>Required changes in the markup</p>\n\n<ol>\n<li>add a class <code>question-container</code> to the question container ie the element with the question id like <code>q1</code>, <code>question1A</code>, etc</li>\n<li>For all radio boxes add an additional attribute <code>data-target</code> which will have the id of the question to be displayed if it was checked. ex <em>Yes</em> button in question question1A will have <code>data-target=\"question1B\"</code> and <em>No</em> button will have <code>data-target=\"question2-1A\"</code></li>\n</ol>\n\n<p>demo: <a href=\"http://jsfiddle.net/arunpjohny/8YSHr/3/\" rel=\"nofollow\">Fiddle</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T13:04:31.607", "Id": "25263", "ParentId": "25262", "Score": "1" } } ]
{ "AcceptedAnswerId": "25263", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-18T12:34:08.230", "Id": "25262", "Score": "5", "Tags": [ "javascript", "jquery", "html" ], "Title": "jQuery-based flow diagram" }
25262
<p>My definition of monkey testing is basically playing with a program in as if I was a monkey (press every button, unplug things, go in the wrong order..etc etc)</p> <p>So I made a rather simple SmartCard library that when I "enable" it it just polls the smart card reader for a card, and reports back information. see code</p> <pre><code>private void CardStatusChange() { readerState[0].dwCurrentState = SCardState.SCARD_STATE_UNAWARE; while (run) { System.Threading.Thread.Sleep(100); if (SCWrapper.SCardGetStatusChange(scHandle, UInt32.MaxValue, readerState, 1) == SCardFunctionReturnCodes.SCARD_S_SUCCESS) { readerState[0].dwCurrentState = readerState[0].dwEventState; SendCardStatus(readerState[0].dwEventState); } } } private void SendCardStatus(SCardState sCardState) { //case SCardState.SCARD_STATE_UNAWARE: //case SCardState.SCARD_STATE_IGNORE: //case SCardState.SCARD_STATE_CHANGED: //case SCardState.SCARD_STATE_UNKNOWN: //case SCardState.SCARD_STATE_UNAVAILABLE: //case SCardState.SCARD_STATE_EMPTY: if (HasStateMask(sCardState, SCardState.SCARD_STATE_EMPTY)) OnCardUnplugged(); //fire event //case SCardState.SCARD_STATE_PRESENT: if (HasStateMask(sCardState, SCardState.SCARD_STATE_PRESENT)) { OnCardPluggedIn(); //fire event SendCardATR(readerState[0].rgbAtr); //fire event } //case SCardState.SCARD_STATE_ATRMATCH: OnATRMatch(HasStateMask(sCardState, SCardState.SCARD_STATE_ATRMATCH)); //case SCardState.SCARD_STATE_EXCLUSIVE: //case SCardState.SCARD_STATE_INUSE: OnCardInUse(HasStateMask(sCardState, SCardState.SCARD_STATE_INUSE)); //case SCardState.SCARD_STATE_MUTE: //case SCardState.SCARD_STATE_UNPOWERED: } private bool HasStateMask(SCardState theValue, SCardState theMask) { return ((theValue &amp; theMask) == theMask); } </code></pre> <p>This part works as expected in that while my thread is running I can plug in and unplug a smartcard as often and as quickly as I want without problem. What I'm struggling with is the Threading portion of it. Visual Studio screams at me for using suspend and I found a bug when using suspend in my thread so I am taking that out (in other words don't comment on that) but this is how I "open" and "enable" my smart card</p> <pre><code>public override bool Open() { readerThread = new Thread(CardStatusChange); //code here to setup the smart card return true; } public override bool Enable() { run = true; //thread start checking for card events switch (readerThread.ThreadState) {//this is probably a mistake case ThreadState.AbortRequested: break; case ThreadState.Aborted: break; case ThreadState.Background: break; case ThreadState.Running: break; case ThreadState.StopRequested: break; case ThreadState.Stopped: break; case ThreadState.SuspendRequested: break; case ThreadState.Suspended: readerThread.Resume();//TODO remove break; case ThreadState.Unstarted: readerThread.Start(); break; case ThreadState.WaitSleepJoin: break; default: break; } return true; } public override void Disable() { run = false; readerThread.Suspend(); //TODO remove } </code></pre> <p>I've never been too good at threading, but I do need this as a thread (I think I do atleast I am open to other ideas). So how should I really Enable and Disable? I used to just set run to true or false, but my monkey testing showed that this doesn't always work and sometimes Windows would cry that it can't start a running thread... SO I dunno what to do. Any thoughts?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T21:21:39.807", "Id": "39147", "Score": "0", "body": "I think I found the answer. It appears to be work. On the Disable instead of `readerThread.Suspend()` I change it to `readertThread.Join()`. Then I just check for the Unstarted flag for Enable and fire it up. So far it is working good with no hicups. still have further testing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-14T15:36:42.030", "Id": "42619", "Score": "1", "body": "Can you post the answer you found as an answer? This will help future users." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-14T16:07:14.803", "Id": "42621", "Score": "0", "body": "@RyanGates Sure can... :)" } ]
[ { "body": "<p>As requested by Ryan Gates I should post my results. I don't remember the entire scope of what i did, but I do know where the code is :)</p>\n\n<p>So the basics are that I want the thread to be able to exit without causing any strange hicups if the user decides to use my library incorrectly. So I made the thread turn into a background thread. I was able to remove the ugly switch statement and just check the appropriate bits are set to make sure I can start my thread (basically only allows one thread to read a smart card instead of multiple reading the same card)</p>\n\n<p>On Disable what I did was set my flag to kill the loop in my readerThread thread. I then wait for it to exit by using the <code>thread.Join</code> Clear as mud??? I can try to clear up more if anyone has questions.</p>\n\n<pre><code>public override bool Open()\n{\n //Code to setup SmartCard\n\n readerThread = new Thread(CardStatusChange);\n readerThread.IsBackground = true;\n\n return true;\n}\npublic override bool Enable()\n{\n run = true;\n //thread start checking for card events\n Globals.tracer.TraceInformation(\"Checking Thread State:{0}\", readerThread.ThreadState);\n var startable = (readerThread.ThreadState &amp; ThreadState.Unstarted);\n if (startable &gt; 0)\n readerThread.Start();\n\n return true;\n}\npublic override void Disable()\n{\n run = false;\n if(readerThread.ThreadState == ThreadState.Unstarted)\n readerThread.Join();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-14T15:59:59.197", "Id": "27405", "ParentId": "25266", "Score": "3" } } ]
{ "AcceptedAnswerId": "27405", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T14:22:26.507", "Id": "25266", "Score": "5", "Tags": [ "c#", "multithreading", "state" ], "Title": "Monkey testing a SmartCard library" }
25266
<p>I'm writing a multithreaded game engine, and I'm wondering about best practices around waiting for threads. It occurs to me that there could be much better options out there than what I've implemented, so I'm wondering what you think.</p> <ol> <li><p><code>wait()</code> method gets called at the top of every other method in the class. This is my current implementation, and I'm realizing it's not ideal.</p> <pre><code>class Texture { public: Texture(const char *filename, bool async = true); ~Texture(); void Render(); private: SDL_Thread *thread; const char *filename; void wait(); static int load(void *data); } void Texture::wait() { if (thread != NULL) { SDL_WaitThread(thread, NULL); thread = NULL; } } int Texture::load(void *data) { Texture *self = static_cast&lt;Texture *&gt;(data); // Load the Image Data in the Thread Here... return 0; } Texture::Texture(const char *filename, bool async) { this-&gt;filename = filename; if (async) { thread = SDL_CreateThread(load, NULL, this); } else { thread = NULL; load(this); } } Texture::~Texture() { // Unload the Thread and Texture Here } void Texture::Render() { wait(); // Render the Texture Here } </code></pre></li> <li><p>Convert the <code>wait()</code> method in to a function pointer. This would save my program from a jmp at the top of every other method, and simply check for <code>thread != NULL</code> at the top of every method. Still not ideal, but I feel like the fewer jumps, the better. (I've also considered just using the <code>inline</code> keyword on the function... but would this include the entire contents of the wait function when all I really need is the <code>if (thread != NULL)</code> check to determine whether the rest of the code should be executed or not?)</p></li> <li><p>Convert all of the class' methods in to function pointers, and ditch the whole concept of calling <code>wait()</code> except while actually loading the texture. I see advantages and disadvantages to this approach... namely, this feels the most difficult to implement and keep track of. Admittedly, my knowledge of the inner workings on GCC's optimizations and assembly and especially memory->cpu->memory communication isn't the best, so using a bunch of function pointers might actually be slower than a properly defined class.</p></li> </ol> <p>Anyone have any even better ideas?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T18:14:59.207", "Id": "63444", "Score": "0", "body": "Just use `std::future::get` if you really wanna wait." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T11:13:59.230", "Id": "66510", "Score": "0", "body": "There's not much code to review here. If you want to discuss architecture and algorithms without presenting corresponding source code, that would be on-topic at [Programmers.SE](http://programmers.stackexchange.com/)." } ]
[ { "body": "<blockquote>\n <p>I'm wondering about best practices around waiting for threads.</p>\n</blockquote>\n\n<p>That's too big a question. Instead I'll just review your existing code.</p>\n\n<blockquote>\n <p>This is my current implementation, and I'm realizing it's not ideal.</p>\n</blockquote>\n\n<p>You construct this with a <code>bool async</code> parameter, so that it loads synchronously or asynchronously. There are (at least) two alternatives.</p>\n\n<p>One is to make two derived subclasses:</p>\n\n<pre><code>class Texture\n{\n ... etc ...\n virtual ~Texture() {}\nprotected:\n Texture(const char *filename)\n {\n this-&gt;filename = filename;\n }\n static int load(void *data);\nprivate:\n virtual void wait() = 0;\n const char *filename;\n}\n\nclass SyncTexture : public Texture {\npublic:\n SyncTexture(const char *filename)\n : Texture(filename)\n {\n load(this);\n }\nprivate:\n virtual void wait() {} // do nothing\n};\n\nclass AsyncTexture : public Texture {\npublic:\n AsyncTexture(const char *filename)\n : Texture(filename)\n {\n thread = SDL_CreateThread(load, NULL, this);\n }\nprivate:\n SDL_Thread *thread;\n virtual void wait() { SDL_WaitThread(thread, NULL); }\n};\n</code></pre>\n\n<p>The above is similar to what you might have been suggesting when you talked about a \"function pointer\": i.e. <code>wait</code> is 'virtual' and called through a so-called <a href=\"http://en.wikipedia.org/wiki/Virtual_method_table\" rel=\"nofollow\">vtable</a>.</p>\n\n<p>The second possibility is to do it using templates:</p>\n\n<pre><code>template &lt;bool async = true&gt;\nclass Texture {\npublic:\n Texture(const char *filename);\n};\n</code></pre>\n\n<p>This may be faster at run-time, because the value of <code>async</code> is known/fixed at compile-time.</p>\n\n<blockquote>\n <p>Convert the \"wait()\" method in to a function pointer.</p>\n</blockquote>\n\n<p>I don't understand what you're thinking of when you say this, and you haven't provided the source code for it.</p>\n\n<blockquote>\n <p>I've also considered just using the \"inline\" keyword on the function... but would this include the entire contents of the wait function when all I really need is the \"if (thread != NULL)\" check to determine whether the rest of the code should be executed or not?</p>\n</blockquote>\n\n<p>I guess that <code>wait</code> is small and simple enough to be inlined.</p>\n\n<p>The \"rest of the code\" is only the following ...</p>\n\n<pre><code>{\n SDL_WaitThread(thread, NULL);\n thread = NULL;\n}\n</code></pre>\n\n<p>... and it wouldn't be called if thread is null: so what are you worrying about: the increase in size of your software? I doubt you have enough methods (places where you call <code>wait</code>), such that inlining them would make significant difference to the size of your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T21:14:57.150", "Id": "67285", "Score": "1", "body": "Separating each class into synchronous and asynchronous subclasses is brilliant. I'm going to move forward with the \"virtual\" method implementation. Thank you! ^_^" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T21:52:17.947", "Id": "67290", "Score": "0", "body": "Sorry this question took so long to answer. The community here has become more active recently." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-20T00:25:27.720", "Id": "39622", "ParentId": "25269", "Score": "3" } } ]
{ "AcceptedAnswerId": "39622", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T17:33:38.237", "Id": "25269", "Score": "10", "Tags": [ "c++", "multithreading" ], "Title": "Thread-safe game engine: multi-threading best practices?" }
25269
<p>I am using a recursive algorithm to find all of the file-paths in a given directory: it returns a dictionary like this: <code>{'Tkinter.py': 'C:\Python27\Lib\lib-tk\Tkinter.py', ...}</code>.</p> <p>I am using this in a script to open modules by solely given the name. Currently, the whole process (for everything in <code>sys.path</code>) takes about 9 seconds. To avoid doing this every time, I have it save to a <code>.pkl</code> file and then just load this in my module-opener program.</p> <p>The original recursive method took too long and sometimes gave me a <code>MemoryError</code>, so what I did was create a helper method to iterate through the subfolders (using <code>os.listdir</code>), and then call the recursive method.</p> <p>Here is my code:</p> <pre><code>import os, os.path def getDirs(path): sub = os.listdir(path) paths = {} for p in sub: print p pDir = '{}\{}'.format(path, p) if os.path.isdir(pDir): paths.update(getAllDirs(pDir, paths)) else: paths[p] = pDir return paths def getAllDirs(mainPath, paths = {}): subPaths = os.listdir(mainPath) for path in subPaths: pathDir = '{}\{}'.format(mainPath, path) if os.path.isdir(pathDir): paths.update(getAllDirs(pathDir, paths)) else: paths[path] = pathDir return paths </code></pre> <p>Is there any way to make this faster? Thanks! </p>
[]
[ { "body": "<pre><code>import os, os.path\ndef getDirs(path):\n</code></pre>\n\n<p>Python convention is to use <code>lowercase_with_underscores</code> for function names</p>\n\n<pre><code> sub = os.listdir(path)\n</code></pre>\n\n<p>Don't needlessly abbreviate, and at least have it be a plural name.</p>\n\n<pre><code> paths = {}\n for p in sub:\n</code></pre>\n\n<p>You don't need to store things in a temporary variable to loop over them</p>\n\n<pre><code> print p\n</code></pre>\n\n<p>Do you really want this function printing?</p>\n\n<pre><code> pDir = '{}\\{}'.format(path, p)\n</code></pre>\n\n<p>Use os.path.join to join paths. That'll make sure it works regardless of your platform.</p>\n\n<pre><code> if os.path.isdir(pDir): \n paths.update(getAllDirs(pDir, paths))\n</code></pre>\n\n<p>You shouldn't both pass it and update it afterwords. That's redundant.</p>\n\n<pre><code> else:\n paths[p] = pDir\n return paths\n\ndef getAllDirs(mainPath, paths = {}):\n</code></pre>\n\n<p>Don't use mutable objects as default values, they have unexpected behavior.</p>\n\n<pre><code> subPaths = os.listdir(mainPath)\n for path in subPaths:\n pathDir = '{}\\{}'.format(mainPath, path)\n if os.path.isdir(pathDir):\n paths.update(getAllDirs(pathDir, paths))\n else:\n paths[path] = pathDir\n return paths\n</code></pre>\n\n<p>This whole section is repeated from the previous function. You should combine them.</p>\n\n<p>Take a look at the <code>os.walk</code> function. It does most of the work you're doing here and you could use to simplify your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T21:06:58.440", "Id": "25273", "ParentId": "25272", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T20:52:06.053", "Id": "25272", "Score": "1", "Tags": [ "python", "optimization", "recursion" ], "Title": "Improve file-path finding method" }
25272
<p>I am working on an application that will use an N-Tiered approach. I would appreciate any feedback and advice on my architecture before I proceed any further.</p> <p><strong>DataLayer (Class Library Project)</strong></p> <p>Context.cs</p> <pre><code>namespace TimeTracker.DataLayer { public class Context : DbContext { public Context() : base("Data") { } public DbSet&lt;User&gt; Users { get; set; } public DbSet&lt;TimeEntry&gt; TimeEntries { get; set; } } } </code></pre> <p>TimeEntry.cs</p> <p>User.cs</p> <p><strong>Framework (Class Library Project)</strong></p> <p>DbContextManager.cs</p> <pre><code>namespace TimeTracker.Framework.DbContextManagement { using System.Data.Entity; /// &lt;summary&gt; /// Abstract base class for all other DbContextManager classes. /// &lt;/summary&gt; public abstract class DbContextManager { /// &lt;summary&gt; /// Returns a reference to an DbContext instance. /// &lt;/summary&gt; /// &lt;typeparam name="TDbContext"&gt;The type of the db context.&lt;/typeparam&gt; /// &lt;returns&gt;The current DbContext&lt;/returns&gt; public abstract TDbContext GetDbContext&lt;TDbContext&gt;() where TDbContext : DbContext, new(); } } </code></pre> <p>DbContextScope.cs</p> <pre><code>namespace TimeTracker.Framework.DbContextManagement { using System; using System.Collections.Generic; using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Threading; /// &lt;summary&gt; /// Defines a scope wherein only one DbContext instance is created, and shared by all of those who use it. /// &lt;/summary&gt; /// &lt;remarks&gt;Instances of this class are supposed to be used in a using() statement.&lt;/remarks&gt; public class DbContextScope : IDisposable { /// &lt;summary&gt; /// List of current DbContexts (supports multiple contexts). /// &lt;/summary&gt; private readonly List&lt;DbContext&gt; contextList; /// &lt;summary&gt; /// DbContext scope definitiion. /// &lt;/summary&gt; [ThreadStatic] private static DbContextScope currentScope; /// &lt;summary&gt; /// Holds a value indicating whether the context is disposed or not. /// &lt;/summary&gt; private bool isDisposed; /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="DbContextScope"/&gt; class. /// &lt;/summary&gt; /// &lt;param name="saveAllChangesAtEndOfScope"&gt;if set to &lt;c&gt;true&lt;/c&gt; [save all changes at end of scope].&lt;/param&gt; protected DbContextScope(bool saveAllChangesAtEndOfScope) { if (currentScope != null &amp;&amp; !currentScope.isDisposed) { throw new InvalidOperationException("DbContextScope instances cannot be nested."); } this.SaveAllChangesAtEndOfScope = saveAllChangesAtEndOfScope; this.contextList = new List&lt;DbContext&gt;(); this.isDisposed = false; Thread.BeginThreadAffinity(); currentScope = this; } /// &lt;summary&gt; /// Gets or sets a value indicating whether to automatically save all object changes at end of the scope. /// &lt;/summary&gt; /// &lt;value&gt;&lt;c&gt;true&lt;/c&gt; if [save all changes at end of scope]; otherwise, &lt;c&gt;false&lt;/c&gt;.&lt;/value&gt; private bool SaveAllChangesAtEndOfScope { get; set; } /// &lt;summary&gt; /// Save all object changes to the underlying datastore. /// &lt;/summary&gt; public void SaveAllChanges() { var transactions = new List&lt;DbTransaction&gt;(); foreach (var context in this.contextList .Select(dbcontext =&gt; ((IObjectContextAdapter)dbcontext) .ObjectContext)) { context.Connection.Open(); var databaseTransaction = context.Connection.BeginTransaction(); transactions.Add(databaseTransaction); try { context.SaveChanges(); } catch { /* Rollback &amp; dispose all transactions: */ foreach (var transaction in transactions) { try { transaction.Rollback(); } catch { // "Empty general catch clause suppresses any errors." // Haven't quite figured out what to do here yet. } finally { databaseTransaction.Dispose(); } } transactions.Clear(); throw; } } try { /* Commit all complete transactions: */ foreach (var completeTransaction in transactions) { completeTransaction.Commit(); } } finally { /* Dispose all transactions: */ foreach (var transaction in transactions) { transaction.Dispose(); } transactions.Clear(); /* Close all open connections: */ foreach (var context in this.contextList .Select(dbcontext =&gt; ((IObjectContextAdapter)dbcontext).ObjectContext) .Where(context =&gt; context.Connection.State != System.Data.ConnectionState.Closed)) { context.Connection.Close(); } } } /// &lt;summary&gt; /// Disposes the DbContext. /// &lt;/summary&gt; public void Dispose() { // Monitor for possible future bugfix. // CA1063 : Microsoft.Design : Provide an overridable implementation of Dispose(bool) // on 'DbContextScope' or mark the type as sealed. A call to Dispose(false) should // only clean up native resources. A call to Dispose(true) should clean up both managed // and native resources. if (this.isDisposed) { return; } // Monitor for possible future bugfix. // CA1063 : Microsoft.Design : Modify 'DbContextScope.Dispose()' so that it calls // Dispose(true), then calls GC.SuppressFinalize on the current object instance // ('this' or 'Me' in Visual Basic), and then returns. currentScope = null; Thread.EndThreadAffinity(); try { if (this.SaveAllChangesAtEndOfScope &amp;&amp; this.contextList.Count &gt; 0) { this.SaveAllChanges(); } } finally { foreach (var context in this.contextList) { try { context.Dispose(); } catch (ObjectDisposedException) { // Monitor for possible future bugfix. // CA2202 : Microsoft.Usage : Object 'databaseTransaction' can be disposed // more than once in method 'DbContextScope.SaveAllChanges()'. // To avoid generating a System.ObjectDisposedException you should not call // Dispose more than one time on an object. } } this.isDisposed = true; } } /// &lt;summary&gt; /// Returns a reference to a DbContext of a specific type that is - or will be - /// created for the current scope. If no scope currently exists, null is returned. /// &lt;/summary&gt; /// &lt;typeparam name="TDbContext"&gt;The type of the db context.&lt;/typeparam&gt; /// &lt;returns&gt;The current DbContext&lt;/returns&gt; protected internal static TDbContext GetCurrentDbContext&lt;TDbContext&gt;() where TDbContext : DbContext, new() { if (currentScope == null) { return null; } var contextOfType = currentScope.contextList .OfType&lt;TDbContext&gt;() .FirstOrDefault(); if (contextOfType == null) { contextOfType = new TDbContext(); currentScope.contextList.Add(contextOfType); } return contextOfType; } } } </code></pre> <p>FacadeBase.cs</p> <pre><code>namespace TimeTracker.Framework.DbContextManagement { using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Data.Entity; using System.Reflection; /// &lt;summary&gt; /// Generic base class for all other TimeTracker.BusinessLayer.Facade classes. /// &lt;/summary&gt; /// &lt;typeparam name="TDbContext"&gt;The type of the db context.&lt;/typeparam&gt; /// &lt;typeparam name="TEntity"&gt;The type of the entity.&lt;/typeparam&gt; /// &lt;typeparam name="TEntityKey"&gt;The type of the entity key.&lt;/typeparam&gt; /// &lt;remarks&gt;&lt;/remarks&gt; public abstract class FacadeBase&lt;TDbContext, TEntity, TEntityKey&gt; where TDbContext : DbContext, new() where TEntity : class { /// &lt;summary&gt; /// Gets the db context. /// &lt;/summary&gt; public TDbContext DbContext { get { if (DbContextManager == null) { this.InstantiateDbContextManager(); } return DbContextManager != null ? DbContextManager.GetDbContext&lt;TDbContext&gt;() : null; } } /// &lt;summary&gt; /// Gets or sets the DbContextManager. /// &lt;/summary&gt; /// &lt;value&gt;The DbContextManager.&lt;/value&gt; private DbContextManager DbContextManager { get; set; } /// &lt;summary&gt; /// Adds a new entity object to the context. /// &lt;/summary&gt; /// &lt;param name="newObject"&gt;A new object.&lt;/param&gt; public virtual void Add(TEntity newObject) { this.DbContext.Set&lt;TEntity&gt;().Add(newObject); } /// &lt;summary&gt; /// Deletes an entity object. /// &lt;/summary&gt; /// &lt;param name="obsoleteObject"&gt;An obsolete object.&lt;/param&gt; public virtual void Delete(TEntity obsoleteObject) { this.DbContext.Set&lt;TEntity&gt;().Remove(obsoleteObject); } /// &lt;summary&gt; /// Gets all entities for the given type. /// &lt;/summary&gt; /// &lt;returns&gt;DbContext Set of TEntity.&lt;/returns&gt; public virtual IEnumerable&lt;TEntity&gt; GetAll() { return this.DbContext.Set&lt;TEntity&gt;(); } /// &lt;summary&gt; /// Gets the entity by the specified entity key. /// &lt;/summary&gt; /// &lt;param name="entityKey"&gt;The entity key.&lt;/param&gt; /// &lt;returns&gt;Entity matching specified entity key or null if not found.&lt;/returns&gt; public virtual TEntity GetByKey(TEntityKey entityKey) { return this.DbContext.Set&lt;TEntity&gt;().Find(entityKey); } /// &lt;summary&gt; /// Deletes the entity for the specified entity key. /// &lt;/summary&gt; /// &lt;param name="entityKey"&gt;The entity key.&lt;/param&gt; public virtual void DeleteByKey(TEntityKey entityKey) { var entity = this.DbContext.Set&lt;TEntity&gt;().Find(entityKey); if (entity != null) { this.DbContext.Set&lt;TEntity&gt;().Remove(entity); } } /// &lt;summary&gt; /// Instantiates a new DbContextManager based on application configuration settings. /// &lt;/summary&gt; private void InstantiateDbContextManager() { /* Retrieve DbContextManager configuration settings: */ var contextManagerConfiguration = ConfigurationManager.GetSection("DbContext") as Hashtable; if (contextManagerConfiguration == null) { throw new ConfigurationErrorsException("A TimeTracker.BusinessLayer.Facade.DbContext tag or its managerType attribute is missing in the configuration."); } if (!contextManagerConfiguration.ContainsKey("managerType")) { throw new ConfigurationErrorsException("dbManagerConfiguration does not contain key 'managerType'."); } var managerTypeName = contextManagerConfiguration["managerType"] as string; if (string.IsNullOrEmpty(managerTypeName)) { throw new ConfigurationErrorsException("The managerType attribute is empty."); } managerTypeName = managerTypeName.Trim().ToUpperInvariant(); try { /* Try to create a type based on it's name: */ var frameworkAssembly = Assembly.GetAssembly(typeof(DbContextManager)); var managerType = frameworkAssembly.GetType(managerTypeName, true, true); /* Try to create a new instance of the specified DbContextManager type: */ this.DbContextManager = Activator.CreateInstance(managerType) as DbContextManager; } catch (Exception e) { throw new ConfigurationErrorsException("The managerType specified in the configuration is not valid.", e); } } } } </code></pre> <p>ScopedDbContextManager.cs</p> <pre><code>namespace TimeTracker.Framework.DbContextManagement { using System.Collections.Generic; using System.Data.Entity; using System.Linq; /// &lt;summary&gt; /// Manages multiple db contexts. /// &lt;/summary&gt; public sealed class ScopedDbContextManager : DbContextManager { /// &lt;summary&gt; /// List of Object Contexts. /// &lt;/summary&gt; private List&lt;DbContext&gt; contextList; /// &lt;summary&gt; /// Returns the DbContext instance that belongs to the current DbContextScope. /// If currently no DbContextScope exists, a local instance of an DbContext /// class is returned. /// &lt;/summary&gt; /// &lt;typeparam name="TDbContext"&gt;The type of the db context.&lt;/typeparam&gt; /// &lt;returns&gt;Current scoped DbContext.&lt;/returns&gt; public override TDbContext GetDbContext&lt;TDbContext&gt;() { var currentDbContext = DbContextScope.GetCurrentDbContext&lt;TDbContext&gt;(); if (currentDbContext != null) { return currentDbContext; } if (this.contextList == null) { this.contextList = new List&lt;DbContext&gt;(); } currentDbContext = this.contextList.OfType&lt;TDbContext&gt;().FirstOrDefault(); if (currentDbContext == null) { currentDbContext = new TDbContext(); this.contextList.Add(currentDbContext); } return currentDbContext; } } } </code></pre> <p>UnitOfWorkScope.cs</p> <pre><code>namespace TimeTracker.Framework.DbContextManagement { /// &lt;summary&gt; /// Defines a scope for a business transaction. At the end of the scope all object changes can be persisted to the underlying datastore. /// &lt;/summary&gt; /// &lt;remarks&gt;Instances of this class are supposed to be used in a using() statement.&lt;/remarks&gt; public sealed class UnitOfWorkScope : DbContextScope { /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="UnitOfWorkScope"/&gt; class. /// &lt;/summary&gt; /// &lt;param name="saveAllChangesAtEndOfScope"&gt;if set to &lt;c&gt;true&lt;/c&gt; [save all changes at end of scope].&lt;/param&gt; public UnitOfWorkScope(bool saveAllChangesAtEndOfScope) : base(saveAllChangesAtEndOfScope) { } } } </code></pre> <p><strong>BusinessLayer (Class Library Project)</strong></p> <p>TimeEntryFacade.cs</p> <pre><code>namespace TimeTracker.BusinessLayer.Facade { using System.Collections.Generic; using System.Linq; using TimeTracker.DataLayer; using TimeTracker.DataLayer.Entities; using TimeTracker.Framework.DbContextManagement; using System; using TimeTracker.Framework.AppException; public class TimeEntryFacade : FacadeBase&lt;Context, TimeEntry, int&gt; { public override IEnumerable&lt;TimeEntry&gt; GetAll() { return base.GetAll() .Distinct() .ToList(); } /// &lt;summary&gt; /// Returns a TimeEntry based on its ID. /// &lt;/summary&gt; /// &lt;param name="productID"&gt;ID of an item.&lt;/param&gt; /// &lt;returns&gt;A TimeEntry object, or null if it does not exist.&lt;/returns&gt; public TimeEntry GetTimeEntryByID(Guid id) { return this.DbContext.TimeEntries.FirstOrDefault(x =&gt; x.UserID.Equals(id)); } private TimeEntry GetLastTimeEntry(int UserID) { return this.DbContext.TimeEntries .OrderByDescending(x =&gt; x.Time) .FirstOrDefault(x =&gt; x.UserID == UserID); } } } </code></pre> <p>My first issue is how to best work with defining the scope of my business transactions. Currently, if I am going to add, delete or modify an object I need to define my scope by writing my using statement.</p> <pre><code>using (new UnitOfWorkScope(true)) { UserFacade userFacade = new UserFacade(); User user = userFacade.GetUserByID(1); user.LastName = "New Last Name"; } </code></pre> <p>What can I do to eliminate the need to constantly write out this using statement throughout my application?</p> <p>Lastly, where would the most appropriate location be to place code like the following?</p> <pre><code>public void ClockIn(string clockNumber) { UserFacade userFacade = new UserFacade(); User user = userFacade.GetUserByClockNumber(clockNumber); if (user == null) throw new InvalidClockNumberException(); TimeEntryFacade timeEntryFacade = new TimeEntryFacade(); TimeEntry lastTimeEntry = timeEntryFacade.GetLastTimeEntry(user.UserID); if (lastTimeEntry.Action == TimeEntryAction.ClockIn) throw new NotClockedOutException(user.UserID); TimeEntry clockIn = new TimeEntry() { TimeEntryID = Guid.NewGuid(), UserID = user.UserID, Time = DateTime.Now, Action = TimeEntryAction.ClockIn }; timeEntryFacade.Add(clockIn); } </code></pre> <p>I currently have this in my UI layer which I realize is a mistake as I should be able to replace my UI without having to disrupt common code like this.</p>
[]
[ { "body": "<p>I like your effort, there is a separation of responsibilities in what you present </p>\n\n<p>Here are my remarks:</p>\n\n<blockquote>\n <p>I am working on an application that will use an N-Tiered approach.</p>\n</blockquote>\n\n<p>While many people use the terms N-Tiered and N-Layered interchangeably, there is a fundamental difference between the two. The former refers to separate services spanning process or host boundaries while the latter refers to the logical seperation in code structure. </p>\n\n<p>Your example looks more like a logical separation than a physical seperation, therefore the term layered would be more appropriate. It would be N-Tiered for example if you deployed your datalayer as a standalone service that would be invoked via remoting or web services. As far as I can see, it is going to live within the same application domain as the caller, invoked via method calls. See <a href=\"http://en.wikipedia.org/wiki/Multilayered_architecture\" rel=\"nofollow\">Multilayered Architechture</a> vs <a href=\"http://en.wikipedia.org/wiki/N-tier\" rel=\"nofollow\">MultiTiered Architecture</a> </p>\n\n<blockquote>\n <p>What can I do to eliminate the need to constantly write out this using statement throughout my application?</p>\n</blockquote>\n\n<p>You could use <a href=\"http://www.codeproject.com/Articles/337564/Aspect-Oriented-Programming-Using-Csharp-and-PostS\" rel=\"nofollow\">Aspect Oriented Programming</a> for such a cross-cutting concern, for example you would create an aspect along the following lines: </p>\n\n<pre><code>[Serializable]\n[MulticastAttributeUsage(MulticastTargets.Method)]\npublic class UnitOfWorkScopeAspect: PostSharp.Aspects.OnMethodBoundaryAspect\n{\n [NonSerialized]\n UnitOfWorkScope _UnitOfWorkScope;\n\n // Invoked at runtime before that target method is invoked.\n public override void OnEntry(PostSharp.Aspects.MethodExecutionArgs args)\n {\n _UnitOfWorkScope = new UnitOfWorkScope(true);\n }\n\n // Invoked at runtime after the target method is invoked (in a finally block).\n public override void OnExit(PostSharp.Aspects.MethodExecutionArgs args)\n {\n _UnitOfWorkScope.Dispose();\n }\n}\n</code></pre>\n\n<p>You then use your newly created Aspect to decorate the methods that should use the unit of work pattern. eg:</p>\n\n<pre><code>[UnitOfWorkScope]\npublic User user CarryOutScopedLogic()\n{\n UserFacade userFacade = new UserFacade();\n User user = userFacade.GetUserByID(1);\n user.LastName = \"New Last Name\";\n return user; \n}\n</code></pre>\n\n<p>You can imagine the above as being replaced with: </p>\n\n<pre><code>OnEntry(); // &lt;- This is where we create a new UnitOfWorkScope\ntry\n{\n // Method body for CarryOutScopedLogic\n OnSuccess();\n}\ncatch ( Exception e )\n{\n OnException();\n}\nfinally\n{\n OnExit(); // &lt;- This is where we dispose our new UnitOfWorkScope\n}\n</code></pre>\n\n<p>This is just a sample using PostSharp, but there are plenty more <a href=\"http://www.codeproject.com/Articles/28387/Rating-of-Open-Source-AOP-Frameworks-in-NET\" rel=\"nofollow\">aop libraries</a> out there.</p>\n\n<p><strong>Some further considerations on the above:</strong> if you need to call many different methods that require their own unit of work logic, you could use a <a href=\"http://msdn.microsoft.com/en-us/library/system.threadstaticattribute.aspx\" rel=\"nofollow\"><code>ThreadStatic</code></a> instance of your UnitOfWorkScope within the aspect and check if it does not already exist then create it as well as keeping track of how many times a UnitOfWork has been entered (UnitOfWorkEntryCount) so that you only dispose of it if the UnitOfWorkEntryCount is zero. </p>\n\n<blockquote>\n <p>where would the most appropriate location be to place code like the following?</p>\n</blockquote>\n\n<pre><code>public void ClockIn(string clockNumber)\n</code></pre>\n\n<p>Your hunch is right, that function shouldn't live side by side a buttonclick event for example. You could split out your UI logic following one flavor of MVP/MVVM or MVC - But even so, for this particular example, such orchestrating logic would live in a business logic class of it's own. </p>\n\n<p>The most likely candidate for this following your architecture would seem to be the <code>EmployeeFacade</code> (or <code>UserFacade</code>) as it is the Employee that clocks in by orchestrating the dependencies accordingly. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-04T20:06:35.963", "Id": "39965", "Score": "0", "body": "I implemented your suggestion and it was just what I was looking for! Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-01T00:10:30.300", "Id": "25668", "ParentId": "25274", "Score": "2" } } ]
{ "AcceptedAnswerId": "25668", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T21:27:26.083", "Id": "25274", "Score": "1", "Tags": [ "c#", "entity-framework" ], "Title": "Feedback and Advice on my N-Tier Application Architecture" }
25274
<p>I want to see if one of two values (a, b) are in an array. Here's my current thought:</p> <pre><code>$match_array = array('a','b'); $array_under_test = array('b', 'd', 'f'); if (array_intersect($match_array, $array_under_test)) { // Success! } </code></pre> <p>Any better implementations?</p>
[]
[ { "body": "<p>If you want to verify that <em>either</em> value is in the <code>$array_under_test</code>, <code>array_intersect</code> may not be the best option. It will continue to test for collisions even after it finds a match. </p>\n\n<p>For two search strings you can just do:</p>\n\n<pre><code>if (in_array('a', $array_under_test) || in_array('b', $array_under_test)) {\n // Success!\n}\n</code></pre>\n\n<p>This will stop searching if <code>'a'</code> is found in the <code>$array_under_test</code>.</p>\n\n<p>For more than two values, you can use a loop:</p>\n\n<pre><code>foreach ($match_array as $value) {\n if (in_array($value, $array_under_test)) {\n // Success!\n break;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T22:26:06.140", "Id": "25280", "ParentId": "25276", "Score": "4" } }, { "body": "<p>In addition to p.w.s.g's answer (which seems fine):</p>\n\n<p>If you have lots of values you need to find, you can use a hash:\n</p>\n\n<pre><code>// the values go into keys of the array\n$needles = array('value1' =&gt; 1, 'value2' =&gt; 1, 'value3' =&gt; 1);\n$haystack = array('test', 'value1', 'etc');\n\n// only go through the array once\n$found = false;\nforeach($haystack as $data) {\n if (isset($needles[$data])) {\n $found = true; break;\n }\n }\n</code></pre>\n\n<p>It's worth doing this if you search $haystack a lot of times.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T06:09:02.023", "Id": "25303", "ParentId": "25276", "Score": "2" } } ]
{ "AcceptedAnswerId": "25280", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T21:42:58.130", "Id": "25276", "Score": "3", "Tags": [ "php", "array" ], "Title": "Best way to check for one of two values in an array in PHP" }
25276
<p>I have a list of plans and a list of contacts, and I have to check whether <code>contact.ProviderId</code> matches <code>plan.ProviderId</code>. If they match I need to store in a <code>contactUI</code> the <code>plan.Name</code>.</p> <p>Provider to plan is a 0..1-to-many relationship, and that's why I couldn't use the <code>Dictionary</code> I tried at first instance.</p> <p>For retrieving the list of object I need to call the DB. So I want to avoid calling it more than needed.</p> <p>I came up with this</p> <pre><code>var offeredPlans = new List&lt;Tuple&lt;int, string&gt;&gt;(); foreach (var plan in plans) { // ....Some code... offeredPlans .Add(new Tuple&lt;int, string&gt;(providerId, plan.Name)); } var compareTo = offeringPlans.ToLookup(pair =&gt; pair.Item1, pair =&gt; pair.Item2); foreach(var contact in contacts) { var plansAttachedTo = Check(providerId.Value, compareTo); foreach (var plan in plansAttachedTo) { // New contactUI with plan.Name as one of its properties } } </code></pre> <p>Being </p> <pre><code>private static IEnumerable&lt;string&gt; Check(int providerId, ILookup&lt;int, string&gt; plans) { return offeringPlans.Where(p =&gt; p.Key == providerId).SelectMany(p =&gt; p); } </code></pre> <p>Is this terrible or does it make sense?</p> <ol> <li>I've never used before these classes (Tuple, Lookup...)</li> <li>I would like my code to be the clearest I can even it it's not the cleverest of the solution I can think of which is not this case for sure, actually I realize now I could have done some kind of SQL joins, right? (but I would like to know if someone can point any obvious error in the current code).</li> </ol> <p><strong>Edit</strong></p> <p>The code inside the loop is this one (in this case I don't even omit code as I'm not sure if it's possible what you suggest p.s.w.g). I am using reflection as only some of the classes that inherit from plan have the ProviderId property.</p> <pre><code>foreach (var plan in plans) { var offeringDetail = new OfferingDetail(); if (plan.GetType() == typeof (OwnedProductSummary)) { var productSummary = plan as OwnedProductSummary; offeringDetail = _offeringBLL.GetById(productSummary.OfferingID); } if (plan.GetType() == typeof (OwnedServiceSummary)) { var serviceSummary = plan as OwnedServiceSummary; offeringDetail = _offeringBLL.GetById(serviceSummary.OfferingID); } // For the other types of summary will be 0 var providerId = offeringDetail.ProviderID; offeredPlans .Add(new Tuple&lt;int, string&gt;(providerId, plan.Name)); } </code></pre>
[]
[ { "body": "<p>Once you've gotten your code into a <code>ILookup</code> you can just call <a href=\"http://msdn.microsoft.com/en-us/library/bb549314.aspx\" rel=\"nofollow\"><code>Item</code></a> property (which in C# is called with <code>[...]</code>) to get all values with a given key. So the <code>Check</code> can be entirely replaced by using the <code>ILookup</code> like this:</p>\n\n<pre><code>ILookup&lt;int, string&gt; plansLookup = ...\nIEnumerable&lt;string&gt; plansForProvider = plansLookup[providerId]; // Finds all plans for this provider\n</code></pre>\n\n<p>However, it's not clear that you need to be creating the <code>List&lt;Tuple&lt;int, string&gt;&gt;</code> in the first place. You can just use Linq to generate your <code>ILookup</code> from scratch:</p>\n\n<pre><code>var plansLookup = \n (from plan in plans\n let productSummary = plan as OwnedProductSummary\n let serviceSummary = plan as OwnedServiceSummary\n let offeringDetail =\n (productSummary != null) ? _offeringBLL.GetById(productSummary.OfferingID) :\n (serviceSummary != null) ? _offeringBLL.GetById(serviceSummary.OfferingID) :\n new OfferingDetail()\n select new \n {\n offeringDetail.ProviderID,\n plan.Name\n })\n .ToLookup(x =&gt; x.ProviderId, x =&gt; x.Name);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T22:24:57.873", "Id": "39148", "Score": "0", "body": "Yes, I pasted the code before checking it as I thought it was relevant. But you're completely right I can create it from scratch" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T22:35:16.637", "Id": "39149", "Score": "0", "body": "Maybe I talked too early in the last comment, I think in this case either it's not possible or it would be a very convoluted expression, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T22:41:05.243", "Id": "39150", "Score": "0", "body": "@mitomed Nah, it's not that bad. See my updated answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T22:59:16.613", "Id": "39152", "Score": "0", "body": "Agreed, apart from a small typo (for instead of from) it works perfectly fine and it's not as terrible as I imagined (fear I had as never got into queries using lets). Thanks very much, I really think you've improved the code a lot" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T22:04:55.107", "Id": "25278", "ParentId": "25277", "Score": "2" } } ]
{ "AcceptedAnswerId": "25278", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T21:47:41.310", "Id": "25277", "Score": "3", "Tags": [ "c#", "lookup" ], "Title": "Tuple/Lookup conundrum" }
25277
<p>I had a code for a layout library which looked like :</p> <pre><code>$this-&gt;layout-&gt;setLayout($layout)-&gt;setTitle($title)-&gt;render() etc. </code></pre> <p>Today I started writing a new code, simpler and smaller :</p> <pre><code>$this-&gt;layout-&gt;data(array( 'view_name' =&gt; 'layout_admin', 'title' =&gt; 'Administration', 'js' =&gt; 'admin/matrix.chat' ))-&gt;view('admin/index'); </code></pre> <p>The previous setters/add methods were like :</p> <pre><code>public function setDoctype($doctype) { $this-&gt;doctype = $doctype; return $this; } public function addJs($name) { if(!in_array($name, $this-&gt;js)) { $this-&gt;js[] = $name; } return $this; } </code></pre> <p>The new data method :</p> <pre><code>public function data($data = array()) { if(isset($data['view_name'])) $this-&gt;ci-&gt;config-&gt;load($data['view_name']); else $this-&gt;ci-&gt;config-&gt;load($this-&gt;data['view_name']); // Mark as forbid because are stored in arrays and // I can add values to those $forbid = array('css', 'js', 'rss'); foreach($this-&gt;ci-&gt;config-&gt;config['layout'] as $key =&gt; $value) { if(isset($data[$key]) &amp;&amp; !in_array($key, $forbid)) $this-&gt;data[$key] = $data[$key]; else $this-&gt;data[$key] = $value; if(isset($data[$key]) &amp;&amp; in_array($key, $forbid)) { if(is_array($data[$key])) { if(count($array) != count($array, COUNT_RECURSIVE)) foreach($data[$key] as $key2 =&gt; $value2) $this-&gt;data[$key][$key2] = $value2; else foreach($data[$key] as $value2) $this-&gt;data[$key][] = $value2; } else $this-&gt;data[$key][] = $data[$key]; } } return $this; } </code></pre> <p>I changed to this because of the many things that I can update for every page. And use ->setThing would be annoying. But I don't find that my code is so OOP.</p> <p>Note that I'm using CodeIgniter.</p> <p>What's the best oop code ? If you want more indications, please tell me I'm new and don't know how to say more ;) .</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T23:48:01.780", "Id": "39154", "Score": "0", "body": "You should add more details, especially code of your layout class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T00:21:45.237", "Id": "39155", "Score": "0", "body": "It is done :) ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T12:16:07.873", "Id": "39183", "Score": "0", "body": "I like ->setThing, because i can use type ahead, also you can easily make a backtrace in the function and you have only backtrace for the manipulations of Thing and not for every other data in your class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-13T16:51:45.180", "Id": "40402", "Score": "0", "body": "Your paths should start with '/', i.e /admin/index. So that they start at the root of the domain (especially if using mod_rewrite)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-17T06:48:28.323", "Id": "62822", "Score": "0", "body": "As John said, it's very effective. It's common practice in many frameworks... and in [Code Igniter itself](http://ellislab.com/codeigniter/user-guide/libraries/pagination.html)!" } ]
[ { "body": "<p>The core of your question is whether or not you should use setters ($tpl->setSomeParam()) or a simple array to bind template parameters. While using an array my not seem very OO, it's actually a pretty effective way of decoupling your data from your templates. As you've discovered, having to add a new setter to your layout manager every time you add a new parameter to one of your templates means the layout manager is tightly coupled to <em>all of your templates</em> – not good.</p>\n\n<p>This is pretty common practice these days. <a href=\"http://twig.sensiolabs.org\" rel=\"nofollow\">Twig</a>, <a href=\"http://underscorejs.org/#template\" rel=\"nofollow\">Underscore.js</a>, and many others do the same thing. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T18:33:22.683", "Id": "26170", "ParentId": "25281", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T22:59:18.750", "Id": "25281", "Score": "4", "Tags": [ "php", "object-oriented" ], "Title": "Best OOP method for a layout library" }
25281
<p><strong>Introduction</strong></p> <p>I'm learning C++ (Coming from Haskell, C, and Assembly - and other languages sparsely) and this was my practice with classes and templates. It's a linked list that you can call in this fashion:</p> <pre><code>#include "list.hpp" int main(void){ linked_list&lt;char&gt; test; char c; while(c != '\n') // test.prepend(c = fgetc(stdin)); std::cout &lt;&lt; test; std::cout &lt;&lt; std::endl; return 0; } </code></pre> <p><strong>Topic</strong></p> <p>I am here to ask if some more experienced coders would point out my mistakes (mainly about classes) so I can break the habits. Thanks for your help!</p> <p>Here is the source code: (Btw, it isn't optimized on purpose, I was only playing with classes/templates)</p> <p>(I do notice the inefficient and potentially dangerous tail() call, but considering the trivial nature of the project - I decided to leave it for later, simply make it a deque. I also naively checked it with memcheck. No leaks and no errors in my library, seemingly.) <strong><a href="http://ideone.com/nEohhY">Ideone Link</a></strong></p> <pre><code>//Compile with "g++ -std=C++11 -O2 -o list main.cpp list.hpp" #ifndef LIST_H #define LIST_H #include &lt;iostream&gt; template &lt;typename T&gt; class linked_list { private: int empty = 1; struct node { T data; struct node * next; } * head; struct node * get_add(int index); public: linked_list(){head = new node;}; linked_list(T data){head = new node; head = data; empty = 0;} ~linked_list(); int size(); inline int nsize(){return sizeof(struct node);}; inline struct node * lhead() {return head;}; inline struct node * tail() {return get_add(size()-1);}; int search(T key); void prepend(T data); void append(T data); int insert(T data, int index); int del(int index); int set(T data, int index); T get(int index); T&amp; operator[](int i); }; template&lt;typename T&gt; std::ostream&amp; operator&lt;&lt; (std::ostream &amp;out, linked_list&lt;T&gt; &amp;list); //////////////IMPLEMENTATION////////////// ////////////////////////////////////////// template &lt;typename T&gt; T&amp; linked_list&lt;T&gt;::operator[](int i){ return (get_add(i)-&gt;data); } template &lt;typename T&gt; std::ostream&amp; operator&lt;&lt; (std::ostream &amp;out, linked_list&lt;T&gt; &amp;list){ int i; for(i = 0; i &lt; list.size(); i++) out &lt;&lt; list.get(i); return out; } template &lt;typename T&gt; int linked_list&lt;T&gt;::size(){ int i; struct node * tmp = head; for(i = 1; tmp-&gt;next != NULL; i++) tmp = tmp-&gt;next; return i; } template &lt;typename T&gt; int linked_list&lt;T&gt;::set(T data, int index){ if(index &gt;= size()) return -1; get_add(index)-&gt;data = data; return data; } template &lt;typename T&gt; void linked_list&lt;T&gt;::prepend(T data){ if(empty){ head-&gt;data = data; empty = 0; } else { struct node * tmp = new node; tmp-&gt;data = head-&gt;data; tmp-&gt;next = head-&gt;next; head-&gt;data = data; head-&gt;next = tmp; } } template &lt;typename T&gt; void linked_list&lt;T&gt;::append(T data){ if(empty){ head-&gt;data = data; empty = 0; } else { struct node * tmp = new node; tmp-&gt;data = data; tmp-&gt;next = NULL; tail()-&gt;next = tmp; } } template &lt;typename T&gt; int linked_list&lt;T&gt;::insert(T data, int index){ if(index &gt;= size()) return -1; if(empty){ head-&gt;data = data; empty = 0; } else { struct node * tmp = new node; struct node * location = get_add(index); struct node * prev = get_add(index-1); tmp-&gt;data = data; tmp-&gt;next = location; prev-&gt;next = tmp; } return 0; } template &lt;typename T&gt; int linked_list&lt;T&gt;::del(int index){ if(index &gt;= size()) return -1; struct node * prev = get_add(index-1); struct node * tmp = prev-&gt;next-&gt;next; delete prev-&gt;next; prev-&gt;next = tmp; return 0; } template &lt;typename T&gt; int linked_list&lt;T&gt;::search(T key){ int i; struct node * tmp = head; for(i = 0; key != tmp-&gt;data; i++) tmp = tmp-&gt;next; return i; } template &lt;typename T&gt; T linked_list&lt;T&gt;::get(int index){ if(index &gt;= size()) return 0; int i; struct node * tmp = head; for(i = 0; tmp-&gt;next != NULL &amp;&amp; i &lt; index; i++) tmp = tmp-&gt;next; return tmp-&gt;data; } template &lt;typename T&gt; struct linked_list&lt;T&gt;::node * linked_list&lt;T&gt;::get_add(int index){ if(index &gt;= size()) return 0; int i = 0; struct node * tmp = head; while(i++ &lt; index) tmp = tmp-&gt;next; return tmp; } template &lt;typename T&gt; linked_list&lt;T&gt;::~linked_list(){ struct node * tmp = head-&gt;next; for(; head-&gt;next != NULL; tmp = head-&gt;next){ head-&gt;next = head-&gt;next-&gt;next; delete tmp; } delete head; } #endif </code></pre> <p>Thanks again.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T10:43:54.937", "Id": "39177", "Score": "1", "body": "In addition to Morwenn's answer, one suggestion is to keep the preprocessor *guards* named consistent with the class (`#ifndef LIST_H`). I'd recommend `#ifndef LINKED_LIST_H` if you don't use namespaces, just to be consistent with the actual template class name." } ]
[ { "body": "<p>This won't be as complete an answer as you often see on Code Review, but here are a few pointers to improve your code:</p>\n\n<pre><code>template &lt;typename T&gt;\nT&amp; linked_list&lt;T&gt;::operator[](int i){\n return (get_add(i)-&gt;data);\n}\n</code></pre>\n\n<p>First of all, you should tell the programmer that your index will never be a negative one. In order to do so, you could change your <code>int</code> parameter to be an <code>unsigned int</code> one. Here, since we are talking about sizes, a <code>size_t</code> or <code>std::size_t</code> parameter would be even better:</p>\n\n<pre><code>template &lt;typename T&gt;\nT&amp; linked_list&lt;T&gt;::operator[](std::size_t i) {\n return get_add(i)-&gt;data;\n}\n</code></pre>\n\n<p>C++ differentiates between functions that change the class members and functions that do not. If your function does not change the member variables, it should be const-qualified. Moreover, this qualification is a part of the function's signature. That means that you can have both the const-qualified version of the function in your class and the normal one:</p>\n\n<pre><code>template &lt;typename T&gt;\nT&amp; linked_list&lt;T&gt;::operator[](std::size_t i) {\n return get_add(i)-&gt;data;\n}\n\ntemplate &lt;typename T&gt;\nconst T&amp; linked_list&lt;T&gt;::operator[](std::size_t i) const {\n return get_add(i)-&gt;data;\n}\n</code></pre>\n\n<p>You can apply my remarks about <code>const</code>-qualified functions to every function that should not change the class (e.g. <code>size</code> and <code>search</code>).</p>\n\n<p>Now, let's talk about this piece of code:</p>\n\n<pre><code>template &lt;typename T&gt;\nstd::ostream&amp; operator&lt;&lt; (std::ostream &amp;out, linked_list&lt;T&gt; &amp;list) { ... }\n</code></pre>\n\n<p>Let's have a look a the function's signature: your parameter is a <code>linked_list&lt;T&gt;&amp;</code>. However, you should specify that this output function will not modify your list by adding a <code>const</code> before the type:</p>\n\n<pre><code>template &lt;typename T&gt;\nstd::ostream&amp; operator&lt;&lt; (std::ostream &amp;out, const linked_list&lt;T&gt; &amp;list) { ... }\n</code></pre>\n\n<p>About <code>for</code> loops in C++:</p>\n\n<pre><code>int i;\nfor(i = 0; i &lt; list.size(); i++)\n out &lt;&lt; list.get(i);\n</code></pre>\n\n<p>In C++, you can use declaration statements in the first part of the <code>for</code>. That means that you don't have to declare your <code>int i</code> <strong>before</strong> the loop. You can declare it inside the <code>for</code>. And that is what should be done, unless you still need the value of <code>i</code> after you leave the loop. You can write it like this:</p>\n\n<pre><code>for(int i = 0; i &lt; list.size(); i++)\n out &lt;&lt; list.get(i);\n</code></pre>\n\n<p>And since your list can not have negative indices, the <code>std::size_t</code> is still welcome:</p>\n\n<pre><code>for(std::size_t i = 0; i &lt; list.size(); i++)\n out &lt;&lt; list.get(i);\n</code></pre>\n\n<p>We will now see this piece of code:</p>\n\n<pre><code>int search(T key);\n</code></pre>\n\n<p>While it is valid, you are passing <code>key</code> by value, which means that if you pass an instance of a big class (if <code>T</code> is a big class), it will be entirely copied before being used. In C++, if we don't need to modify the object passed to a function, it is better to pass it by <code>const</code> reference: it will not change the way you use it, but the compiler will use the address of the instance instead of doing a whole copy. To search, you don't need to modify your key, so it is better to pass by <code>const</code> reference:</p>\n\n<pre><code>int search(const T&amp; key);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T18:21:11.170", "Id": "39186", "Score": "0", "body": "Morwenn, this was exactly what I was hoping to get for an answer. Thanks, I'll mark this question as answered if nobody else answers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T09:21:47.580", "Id": "25290", "ParentId": "25283", "Score": "8" } }, { "body": "<p>Here's a few issues that I noticed:</p>\n\n<ol>\n<li><p>Initialising private member <code>empty</code> is not allowed</p></li>\n<li><p>I would find it more natural to have the <code>head</code> pointer as just a <code>struct node *</code> instead of being a node itself. Then if <code>head</code> is NULL, the list is empty and the <code>empty</code> variable is not necessary.</p></li>\n<li><p>I would prefer <code>get_address</code>, or at least <code>get_addr</code> to <code>get_add</code></p></li>\n<li><p>2nd constructor should say <code>head-&gt;data = data;</code></p></li>\n<li><p><code>nsize</code> better as <code>sizeof(node)</code></p></li>\n<li><p><code>tail</code> fails if list is empty</p></li>\n<li><p>do the method names match those of standartd containers?</p></li>\n<li><p>operator[] fails if list is empty</p></li>\n<li><p>use braces even on single-line blocks (after if, for, etc)</p></li>\n<li><p>declare loop-variabless within loops where possible</p></li>\n<li><p><code>size</code> returns 1 even for an empty list</p></li>\n<li><p><code>set</code> returns <code>int</code> rather than <code>T</code></p></li>\n<li><p>in <code>prepend</code> it would be slightly easier to replace the <code>head</code> pointer with <code>tmp</code></p></li>\n<li><p><code>insert</code> fails if index is zero. It would also be more logical just to search for <code>index-1</code> (if index!=0) instead of searching for both <code>index-1</code> <strong>and</strong> <code>index</code></p></li>\n<li><p><code>del</code> fails if index is zero.</p></li>\n<li><p><code>insert</code> and <code>del</code> might be better returning <code>bool</code> rather than 0/-1</p></li>\n<li><p><code>search</code> should handle an empty list separately</p></li>\n<li><p><code>get</code> could be written using <code>get_add</code></p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-29T07:30:38.783", "Id": "39650", "Score": "0", "body": "1. is no longer true for C++11. This has been introduced as \"non-static data member initializers\"." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T20:50:05.573", "Id": "25296", "ParentId": "25283", "Score": "3" } }, { "body": "<p>A specific note on memory management in particular:</p>\n\n<ul>\n<li>Don't use raw pointers (<code>std::unique_ptr</code> is better -- and then <code>std::shared_ptr</code> but only if you're absolutely sure you need to share) -- e.g., you can express the fact that your list owns the resource by using <code>std::unique_ptr</code>, while raw pointers leave the ownership semantics unexpressed &amp; undocumented (it's best to be as clear as possible when expressing the intent in the code).</li>\n<li>Don't use raw <code>new</code> (right now you're leaking memory if you forget to <code>delete</code> after <code>new</code> -- and this happens all too often in practice) -- prefer <code>make_unique</code> (soon in the standard, for now just Google it) and <code>std::make_shared</code> instead.</li>\n<li>Prefer RAII.</li>\n</ul>\n\n<p>See:<br>\n- <a href=\"http://speakerdeck.com/lichray/resource-management-the-c-plus-plus-way\">http://speakerdeck.com/lichray/resource-management-the-c-plus-plus-way</a><br>\n- <a href=\"http://www.informit.com/articles/article.aspx?p=1944072\">http://www.informit.com/articles/article.aspx?p=1944072</a><br>\n- <a href=\"http://klmr.me/slides/modern-cpp/\">http://klmr.me/slides/modern-cpp/</a><br>\n- <a href=\"http://www.hackcraft.net/raii/\">http://www.hackcraft.net/raii/</a><br>\n- <a href=\"http://www.slideshare.net/adankevich/raii-and-scopeguard\">http://www.slideshare.net/adankevich/raii-and-scopeguard</a> </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T03:27:37.087", "Id": "25721", "ParentId": "25283", "Score": "8" } }, { "body": "<ul>\n<li><p><code>node</code> doesn't have a constructor: this means that every instance you create starts out with a garbage <code>next</code> pointer, which could cause problems (besides, it's just nasty)</p>\n\n<pre><code>struct node {\n T data;\n node *next; // note that node is a type name in C++\n\n // requires that T is default-constructable\n node() : next(NULL) {}\n // requires that T is copy-constructable\n node(T const &amp;source) : data(source), next(NULL) {}\n // requires C++11 and that T is move-constructable\n node(T &amp;&amp;source) : data(std::move(source)), next(NULL) {}\n};\n</code></pre></li>\n<li><p>you <em>always</em> <code>new</code> and then <code>delete</code> your head node, so the indirection doesn't buy you any flexibility (ie, it can never legally be NULL). So, just make it a regular member:</p>\n\n<pre><code>node head; // this is a sentinel-style list head\n</code></pre>\n\n<p>and now you never need to <code>new</code> or <code>delete</code> it. Now it has a default constructor too, you don't need to mention it in your constructors at all</p></li>\n<li><p><code>empty</code> should be type <code>bool</code>, if it can only be <code>true</code> or <code>false</code>. However, we can do without it entirely, since the identity <code>empty == (head.next == NULL)</code> is required to be true. Let's just add</p>\n\n<pre><code>bool empty() const { return head.next == NULL; }\n</code></pre>\n\n<p>and use <code>empty()</code> instead of <code>empty</code> everywhere.</p></li>\n<li><p>conversely, <code>size()</code> is really expensive, so we can replace the member we just saved with <code>int size;</code> and use that instead of the function call</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-02T17:57:10.077", "Id": "25748", "ParentId": "25283", "Score": "5" } } ]
{ "AcceptedAnswerId": "25290", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T01:41:31.040", "Id": "25283", "Score": "7", "Tags": [ "c++", "object-oriented", "c++11", "linked-list", "template" ], "Title": "General advice on a practice linked_list for C++ classes/templates" }
25283
<p><em>The Art and Science of Java</em>, a course book that uses the ACM library, has an exercise that reads like this:</p> <blockquote> <p>Implement a new class called Card that includes the following entries:</p> <p>• Named constants for the four suits (CLUBS, DIAMONDS, HEARTS, SPADES) and the four ranks that are traditionally represented in words (ACE, JACK, QUEEN, KING). The values of the rank constants should be 1, 11, 12, and 13, respectively.</p> <p>• A constructor that takes a rank and a suit and returns a Card with those values. • Accessor methods getRank and getSuit to retrieve the rank and suit components of a card.</p> <p>• An implementation of the toString method that returns the complete name of the card.</p> </blockquote> <p>Now, this question is a little hard to understand, but nevertheless I've done a class that I think answers this:</p> <pre><code>/** Ficheiro: Carta.java * * Classe que vai representar os diferentes valores e naipes de uma carta de um baralho normal * de 52 cartas. Exercício para construir uma classe completa juntamente com construtores, * gets de Valores e Naipes e de método toString. */ public class Carta { // Constantes do Naipe (Rank) das Cartas public static final String AS = "Ás"; public static final String REI = "Rei"; public static final String DAMA = "Dama"; public static final String VALETE = "Valete"; // Constantes do Valor Facial (Suit) das Cartas public static final String COPAS = "Copas"; public static final String PAUS = "Paus"; public static final String OUROS = "Ouros"; public static final String ESPADAS = "Espadas"; /** * Cria uma nova carta de um baralho regular de 52 cartas. * @param valor O valor facial da carta (ex. Ás, Rei, 10...) * @param naipe O naipe da carta */ public Carta (int valor, int naipe) { valorCarta = valor; numNaipe = naipe; } /** * Obtém o valor facial da carta (existem 13 valores faciais) * @return O valor facial da carta em String */ public String getValorCarta() { switch (valorCarta) { case 1: return AS; case 11: return REI; case 12: return DAMA; case 13: return VALETE; default: return "" + valorCarta; } } /** * Obtém o naipe da carta (existem 4 naipes) * @return O naipe da carta em String */ public String getNaipeCarta () { switch (numNaipe) { case 1: return COPAS; case 2: return PAUS; case 3: return OUROS; case 4: return ESPADAS; default: return ("Naipe Inválido"); } } /** * Cria uma representação em String da Carta (Valor e Naipe) * @return Representação em String da Carta (Valor e Naipe) */ public String toString () { return getValorCarta() + " de " + getNaipeCarta(); } // variáveis de instância que registam o Valor e o Naipe da Carta em integers. private int valorCarta; private int numNaipe; } </code></pre> <p>Sorry about the commentaries. I speak Portuguese and I've written the commentaries in that language. I hope the code is easy enough to understand.</p> <p>I want to know if I have written well the class, according to specifications, especially the Public Constants and the Get Methods.</p> <p>I am not sure if they wanted me to make the constants <code>int</code> types instead of <code>String</code>s. Also I didn't assign any parameters to the Get Methods, so they will only give me the rank or suit of a new Card Object. I am not sure if they wanted me to attribute an int param to these methods.</p> <p>As a sidenote, I wrote a short program that demonstrates this class in action, in choosing and displaying a random card (note that the run method is the main method in <code>acm</code> libraries):</p> <pre><code>import acm.program.*; import acm.util.*; public class testeCarta extends ConsoleProgram{ // Escolhe uma carta aleatóriade um baralho de 52 cartas e imprime no ecrã public void run () { println ("Este programa vai seleccionar uma carta aleatória"); Carta cartaAleat = new Carta (rGen.nextInt(1,13),rGen.nextInt(1,4)); println (cartaAleat); } // variável de instància que permite a utilização de gerador de números aleatórios public RandomGenerator rGen = RandomGenerator.getInstance(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T03:52:03.150", "Id": "39158", "Score": "1", "body": "I would think that you did not do it right. I believe they are hinting at using a enum. Because your method accepts 2 integers you could put a suit into a rank and a rank into a suit and Java wouldn't complain. If you used a enum though your types would be checked and that problem is reduced." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T04:12:28.613", "Id": "39159", "Score": "0", "body": "@RobertSnyder The Book where I did this exercise still hasn't made any mention of Enums so I'm pretty sure they aren't meant to be used in this case." } ]
[ { "body": "<h2>Enums</h2>\n\n<p>Java enums have been around for a long time, so it's really a waste <strong>not</strong> to be using them at this point.</p>\n\n<p><em>However</em>, I understand that this may simply be an <em>exercise</em>, to test and build your understanding of Java, one step at a time. If that is the case, (or maybe if the exercises are given in a specific order, and you haven't yet progressed to the Chapter on <code>enums</code>) then maybe you are intended to avoid them. I'll work on that assumption (no enums).</p>\n\n<h2>Representation</h2>\n\n<blockquote>\n <p>Named constants for the four suits (CLUBS, DIAMONDS, HEARTS, SPADES)\n and the four ranks that are traditionally represented in words (ACE,\n JACK, QUEEN, KING).</p>\n</blockquote>\n\n<p>A <em>named constant</em> simply means that in code, your Java can refer to constant values with variable names that are meaningful. It does <strong>not</strong> mean that those constants must be <code>Strings</code>, and usually, they should not be. If you have:</p>\n\n<pre><code>public class Carta {\n\n public static final int REI = 11;\n</code></pre>\n\n<p>then, this code is using a <em>named constant</em>:</p>\n\n<pre><code>int rank = REI;\n</code></pre>\n\n<p>while this code is not:</p>\n\n<pre><code>int rank = 11;\n</code></pre>\n\n<blockquote>\n <p>The values of the rank constants should be 1, 11, 12, and 13, respectively.</p>\n</blockquote>\n\n<p>This clearly is requesting an implementation where the constants are integer types, not <code>String</code> objects:</p>\n\n<pre><code>public static final int AS = 1; // Ace\npublic static final int VALETE = 11; // Jack\npublic static final int DAMA = 12; // Queen\npublic static final int REI = 13; // King\n</code></pre>\n\n<p>(you'll have to double check my values .. I don't speak Portuguese, and I think I recognize the word <em>Rei</em> and <em>Dama</em>, but not the others)</p>\n\n<p>These constants are in addition to the other cards, ranked <code>2</code> through <code>10</code>.</p>\n\n<h2>Specification Terminology</h2>\n\n<blockquote>\n <p>... that are traditionally represented in words </p>\n</blockquote>\n\n<p>This language may be confusing, I understand. When they say \"words\", they're not asking for <code>String</code> constants. They are referring to the fact that, outside of JACK/QUEEN/KING/ACE, the other cards are 2,3,4,5,6,7,8,9,10 ... which are <strong>numbers</strong>.</p>\n\n<h2>Comments</h2>\n\n<p>You have some comments here (again, with my limited understanding of Portuguese), that I believe are backwards:</p>\n\n<pre><code>// Constantes do Naipe (Rank) das Cartas\npublic static final String AS = \"Ás\";\n\n// Constantes do Valor Facial (Suit) das Cartas\npublic static final String COPAS = \"Copas\";\n</code></pre>\n\n<p><code>As</code> (or Ace) is not a <code>Naipe</code>, it is a <code>Valor</code> (value, or rank). Even if the <strong>code</strong> is correct, it's important in software development to make the comments correct, too.</p>\n\n<h2>toString()</h2>\n\n<p>Finally, concerning the specification for <code>toString()</code>, I believe that your existing code satisfies the requirement. But, remember, the constants really should be implemented as integers, not <code>String</code> constants. So, if you rewrite the class to represent values as integers, you'll then need a new method to convert integer values to <code>Strings</code>. </p>\n\n<p>A <code>HashMap&lt;Integer,String&gt;</code> would probably work for that purpose. If you haven't gotten to using <em>generics</em> yet, even an array of strings (<code>String[]</code>) could be used to map <code>int</code> values to <code>String</code>, as long as you keep track of the 0 index, or use the 0 index element as an <code>Invalid</code> value.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T10:26:39.280", "Id": "39173", "Score": "0", "body": "+1 Good job with the Portuguese. It's not easy. I say this because I do speak it myself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T10:30:44.073", "Id": "39174", "Score": "0", "body": "I once worked in an office cube with an Australian guy who talked to his Brazilian wife on the phone all the time :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T11:13:24.967", "Id": "39178", "Score": "0", "body": "@Nate Thank you for you help in understanding the exercise. I see now that it was int all along that they wanted, so I'll atribute those to my Switch Cases (like switch (numNaipe) { case COPAS: return \"Copas\";) and will work from there. Your Portuguese is really admirable... yes I had that comment in Portuguese wrong - it was late and I was getting very sleepy :) - I will also correct it ofc! Thank you very much for your input, I learned something new today!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T09:49:57.680", "Id": "25291", "ParentId": "25285", "Score": "11" } } ]
{ "AcceptedAnswerId": "25291", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T02:15:42.947", "Id": "25285", "Score": "6", "Tags": [ "java", "optimization", "classes", "playing-cards" ], "Title": "Playing Card Class - is this right?" }
25285
<p>I have <a href="http://bl.ocks.org/nkhine/3150901" rel="nofollow">this code</a> and would like to have it reviewed:</p> <pre><code>function thisClient() { "use strict" var self = this var width = 960, height = 500, centered, data this.init = function () { //now.receiveLocation = function(message) { // console.log(message) // // FIXME only push markers depending on the country/adm1 level // self.drawMarker(message) //} self.drawMap() } this.fileExists = function (url) { "use strict" var http = new XMLHttpRequest() http.open('HEAD', url, false) http.send() return http.status != 404 } this.quantize = function (d) { "use strict" return "q" + Math.floor(getCountyNorm(d.id) * 10) + "-9"; } // Map code this.drawMap = function () { "use strict" var map = d3.geo.equirectangular().scale(150) self.path = d3.geo.path().projection(map) self.svg = d3.select("#map").append("svg") .attr("width", "100%") .attr("height", "90%") .attr("viewBox", "0 0 " + width + " " + height) .attr("preserveAspectRatio", "xMidYMid") // Add a transparent rect so that zoomMap works if user clicks on SVG self.svg.append("rect") .attr("class", "background") .attr("width", width) .attr("height", height) .on("click", self.zoomMap) // Add g element to load country paths self.g = self.svg.append("g") .attr("id", "countries") // Load topojson data d3.json("./topo/world.json", function (topology) { self.g.selectAll("path") //.data(topology.features) .data(topojson.object(topology, topology.objects.countries).geometries) .enter().append("path") .attr("d", self.path) .attr("id", function (d) { return d.properties.name }) //.attr("class", data ? self.quantize : null) .on("mouseover", function (d) { d3.select(this) .style("fill", "orange") .append("svg:title") .text(d.properties.name) //self.activateTooltip(d.properties.name) }) .on("mouseout", function (d) { d3.select(this) .style("fill", "#aaa") //self.deactivateTooltip() }) .on("click", self.zoomMap) // Remove Antarctica self.g.select("#Antarctica").remove() }) } // end drawMap this.zoomMap = function (d) { "use strict" var x, y, k if (d &amp;&amp; centered !== d) { var centroid = self.path.centroid(d) x = centroid[0] y = centroid[1] k = 2 centered = d self.loadCountry(d, x, y, k) } else { // zoom out, this happens when user clicks on the same country x = width / 2 y = height / 2 k = 1 self.centered = null // as we zoom out we want to remove the country layer self.svg.selectAll("#country").remove() } self.g.selectAll("path") .classed("active", centered &amp;&amp; function (d) { return d === centered }) self.g.transition() .duration(1000) .delay(100) .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")") .style("stroke-width", 1.5 / k + "px") } // end zoom function this.loadCountry = function (d, x, y, k) { "use strict" // we remove the country self.svg.selectAll("#country").remove() // load country json file var adm1_key = d.id + "_adm1" var adm1_path = "./topo/" + d.id + "_adm1.json" // check to see if country file exists if (!self.fileExists(adm1_path)) { console.log("We couldn't find that country!") } else { console.log("Load country overlay") var country = self.svg.append("g").attr("id", "country") self.countryGroup = self.svg.select("#country") d3.json(adm1_path, function (error, topology) { var regions = topology.objects for (var adm1_key in regions) { var o = regions[adm1_key] } self.countryGroup.selectAll("path") .data(topojson.object(topology, o).geometries) .enter().append("path") .attr("d", self.path) .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")") .attr("id", function (d) { return d.properties.NAME_1 }) .classed("country", true) .attr("class", "country") .style("stroke-width", 1.5 / k + "px") .on("mouseover", function (d) { d3.select(this) .style("fill", "#6C0") .append("svg:title") .text(d.properties.NAME_1) }) .on("mouseout", function (d) { d3.select(this) .style("fill", "#000000") }) .on("click", function (d) { console.log('clicked on country') self.loadProjects() }) }) } // end else } this.loadProjects = function () { console.log('loadProjects') } // end loadProjects this.init() } // end thisClient jQuery(function () { thisClient = new thisClient() }) </code></pre>
[]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li>Because you have <code>use strict</code> on top in <code>function thisClient() {</code>, you do not need it within functions declared within <code>thisClient</code> like <code>this.fileExists</code></li>\n<li>I am all for Spartan coding but variable like <code>d</code> and <code>k</code> have to go</li>\n<li>Using the http method <code>HEAD</code> is cool, I learned something</li>\n<li>Don't keep commented out code</li>\n<li>You do not use semicolons, please use semicolons; what will the neighbors say?</li>\n<li>The lack of semicolons also breaks JsHint</li>\n<li><p>Your aligning is a bit odd in this part:</p>\n\n<pre><code>d3.json(\"./topo/world.json\", function (topology) {\n self.g.selectAll(\"path\")\n //.data(topology.features)\n .data(topojson.object(topology, topology.objects.countries).geometries)\n .enter().append(\"path\")\n .attr(\"d\", self.path)\n .attr(\"id\", function (d) {\n return d.properties.name\n })\n //.attr(\"class\", data ? self.quantize : null)\n .on(\"mouseover\", function (d) {\n d3.select(this)\n .style(\"fill\", \"orange\")\n .append(\"svg:title\")\n .text(d.properties.name)\n //self.activateTooltip(d.properties.name)\n })\n .on(\"mouseout\", function (d) {\n d3.select(this)\n .style(\"fill\", \"#aaa\")\n //self.deactivateTooltip()\n })\n .on(\"click\", self.zoomMap)\n</code></pre>\n\n<p>I would put the <code>.on</code> next tothe <code>})</code>:</p>\n\n<pre><code>d3.json(\"./topo/world.json\", function (topology) {\n self.g.selectAll(\"path\")\n .data(topojson.object(topology, topology.objects.countries).geometries)\n .enter().append(\"path\")\n .attr(\"d\", self.path)\n .attr(\"id\", function (d) {\n return d.properties.name\n }).on(\"mouseover\", function (d) {\n d3.select(this)\n .style(\"fill\", \"orange\")\n .append(\"svg:title\")\n .text(d.properties.name)\n //self.activateTooltip(d.properties.name)\n }).on(\"mouseout\", function (d) {\n d3.select(this)\n .style(\"fill\", \"#aaa\")\n //self.deactivateTooltip()\n }).on(\"click\", self.zoomMap)\n</code></pre></li>\n<li>It is kind of evil to create a constructor and then replace it with an instance of it self, you cant possibly name that variable correctly ;)</li>\n<li>Please do not use <code>console.log</code> in production code</li>\n<li>You should assign color constants <code>.style(\"fill\", \"#6C0\")</code> to properly named variables, somewhere on the top</li>\n<li><p>There must be better ways than this to get the last <code>adm1_key</code>:</p>\n\n<pre><code>for (var adm1_key in regions) {\n var o = regions[adm1_key]\n}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-21T13:13:42.530", "Id": "44969", "ParentId": "25289", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T07:00:50.300", "Id": "25289", "Score": "2", "Tags": [ "javascript", "jquery", "svg", "d3.js" ], "Title": "D3.js zoomable map" }
25289
<p>I've written a simple numeric menu which displays in the console. When the user types in '1', something happens. When the user hits ENTER, I clear the whole output except for the menu itself. When the user types in '5', the program ends.</p> <p>However, the code got ugly. It's full of <code>cin.get()</code>s, <code>cout</code>s, and other stuff.</p> <pre><code>int main() { using namespace std; node *root = NULL; char ch = '0'; while(ch != '5') { cout &lt;&lt; "1. Add new elements\n" "2. Display info about the tree\n" "3. Remove nodes\n" "4. Export to file\n" "5. Exit\n"; cin &gt;&gt; ch; cin.get(); switch(ch) { case '1': case '3': { vector&lt;int&gt; numbers; string line; cout &lt;&lt; "\nProvide numbers divided with spaces: "; getline(cin, line); istringstream in(line, istringstream::in); int current; while (in &gt;&gt; current) numbers.push_back(current); (ch == '1') ? insert(root, numbers) : remove(root, numbers); cout &lt;&lt; "\nClick to return to menu"; cin.get(); break; } case '2': { displayTreeInfo(root, cout); cout &lt;&lt; "\n\nClick to return to menu"; cin.get(); break; } case '4': { string name; cout &lt;&lt; "Provide filename: "; cin &gt;&gt; name; buildTree(root, loadNumbersFromFile(name)); exportTreeToFile(root, name); std::cout &lt;&lt; "\nData has been exported.\n\n"; cin.get(); cin.get(); break; } } system("cls"); } exit(EXIT_SUCCESS); } </code></pre> <p>How could I improve this code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T19:05:17.497", "Id": "39188", "Score": "0", "body": "Have you compiled this code yourself before? I'm doing it now, and it already says that node is undeclared (obvious when just looking at it, too). Also, why is `using namespace std` inside of `main`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T19:14:33.860", "Id": "39189", "Score": "0", "body": "Okay, assuming this is not the entire program (though it would be nice to see all of it), I'll see what can be cleaned here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T19:15:09.410", "Id": "39190", "Score": "0", "body": "This is only part of the code. Rest of it, structure (node), functions etc. looks o.k. for me, so I didn't post it. According to the using namespace std inside of main - I've heard it's a good practice to place it there instead of at the top of the program. Isn't it true?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T19:17:53.357", "Id": "39191", "Score": "0", "body": "Thank you, I'm waiting for your suggestions. If you want to see the whole code, I can post it on ideone, here - http://ideone.com/gCcGlv. It compiles and works in VS 2012, though ideone shows a couple of errors (maybe I chose wrong c++ standard from the list, I don't know)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T19:18:25.530", "Id": "39192", "Score": "0", "body": "I haven't heard that before, but I do know that it itself isn't good practice. Read this post for more information: http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-a-bad-practice-in-c. Beyond that, thanks for the clarification. I'll proceed, but I'll ignore the node things in your code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T19:19:30.067", "Id": "39193", "Score": "0", "body": "Ok. Also, console output and comments are in polish, but the rest of the code is in english, so I hope everything will be clear enough." } ]
[ { "body": "<ul>\n<li><p><strong><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>Using namespace std</code></a></strong>: I've already mentioned this in the comments. Although it's not a huge deal for small programs such as this, it's still not a good habit to develop.</p></li>\n<li><p><strong><code>While</code> loop</strong>: Put <code>std::cin &lt;&lt; ch</code> both before the loop and after the <code>switch</code>. You could also change the loop condition to</p>\n\n<pre><code>(ch == '1' || ch == '2' || ch == '3' || ch == '4')\n</code></pre>\n\n<p>if you really want to make sure that the program will only proceed with a valid input. Other than that, your original condition is okay.</p></li>\n<li><p><strong><code>std::cin</code></strong>: You don't need <code>std::cin.get()</code> alongside <code>std::cin &gt;&gt;</code>. Just use <code>std::cin &gt;&gt;</code> for <code>char</code> inputs. However, you'll need a <code>std::cin.ignore()</code> before each <code>getline</code> since you're doing a <code>char</code> input (menu prompt) before a <code>std::string</code> input in your cases. For <code>case</code> 4, keep a consistent <code>getline</code> for the filename input and put an <code>ignore</code> before it.</p>\n\n<p>Also, you don't need any <code>cin</code>s after your cases since your <code>while loop</code> will always ask for an input for <code>ch</code>. I do see what you're doing with your outputs in your cases, but you don't need to do that. Just let your cases do their things and go straight to the menu and/or prompt again.</p></li>\n<li><p><strong>Filename input</strong>: You should provide validation for the filename input. If the user enters in invalid filename, what should happen? Consider implementing a loop asking the user for a valid filename as long as such file cannot be opened. With the provided code here, it's a bit tough for me to give a piece of example code for that.</p></li>\n<li><p><strong>Functions</strong>: You could nicely organize your <code>switch</code> statements by putting the body code into functions. Just name them as they appear in your menu. Call each one in your respective cases, along with the breaks. Also, it might be better to have separate procedures for add/remove.</p></li>\n<li><p><strong>Exit</strong>: You don't really need <code>exit(EXIT_SUCCESS)</code> here if the program will always terminate successfully. You also don't need <code>system(\"cls\")</code>, so just leave it out. If you're doing that just to prevent the menu from appearing before each prompt, just pt it before the <code>while</code> loop.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T20:20:21.110", "Id": "39198", "Score": "0", "body": "You're welcome. I did leave out something, so I'll add it in. If you're still curious about the filename input validation, you can always request an idea on Stack Overflow." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T19:31:17.393", "Id": "25294", "ParentId": "25293", "Score": "2" } } ]
{ "AcceptedAnswerId": "25294", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T18:39:24.157", "Id": "25293", "Score": "4", "Tags": [ "c++", "console" ], "Title": "Input stream for console menu" }
25293
<p>This is my first COBOL program, and I'd like to get a critique as I am unfamiliar with best practices.</p> <p>Particularly, I'd like to know how to get the input and output to be more elegant and less dependent on how the file fields are structured.</p> <p>Some type of analogy to C's <code>scanf()</code>, <code>getch()</code>, or any of the Java console IO routines would be helpful.</p> <p><a href="https://gist.github.com/anonymous/5427201" rel="noreferrer">https://gist.github.com/anonymous/5427201</a></p> <pre><code> DATA DIVISION. WORKING-STORAGE SECTION. 01 TIME-STORAGE. 03 CURRENT-TIME-NUMERIC PIC 9(8). 03 ETA-NUMERIC PIC 9(8) REDEFINES CURRENT-TIME-NUMERIC. 03 CURRENT-TIME REDEFINES CURRENT-TIME-NUMERIC. 05 CURRENTHOUR PIC 99. 05 CURRENTMINUTE PIC 99. 05 FILLER PIC 9(4). 03 ARIVAL-TIME-NUMERIC PIC 9(8). 03 ARIVAL-TIME REDEFINES ARIVAL-TIME-NUMERIC. 05 ARRIVALHOUR PIC 99. 05 ARRIVALMINUTE PIC 99. 05 FILLER PIC 9(4). PROCEDURE DIVISION. BEGIN-BUG-NORMAN. DISPLAY "when will you be ariving?" DISPLAY "HH [enter]" ACCEPT ARRIVALHOUR DISPLAY "MM [enter]" ACCEPT ARRIVALMINUTE ACCEPT CURRENT-TIME FROM TIME. SUBTRACT ARIVAL-TIME-NUMERIC FROM CURRENT-TIME-NUMERIC GIVING ETA-NUMERIC. DISPLAY "RESULTING ETA:" DISPLAY ETA-NUMERIC. DISPLAY "HOURS:" DISPLAY CURRENTHOUR DISPLAY "MINUTES:" DISPLAY CURRENTMINUTE STOP RUN. </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T21:27:45.780", "Id": "39200", "Score": "3", "body": "Might be nice for privileged user to create a COBOL tag." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T21:06:17.377", "Id": "58466", "Score": "2", "body": "Wow I thought I'd never see *actual COBOL code* - that's what sent mankind to the moon right? If it's any consolation, I don't think there's a lot of people [alive] familiar with COBOL best-practices :) (no offense intended at any *actual* COBOL programmer out there!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T21:11:11.283", "Id": "58467", "Score": "5", "body": "@retailcoder See http://www.exit109.com/~ghealton/y2k/y2k_humor/Cobol.html and weep." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T21:33:13.163", "Id": "58472", "Score": "0", "body": "@retailcoder: http://stackoverflow.com/questions/tagged/cobol" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T23:00:58.073", "Id": "58485", "Score": "3", "body": "I've had to work with COBOL in school last year. I'm still having nightmares" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T14:37:56.010", "Id": "64348", "Score": "0", "body": "Has anyone looked at COBOL on Wheelchair? It's like Ruby on Rails for the masochistic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-14T07:15:21.687", "Id": "259236", "Score": "0", "body": "@Mat'sMug Do not underestimate COBOL, it is very likely that your bank account and your credit card are handled by COBOL programs! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T16:23:50.133", "Id": "528451", "Score": "0", "body": "The `DATA DIVISION.` should start at column 8 to 11" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T16:24:54.420", "Id": "528453", "Score": "0", "body": "What if the person will arrive past midnight?" } ]
[ { "body": "<p>While the code is crisp and clean (COBOL always is .... ;-) ) I see some logic flaws in your computations.</p>\n\n<p>Specifically, consider the current time <code>14450000</code> (2:45pm) and the user enters <code>15</code> for [HH] and <code>15</code> for [MM] as his ETA (3:15pm)</p>\n\n<p>Your subtract will store the difference between <code>14450000</code> and <code>15150000</code>. The difference stored in <code>ETA-NUMERIC</code> will be <code>00700000</code>, and the code will display <code>HOURS:00</code> and <code>MINUTES:70</code>, but, we know that there's only 30 minutes between them.</p>\n\n<p>The code does not take in to account that minutes are base-60.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T14:35:51.140", "Id": "64346", "Score": "0", "body": "Thanks for pointing out the error in logic. I haven't been able to find an equivalent to jodatime for cobol yet. The company had a bunch of internal date handling code, but it was a bit over my head to try and understand. All the libraries I found that might have worked won't compile with the flags we are forced to use." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T21:20:23.417", "Id": "35880", "ParentId": "25295", "Score": "10" } }, { "body": "<p>A couple of things I noticed:</p>\n\n<ol>\n<li>No Identification Division. \"The <code>IDENTIFICATION DIVISION</code> has <em>no</em> effect on the execution of the program but is, nevertheless, <em>required</em> as a means of identifying the program to the computer\" - Stern &amp; Stern</li>\n<li>There is no real reason for the first <code>REDEFINES</code>. Also, you seem to be using it wrong. A redefines clause is simply another way to reference the same working storage location. If you want to store different data, that will require different variables. While you can keep redefining the same variable and using it in different way, it can get messy and storing things gets harder.</li>\n<li>While you can have level 3 variables, I have found it to be best practice to go up in increments of 5</li>\n<li>A lot of the time, if you are working in a real COBOL environment, you will need an environment division. Clearly here you don't, but keep that in mind</li>\n<li>You should start all variable names in the <code>WORKING-STORAGE SECTION</code> with <code>WS-</code> because if this program need to interact with any other programs, you will have a <code>LINKAGE-SECTION</code> with its own set of variables.</li>\n<li>Only use periods to end paragraphs. Technically, you can use a period to end anything. This leads to messy code. Also, a period closes ALL open statements. If you have a triple nested <code>IF</code> and you end with one period, it will close all 3. When you get to that point, use the proper scoop terminators such as <code>END-IF</code> and <code>END-PERFORM</code></li>\n<li>Spacing is important as well.</li>\n</ol>\n\n<p>The logic problems have already been address in another answer, so I will not address that here. I have included the code below with my suggestions added to it:</p>\n\n<pre><code> INDENTIFICATION DIVISION\n PROGRAM-ID. THE-TIMER.\n AUTHOR. name.\n DATE-WRITTEN. date.\n DATE-COMPILED. date.\n *****************************************************************\n *header comment about the program change logs ect *\n *****************************************************************\n\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n\n 01 TIME-STORAGE.\n 05 WS-CURRENT-TIME PIC 9(8).\n 10 WS-CURRENTHOUR PIC 99.\n 10 WS-CURRENTMINUTE PIC 99.\n 10 WS-FILLER PIC 9(4).\n\n 05 WS-ARIVAL-TIME PIC 9(8).\n 10 WS-ARRIVALHOUR PIC 99.\n 10 WS-ARRIVALMINUTE PIC 99.\n 10 WS-FILLER PIC 9(4).\n\n 05 WS-ETA PIC 9(8).\n 10 WS-ETAHOUR PIC 99.\n 10 WS-ETAMINUTE PIC 99.\n 10 WS-FILLER PIC 9(4).\n\n\n PROCEDURE DIVISION.\n\n BEGIN-BUG-NORMAN.\n\n DISPLAY \"when will you be ariving?\"\n DISPLAY \"HH [enter]\"\n ACCEPT WS-ARRIVALHOUR\n DISPLAY \"MM [enter]\"\n ACCEPT WS-ARRIVALMINUTE\n\n ACCEPT WS-CURRENT-TIME FROM TIME\n SUBTRACT WS-ARIVAL-TIME \n FROM WS-CURRENT-TIME\n GIVING WS-ETA\n\n DISPLAY \"RESULTING ETA: \"\n DISPLAY ETA-NUMERIC\n DISPLAY \"HOURS: \"\n DISPLAY CURRENTHOUR\n DISPLAY \"MINUTES: \"\n DISPLAY CURRENTMINUTE\n\n IF WS-ETAHOUR &gt; 5\n DISPLAY \" It could be a while\"\n END-IF\n\n STOP RUN.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-03T13:39:50.073", "Id": "64145", "Score": "10", "body": "Oh, no!!! Someone who actually **knows** COBOL instead of just can read it! (nice answer, BTW)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-03T13:59:07.517", "Id": "64149", "Score": "1", "body": "Thanks! I am new a new poster to codereview and stackoverflow but a long time reader. I just want to give back!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-03T14:01:56.887", "Id": "64150", "Score": "0", "body": "Can anyone tell me why my codeblock wont indent?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-03T14:22:18.050", "Id": "64153", "Score": "2", "body": "I am not sure why the indent on the PROCEDURE DIVISION was wrong (it was wrong in the raw text, not the markup), but, I added additional spaces. I have the code now aligned on column 12." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T14:36:50.253", "Id": "64347", "Score": "0", "body": "Any particular rhyme or reason for when you put double newlines in? The codebase I was working on seemed to be completely missing them so I just did the same.\n\nSomething about compiler efficacy." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-06T11:57:13.523", "Id": "64547", "Score": "0", "body": "I am not sure what you mean by double newlines, do you mean why do I the Header information in the IDENTIFICATION DIVISION and in a header comment?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T11:46:24.723", "Id": "64864", "Score": "0", "body": "I mean literally hitting enter twice to make empty lines as visual breaks in the code. I saw a 30k line file in the code-base that basically had none." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-08T12:21:46.270", "Id": "64865", "Score": "1", "body": "It could affect the initial compile, but thats it. When you compile, that compiled code is stored in a load library to be run by either a JCL or to be invoked by CICS. I personally add them as do my collegues because readability is dramatically increased. I have also seen people comment out those lines. In my opinion the readability of the code is more important than the inital compile time." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-01-03T12:47:24.493", "Id": "38495", "ParentId": "25295", "Score": "19" } }, { "body": "<p>For the most part, you are assuming valid numeric values, nothing will get you a s0c7 faster. In laymans terms, an system completion code 0C7 aka s0c7. It means 'attempting to perform numeric operations on non numeric data.' BTW, if the user enters a space thinking that means zero, bam, s0c7.</p>\n\n<p>So best practices is to add a 'If WS-CURRENTHOUR is numeric then ....'</p>\n\n<p>of course you may want to combine many checks, but that makes meaningful error message more difficult.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-03T18:42:59.380", "Id": "38527", "ParentId": "25295", "Score": "6" } }, { "body": "<p>Searching for \"Best Practices\" is commendable and should benefit you.</p>\n\n<p>However, don't expect agreement, even after 50+ years, of what is and isn't \"Best Practice\".</p>\n\n<p>That aside, you should have a set of \"local standards\" for your site. These you should adhere it, as should others there. If they contain dumb things, try to get them discussed, but go with the consensus after that. If everyone has the best chance of understanding the code that everyone else writes, things will be better. Traditionally COBOL systems are team efforts, so understanding other people's code, and making yours understandable, is very important.</p>\n\n<p>Sometimes the local standards are not what many would describe as best practice. They may have been at least good practice at some time in the past, but local standards change slowly.</p>\n\n<p>You ask in a comment about blank lines. Perhaps 40 years ago (less depending on hardware at a particular site) not having blank lines would make sense. Each blank line would be a punched-card. Each card takes some time to read. Each card may become faulty and jam the reader, or be rejected.</p>\n\n<p>Even slightly after that sort of time, CPUs weren't anywhere near as fast as they are today. So reading a blank line just for the compiler to ignore would have some effect on compiler throughput for large programs, and with perhaps one address-space only dedicated to compiles and running 24-hours-a-day, little things add up.</p>\n\n<p>Today, don't worry about it at all. Make your program readable for a human. The compiler will always manage, it is us who needs help in reading programs, so give it to us.</p>\n\n<pre><code>A. MOVE B TO C. PERFORM D. D. MOVE E TO F. PERFORM I. I. MOVE Z TO Q.\n</code></pre>\n\n<p>That's \"valid\" COBOL. Theoretically faster to compile than coding eight separate lines (even without blank lines), but work out how much longer it takes a human to understand what is happening.</p>\n\n<pre><code>NEW-CLIENT-RECORD.\n\n [all the stuff you need to do for establishing a new client record]\n\n PERFORM NEW-CLIENT-SUB-RECORD\n .\nNEW-CLIENT-SUB-RECORD.\n\n [all the stuff you need to do ...]\n\n PERFORM CLIENT-COMPLIANCE-VERIFICATION\n .\n\nCLIENT-COMPLIANCE-VERIFICATION.\n\n [all the stuff you need to do ...]\n .\n</code></pre>\n\n<p>Do not try to \"save storage\" by using REDEFINES. Define separate fields, and avoid the \"side effect\" headaches, either when you write the code, or when someone (perhaps you) throws in a careless change in two months time.</p>\n\n<p>Use good names for everything. Ditch any idea of VAR1 or I, J, K.</p>\n\n<pre><code>IF VAR1(J)&gt;7\n MOVE \"Y\" TO VAR4\nEND-IF\n</code></pre>\n\n<p>Would you prefer debugging that, or writing this:</p>\n\n<pre><code>IF CT-OF-APPLES-IN-STOCK ( WAREHOUSE-STOCKED-IN )\n GREATER THAN MAX-CT-FOR-PERISHABLES-TYPE-P014 [which has a value of 7]\n SET OVERSTOCKED-ORANGES TO TRUE\nEND-IF\n</code></pre>\n\n<p>In fact, look, you can't even write that about the oranges, can you? Whilst writing, you can even ask yourself (and look at the spec, ask the analyst/designer/business-user) should that be the \"count\" of the apples, or something like \"box\" or \"pallet\" or whatever, because apples in a warehouse aren't usually stored singly.</p>\n\n<p>Try to get anything useful out of the VAR1/I rubbish and you'll spend a lot of time tracking down what a field holds, and what it means.</p>\n\n<p>Make your programs readable. Do nothing to make things obscure. Follow local standards.</p>\n\n<p>Read the manuals. Read other people's code. Experiment. Think about what people suggest, and what benefit it gives you.</p>\n\n<p>For instance, you will find WS01-data-name, WS02-data-name etc. The W is useful, the rest is nonsense which will cause frustration when defining data. Without renaming everything, it will not be possible to include new data in a group of existing data it is related to. You will find local standards dictating such things. Try to get those changed, but go with the flow if you fail (write some macros/scripts to do the work for you, of course).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T19:30:26.173", "Id": "68504", "Score": "0", "body": "I didn't even think of the fact that it may have started out on punch cards. Other than that, it did seem to be a lot of the really old code had to work within the limitations of the time.\n\nuo;" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T19:40:07.280", "Id": "68506", "Score": "0", "body": "Sadly, even the new development stuff was still being written with those limitations. I ended up burning out on all the COBOL that I had to deal with. But I did get to learn about all sorts of programming anti-patterns.\n\nI think I would have enjoyed working on code like your second example. My biggest problem was that there were no real standards to follow and there wasn't any push to make it happen from anyone.\n\nI came into it thinking that the stuff you mention should be par for the course in most programming languages, but I don't think that is the case anymore." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T22:01:56.443", "Id": "68516", "Score": "1", "body": "@Ape-inago I sympathise. It is a language which can be used well, or badly. Many who use it badly, think they use it well." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T00:00:10.613", "Id": "40411", "ParentId": "25295", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T20:08:11.767", "Id": "25295", "Score": "22", "Tags": [ "beginner", "datetime", "cobol" ], "Title": "Current and estimated arrival times" }
25295
<p>I have a block of code that pulls the current menu position and compares it to what users selected, if the selection is different the database is updated with the new selection. As I am still new with EF I was hoping for a general code review for suggestions on a possible better, more efficient, and/or easier way to code this. Here is my existing code:</p> <pre><code>using (var db = new SectionInfoAdmin()) { var dtCategories = (from n in db.Navigation where n.SectionID == SectionID select new { n.Category }).ToList(); string PrimaryCategory = dtCategories[0].Category.ToString(); if (ddlPrimaryCategory.SelectedValue != PrimaryCategory) { var Category = (from n in db.Navigation where n.Category == PrimaryCategory &amp;&amp; n.SectionID == SectionID select n).First(); Category.Category = PrimaryCategory; } if (dtCategories.Count &gt; 1) { string SecondaryCategory = dtCategories[1].Category.ToString(); if (ddlSecondaryCategory.SelectedValue == SecondaryCategory) { var Category = (from n in db.Navigation where n.Category == SecondaryCategory &amp;&amp; n.SectionID == SectionID select n).First(); Category.Category = SecondaryCategory; } } db.SaveChanges(); lblResults.Text = "Information updated."; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T23:12:44.703", "Id": "39206", "Score": "2", "body": "Let me throw something at you: why only save if there is a difference? Why not just save anyway? Unless you have database congestion (table locking etc) then a database access is cheap (EF generates efficient code), and this way you avoid complexity. Some would say *\"but why hit the database if you don't have to?\"*. The answer is *\"Why not - especially if the decision to do so is computationally expensive, risky, or just unnecessary\"*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T00:02:29.337", "Id": "39207", "Score": "0", "body": "I am used to working directly against the DB and keep forgeting EF is more effeciant in the way it generates it code. Also did not know about codereview site, will keep that in mide for the feature." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T01:46:06.257", "Id": "39209", "Score": "0", "body": "I would start by splitting common code into methods. For example your Linq to get your category could be moved into it's own method." } ]
[ { "body": "<p>As @dreza mentioned, you might want to move the code around your LINQ-Statements to a method.</p>\n\n<pre><code>public void changeCategoryTo(String newCategory){\n var record = (from n in db.Navigation where n.Category == newCategory\n &amp;&amp; n.SectionId == SectionID select n).First();\n record.Category = newCategory;\n}\n</code></pre>\n\n<p>this greatly reduces duplication. </p>\n\n<p>further points:</p>\n\n<ol>\n<li><p>Try to stick to either camelCase or MixedCase to have consistent and speaking variable names:</p>\n\n<ul>\n<li>something like <code>var Category</code>, <code>String PrimaryCategory</code> and similar are diffifult to associate to clear roles in your code.</li>\n<li>try to refrain from naming your variables after their type only, this leads to greatly increased effort when handling multiple objects of the same type.</li>\n</ul></li>\n<li><p>Your if-statement for updating the <code>SecondaryCategory</code> is different from the if-statement for updating <code>PrimaryCategory</code></p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T08:31:48.160", "Id": "42938", "ParentId": "25299", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-19T23:01:44.260", "Id": "25299", "Score": "5", "Tags": [ "c#", "asp.net" ], "Title": "Sugestion on a better way to code this EF update?" }
25299
<p>I just finished a program that is a simple Swing GUI. It takes in user info, such as password and username, turns them into strings, and puts them in a text file called nuserInfo.txt.</p> <p>I just want corrections on how the code works and what I can do to improve my saving, GUI, and code in general. I'll post all the code below (just one class). Feel free to make any remarks, comments, criticism, or ask any questions in the comments below. </p> <p><code>CreateAccount</code> class:</p> <pre><code>package passwordProgram; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.UIManager; public class CreateAccount implements ActionListener { JFrame frame; JPanel panel; JTextField username; JPasswordField password; JPasswordField confirmPassword; JLabel warningLabel; public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } CreateAccount window = new CreateAccount(); window.go(); } public void go() { frame = new JFrame("Create a new account"); panel = new JPanel(); panel.setLayout(new GridBagLayout()); frame.getContentPane().add(BorderLayout.CENTER, panel); panel.setBackground(Color.ORANGE); JLabel userLabel = new JLabel("Username:"); JLabel passwordLabel = new JLabel("Password:"); JLabel confirmPasswordLabel = new JLabel("Confirm Password:"); username = new JTextField(15); password = new JPasswordField(15); confirmPassword = new JPasswordField(15); GridBagConstraints right = new GridBagConstraints(); right.anchor = GridBagConstraints.WEST; GridBagConstraints left = new GridBagConstraints(); left.anchor = GridBagConstraints.EAST; right.weightx = (int) 2; right.fill = GridBagConstraints.REMAINDER; right.gridwidth = GridBagConstraints.REMAINDER; // actual GUI panel.add(userLabel, left); panel.add(username, right); panel.add(passwordLabel, left); panel.add(password, right); panel.add(confirmPasswordLabel, left); panel.add(confirmPassword, right); frame.setSize(300, 250); frame.setVisible(true); JButton createAccount = new JButton("Create this account"); frame.getContentPane().add(BorderLayout.SOUTH, createAccount); createAccount.addActionListener(this); warningLabel = new JLabel(); frame.getContentPane().add(BorderLayout.NORTH, warningLabel); } // This is where the problem is! public void actionPerformed(ActionEvent event) { if (!(Arrays.equals(password.getPassword(), confirmPassword.getPassword()))) { warningLabel.setText("Your passwords do not match! Please try again."); } else if (password.getPassword().length &lt; 1) { warningLabel.setText("That password is not long enough! Please try again!"); } else { try { FileWriter writer = new FileWriter(new File("nuserInfo.txt")); writer.write(username.getText() + "/" + password.toString()); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } </code></pre>
[]
[ { "body": "<ul>\n<li><p>I put your Swing components on the Event Dispatch thread (EDT) in the main method.</p></li>\n<li><p>I rearranged your Swing component definitions in the go method to group like things together. I made sure that the JFrame setVisible method was the last method called in the go method. I added a call to the JFrame setDefaultCloseOperation so that when you closed the GUI, your application would exit.</p></li>\n<li><p>Your password field returns a character array. I had to look up how to do it, but you have to convert the character array to a String to write it to a file.</p></li>\n<li><p>I added the BufferedWriter to your actionPerformed method.</p></li>\n</ul>\n\n<p>.</p>\n\n<pre><code>package passwordProgram;\n\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.GridBagConstraints;\nimport java.awt.GridBagLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.Arrays;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JPasswordField;\nimport javax.swing.JTextField;\nimport javax.swing.SwingUtilities;\nimport javax.swing.UIManager;\n\npublic class CreateAccount implements ActionListener {\n\n JFrame frame;\n JPanel panel;\n JTextField username;\n JPasswordField password;\n JPasswordField confirmPassword;\n JLabel warningLabel;\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n try {\n UIManager.setLookAndFeel(UIManager\n .getSystemLookAndFeelClassName());\n } catch (Exception e) {\n e.printStackTrace();\n }\n CreateAccount window = new CreateAccount();\n window.go();\n }\n });\n }\n\n public void go() {\n panel = new JPanel();\n panel.setLayout(new GridBagLayout());\n panel.setBackground(Color.ORANGE);\n\n frame = new JFrame(\"Create a new account\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.getContentPane().add(BorderLayout.CENTER, panel);\n\n JLabel userLabel = new JLabel(\"Username:\");\n JLabel passwordLabel = new JLabel(\"Password:\");\n JLabel confirmPasswordLabel = new JLabel(\"Confirm Password:\");\n username = new JTextField(15);\n password = new JPasswordField(15);\n confirmPassword = new JPasswordField(15);\n\n GridBagConstraints right = new GridBagConstraints();\n right.anchor = GridBagConstraints.WEST;\n GridBagConstraints left = new GridBagConstraints();\n left.anchor = GridBagConstraints.EAST;\n\n right.weightx = (int) 2;\n right.fill = GridBagConstraints.REMAINDER;\n right.gridwidth = GridBagConstraints.REMAINDER;\n // actual GUI\n\n panel.add(userLabel, left);\n panel.add(username, right);\n panel.add(passwordLabel, left);\n panel.add(password, right);\n panel.add(confirmPasswordLabel, left);\n panel.add(confirmPassword, right);\n\n JButton createAccount = new JButton(\"Create this account\");\n frame.getContentPane().add(BorderLayout.SOUTH, createAccount);\n createAccount.addActionListener(this);\n\n warningLabel = new JLabel();\n frame.getContentPane().add(BorderLayout.NORTH, warningLabel);\n\n frame.setSize(300, 250);\n frame.setVisible(true);\n }\n\n // This is where the problem is!\n public void actionPerformed(ActionEvent event) {\n if (!(Arrays.equals(password.getPassword(),\n confirmPassword.getPassword()))) {\n warningLabel\n .setText(\"Your passwords do not match! Please try again.\");\n } else if (password.getPassword().length &lt; 1) {\n warningLabel\n .setText(\"That password is not long enough! Please try again!\");\n } else {\n try {\n BufferedWriter writer = new BufferedWriter(new FileWriter(\n \"nuserInfo.txt\"));\n writer.write(username.getText() + \"/\"\n + new String(password.getPassword()));\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T17:46:25.587", "Id": "25383", "ParentId": "25300", "Score": "3" } } ]
{ "AcceptedAnswerId": "25383", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T01:44:04.407", "Id": "25300", "Score": "3", "Tags": [ "java", "swing", "gui", "user-interface" ], "Title": "Account-creation program" }
25300
<p>Which version is more efficient in calculating the square root ? </p> <p>There are 2 versions I have written to calculate square root programatically. Note reqs strictly state not using library functions ? </p> <p>This is puzzling, the first method takes one extra iteration over the 2nd one but returns the more accurate answer of 3.00. </p> <p>Why does it take an extra iteration ? </p> <ul> <li>So, which one is more efficient ? </li> <li>Do you find any bugs in this code ? </li> <li>When will it overflow ? </li> <li>Do both approaches seem logical, one is trying to calculate the difference between square of approximation and actual number, whereas other trying to bisect the interval. Would you pick one over the other ? </li> </ul> <pre class="lang-java prettyprint-override"><code>public void squareRoot() { double n = 9; double epsilon = 0.001; double guess = n*n; double low = 0; double high = n; int cnt=0; while(Math.abs(guess*guess-n)&gt;epsilon) { guess = (low + high)/2; if(guess*guess&gt;n) high = guess; else low = guess; cnt+=1; System.out.println("Low:"+low+"high:"+high+"guess:"+guess+"cnt:"+cnt); } if(guess*guess-n&lt;epsilon) { System.out.println("The square root is:"+guess); } } public void anotherSquareRoot() { double n = 9; double epsilon = 0.001; double guess = n*n; double low = 0; double high = n; int cnt=0; while(high-low&gt;epsilon) { guess = (low + high)/2; if(guess*guess&gt;n) high = guess; else low = guess; cnt+=1; System.out.println("Low:"+low+"high:"+high+"guess:"+guess+"cnt:"+cnt); } if(guess*guess-n&lt;epsilon) { System.out.println("The square root is:"+guess); } } </code></pre>
[]
[ { "body": "<p>In version 1, you are testing the difference of the square is within 0.001. </p>\n\n<p>The square root of 9.001 is 3.000167 </p>\n\n<p>In version 2, you are testing the difference of the square root part. When you square it, the error becomes bigger.</p>\n\n<p>The square of 3.001 is 9.006001</p>\n\n<p>One error:</p>\n\n<p>You need to get rid of the </p>\n\n<pre><code>if(guess*guess-n&lt;epsilon)\n</code></pre>\n\n<p>at the end of version 2, it will not print for positive differences > 0.001 e.g. for 3.001 9.006001 is 0.00601 bigger.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T13:50:06.277", "Id": "39268", "Score": "0", "body": "Which one is more correct ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T14:51:29.507", "Id": "39279", "Score": "0", "body": "It depends on your requirements. The only one you have stated is no library functions and version 1 uses Math.abs (although it would be easy to implement yourself) so version 2 is more correct. If you want better accuracy, version 1 is better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T02:26:50.967", "Id": "39309", "Score": "0", "body": "Y is square of the error a better solution ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T06:05:29.250", "Id": "39321", "Score": "0", "body": "I'm not saying one is better, just different but if I had to choose, I would choose version 2 as it gives you the square root within the error you have specified and uses subtraction, which will be faster than squaring and taking the absolute." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T21:42:56.937", "Id": "25313", "ParentId": "25301", "Score": "1" } }, { "body": "<p>There are some fairly bizarre things which are present in both.</p>\n\n<ul>\n<li>Neither of them takes a parameter</li>\n<li>Both of them start with <code>double guess = n*n;</code> and then proceed to square the guess again. This is never going to be useful.</li>\n<li>They use unguided binary chop for a nonlinear function</li>\n</ul>\n\n<p>I would use a Taylor expansion to three or four terms to get a starting point and then Newton-Raphson should home in very fast.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T12:47:21.367", "Id": "25368", "ParentId": "25301", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T03:37:42.653", "Id": "25301", "Score": "3", "Tags": [ "java", "comparative-review", "numerical-methods" ], "Title": "Square root approximations, implemented two ways" }
25301
<p>I want to move this to a class that will open an sqlite connection that can be re-used, rather than disposing of it every time I write to the database. Furthermore I am more than happy for any best practices from sqlite users! I am aware of a similar thread and am trying to absorb it:</p> <p><a href="https://codereview.stackexchange.com/questions/23284/sqlite-helper-class">SQLite helper class</a></p> <pre><code>void createDB() { // Dont forget to del if refreshing if (!File.Exists(connstring)) { SQLiteConnection.CreateFile(connstring); SQLiteConnection sqliteCon = new SQLiteConnection(@"Data Source=" + connstring); sqliteCon.Open(); // Define db structure string createfilesTableSQL = "CREATE TABLE files ( id INTEGER PRIMARY KEY, filename TEXT, creationtime TEXT, lastwrite TEXT, lastaccess TEXT, checksum TEXT);"; string createfoldersTableSQL = "CREATE TABLE folders ( id INTEGER PRIMARY KEY, dirname TEXT, creationtime TEXT, lastwrite TEXT, lastaccess TEXT, checksum TEXT);"; using (SQLiteTransaction sqlTransaction = sqliteCon.BeginTransaction()) { // Create the tables SQLiteCommand createCommand = new SQLiteCommand(createfilesTableSQL, sqliteCon); createCommand.ExecuteNonQuery(); createCommand.Dispose(); SQLiteCommand createCommand2 = new SQLiteCommand(createfoldersTableSQL, sqliteCon); createCommand2.ExecuteNonQuery(); createCommand2.Dispose(); // Commit the changes into the database sqlTransaction.Commit(); } // end using // Close the database connection sqliteCon.Close(); sqliteCon.Dispose(); } } public int fileExists(string filename, string lastwrite, string hash) { /* Here is a quick Map 0 "The file does not exist in the database 1 "The Hash Matches, leave it alone 2 "the file is newer than that of the databse 3 "the file is older than that of the databse" 4 "the file is the same as that of the database" */ // Connect to database SQLiteConnection sqliteCon = new SQLiteConnection(@"Data Source=" + connstring); sqliteCon.Open(); //Query //string selectSQL = "SELECT EXISTS(SELECT 1 FROM files WHERE filename=" + filename + " LIMIT 1) as result;"; string selectSQL = "SELECT * FROM files WHERE filename=" + filename + ";"; SQLiteCommand selectCommand = new SQLiteCommand(selectSQL, sqliteCon); SQLiteDataReader dataReader = selectCommand.ExecuteReader(); //does file exist bool exists = dataReader.Read(); if (!exists) { dataReader.Dispose(); sqliteCon.Dispose(); return 0; //it doesnt exist in the database } string dbhash = dataReader["checksum"].ToString(); string dblastwrite = dataReader["lastwrite"].ToString(); string lastwritex = lastwrite.Replace("'", ""); string hashx = hash.Replace("'", ""); DateTime dblastwriteDT = Convert.ToDateTime(dblastwrite); DateTime lastwriteDT = Convert.ToDateTime(lastwritex); dataReader.Dispose(); sqliteCon.Dispose(); if (dbhash == hashx) { return 1; //hash matches the database version } if (lastwriteDT &gt; dblastwriteDT) { return 2; //the file is newer than that of the databse } if (lastwriteDT &lt; dblastwriteDT) { return 3; //the file is older than that of the databse } else { return 4; //the file is the same as that of the database } } void cleanDB() { SQLiteConnection sqliteCon = new SQLiteConnection(@"Data Source=" + connstring); sqliteCon.Open(); // Define db structure string createfilesTableSQL = "delete from files;"; string createfoldersTableSQL = "delete from folders;"; using (SQLiteTransaction sqlTransaction = sqliteCon.BeginTransaction()) { // Create the tables SQLiteCommand createCommand = new SQLiteCommand(createfilesTableSQL, sqliteCon); createCommand.ExecuteNonQuery(); createCommand.Dispose(); SQLiteCommand createCommand2 = new SQLiteCommand(createfoldersTableSQL, sqliteCon); createCommand2.ExecuteNonQuery(); createCommand2.Dispose(); // Commit the changes into the database sqlTransaction.Commit(); } // end using // Close the database connection sqliteCon.Dispose(); } private void addFile(string filename, string creationtime, string lastwrite, string lastaccess, string checksum) { // Open connection to database SQLiteConnection sqliteCon = new SQLiteConnection(@"Data Source=" + connstring); sqliteCon.Open(); using (SQLiteTransaction SQLiteTrans = sqliteCon.BeginTransaction()) { using (SQLiteCommand cmd = sqliteCon.CreateCommand()) { // Insert a new file record cmd.CommandText = "INSERT INTO files(filename, creationtime, lastwrite, lastaccess, checksum)" + " VALUES (?,?,?,?,?)"; SQLiteParameter Field1 = cmd.CreateParameter(); SQLiteParameter Field2 = cmd.CreateParameter(); SQLiteParameter Field3 = cmd.CreateParameter(); SQLiteParameter Field4 = cmd.CreateParameter(); SQLiteParameter Field5 = cmd.CreateParameter(); cmd.Parameters.Add(Field1); cmd.Parameters.Add(Field2); cmd.Parameters.Add(Field3); cmd.Parameters.Add(Field4); cmd.Parameters.Add(Field5); Field1.Value = filename; Field2.Value = creationtime; Field3.Value = lastwrite; Field4.Value = lastaccess; Field5.Value = checksum; cmd.ExecuteNonQuery(); } SQLiteTrans.Commit(); } sqliteCon.Dispose(); } private void addFolder(string dirname, string creationtime, string lastwrite, string lastaccess, string checksum) { // Open connection to database SQLiteConnection sqliteCon = new SQLiteConnection(@"Data Source=" + connstring); sqliteCon.Open(); using (SQLiteTransaction SQLiteTrans = sqliteCon.BeginTransaction()) { using (SQLiteCommand cmd = sqliteCon.CreateCommand()) { // Insert a new file record cmd.CommandText = "INSERT INTO folders(dirname, creationtime, lastwrite, lastaccess, checksum)" + " VALUES (?,?,?,?,?)"; SQLiteParameter Field1 = cmd.CreateParameter(); SQLiteParameter Field2 = cmd.CreateParameter(); SQLiteParameter Field3 = cmd.CreateParameter(); SQLiteParameter Field4 = cmd.CreateParameter(); SQLiteParameter Field5 = cmd.CreateParameter(); cmd.Parameters.Add(Field1); cmd.Parameters.Add(Field2); cmd.Parameters.Add(Field3); cmd.Parameters.Add(Field4); cmd.Parameters.Add(Field5); Field1.Value = dirname; Field2.Value = creationtime; Field3.Value = lastwrite; Field4.Value = lastaccess; Field5.Value = checksum; cmd.ExecuteNonQuery(); } SQLiteTrans.Commit(); } sqliteCon.Dispose(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T20:02:41.897", "Id": "39227", "Score": "0", "body": "First suggestion is for `public int fileExists` you are returning an int that has meaning to it. It would be better to make a enum with those values so that there is a name attached to those numbers. This way in the future you'll know what those values returned mean without having to reread your code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-24T10:22:55.520", "Id": "39412", "Score": "0", "body": "absolutely! and thanks. It truly is easier to work with, as you can see from my own comments trying to track what return did what." } ]
[ { "body": "<p>Just a few comments:</p>\n\n<ol>\n<li>Try to use the 'using' construct for SQLiteTransaction, SQLiteCommand and SQLConnection objects everywhere, not just in selected places. Get rid of explicit calls to Dispose() method. Also there is a connection string parameter 'Pooling=true', which tells driver to return previously opened connection to the connection pool and reuse it later. This will improve performance.</li>\n<li>Be consistent with naming of your variables. Try to use camelCase for every variable name. There are several places in your code where you start using all lowercase for no good reason.</li>\n<li>Try to use parameterization in all queries. The 'SELECT' query concatenates filename directly, but should use parameter instead.</li>\n<li>Try to avoid plain numeric return values. You should use enum with self-descriptive member names instead. This will also make the comment describing return codes redundant. Also the function 'fileExists' does a little bit more than just checking if the file exists. You should probably refactor it into several functions with distinct responsibility and self-documenting names.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-24T10:14:12.420", "Id": "39410", "Score": "0", "body": "Thank you nullop! I would assume that I should still be closing the connection if I set pooling to true?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-24T10:22:04.093", "Id": "39411", "Score": "0", "body": "Thank you for your time nullop! Point well taken on enum! I have looked into it and have added it to my code. I am curious, what is the detriment to a direct concat in the select string? Is it just bad SOP or is there something else to learn here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T10:22:23.733", "Id": "39507", "Score": "0", "body": "If you are using 'using' construct then Close() is called for you automatically by Dispose() method. If you're not using the dispose pattern, then you should call Close() explicitly to let the driver return connection back to the pool. As for the concatenation, it could possibly lead to sql injection if the part of filename comes from user input and is inserted into the sql query text. Parameters are processed automatically to avoid possible sql injections. Also parameterization allows sql engine to re-use previously calculated execution plan and reduces the load applied to sql engine." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T20:48:46.377", "Id": "25311", "ParentId": "25304", "Score": "1" } } ]
{ "AcceptedAnswerId": "25311", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T06:50:28.883", "Id": "25304", "Score": "2", "Tags": [ "c#", "beginner", "sqlite" ], "Title": "Working with sqlite and moving functions to class" }
25304
<p>The code below is equivalent. I can see pros and cons for both versions. Which is better: the short, clever way, or the long, <kbd>ctrl</kbd>+<kbd>c</kbd> way?</p> <p>Short version:</p> <pre><code>character.on("key",function(key){ var action = ({ "a":{axis:"x",direction:-1}, "d":{axis:"x",direction:1}, "w":{axis:"y",direction:1}, "s":{axis:"y",direction:-1}})[key[1]], stop = key[0]=="-"; if (action) if (stop) this.walkdir[action.axis] = 0; else this.walkdir[action.axis] = this.lookdir[action.axis] = action.direction; }); </code></pre> <p>Long version:</p> <pre><code>character.on("key",function(key){ switch (key){ case "+a": this.walkdir.x = -1; this.lookdir.x = -1; break; case "+d": this.walkdir.x = 1; this.lookdir.x = 1; break; case "+w": this.walkdir.y = 1; this.lookdir.y = 1; break; case "+s": this.walkdir.y = -1; this.lookdir.y = -1; break; case "-a": if (this.walkdir.x == -1) this.walkdir.x = 0; break; case "-d": if (this.walkdir.x == 1) this.walkdir.x = 0; break; case "-w": if (this.walkdir.y == 1) this.walkdir.y = 0; break; case "-s": if (this.walkdir.y == -1) this.walkdir.y = 0; break; case "space": this.setStance("jumping"); break; }; }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T17:09:58.663", "Id": "39212", "Score": "0", "body": "I don't see how the long version is better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T17:26:43.297", "Id": "39213", "Score": "0", "body": "It's faster and probably much easier to understand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T17:52:07.620", "Id": "39215", "Score": "0", "body": "@Dokkat In the first example you shouldn't be defining a static object when the function is called - that's definitely going to become costly. Try benchmarking that by removing the object definition out of the function and just accessing it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T17:53:41.323", "Id": "39216", "Score": "3", "body": "Faster? Probably not. Even if it were, I doubt it'd make any difference in real code. Easier to read? I think that's where we diverge :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T18:12:40.690", "Id": "39217", "Score": "0", "body": "@FlorianMargaine my point is not that it is easier to read. It's easier to understand, because it needs less knowledge in general (the first is full of JavaScript particularities)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T18:14:03.947", "Id": "39218", "Score": "0", "body": "@izuriel sure, but moving the object out the function would make it even more complicated for newcomers, as I'd have to introduce a closure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T18:15:33.843", "Id": "39219", "Score": "5", "body": "@Dokkat These objections are pretty irrelevant: writing code for people who don’t understand the language is counter-productive since it prevents you from using its features properly. Never succumb to the temptation of doing that. In addition, this code only uses core language features, not obscure hacks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T18:28:46.200", "Id": "39221", "Score": "0", "body": "I see. The remaining concern would be the speed. I think I have 3 choices: letting it as it is, and it creates a new object every function call (slow). Moving the object outside, and polluting the outer namespace. Wrapping it into a closure, and making the code possibly more complicated. Which one?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T18:44:44.770", "Id": "39225", "Score": "0", "body": "Wait, what? There seems to be some disagrement here, I'll benchmark it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T18:52:16.093", "Id": "39226", "Score": "0", "body": "http://jsperf.com/object-inside-outside-function \ndeclaring the object inside looks slower, but I'd expect it to be MUCH slower. Weird." } ]
[ { "body": "<p>The short code wins hands down. I understood it <em>immediately</em>, and more importantly, I can trivially verify that the code is reasonably error free. This is <em>much</em> harder with the longer code.</p>\n\n<p>You say that the longer code is easier to understand but I claim that this is <em>objectively wrong</em>.</p>\n\n<p>Case in point, the long code uses lots of magic numbers: 1, 0, -1, … what do these stand for? Ah, the short code tells us: they are <code>direction</code>s.</p>\n\n<p>The longer code also makes us scroll (depending on the screen size) to see the whole method. This <em>significantly</em> impacts ease of understanding. I believe there were even studies demonstrating this empirically (but I cannot cite them; <em>Code Complete</em> would probably be the relevant reference here).</p>\n\n<p>The one thing I would change in the short code is the lookup itself: define the dictionary separately, maybe even outside the method, and perform the lookup as follows:</p>\n\n<pre><code>var action = movement_commands[key[1]];\n</code></pre>\n\n<p>And maybe think about tokenising <code>key</code> properly, i.e. assigning the parts to variables before using them. However, I think that the method is short enough to make this unnecessary.</p>\n\n<p>You also said that the longer code is more efficient but I’d like to see a benchmark before I believe that. You probably think that the first code is slower because of the dictionary lookup. But consider that JavaScript is a dynamic language – every single variable access is potentially a dictionary lookup internally. So there is no difference in performance – indeed, the short code could be <em>faster</em> since there’s less variable lookup involved.</p>\n\n<p>(Of course the two code snippets do different things: the long version handles jumping, and they behave differently when the character was previously walking in one direction and now you cancel walking into a different direction.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T18:24:33.920", "Id": "39220", "Score": "0", "body": "I argue it's easier to understand, not read; mainly for a novice trying to grasp the code; but I'm not sure I should worry about that. About the speed, it's not because of the dictionary lookup, but because of it's creation, which makes it obviously much heavier. As you said, moving the object out of the function would solve the issue, but then, in order not to pollute the outer namespace, I'd have to introduce a closure, making it even worse for novices (and much less readable in general, IMO): http://jsfiddle.net/EXv7e/ . Note: I obviously prefer the smaller version. Great answer by the way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T18:38:05.783", "Id": "39224", "Score": "0", "body": "@Dokkat Well you could declare `actions` outside of `on.character` entirely, as a global variable. I’m not a big fan of this, however (keep scope as small as possible)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T01:07:46.263", "Id": "39231", "Score": "0", "body": "@Dokkat A novice will only be a novice for a short time; once they encounter and learn how the short code works, they've learned something new that will help them from then on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T01:13:10.970", "Id": "39233", "Score": "0", "body": "@Dokkat Also, the speed hit in creating a small, static dictionary like that is going to be completely unnoticeable given what the event is reacting to. (And probably unnoticeable in general compared to the function call itself; and it may just be JIT-compiled and only created once anyway... (I'm not entirely sure if it would, though))" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T18:10:48.740", "Id": "25309", "ParentId": "25308", "Score": "13" } } ]
{ "AcceptedAnswerId": "25309", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T17:03:39.890", "Id": "25308", "Score": "5", "Tags": [ "javascript", "game", "comparative-review", "event-handling" ], "Title": "Two keyboard handlers for a video game character" }
25308
<p>I would like to re-write this C# code so it is easier to understand. Should I create a separate function to configure a menu item? Is there is some kind of <code>using</code> statement so I only need to mention the menu name once?</p> <pre><code>private void initializeContextMenuRightClick() { try { ctxMenuStripRightClick = new ContextMenuStrip(); ctxMenuStripRightClick.Opening += ctxMenuStrip_Opening; ToolStripMenuItem addMenuItem = new ToolStripMenuItem("Add", null, AddMenuItem_Click); ToolStripMenuItem deleteMenuItem = new ToolStripMenuItem("Delete", null, DeleteMenuItem_Click); ToolStripMenuItem editMenuItem = new ToolStripMenuItem("Edit", null, EditMenuItem_Click); ToolStripMenuItem markDoneMenuItem = new ToolStripMenuItem("Mark Done", null, MarkDoneMenuItem_Click); ToolStripSeparator separatorMenuItem = new ToolStripSeparator(); ctxMenuStripRightClick.Items.Add(addMenuItem); ctxMenuStripRightClick.Items.Add(deleteMenuItem); ctxMenuStripRightClick.Items.Add(editMenuItem); ctxMenuStripRightClick.Items.Add(separatorMenuItem); ctxMenuStripRightClick.Items.Add(markDoneMenuItem); } catch (Exception ex) { HandleException.Show(ex); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T20:42:54.230", "Id": "39228", "Score": "2", "body": "Do you need the intermediate tool menu variables? Could you not just use ctxMenuStripRightClick.Items.Add(new ToolStripMenuItem(\"Add\", null, AddMenuItem_Click)) etc" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T21:29:12.950", "Id": "39229", "Score": "0", "body": "Good idea. Is there a way I can avoid repeatedly mentioning ctxMenuStripRightClick ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T00:44:29.923", "Id": "39230", "Score": "0", "body": "Yes, see my answer as a bit much for a comment" } ]
[ { "body": "<blockquote>\n <p>Is there a way I can avoid repeatedly mentioning\n ctxMenuStripRightClick.</p>\n</blockquote>\n\n<p>Yes, I guess you could do something like:</p>\n\n<pre><code>ctxMenuStripRightClick = new ContextMenuStrip();\nctxMenuStripRightClick.Opening += ctxMenuStrip_Opening;\nctxMenuStripRightClick.Items.AddRange(new List&lt;ToolStripMenuItem&gt;\n{\n new ToolStripMenuItem(\"Add\", null, AddMenuItem_Click),\n new ToolStripMenuItem(\"Delete\", null, DeleteMenuItem_Click),\n // etc\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T00:39:42.420", "Id": "25317", "ParentId": "25310", "Score": "3" } }, { "body": "<p>I think you should create new function to add item</p>\n\n<pre><code>private void AddMenuItem(string caption, EventHandler onClick) {\n ctxMenuStripRightClick.Items.Add(\n new ToolStripMenuItem(caption, null, onClick)\n ); \n}\n</code></pre>\n\n<p>So your initialization method will be</p>\n\n<pre><code>ctxMenuStripRightClick = new ContextMenuStrip();\nctxMenuStripRightClick.Opening += ctxMenuStrip_Opening;\nAddMenuItem(\"Add\", AddMenuItem_Click);\nAddMenuItem(\"Delete\", DeleteMenuItem_Click);\nAddMenuItem(\"Edit\", EditMenuItem_Click);\nctxMenuStripRightClick.Items.Add(new ToolStripSeparator());\nAddMenuItem(\"Mark Done\", MarkDoneMenuItem_Click);\n</code></pre>\n\n<p>EDIT: If you really don't want a separated function, you can use lambda expression:</p>\n\n<pre><code>Action&lt;string, EventHandler&gt; addMenuItem = (caption, onClick) =&gt;\n{\n ctxMenuStripRightClick.Items.Add(\n new ToolStripMenuItem(caption, null, onClick)\n );\n};\naddMenuItem(\"Add\", AddMenuItem_Click);\n...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T15:48:17.690", "Id": "39281", "Score": "0", "body": "i like the separate function idea, but I want ctxMenuStripRightClick to be private to the main procedure" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T05:02:29.617", "Id": "39486", "Score": "0", "body": "@kirsteng See my update." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T13:11:35.540", "Id": "25332", "ParentId": "25310", "Score": "1" } } ]
{ "AcceptedAnswerId": "25317", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T20:31:18.310", "Id": "25310", "Score": "1", "Tags": [ "c#", "winforms", "crud" ], "Title": "CRUD menu creation" }
25310
<p>I've found a <a href="https://stackoverflow.com/a/5158227/435460">good example of how to do this in Java</a> and <a href="https://stackoverflow.com/a/838985/435460">how you can get the same behavior in c#</a>, so I've made made an attempt at it:</p> <pre><code>public class CircularReferenceOne { public int Identifier; public CircularReferenceTwo CR2; public CircularReferenceOne HCopy() { var track = new Dictionary&lt;int, object&gt;(); return this.HCircCopy(this, track); } public CircularReferenceOne HCircCopy(object obj, Dictionary&lt;int, object&gt; track) { object clone; if (track.TryGetValue(RuntimeHelpers.GetHashCode(obj), out clone)) { var c = clone as CircularReferenceOne; if (null != c) return c; } var myClone = new CircularReferenceOne(); track.Add(RuntimeHelpers.GetHashCode(obj), myClone); myClone.Identifier = this.Identifier; CircularReferenceTwo cr = this.CR2; myClone.CR2 = null == cr ? null : cr.HCircCopy(cr, track); return myClone; } } </code></pre> <p>Note: <code>CircularReferenceTwo</code> is identical to <code>CircularReferenceOne</code>.</p> <p>Can anyone can see any potential limitations with this approach? If so, do you know of a better way to do this?</p> <p>Keep in mind that I'd like the approach to be as performant as possible (memory/cpu), even if readability is sacrificed a bit.</p> <p>Note: The goal is to find the general algorithm for performing a deep-copy by hand in the most efficient way possible, so using things like <a href="https://stackoverflow.com/a/78612/435460">binary serialization</a> are out of the question.</p> <p><strong>Edit</strong> Updated version based on @svick's answer:</p> <pre><code>public class CircularReferenceOne { public int Identifier; public CircularReferenceTwo CR2; public CircularReferenceOne HCopy() { var track = new Dictionary&lt;object, object&gt;(ObjectReferenceComparer.Instance); return this.HCircCopy(track); } public CircularReferenceOne HCircCopy(Dictionary&lt;object, object&gt; track) { object clone; if (track.TryGetValue(this, out clone)) { var c = clone as CircularReferenceOne; if (null != c) return c; } var myClone = new CircularReferenceOne(); track.Add(this, myClone); myClone.Identifier = this.Identifier; CircularReferenceTwo cr = this.CR2; myClone.CR2 = null == cr ? null : cr.HCircCopy(track); return myClone; } } </code></pre> <p>Here's the implementation for <code>ObjectReferenceComparer</code>:</p> <pre><code>public class ObjectReferenceComparer : EqualityComparer&lt;object&gt; { public static readonly ObjectReferenceComparer Instance = new ObjectReferenceComparer(); public override bool Equals(object first, object second) { return object.ReferenceEquals(first, second); } public override int GetHashCode(object obj) { return RuntimeHelpers.GetHashCode(obj); } } </code></pre> <p><strong>Update</strong> I came across <a href="https://stackoverflow.com/a/4901403/435460">this StackOverflow answer</a>, and after reading Ani's answer I decided to actually check out the implementation for <code>System.Dynamic.Utils.ReferenceEqualityComparer&lt;T&gt;</code> which I've added here for future reference:</p> <pre><code>// Type: System.Dynamic.Utils.ReferenceEqualityComparer`1 // Assembly: System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Core.dll using System.Collections.Generic; using System.Runtime.CompilerServices; namespace System.Dynamic.Utils { internal sealed class ReferenceEqualityComparer&lt;T&gt; : IEqualityComparer&lt;T&gt; { internal static readonly ReferenceEqualityComparer&lt;T&gt; Instance = new ReferenceEqualityComparer&lt;T&gt;(); static ReferenceEqualityComparer() { } private ReferenceEqualityComparer() { } public bool Equals(T x, T y) { return object.ReferenceEquals((object) x, (object) y); } public int GetHashCode(T obj) { return RuntimeHelpers.GetHashCode((object) obj); } } } </code></pre> <p>Now I'm much more comfortable with this implementation!</p>
[]
[ { "body": "<p>You should never use hash codes like this, because they are not unique. Two different objects can have the same hash code and when that happens, your algorithm breaks down. Instead you should use <a href=\"https://stackoverflow.com/a/1890230/41071\">an implementation of <code>IEqualityComparer</code> that uses <code>object.ReferenceEquals()</code> and <code>RuntimeHelpers.GetHashCode()</code></a>.</p>\n\n<p>Also, I don't understand why does <code>HCircCopy()</code> have the <code>obj</code> parameter, when it's always going to be <code>this</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T01:51:54.543", "Id": "39235", "Score": "0", "body": "How does the revision look?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T02:17:38.727", "Id": "39237", "Score": "1", "body": "@JesseBuesking Yeah, that's much better. One more thing I noticed: in C#, it's not necessary to use Yoda conditions, just write `if (c != null)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T02:34:45.237", "Id": "39238", "Score": "0", "body": "yeah, force of habit :D" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T00:23:45.453", "Id": "25316", "ParentId": "25314", "Score": "2" } } ]
{ "AcceptedAnswerId": "25316", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T23:20:50.673", "Id": "25314", "Score": "0", "Tags": [ "c#", "algorithm" ], "Title": "Deep copying objects with circular references" }
25314
<p>Given two integers, <code>X</code> and <code>Y</code>, you must create all possible integer sequences of length <code>Y</code> using the numbers from 1 to <code>X</code>.</p> <p>For certain reasons, the function must return a <code>deque&lt;deque&lt;int&gt; &gt;</code> representing such (the primary <code>deque</code> holds all my sequences - each of then is a <code>deque</code> of <code>int</code>s).</p> <p>This is not a permutation generator.</p> <h1>Example Input</h1> <pre><code>X = 3, Y = 3 </code></pre> <p>This means that I require sequences of length <code>3</code> each one. To compose the sequences, I use the integers <code>1</code>, <code>2</code>, and <code>3</code>.</p> <h1>Example Output</h1> <p>The previous input should produce:</p> <pre><code>1 1 1 1 1 2 1 1 3 1 2 1 1 2 2 1 2 3 1 3 1 1 3 2 1 3 3 2 1 1 2 1 2 2 1 3 2 2 1 2 2 2 2 2 3 2 3 1 2 3 2 2 3 3 3 1 1 3 1 2 3 1 3 3 2 1 3 2 2 3 2 3 3 3 1 3 3 2 3 3 3 </code></pre> <h1>My Idea</h1> <p>I'm not very good with this stuff. My approach is:</p> <ul> <li>Create a start and end integer <ul> <li>Start is <code>1</code> repeated <code>Y</code> times. So in the previous example it is <code>111</code></li> <li>End is <code>X</code> repeated <code>Y</code> times. So in the previous example it is <code>333</code></li> </ul></li> <li>I count <code>i</code> from <code>start</code> to <code>end</code>. <ul> <li>If <code>i</code> contains an invalid digit (like <code>4</code>, <code>5</code>,...), abort this sequence.</li> <li>If <code>i</code> is valid, then this sequence is valid, thus add it to my resulting <code>deque</code>.</li> <li>When a sequence is valid, due to my needs, I split the integer and make a <code>deque</code> of each of its digits.</li> </ul></li> </ul> <h1>Why I need a review</h1> <p>I think it is pretty clear that this method doesn't sound very efficient. So many wasted iterations! Can you help me improve this code, and, perhaps, shorten it?</p> <h1>My Attempt</h1> <p><em>Note, you may notice that instead of "sequences" I call then "procedures".</em></p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;deque&gt; using namespace std; // Converts a value to any type template &lt;typename T,typename S&gt; T convert(S original) { stringstream ss; ss &lt;&lt; original; T result; ss &gt;&gt; result; return result; } // The actual function deque&lt;deque&lt;int&gt; &gt; allPossibleProcedures(int values, int depth) { deque&lt;deque&lt;int&gt; &gt; result; // I create a start point and an end point for my counting string minString; for (int d = 0; d &lt; depth; ++d) { minString.append("1"); } string limitString; for (int d = 0; d &lt; depth; ++d) { limitString.append(convert&lt;string&gt;(values)); } int start = convert&lt;int&gt;(minString); int limit = convert&lt;int&gt;(limitString); // I begin counting for (int i = start; i &lt;= limit; ++i) { deque&lt;int&gt; procedure; string text = convert&lt;string&gt;(i); bool ok = true; for (int c = 0; c &lt; text.length() &amp;&amp; ok; ++c) { int x = convert&lt;int&gt;(text.at(c)); if (x &lt;= values &amp;&amp; x &gt; 0) { // This is a valid character. Add to procedure. procedure.push_back(x); }else{ // Not a valid character. Abort this procedure. ok = false; break; } } if (ok) { result.push_back(procedure); } } return result; } int main(int argc, const char * argv[]) { deque&lt;deque&lt;int&gt; &gt;procedures = allPossibleProcedures(3,3); for (int i = 0; i &lt; procedures.size(); ++i) { for (int j = 0; j &lt; procedures[i].size(); ++j) { cout &lt;&lt; procedures[i][j] &lt;&lt; " "; } cout &lt;&lt; endl; } return 0; } </code></pre>
[]
[ { "body": "<p>I don't have time to do a style review at the moment, so until I can expand on this later, I'll just suggest a different algorithm.</p>\n\n<hr>\n\n<p>Rather than depending on string manipulation and generating more items than you need, just take an arithmetic approach.</p>\n\n<p>In particular, you can take a deque of ints and add 1 to it until it is equal to the max value.</p>\n\n<pre><code>std::deque&lt; std::deque&lt;int&gt; &gt; results;\nstd::deque&lt;int&gt; min(Y, 1);\nstd::deque&lt;int&gt; max(Y, X);\nfor (; min != max; min = increment(min, Y)) {\n results.push_back(min);\n}\nresults.push_back(max);\n</code></pre>\n\n<p>As a bit more explanation, a <code>std::deque&lt;unsigned int&gt;</code> is frequently used as a make-shift arbitrary precision integer. The way this is done is to have a sign flag, and then to see each element of the deque as part of a <code>radix = std::numeric_limits&lt;unsigned int&gt;::max()</code> number.</p>\n\n<p>As a concrete example, a <code>std::deque&lt;unsigned char&gt; d = {95, 14, 230}</code> would represent <code>95 * 255^2 + 14 * 255^1 + 230 * 255^0</code> in the same way common base ten <code>134 = 1 * 10^2 + 3 * 10^2 + 4 * 10^0</code>.</p>\n\n<p>Anyway, I'm getting carried away with this. </p>\n\n<p>What you're in need of is a much more specific case of this. Rather than making a generic adder, all you have to do is just add 1, and if that causes the lowest digit to overflow, push it back down to a 1 and carry the add up the chain.</p>\n\n<pre><code>std::deque&lt;int&gt; increment(std::deque&lt;int&gt; d, int Y)\n{\n bool carry = true;\n for (std::deque&lt;int&gt;::reverse_iterator it = d.rbegin(), end = d.rend(); it != end; ++it) {\n *it += 1;\n if (*it &gt; Y) {\n *it = 1;\n } else {\n carry = false;\n }\n }\n if (carry) {\n d.push_front(1);\n }\n return d;\n} \n</code></pre>\n\n<p>The above code is untested and unoptimized. It can probably be written more compactly, but it's been a long time since I've done anything like this, and I'm just trying to illustrate how it can be done arithmetically. </p>\n\n<p>Also, if you're concerned about performance, you might want to have <code>increment</code> mutate <code>d</code> rather than return a modified copy.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T02:00:21.373", "Id": "39307", "Score": "0", "body": "Hello Corbin. I tested your code, but (3,3) gave me http://pastebin.com/neUny5N8 - I don't fully understand why." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T03:12:07.577", "Id": "39310", "Score": "0", "body": "@Omega Whoops, will edit my answer in a bit, but for now, change the ` min <= max` to `min != max` and then after the loop add `results.push_back(max)`. Got overzealous and forgot that lexicographical ordering will not work here since 1111 is considered lexicographically less than 333." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T03:19:53.093", "Id": "39311", "Score": "0", "body": "I believe that now I get 111, 222, and 333. Hmm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T03:59:26.493", "Id": "39316", "Score": "0", "body": "Ok, I'm not sure what the problem was, but I based myself on your code and got this working: http://pastebin.com/DAyc3Bhv - it looks nice, thanks a lot! Now I got to see how to make it faster." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T02:28:33.870", "Id": "25320", "ParentId": "25315", "Score": "4" } }, { "body": "<p>Say X = 3 and Y = 3, then the combination is:</p>\n\n<p>So basically, you have a:</p>\n\n<p>min number which is 111</p>\n\n<p>max number which is 333 </p>\n\n<p>so: </p>\n\n<ul>\n<li><p>calculate min number which is = the number 1 repeated Y times.</p></li>\n<li><p>calculate max number which is = the number X repeated Y times. </p></li>\n<li><p>you start with min number</p></li>\n<li><p>if last digit is &lt; X, add 1</p></li>\n<li>if last digit is = X, add (11 - X)</li>\n<li>if second from last digit is = X, add 100 to min</li>\n<li>repeat last three steps until the number you have is equal to max.</li>\n</ul>\n\n<p>This is the basic idea, you might need to tweak it a bit as the numbers get higher.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T04:20:17.443", "Id": "25322", "ParentId": "25315", "Score": "1" } }, { "body": "<p>A question like this is basically crying out for recursion - we know we'll (effectively) need to loop <code>y</code> times from <code>1</code> to <code>x</code>. We can encode the loop number in the recursion:</p>\n\n<pre><code>void recurse(std::deque&lt;std::deque&lt;int&gt;&gt;&amp; deq, std::deque&lt;int&gt;&amp; d, \n int x, int y, int ymax)\n{\n if(y == ymax) return;\n for(int i = 1; i &lt;= x; ++i) {\n d[y] = i;\n deq.push_back(d);\n recurse(deq, d, x, y + 1, ymax); \n }\n}\n</code></pre>\n\n<p>This is relatively safe, because we only recurse to a depth of <code>y</code>. Since the number of elements grows at a rate of <code>y^x</code>, any practical computable value will require <code>y</code> and <code>x</code> to be relatively small.</p>\n\n<p>Unfortunately the above generates some duplicate elements (it could be modified so that it did not). Some sorting and filtering out only unique values will give you what you want, however:</p>\n\n<pre><code>std::deque&lt;std::deque&lt;int&gt;&gt; all_sequences(int x, int y)\n{\n std::deque&lt;std::deque&lt;int&gt;&gt; deq;\n std::deque&lt;int&gt; d(y, x);\n recurse(deq, d, x, 0, y);\n std::sort(deq.begin(), deq.end(), [](const std::deque&lt;int&gt;&amp; d1, \n const std::deque&lt;int&gt;&amp; d2) \n { return d1 &lt; d2; });\n auto it = std::unique(deq.begin(), deq.end());\n deq.resize(std::distance(deq.begin(), it));\n return deq;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T07:24:42.947", "Id": "39245", "Score": "0", "body": "Perhaps our brains just latched onto this in different ways, but I don't think this cries out for recursion at all. Your explanation of the recursion is practically explaining a loop transformed into recursion. To each his own, though, I suppose :)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T08:00:06.033", "Id": "39250", "Score": "0", "body": "@Corbin Yeah, it's more of a \"to my mind ...\". When I see a problem like this I immediately start looking for a recursive solution, but that may just be me." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T05:10:46.017", "Id": "25323", "ParentId": "25315", "Score": "1" } } ]
{ "AcceptedAnswerId": "25320", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-21T23:43:58.627", "Id": "25315", "Score": "5", "Tags": [ "c++" ], "Title": "All integer sequences given amount of integers and length of sequence" }
25315
<p>I really hate messy code, but I seem to be rolling in it. I just want to see if anyone has some helpful advice on how to tidy this up.</p> <pre><code>&lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th&gt;Zona&lt;/th&gt; &lt;th&gt;Baptismos Mulheres&lt;/th&gt; &lt;th&gt;Conf. Mulheres&lt;/th&gt; &lt;th&gt;Batismos Homems&lt;/th&gt; &lt;th&gt;Conf. Homems&lt;/th&gt; &lt;/tr&gt; &lt;?php $currWeek = $CONF-&gt;getSetting('current_week'); $zones = $PDO-&gt;query("SELECT * FROM zones WHERE active = 1"); foreach($zones as $zone) { $zoneName = $zone['name']; $zoneUid = $zone['uid']; ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php print $zoneName; ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php $areas = $PDO-&gt;query("SELECT * FROM areas WHERE zone = '".$zoneUid."'"); foreach($areas as $area) { $areaName = $area['name']; $areaUid = $area['uid']; ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php print $areaName; ?&gt; &lt;?php $missionaries = $PDO-&gt;query("SELECT missionary FROM missionary_areas WHERE semana = '".$currWeek."' AND area_uid = '".$areaUid."'"); $compArr = array(); foreach($missionaries as $missionary) { $companions = $PDO-&gt;query("SELECT CONCAT(title, ' ', mission_name) as name from missionarios WHERE mid = '".$missionary['missionary']."'"); foreach($companions as $comp) { $compArr[] = $comp['name']; } } $compList = $CONF-&gt;commaSeparate($compArr); ?&gt; &lt;?php print $compList; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;?php } } ?&gt; </code></pre> <p>I am still a bit inexperienced and would like some helpful tips. My MySQL directory stucture is necessaraly crazy so I have to do a bunch of queries to get some simple data. Using PDO is helping quite a bit though.</p> <p><strong>Edit:</strong></p> <p>Database structure</p> <p><img src="https://i.stack.imgur.com/BBjA0.png" alt="Here is a photo showing the DataBase structure"></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T05:34:09.207", "Id": "39242", "Score": "0", "body": "I'm not familiar with PDO but can't you divide your PHP code into functions and put them in one file. You can then call them as necessary. It would also be a good idea to use templates or a templating framework." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T12:55:23.490", "Id": "39267", "Score": "0", "body": "Normalizing a database is not always the best approach, so can you tell me something about the number of entries in the tables." } ]
[ { "body": "<p>WKS is right, first of all you should split your layout from your logic and your logic from your database query. (see Model-View-Controller-Pattern)</p>\n\n<p>Lets start with your model (Model.php): (actually you could split it in a model for each entity/database table)</p>\n\n<pre><code>&lt;?php\nclass Model()\n{\n public function __construct(PDO $connection)\n {\n $this-&gt;connection=connection;\n }\n\n public function getZones($week) //find a nicer name\n {\n //... see Peters post for a sample join\n // prepare multi dimensional array as needed in your template\n return $zones;\n }\n}\n</code></pre>\n\n<p>It is in general a bad idea to run SQL queries in a loop, so try to create one join for all your queries.</p>\n\n<p>Now the simple Controller (index.php)</p>\n\n<pre><code>&lt;?php\nrequire 'Model.php';\n$connection=new PDO(...);\n$model=new Model($connection);\n$currentWeek = ...;\n$zones= $model-&gt;getZones($currentWeek);\n\ninclude \"view.php\"\n</code></pre>\n\n<p>That's it! Nothing fancy. Now the view:</p>\n\n<pre><code>&lt;table&gt;\n &lt;tr&gt;\n &lt;th&gt;Zona&lt;/th&gt;\n &lt;th&gt;Baptismos Mulheres&lt;/th&gt;\n &lt;th&gt;Conf. Mulheres&lt;/th&gt;\n &lt;th&gt;Batismos Homems&lt;/th&gt;\n &lt;th&gt;Conf. Homems&lt;/th&gt;\n &lt;/tr&gt;\n &lt;?php foreach($zones as $zone):?&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;?php echo $zone['name']; ?&gt;&lt;/td&gt;\n &lt;td colspan=\"4\"&gt;&lt;/td&gt;\n &lt;/tr&gt; \n &lt;?php foreach($zones['areas'] as $area):?&gt;\n &lt;tr&gt;\n &lt;td&gt;\n &lt;?php $area['name']; ?&gt; &lt;?php echo $area['companions']; ?&gt;\n &lt;/td&gt;\n &lt;td colspan=\"4\"&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php endforeach?&gt;\n &lt;?php endforeach?&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>Don't use all-capital-letter variable names. And don't use global variables. Both is considered bad practice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T07:37:04.390", "Id": "39246", "Score": "0", "body": "You Model class is a God object and has a hard dpeendency on a SQL storage which is also a bad practise and this way the OP won't be closer to an MVC approach." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T07:48:29.000", "Id": "39247", "Score": "1", "body": "@PeterKiss Please read 'actually you could split it in a model for each entity/database table' again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T07:52:27.627", "Id": "39248", "Score": "0", "body": "@PeterKiss \"has a hard dpeendency on a SQL storage\". I don't get it? Do you would use a Singleton or a kind of Dependency Injection? My solution is the first step away from the global $PDO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T07:58:08.633", "Id": "39249", "Score": "0", "body": "What happens with your code if you want to unit test it? How can you fake the PDO? You can't. And yes we can split again the code into new classes but none of them should no anything about their storage only an abstraction. In a domain model we should not have anything related to a datastorage like PDOStatement and others." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T08:05:03.790", "Id": "39251", "Score": "0", "body": "If you want to test the model/repository you need the real database anyway, otherwise your test is useless. If you want to test the controller, inject an other model. In general you are right, but you are totally missing your audience here. Sun-tzus script will not evolve from a one-file-solution to a full featured business application in one stackexchange questions. My intermediate step meet his requirement and is not to complex or over engineered ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T11:22:35.023", "Id": "39263", "Score": "0", "body": "Just a couple questions: 1. Do you have an example of how I could do the join? 2. Why isn't $area in the $zone loop?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T11:34:08.557", "Id": "39264", "Score": "0", "body": "The joins you can adapt from Peter and I will edit my post to fix 2 . Due the lack of indentation I missed the end of the foreach loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T12:51:31.573", "Id": "39266", "Score": "0", "body": "@mnhg thanks for your help so far. I just added a picture of the database structure. It is kinda complicated because I need to keep the records around for referencing purposes and the data changes weekly. My brain is just having a hard time keeping track of everything." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T07:01:11.163", "Id": "25325", "ParentId": "25318", "Score": "3" } }, { "body": "<h2>First things first</h2>\n\n<p>Create two model classes:</p>\n\n<pre><code>&lt;?php\n\nclass Zone {\n public $Name;\n public $ID;\n public $Areas = array();\n\n public function __construct($id = NULL, $name = NULL) {\n $this-&gt;Name = $name;\n $this-&gt;ID = $id;\n }\n}\n\nclass Area {\n public $Name;\n public $ID;\n public $Companions = array();\n\n public function __construct($id = NULL, $name = NULL) {\n $this-&gt;Name = $name;\n $this-&gt;ID = $id;\n }\n}\n</code></pre>\n\n<p>Then you have to clear your SQL statements becouse you are running to much query against the database while you can fatch all data with only 2 query.</p>\n\n<h2>SQL</h2>\n\n<p>First the companions:</p>\n\n<pre><code>&lt;?php\n\n$companionsResult = $PDO-&gt;query(\"SELECT CONCAT(title, ' ', mission_name) as MissName, area.uid AS AreaID\nFROM missionarios\nINNER JOIN missionary_areas ON missionary_areas.missionary = missionarios.mid\nAND semana = '\".$CONF-&gt;getSetting('current_week').\"' AND area.uid IN (\n SELECT areas.uid AS AreaID\n FROM zones\n INNER JOIN areas ON areas.zone = zones.uid\n WHERE zones.active = 1\n)'\";\n\n$companions = array();\nforeach ($companionsResult-&gt;fetchAll(PDO::FETCH_CLASS) as $c) {\n if (!isset($companions[$c-&gt;AreaID])) {\n $companions[$c-&gt;AreaID] = array();\n }\n\n $companions[$c-&gt;AreaID][] = $c-&gt;MissName;\n}\n</code></pre>\n\n<p>Zones and areas with merging areas with companions:</p>\n\n<pre><code>$zonesResult = $PDO-&gt;query(\n \"SELECT zones.name AS ZoneName, zones.uid AS ZoneID, areas.name AS AreaName, areas.uid AS AreaID\n FROM zones\n LEFT JOIN areas ON areas.zone = zones.uid\n WHERE zones.active = 1\");\n\n$zones = array();\n\nforeach($zonesResult-&gt;fetchAll(PDO::FETCH_CLASS) as $zoneres) {\n if (!isset($zones[$zoneres-&gt;ZoneID])) {\n $zones[$zoneres-&gt;ZoneID] = new Zone($zoneres-&gt;ZoneID, $zoneres-&gt;ZoneName);\n }\n\n $area = new Area($zoneres-&gt;AreaID, $zoneres-&gt;AreaName);\n\n if (isset($companions[$area-&gt;ID])) {\n $area-&gt;Companions = $companions[$area-&gt;ID];\n }\n\n $zones[$zoneres-&gt;ZoneID]-&gt;Areas[] = $area;\n}\n</code></pre>\n\n<h2>Result</h2>\n\n<p>\n\n<p>var_dump($zones);</p>\n\n<h2>HTML</h2>\n\n<p>After viewing the results you can create your own view to display the date without having queries and other not view related stuff between your HTML stuff.</p>\n\n<p>(I'm sure that i have made some typos in the code but it should work after some fix.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T09:12:12.490", "Id": "39255", "Score": "0", "body": "If you are using Value Objects please check: [PDO Fetch Class](http://stackoverflow.com/questions/5137051/pdo-php-fetch-class) otherwise use FETCH_ASSOC to skip the intermediate objects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T09:20:47.947", "Id": "39257", "Score": "0", "body": "Great suggestion but in the example above i need to use intermediate objects becouse the query result classes (and their \"properties\") arn't matching any other class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T09:26:09.987", "Id": "39258", "Score": "0", "body": "You are right, missed to scroll to get the whole join :) But than I would prefer fetch assoc. I read a benchmark somewhere, maybe I will find it again." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T07:28:24.320", "Id": "25327", "ParentId": "25318", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T01:12:00.973", "Id": "25318", "Score": "1", "Tags": [ "php", "mysql", "html", "pdo" ], "Title": "Assist cleaning up messy HTML/PHP code" }
25318
<p>Sometimes I need an <code>NSDictionary</code>-like object that maps a few integers (non-negative) to objects. At first glance, <code>NSMutableArray</code> is great for this, provided that the indexes aren't too high so I came up with <a href="http://cutecoder.org/programming/behold-holy-array/" rel="nofollow">a quick category to allow holes in an array</a>:</p> <pre><code>@implementation NSArray (FoundationAdditions) -(id) objectAtCheckedIndex:(NSUInteger) index { if(index &gt;= self.count) { return nil; } else { id result = [self objectAtIndex:index]; return result == [NSNull null] ? nil : result; } } @end @implementation NSMutableArray (FoundationAdditions) -(void) setObject:(id) object atCheckedIndex:(NSUInteger) index { NSNull* null = [NSNull null]; if (!object) { object = null; } NSUInteger count = self.count; if (index &lt; count) { [self replaceObjectAtIndex:index withObject:object]; } else { if (index &gt; count) { NSUInteger delta = index - count; for (NSUInteger i=0; i&lt;delta;i++) { [self addObject:null]; } } [self addObject:object]; } } @end </code></pre> <p>Is there a better/easier/simpler way to do this? Preferably using something that's pre-existing in the Cocoa stack. Yes I know STL has some pretty good containers in this area, but mixing-in C++ just for this is overkill.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T04:59:12.520", "Id": "39239", "Score": "0", "body": "Can you clarify what your motivation is? Are you wanting to optimize for lookup speed, at the expense of memory usage? Something else?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T05:10:08.680", "Id": "39240", "Score": "0", "body": "@nate Both lookup speed and saving some memory – without needing to store `NSNumber` objects as keys if I use `NSDictionary` for this use." } ]
[ { "body": "<p>I would write a custom class that uses an <code>NSMutableDictionary</code> internally, boxing the indexes into <code>NSNumber</code> keys.</p>\n\n<p>Depending on your particular use case it’s probably going to be both faster and more memory efficient than stuffing the unused array items with <code>NSNull</code>. Boxing the integer indexes into <code>NSNumber</code> key objects sounds like a lot of work performance-wise, but since the implementation uses <a href=\"http://objectivistc.tumblr.com/post/7872364181/tagged-pointers-and-fast-pathed-cfnumber-integers-in\" rel=\"nofollow\">tagged pointers</a>, it should be pretty fast.</p>\n\n<p>For extra points you can implement the <a href=\"http://clang.llvm.org/docs/ObjectiveCLiterals.html\" rel=\"nofollow\">object subscripting accessors</a> (<code>objectAtIndexedSubscript:</code> and <code>setObject:atIndexedSubscript:</code>) and enjoy simple access syntax (<code>foo[x]</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-24T13:15:47.737", "Id": "39421", "Score": "0", "body": "Yep, you're right. I started this back in iOS 3 and tagged pointers just made this obsolete." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T18:43:22.857", "Id": "25348", "ParentId": "25321", "Score": "4" } } ]
{ "AcceptedAnswerId": "25348", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T02:29:03.213", "Id": "25321", "Score": "4", "Tags": [ "objective-c", "category" ], "Title": "Simple yet efficient integer-to-object dictionaries?" }
25321
<p>I am creating a web application for an enterprise and I would like to improve my way of coding, know what I do wrong and what I do well. I'll leave the main class' code here:</p> <pre><code>package com.puntobile; import com.google.gson.Gson; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import com.google.gwt.event.dom.client.KeyPressHandler; import com.vaadin.annotations.Theme; import com.vaadin.client.ui.layout.Margins; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.data.util.IndexedContainer; import com.vaadin.event.Action; import com.vaadin.event.Action.Handler; import com.vaadin.event.ShortcutAction; import com.vaadin.server.*; import com.vaadin.shared.ui.datefield.Resolution; import com.vaadin.ui.*; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Upload.Receiver; import com.vaadin.ui.Upload.SucceededEvent; import com.vaadin.ui.Upload.SucceededListener; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.util.*; import java.io.*; import java.lang.reflect.Type; import org.quartz.*; @Theme("puntobiletheme") public class PuntobileUI extends UI implements Receiver, SucceededListener { private static final long serialVersionUID = 1L; private final String[] fieldNames = { "Nombre", "IP", "Directorio", "Estado" }; public static PuntobileUI INSTANCE; Table signs = new Table("Signs"); IndexedContainer signsContainer = new IndexedContainer(); List&lt;Sign&gt; signList = new ArrayList&lt;Sign&gt;(); Table schedule = new Table(); String owner = "guest"; List&lt;User&gt; userList = new ArrayList&lt;User&gt;(); @Override protected void init(VaadinRequest request) { INSTANCE = this; loadUsers(); FormLayout loginLayout = new FormLayout(); this.setContent(loginLayout); Label lblLogin = new Label("Iniciar sesión"); lblLogin.setStyleName("boldLabel"); final TextField username = new TextField("Nombre de usuario: "); final PasswordField password = new PasswordField("Contraseña: "); Button btnLogin = new Button("Iniciar sesión"); btnLogin.addClickListener(new ClickListener() { private static final long serialVersionUID = 8727890390426574530L; @Override public void buttonClick(ClickEvent event) { boolean worked = false; for(User u : userList) if ((username.getValue().equals(u.username) &amp;&amp; password .getValue().equals(u.password))) { initLayout(username.getValue()); initSigns(); initSchedule(); worked = true; } else { } if(!worked) Notification.show("Usuario o contraseña erróneos", Notification.Type.WARNING_MESSAGE); } }); loginLayout.setMargin(true); loginLayout.addComponent(lblLogin); loginLayout.addComponent(username); loginLayout.addComponent(password); loginLayout.addComponent(btnLogin); } @SuppressWarnings("serial") private void initLayout(final String owner) { this.owner = owner; HorizontalSplitPanel splitPanel = new HorizontalSplitPanel(); this.setContent(splitPanel); VerticalLayout leftLayout = new VerticalLayout(); leftLayout.addComponent(signs); Button btnManage = new Button("Administrar cuentas"); BrowserWindowOpener popupOpener = new BrowserWindowOpener(UserManager.class); popupOpener.extend(btnManage); Button btnDel = new Button("Borrar"); btnDel.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { if(signs.getValue() != null) signList.remove(((Integer) signs.getValue()) - 1); refreshSigns(); } }); HorizontalLayout bottomLayout = new HorizontalLayout(); bottomLayout.addComponent(btnDel); if (this.owner.equals("PuntoBile")) bottomLayout.addComponent(btnManage); leftLayout.addComponent(bottomLayout); splitPanel.addComponent(leftLayout); signs.setSizeFull(); VerticalLayout rightLayout = new VerticalLayout(); splitPanel.addComponent(rightLayout); rightLayout.setMargin(true); FormLayout addLayout = new FormLayout(); addLayout.setMargin(true); rightLayout.addComponent(addLayout); Label lblAdd = new Label("Añadir"); lblAdd.setStyleName("boldLabel"); addLayout.addComponent(lblAdd); final TextField txtIP = new TextField("IP: "); final TextField txtName = new TextField("Nombre: "); final TextField txtRoot = new TextField("Directorio: "); Button btnAdd = new Button("Añadir"); btnAdd.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { signList.add(new Sign(txtIP.getValue(), txtName.getValue(), new File(txtRoot.getValue()), owner)); txtIP.setValue(""); txtName.setValue(""); txtRoot.setValue(""); refreshSigns(); saveSigns(); } }); addLayout.addComponent(txtName); addLayout.addComponent(txtRoot); addLayout.addComponent(txtIP); addLayout.addComponent(btnAdd); VerticalLayout scheduleLayout = new VerticalLayout(); Label lblSchedule = new Label("Programación"); lblSchedule.setStyleName("boldLabel"); scheduleLayout.addComponent(lblSchedule); scheduleLayout.addComponent(schedule); rightLayout.addComponent(scheduleLayout); FormLayout uploadLayout = new FormLayout(); Label lblUpload = new Label("Subir vídeo"); lblUpload.setStyleName("boldLabel"); uploadLayout.addComponent(lblUpload); Upload upload = new Upload(null, this); upload.setButtonCaption("Subir"); upload.addSucceededListener(this); uploadLayout.addComponent(upload); rightLayout.addComponent(uploadLayout); FormLayout schedulePlayLayout = new FormLayout(); Label lblSchedulePlay = new Label("Programar un vídeo"); lblSchedulePlay.setStyleName("boldLabel"); schedulePlayLayout.addComponent(lblSchedulePlay); final ComboBox cbVideos = new ComboBox("Elige un vídeo: "); signs.addValueChangeListener(new ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { cbVideos.removeAllItems(); if (signs.getValue() != null &amp;&amp; signList.get((Integer) signs.getValue() - 1).root .listFiles() != null) for (File f : signList.get((Integer) signs.getValue() - 1).root .listFiles()) cbVideos.addItem(f.getName()); } }); schedulePlayLayout.addComponent(cbVideos); final InlineDateField date = new InlineDateField("Horario: "); date.setValue(new Date()); date.setResolution(Resolution.MINUTE); schedulePlayLayout.addComponent(date); ComboBox cbRepeat = new ComboBox("Repetir: "); cbRepeat.addItem("Nunca"); cbRepeat.addItem("Cada 24 horas"); Button btnAddSchedule = new Button("Añadir"); btnAddSchedule.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { //TODO: Add schedules } }); rightLayout.addComponent(schedulePlayLayout); } private void initSigns() { this.signsContainer.addContainerProperty(fieldNames[0], String.class, fieldNames[0]); this.signsContainer.addContainerProperty(fieldNames[1], String.class, fieldNames[1]); this.signsContainer.addContainerProperty(fieldNames[2], String.class, fieldNames[2]); this.signsContainer .addContainerProperty(fieldNames[3], Image.class, new Image( "Conectado", new ThemeResource("icons/accept16.png"))); signs.setContainerDataSource(signsContainer); signs.setVisibleColumns(fieldNames); signs.setSelectable(true); loadSigns(); } private void initSchedule() { schedule.addContainerProperty("Horario", String.class, "Horario"); schedule.addContainerProperty("Video", String.class, "Video"); schedule.setVisibleColumns(new String[] { "Horario", "Video" }); schedule.setSizeFull(); schedule.setSortEnabled(false); schedule.setPageLength(schedule.size()); schedule.addValueChangeListener(new ValueChangeListener() { private static final long serialVersionUID = 1L; @Override public void valueChange(ValueChangeEvent event) { schedule.removeAllItems(); } }); } @SuppressWarnings("unchecked") private void refreshSigns() { signs.removeAllItems(); signsContainer = new IndexedContainer(); this.signsContainer.addContainerProperty(fieldNames[0], String.class, fieldNames[0]); this.signsContainer.addContainerProperty(fieldNames[1], String.class, fieldNames[1]); this.signsContainer.addContainerProperty(fieldNames[2], String.class, fieldNames[2]); this.signsContainer .addContainerProperty(fieldNames[3], Image.class, new Image( "Conectado", new ThemeResource("icons/accept16.png"))); signs.setContainerDataSource(signsContainer); for (Sign s : signList) { if (s.owner.equals(this.owner) || this.owner.equals("PuntoBile")) { Object id = signsContainer.addItem(); this.signsContainer.getContainerProperty(id, fieldNames[0]) .setValue(s.nickname); this.signsContainer.getContainerProperty(id, fieldNames[1]) .setValue(s.url); this.signsContainer.getContainerProperty(id, fieldNames[2]) .setValue(s.root.getPath()); if (s.isOnline()) this.signsContainer.getContainerProperty(id, fieldNames[3]) .setValue( new Image("Conectado", new ThemeResource( "icons/accept16.png"))); else this.signsContainer.getContainerProperty(id, fieldNames[3]) .setValue( new Image("Conectado", new ThemeResource( "icons/stop16.png"))); } } } private void saveSigns() { File f = new File("signs.json"); try { BufferedWriter bw = new BufferedWriter(new FileWriter(f)); bw.write(new Gson().toJson(this.signList)); bw.close(); } catch (IOException e) { Notification.show("Error al crear la base de datos en " + f.getAbsolutePath()); e.printStackTrace(); } } private void loadSigns() { try { Type t = new TypeToken&lt;ArrayList&lt;Sign&gt;&gt;() { }.getType(); signList = new Gson().fromJson(new FileReader("signs.json"), t); if (signList == null) signList = new ArrayList&lt;Sign&gt;(); refreshSigns(); } catch (JsonIOException e) { e.printStackTrace(); } catch (JsonSyntaxException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void saveUsers() { File f = new File("users.json"); try { BufferedWriter bw = new BufferedWriter(new FileWriter(f)); bw.write(new Gson().toJson(this.userList)); bw.close(); } catch (IOException e) { Notification.show("Error al crear la base de datos en " + f.getAbsolutePath()); e.printStackTrace(); } } private void loadUsers() { try { Type t = new TypeToken&lt;ArrayList&lt;User&gt;&gt;() { }.getType(); userList = new Gson().fromJson(new FileReader("users.json"), t); if (userList == null) userList = new ArrayList&lt;User&gt;(); refreshSigns(); } catch (JsonIOException e) { e.printStackTrace(); } catch (JsonSyntaxException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } File file; @Override public OutputStream receiveUpload(String filename, String mimeType) { FileOutputStream fos = null; try { file = new File("/tmp/uploads/" + filename); fos = new FileOutputStream(file); } catch (final java.io.FileNotFoundException e) { Notification.show("No se ha podido encontrar el archivo", Notification.Type.ERROR_MESSAGE); return null; } return fos; } @Override public void uploadSucceeded(SucceededEvent event) { file.renameTo(new File( signList.get((Integer) signs.getValue() - 1).root + File.separator + file.getName())); Notification.show("Video subido"); } } </code></pre>
[]
[ { "body": "<p>Some comments: (I bet other reviewers can find more)</p>\n\n<p><strong>Private and final</strong></p>\n\n<p>As much as possible, fields should be marked with <code>private</code> and <code>final</code>. One of these fields is <code>signs</code>. There are several others that have the \"default\" visibility when they can probably be marked <strong>private</strong>.</p>\n\n<pre><code>private final Table signs = new Table(\"Signs\");\n</code></pre>\n\n<p><strong>Handling exceptions</strong></p>\n\n<pre><code> } catch (JsonIOException e) {\n e.printStackTrace();\n } catch (JsonSyntaxException e) {\n e.printStackTrace();\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n }\n</code></pre>\n\n<p>As this seems to be an UI application, <strong>don't simply print the stacktrace of an exception</strong>. I doubt that the users are able to see the stack trace in the output, and even if they could, most of them would have no idea what it a <code>JsonIOException</code> means. Instead, provide appropriate error messages in dialogs.</p>\n\n<p><strong>Empty else</strong></p>\n\n<p>On one occasion you have this:</p>\n\n<pre><code> } else {\n\n }\n</code></pre>\n\n<p>The else is not needed since it doesn't do anything there. If you plan on doing something there, add a <code>// TODO: Fix this</code> (but with a better message to yourself than \"Fix this\" otherwise you will have a hundred \"Fix this\" sooner or later - trust me, I've seen it happen). If you believe that an <code>else</code> cannot happen, either throw an exception or show an error message telling you that it actually <strong>did</strong> happen.</p>\n\n<p><strong>Long method</strong></p>\n\n<p>A very common <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow\">code smell</a> is to have a very long method. Although very common with methods that are initializing layouts, consider splitting your <code>initLayout</code> method in multiple pieces.</p>\n\n<p><strong>public static PuntobileUI INSTANCE</strong></p>\n\n<p>This tells me that your <code>PuntobileUI</code> is a singleton. Although singletons are handy sometimes, using UI-singletons regularly breaks the <a href=\"http://pragprog.com/articles/tell-dont-ask\" rel=\"nofollow\">Tell-Don't-Ask</a> principle. I prefer to inform objects about \"this is my PuntobileUI instance\" rather than having the objects use a singleton instance. By referencing a singleton instance from other classes, you make your code less independent and increase the <a href=\"http://en.wikipedia.org/wiki/Coupling_%28computer_programming%29\" rel=\"nofollow\">coupling</a> of your classes which is generally bad because it reduces code re-usability.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T22:43:18.660", "Id": "35641", "ParentId": "25326", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T07:28:13.250", "Id": "25326", "Score": "2", "Tags": [ "java" ], "Title": "Vaadin web application" }
25326
<p>I have a Drupal site with roughly the following in my template.php <a href="http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_init/7" rel="nofollow">hook_init</a> block:</p> <pre><code>function mytemplate_init() { if (request_path() == "widgets_json") { drupal_json_output(_get_widgets()); exit; } if (request_path() == "people_json") { drupal_json_output(_get_people()); exit; } } </code></pre> <p>Are there any problems with this approach?</p> <p>On the face of it, the two main problems are that it's going to break if URL's ever change, and it's impossible to theme the output of those functions using an appropriate page--<code>widget_json.tpl.php</code> or <code>page--people_json.tpl.php</code> template. On the other hand, adding a content type just for a few JSON output pages that are never going to change paths seems like overkill.</p> <p>What do you think of this approach?</p>
[]
[ { "body": "<p>From what I see, you could use two different methods: Ternaries and <code>switch</code>es:</p>\n\n<hr>\n\n<p>From a <code>switch</code> point of view, you could use the following to proceed:</p>\n\n<pre><code>function mytemplate_init() {\n switch(request_path()) {\n case \"widgets_json\":\n drupal_json_output(_get_widgets());\n break;\n case \"people_json\":\n drupal_json_output(_get_people());\n break;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Or, one can replace that with a ternary to shorten it:</p>\n\n<blockquote>\n<pre><code>if (request_path() == \"widgets_json\") {\n drupal_json_output(_get_widgets());\n exit;\n}\nif (request_path() == \"people_json\") {\n drupal_json_output(_get_people());\n exit;\n}\n</code></pre>\n</blockquote>\n\n<p>into:</p>\n\n<pre><code>request_path() == \"widgets_json\" ? drupal_json_output(_get_widgets()) : (request_path() == \"people_json\" ? drupal_json_output(_get_people()) : \"\" )\nexit;\n</code></pre>\n\n<p>The shortside to ternaries is that you sacrifice readability for effectiveness.</p>\n\n<p>However, if you can move past that, ternaries are an effective part of a <em>Programmer's Toolbelt</em><sup>(TM)</sup></p>\n\n<hr>\n\n<p>Or, as I've since come to understand, we can use objects!</p>\n\n<pre><code>$functions = [\n \"widgets_json\" =&gt; _get_widgets,\n \"people_json\" =&gt; _get_people\n ];\n$functions[request_path()]();\n</code></pre>\n\n<hr>\n\n<p>Unfortunately, with such a small amount of code supplied, very little can be reviewed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-27T16:17:21.567", "Id": "173086", "Score": "1", "body": "\"shorter\" doesn't always mean \"simpler\". In this case, I think the original is simpler: you know what's going on with only half eye open. The ternary is very very far from that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-27T17:18:52.563", "Id": "173090", "Score": "2", "body": "Also, readability has been sacrificed as a trade-off." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-30T05:23:00.530", "Id": "173622", "Score": "0", "body": "Pretty old post, surprised to see it get an answer - I probably should have specified that I wanted answers from a Drupal perspective, but I thought the \"Drupal\" tag and the \"on the face of it\" para should make it fairly clear what my concerns are? I'm aware that I could rewrite the code with a switch or a ternary, but tbh I think both of those options are less clear than the current code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-28T18:00:16.627", "Id": "206998", "Score": "0", "body": "How is that last example valid, unless the `_get_widgets` and `_get_people` are constants? They probably should the in quotes." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-27T15:42:02.487", "Id": "94911", "ParentId": "25328", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T08:09:00.103", "Id": "25328", "Score": "3", "Tags": [ "php", "drupal" ], "Title": "Dumping output from template_init()" }
25328
<p>I have a few big arrays stored in separate files that are included into PHP as and when they are required:</p> <p>Array File:</p> <pre><code>&lt;?php $cty_arr["af"] = "Afghanistan"; $cty_arr["ax"] = "Åland Islands"; $cty_arr["al"] = "Albania"; $cty_arr["dz"] = "Algeria"; $cty_arr["as"] = "American Samoa"; ... ?&gt; </code></pre> <p>Main Script:</p> <pre><code>&lt;?php require("/var/www/include/array_file.php"); ... ?&gt; </code></pre> <p>I am not very sure how PHP utilizes memory, but I have this thought that some RAM is allocated to store the big array for each instance that the script is run. Since these arrays are static, could there be a better way of loading such arrays to achieve some memory savings?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T09:53:17.853", "Id": "39259", "Score": "0", "body": "Slightly related to [PHP parse_ini_file() performance?](http://stackoverflow.com/questions/2120401/php-parse-ini-file-performance)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T09:56:25.937", "Id": "39261", "Score": "0", "body": "I think you should read about [Memcache](http://php.net/manual/en/book.memcache.php) and similar concepts. In plain php, I think there is nothing you can do about it." } ]
[ { "body": "<p>I thought about this again. My comments are still valid, so <a href=\"https://stackoverflow.com/questions/2120401/php-parse-ini-file-performance\">including it in a php file</a> is the cheapest way to get the array into your system and without a <a href=\"http://php.net/manual/en/book.memcache.php\" rel=\"nofollow noreferrer\">shared memory</a> you will not reduce the total memory usage.</p>\n\n<p>But maybe you can optimize it at an higher level of abstraction. Assuming that you always only need some countries/settings/localization in your loaded page and never all, you could split this array into multiple files.</p>\n\n<pre><code>&lt;?php\n...\nfunction countryCodeToName($key)\n{\n if (isset($this-&gt;countries[$key])) return $this-&gt;countries[$key];\n $firstCharacter=$key[0]\n include \"country_\".$firstCharacter.\".php\"; //similar to your file above\n $this-&gt;countries=$this-&gt;countries + $cty_arr;\n //some handling if still missing \n //and return ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T14:36:58.147", "Id": "39275", "Score": "1", "body": "+1 ,this is quite an interesting approach.. Let me spend some time to think about it. Thanks :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T05:22:34.133", "Id": "39319", "Score": "1", "body": "@QuestionOverflow Please post your benchmark here again. I'm really interested in the results." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T06:07:01.100", "Id": "39487", "Score": "1", "body": "I have thought over it and finds that this solution is not really practical since there will be some scripts where I would need to echo all the values from the array, then there would be others where a portion of it will be selected at random. I have also did a little benchmark with `memory_get_usage()` both true and false, to get the memory allocated and used by the script. In one of the scripts, the memory allocated doubles from 262kB to 524kB as soon as the array is loaded although the memory used only increased by 15%. Do you know of any other way to do the benchmark? Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T07:55:48.377", "Id": "39493", "Score": "1", "body": "I think for a benchmark memory_get_usage(false) is the better start. You will see even minor changes. But finally the real memory is import and even if you only need one Byte of a new block all the memory will be listed when you call the method with `true`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T07:56:42.097", "Id": "39494", "Score": "1", "body": "So if you don't find a way to use only a part of the values, I think you have do check if you can use a Memcache etc." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T10:56:53.917", "Id": "25331", "ParentId": "25330", "Score": "2" } } ]
{ "AcceptedAnswerId": "25331", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T09:36:57.087", "Id": "25330", "Score": "3", "Tags": [ "php", "memory-management" ], "Title": "What is the most memory efficient way to load big arrays into PHP script?" }
25330
<p>Here's the problem statement:</p> <blockquote> <p>Given an integer value, print out Pascal's Triangle to the corresponding depth in row-major format:</p> <p><strong>Input Sample:</strong></p> <pre><code>6 </code></pre> <p><strong>Output Sample:</strong></p> <pre><code>1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 </code></pre> </blockquote> <p>I need some practice with recursion, so I tried that approach:</p> <pre><code>var pascalDepth = parseInt(line, 10); //The input integer is provided on a single line as a text value, so this handles it. var testTriangle = pascalTriangle(pascalDepth); var output = []; for(var i = 0; i &lt; testTriangle.length; i++){ for(var j = 0; j &lt; testTriangle[i].length; j++){ output.push(testTriangle[i][j]); } } console.log(output.join(" ")); function pascalTriangle(totalLines, triangle) { if (typeof triangle === 'undefined') { triangle = []; } if (triangle.length === totalLines) { return triangle; } if (triangle.length &gt; 0) { var triangleLine = []; for (var i = 0; i &lt; triangle.length; i++) { if (typeof triangle[triangle.length - 1][i - 1] === 'undefined') { triangleLine.push(1); } else { triangleLine.push((triangle[triangle.length - 1][i - 1] + triangle[triangle.length - 1][i])); } } triangleLine.push(1); triangle.push(triangleLine); } else { triangle.push([1]); } return pascalTriangle(totalLines, triangle); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T14:16:51.447", "Id": "39270", "Score": "0", "body": "Typically, recursive functions should not have side effects. This means you should not be mutating a variable getting passed down through the stack. It should be returned instead and combined with the current result in local variables with each iteration. Also you could I think make the code a little easier to understand by replacing some repeated expressions with variables, e.g.: `triangle.length` and `triangle[triangle.length - 1]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T14:58:24.057", "Id": "39280", "Score": "0", "body": "I don't think this is the sort of problem that suits recursion - an iterative approach makes much more sense. You are doing an operation N times (the depth of the triangle) rather than breaking a problem down into smaller chunks." } ]
[ { "body": "<p>I have <a href=\"http://jsfiddle.net/N3bfw/1/\" rel=\"nofollow\">this implementation</a> right off the top of my head and it doesn't use recursion. It's a plain loop that creates the current row with the previous row.</p>\n\n<p>Here's the <a href=\"http://jsperf.com/pascal-s-triangle#run\" rel=\"nofollow\">jsPerf results</a> as well, with improvements in performance in some browsers, double especially Safari and Firefox.</p>\n\n<pre><code>//we need our depth input, and our storage array\nvar depth = 6,\n output = [];\n\n//we have a function that calculates the row using the existing triangle\nfunction triangulate(triangle, rowIndex) {\n\n //we declare variables up the top of the scope like how JS sees it\n //this also makes clear what variables are in the scope\n var previousRow = triangle[rowIndex - 1],\n row = [],\n i, left, right, length;\n\n //if our row is the first row, the previous should be undefined\n //so we return an array containing only 1\n if (!previousRow) return [1];\n\n //we cache the limit to a variable to avoid property access overhead\n length = previousRow.length;\n\n //we run the loop from the first number to the cell after the last number\n for (i = 0; i &lt;= length; i++) {\n\n //we start with the first number in the row and the one before that\n left = previousRow[i - 1];\n right = previousRow[i];\n\n //loose comparison is used since there are no zeroes in Pascal's triangle\n\n //if we start with the first number, the one before it should be undefined\n //thus we push the one at the right, which is our first number\n if (!left) {row.push(right);continue;}\n\n //if we end at the cell after the last number, that cell should be undefined\n //thus we push the one at the left, which is the last number in the row\n if (!right) {row.push(left);continue;}\n\n //if both conditions fail, this means left and right are both numbers\n //we add and push them to the current row\n row.push(left + right);\n }\n\n return row\n}\n\nfor (var i = 0; i &lt; depth; i++) {\n output.push(triangulate(output, i))\n}\n\nconsole.log(output.toString());\n</code></pre>\n\n<p>Looks long? Take a look at the comment-free version, pure code glory!</p>\n\n<pre><code>var depth = 6,\n output = [];\n\nfunction triangulate(triangle, rowIndex) {\n\n var previousRow = triangle[rowIndex - 1],\n row = [],\n i, left, right, length;\n\n if (!previousRow) return [1];\n\n length = previousRow.length;\n\n for (i = 0; i &lt;= length; i++) {\n\n left = previousRow[i - 1];\n right = previousRow[i];\n\n if (!left) {row.push(right);continue;}\n if (!right) {row.push(left);continue;}\n\n row.push(left + right)\n }\n return row;\n}\n\nfor (var i = 0; i &lt; depth; i++) {\n output.push(triangulate(output, i))\n}\n\nconsole.log(output.toString());\n</code></pre>\n\n<p>Try uglifying it, it's a billion times shorter!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T14:37:29.657", "Id": "25337", "ParentId": "25333", "Score": "1" } }, { "body": "<p>Like the Fibonacci sequence, calculating Pascal's triangle recursively using a pure functional approach wouldn't be very efficient, since you would repeatedly compute many of the entries.</p>\n\n<p>You've implemented a recursive solution with memoization, which is smarter. However, with memoization, the solution is stylistically iterative. Consider the following function, which behaves identically to yours, but is written in a more straightforward manner:</p>\n\n<pre><code>function pascalTriangle(totalLines) {\n var triangle = [];\n while (triangle.length &lt; totalLines) {\n if (triangle.length &gt; 0) {\n var triangleLine = [];\n for (var i = 0; i &lt; triangle.length; i++) {\n if (typeof triangle[triangle.length - 1][i - 1] === 'undefined') {\n triangleLine.push(1);\n } else {\n triangleLine.push((triangle[triangle.length - 1][i - 1] + triangle[triangle.length - 1][i]));\n }\n }\n triangleLine.push(1);\n triangle.push(triangleLine);\n } else {\n triangle.push([1]);\n }\n }\n return triangle;\n}\n</code></pre>\n\n<p>You could consider your \"recursion\" to be a fancy <code>goto</code>. Alternatively, you could conclude that Pascal's triangle does not lend itself to recursion.</p>\n\n<hr>\n\n<p>That said, your implementation could be more compact. Think of deriving the next line this way:</p>\n\n<pre><code> [ , 1, 3, 3, 1]\n+ [1, 3, 3, 1, ]\n—————————————————\n [1, 4, 6, 4, 1]\n</code></pre>\n\n<p>Then, you can use higher-level thinking: make two arrays with the appropriate offset, and find the sums of the corresponding elements.</p>\n\n<pre><code>function pascalTriangle(totalLines, triangle) {\n // Helper function to add corresponding elements of two arrays\n function sum(a, b) {\n return a.map(function(_, i) {\n return a[i] + b[i];\n });\n };\n\n if (triangle == null) { // Initial call with just one parameter\n triangle = [[1]];\n }\n if (totalLines === triangle.length) { // Final case\n return triangle;\n }\n var prevLine = triangle[triangle.length - 1];\n var nextLine = sum([0].concat(prevLine), prevLine.concat([0]));\n return arguments.callee(totalLines, triangle.concat([nextLine]));\n}\n</code></pre>\n\n<p>I've used <code>arguments.callee</code> for the function to refer to itself, so that if you rename the function (or make it anonymous), it can still work.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-22T21:35:29.650", "Id": "37921", "ParentId": "25333", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T13:36:58.650", "Id": "25333", "Score": "4", "Tags": [ "javascript", "recursion" ], "Title": "Printing out Pascal's Triangle in row-major format" }
25333
<p>Within our project we've used a lot of <code>boolean setOutputValue(char pinNumber, boolean pinValue)</code> kind of functions.</p> <p>Within those functions we do the following (for example):</p> <p>hardware_layer:</p> <pre><code>#define L9823_HIGH 0 #define L9823_LOW 1 void hardware_L9823_setOutput(U8BIT pin, U8BIT value) { /* some SPI interfacing is handled here */ } </code></pre> <p>IO_layer:</p> <pre><code>#define IO_ACTIVE 1 #define IO_INACTIVE 0 void io_outputDriver_setOutput(U8BIT pin, U8BIT value) { if (value == IO_ACTIVE) { hardware_L9823_setOutput(pinMapping[pin], L9823_HIGH); } else { hardware_L9823_setOutput(pinMapping[pin], L9823_LOW); } } </code></pre> <p>component_layer:</p> <pre><code>#define COMPONENT_ASIMPLEDEVICE_A_ON 1 #define COMPONENT_ASIMPLEDEVICE_A_OFF 0 void component_aSimpleDeviceA_set(U8BIT value) { if (value == COMPONENT_ASIMPLEDEVICE_A_ON) { io_outputDriver_setOutput(DEVICE_PIN_A, IO_INACTIVE); } else { io_outputDriver_setOutput(DEVICE_PIN_A, IO_ACTIVE); } } #define COMPONENT_ASIMPLEDEVICE_B_ON 1 #define COMPONENT_ASIMPLEDEVICE_B_OFF 0 void component_aSimpleDeviceB_set(U8BIT value) { if (value == COMPONENT_ASIMPLEDEVICE_B_ON) { io_outputDriver_setOutput(DEVICE_PIN_B, IO_INACTIVE); } else { io_outputDriver_setOutput(DEVICE_PIN_B, IO_ACTIVE); } } </code></pre> <p>unit_layer:</p> <pre><code>#define COMPLEXDEVICE_ON 1 #define COMPLEXDEVICE_OFF 0 void component_aComplexDeviceWithMultipleComponents_set(U8BIT value) { if (value == COMPLEXDEVICE_ON) { component_aSimpleDeviceA_set(COMPONENT_ASIMPLEDEVICE_A_ON); component_aSimpleDeviceB_set(COMPONENT_ASIMPLEDEVICE_A_ON); } else { component_aSimpleDeviceA_set(COMPONENT_ASIMPLEDEVICE_A_OFF); component_aSimpleDeviceB_set(COMPONENT_ASIMPLEDEVICE_A_OFF); } } </code></pre> <p>This is a rather simple example, but in our case we have a total of 4 layers to seperate hardware/io/component and module implementations. So this has to propagate 4 layers down before it reaches the hardware register.</p> <p>It does give less code to maintain and less comments to maintain (each function has a header of atleast 9 lines of code.</p> <p>I've raised the concern of having many if-statements while trying to set a hardware register and proposed to start splitting these functions in to each having their own function like so:</p> <pre><code>boolean setOutputLow(char pinNumber) { if (pinNumber is within limits of output register mapping) { regMapping[pinNumber] = OUTPUTLOW; } } </code></pre> <p>and the same ofc. for the High variant. Which seems to save a lot of if-else logic down the road but does increase code size a tiny bit.</p> <p>Which would be a prefered way of handling these kind of things? Are there even better ways? Or is this the right road to walk?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T14:01:32.207", "Id": "39269", "Score": "0", "body": "`void aModuleSetValue(boolean lowHigh) { setOutputValue(PINBELONGINGTOTHISMODULE, lowHigh); }` would be a starting point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T14:17:23.740", "Id": "39271", "Score": "0", "body": "@Morwenn Sadly that is not allowed according to the architecture :-( Say layer 1 = lowest and layer 5 = highest layer. We are never allowed to include 'upwards' and downwards we are only allowed to include the layer directly below the current one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T14:24:04.913", "Id": "39272", "Score": "0", "body": "Er, what I did has IMHO nothing to do with architecture: I just proposed to change `if (a==false) b(false); else b(true);` by `b(a)`. It is just a static analysis optimization. It seems that you are talking as if I tried to modify `setOutputValue` in your previous comment :o" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T14:26:12.787", "Id": "39273", "Score": "0", "body": "I understand what you ment. The values to 'set' to the lower levels just need to be seperated from the higher level functions. That means the higher level functions don't know what value to set except for the value below their own layer." } ]
[ { "body": "<p>This would be better if you could post a real extract of the four layers and the real proposed C replacement code rather than pseudocode. </p>\n\n<p>But you might also consider why software four levels up from the hardware even knows about the names of registers and the polarity of signals at pin level. In other words, the upper level might know that it wants to turn on the \"bit-digester\" (or some such), but only the driver (ie. lower) layer needs to know which register/bit/level that involves. That is just my general feeling without knowing any details of your project - of course there might be good reasons for this information to propagate upwards in your application, but it needs to be strong reason to propagate very far...</p>\n\n<p><hr></p>\n\n<h2>EDIT after OP updated question</h2>\n\n<p>There are always many ways to do these things and my guess is that someone senior set down this arrangement and will be unimpressed by you suggesting it should be changed.</p>\n\n<p>However, that doesn't mean you shouldn't try :-) I can think of a number of approaches:</p>\n\n<ol>\n<li><p>What you currently have. This has the advantage of being simple to understand, but is verbose and involves many conditionals.</p></li>\n<li><p>What others have suggested, namely passing the 'value' straight through without the conditionals. This would be more efficient but effectively extends a dependency from the hardware level all the way up through these layers. The dependency is hidden because the values passed are just assumed to be all the same - 1 on, 0 off. But it is a dependency all the same and so I don't subscribe to this option.</p></li>\n<li><p>Use a translation at each level that doesn't involve a conditional. For example in <code>component_deviceA_set</code></p>\n\n<pre><code>#define COMPONENT_DEVICE_A_MASK 0x1\nvoid component_deviceA_set(U8BIT value)\n{\n static const U8BIT level[] = {IO_INACTIVE, IO_ACTIVE};\n const U8BIT output = level[value &amp; COMPONENT_DEVICE_A_MASK];\n io_outputDriver_setOutput(DEVICE_PIN_A, output);\n}\n</code></pre>\n\n<p>When I try this, I get significantly less code and no conditional as long as the compiler cannot inline the call to <code>io_outputDriver_setOutput</code>. If the compiler can inline that function, it recreates the conditional (looking in the assembler on x86).</p>\n\n<p>So this approach is probably faster than what you have, and the <code>level[]</code> array need not be repeated for every such function. But on the downside it involves an extra #define and becomes more complicated if there are cases where there are, say, 3 options instead of 2 (ie. what to do about the invalid 4th option covered by a mask of 0x11).</p></li>\n<li><p>Use the functional approach you suggest. This leads to even simpler code than (3) and in my mind gives the nicest result. It does lead to a doubling of the number of functions but they are all trivial and take no parameters. The noisy #defines (COMPONENT_DEVICE_B_ON, etc) disappear, which is nice.</p></li>\n</ol>\n\n<p>So (4) looks like the nicest option to me. </p>\n\n<p>Note that if the compiler can see the guts of all of these functions it might be able to optimise away the conditional in option (1). But I expect they are in different files, so that will not happen. </p>\n\n<p>Note also that using <code>U8BIT</code> instead of <code>int</code> gains nothing and in fact probably makes the code slightly slower, because the compiler will insert byte-to-long sign extensions when passing them around. These U8BIT parameters are also dishonest, because the <code>value</code> parameters don't contain a 'bit', they contain a logical on/off state (or conceivably an on/off/standby etc); yes that in general does come down to a bit at the lower level, but the upper level has no business knowing that. As far as the upper level is concerned it is just turning something on and whether that involves setting one or a hundred bits is not its concern.</p>\n\n<p>Note also that these U8BIT parameters cause warnings in my compiler (\"passing argument 1 of 'io_outputDriver_setOutput' with different width due to prototype\") due to my default warning settings</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T07:23:43.423", "Id": "39324", "Score": "0", "body": "Updated my question with real C instead of the pseudocode" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T08:03:17.107", "Id": "39325", "Score": "0", "body": "Also I think either I said it wrong or you read it wrong. But we only propagate down and never up. We are only allowed to call one layer down. We are never allowed to call upwards. (where down = hardware and up = unit)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T14:30:40.730", "Id": "39333", "Score": "0", "body": "We are using a microcontroller so the x86 compiler might indeed be complaining. It is a 16-bit fujitsu (ugh) processor and using the softune provided toolchain. Your (3) solution indeed looks nice. And if we didnt have to do boundary checking then I surely would have picked that. Sadly boundary check adds an extra conditional :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T09:45:03.817", "Id": "39562", "Score": "0", "body": "I've discussed your answer with our team and we all agreed upon starting to use the (4) approach. Thanks for backing it up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T11:54:04.630", "Id": "39565", "Score": "0", "body": "That is good news :-)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T14:54:45.733", "Id": "25339", "ParentId": "25334", "Score": "4" } }, { "body": "<p>I am really confused why the following code exists in your upper level.</p>\n\n<pre><code>void aModuleSetValue(boolean lowHigh)\n{\n if (lowHigh == false)\n {\n setOutputValue(PINBELONGINGTOTHISMODULE, false);\n else\n {\n setOutputValue(PINBELONGINGTOTHISMODULE, true); //BTW, corrected spelling\n }\n}\n</code></pre>\n\n<p>If that variable <code>lowHigh</code> is truly boolean, better code would be to simply pass it on to the lower level for the PIN associated with the method. </p>\n\n<pre><code>void aModuleSetValue(boolean lowHigh)\n{\n setOutputValue(PINBELONGINGTOTHISMODULE, lowHigh);\n}\n</code></pre>\n\n<p>If <code>lowHigh</code> is (somehow) something more \"truthy\" than strictly the boolean values <code>true</code> or <code>false</code> (0 or 1 when cast to an integer, IIRC), you could also convert appropriately. This might be redundant, but I don't remember what C requires to happen if a \"truthy\" int (either a value not zero or zero) needs to be cast to a boolean type instance other than that only zero is regarded as false when in a boolean expression.</p>\n\n<pre><code>void aModuleSetValue(int lowHighTruthy)\n{\n //explicitly restrict a \"truthy\" integer to one of only two values.\n boolean lowHigh = lowHighTruthy? true: false; \n setOutputValue(PINBELONGINGTOTHISMODULE, lowHigh);\n}\n</code></pre>\n\n<p>Tell me about that, first, and then we can consider whether the other blocks are needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T17:42:38.170", "Id": "39285", "Score": "1", "body": "Exactly what I was trying to say :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T07:23:17.640", "Id": "39323", "Score": "1", "body": "@JayC I have updated my question with a more thorough example of how the software is right now. We are not allowed to have implicit boolean logic because we have to comply with MISRA-C. Thus `A ? B : C` is not allowed, `A == VALUE ? B : C` is though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T15:25:34.680", "Id": "25340", "ParentId": "25334", "Score": "3" } }, { "body": "<p>The lowest layer should be something like an \"SPI controller driver\", whose job is to abstract the details of the controller's hardware from higher levels. It might provide functions like <code>send_bit(device, bit)</code>, <code>bit = get_bit(device)</code>, <code>bit = exchange_bits(device, bit)</code> and the same for sending/receiving bytes instead of bits.</p>\n\n<p>At next layer should be \"SPI device drivers\". These rely on the abstraction provided by the \"SPI controller driver\" to talk to a device without caring about any of the controller's details. An \"SPI device driver\" would also provide some sort of abstraction to higher levels; but the nature and design of this abstraction depends on the type of device. For example, it might be a <code>read_temperature()</code> function and nothing else, or it could be a <code>play_sound()</code> function and nothing else, or it might be a pair of functions (e.g. <code>read()</code> and <code>write()</code>) to transfer data to an SD card, or whatever else makes sense for the specific type of device.</p>\n\n<p>There is no need for other layers; and having 4 different layers is likely to cause unnecessary confusion for no benefit. A good example of this is your own <code>io_outputDriver_setOutput()</code> function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T08:43:39.930", "Id": "39326", "Score": "0", "body": "Sadly that is something that I can't change any more. I agree with you. But this is how the hierarchy was decided upon a year or two ago. Including what type of 'modules' go in what layer. Yet I still wholeheartily agree with you. And if I could change that part I definitely would." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T08:04:56.687", "Id": "25362", "ParentId": "25334", "Score": "0" } } ]
{ "AcceptedAnswerId": "25339", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T13:39:44.487", "Id": "25334", "Score": "2", "Tags": [ "c" ], "Title": "One function two functionalities or two functions each with one functionality" }
25334
<p>I was given a simple requirement for reversing a string. The requirement is as follows: </p> <p>In any programming language, create an input that accepts "My name is Albert McDonald." and outputs the reversed value "Ym eman si Trebla DlAnodcm."</p> <p>I got it to work like this:</p> <pre><code>string expectedInput = "My name is Albert McDonald."; //Prompt the user to enter "My name is Albert McDonald." Console.WriteLine("Please enter the sentence \"" + expectedInput + "\""); Console.WriteLine(); //Wait for the users input. string inputText = Console.ReadLine(); //Convert the input to a char array. List&lt;char&gt; characters = inputText.ToList&lt;char&gt;(); //Get the list of uppercase indexes List&lt;int&gt; upperIndexes = new List&lt;int&gt;(); for (int index = 0; index &lt; characters.Count; index++) { if (Char.IsUpper(characters[index])) upperIndexes.Add(index); } //Remove the period at the end inputText = inputText.Substring(0, inputText.Length - 1); //Get the reversed array of words. string[] words = inputText.Split(' ').Reverse().ToArray(); //Join the array back to a string. string revesedWords = string.Join(" ", words); //Reverse the entire string and make it all lower case. string result = new string(revesedWords.Reverse().ToArray()).ToLower(); StringBuilder sb = new StringBuilder(result); //Change the case of the original index foreach (int index in upperIndexes) { char newCharacter = char.Parse(result.Substring(index, 1).ToUpper()); sb[index] = newCharacter; } //Output the resutlt Console.WriteLine("Your name in reverse by word is: \"" + sb.ToString() + ".\""); Console.WriteLine(); //Inform the user how to close the screen. Console.WriteLine("Press any key to close the screen."); Console.ReadLine(); </code></pre> <p>Is there a better way in terms of lines of code and performance-wise?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T14:38:45.860", "Id": "39276", "Score": "1", "body": "So, each word is reversed separately? How exactly is a ”word” defined? For example, should `123` considered as a word? What about `?!`?" } ]
[ { "body": "<p>If you aim for fewer lines of code, you could of course put everything into a single line, but that would not helpful at all. </p>\n\n<p>However, you could shorten your code a bit by using a simple regular expression and some linq-fu, something like:</p>\n\n<pre><code>var s = yourInputString;\n\n// split string into words\nvar splitted = Regex.Split(s, @\"(\\W)\").Select(r =&gt; r.AsEnumerable()).ToArray();\n\n// reverse each word\nvar reversed = splitted.Select(sp =&gt; sp.Reverse().ToArray());\n\n// adjust case\nvar zipped = splitted.Zip(reversed, (a, b) =&gt; string.Join(\"\", a.Select((c, i) =&gt; char.IsUpper(c) ? \n char.ToUpper(b[i]) : \n char.ToLower(b[i]))));\n\n// join back to string\nvar result = string.Join(\"\", zipped);\n</code></pre>\n\n<p>I would not care about performance in this case, because it would be pointless. </p>\n\n<p>Also, reversing a string with <code>Reverse().ToArray()</code> will corrupt your string if it contains surrogate characters, but this is probably out of scope of your task.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T14:42:09.170", "Id": "39277", "Score": "0", "body": "Is the `Where()` necessary? I think it won't actually affect the output." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T14:38:10.300", "Id": "25338", "ParentId": "25335", "Score": "7" } }, { "body": "<p>My algorithm is roughly the same. However it changes some things that you might find quite obvious after reading it. </p>\n\n<pre><code> static string ReverseString(string str)\n {\n string[] arr = str.Split(' ');\n string result = \"\";\n\n foreach (var s in arr)\n {\n for (int i = s.Length - 1; i &gt;= 0; i--)\n {\n if (Char.IsUpper(s[s.Length - 1 - i]))\n result += s[i].ToString().ToUpper();\n else\n result += s[i].ToString().ToLower();\n }\n result += \" \";\n }\n\n return result;\n }\n</code></pre>\n\n<p>Another thing that might be helpful is knowing whether punctuation symbols are part of the words or not. That's easy to catch though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T18:52:30.520", "Id": "39292", "Score": "0", "body": "Could you explain what exactly did you change?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T19:10:33.403", "Id": "39293", "Score": "0", "body": "well for instance I don't use .Reverse() which saves me one method call (almost nothing) but more important allows me not to use an index list and saving me another loop, although is still O(n)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T15:40:18.470", "Id": "25341", "ParentId": "25335", "Score": "1" } } ]
{ "AcceptedAnswerId": "25338", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T14:14:25.173", "Id": "25335", "Score": "6", "Tags": [ "c#", "performance", "strings" ], "Title": "Reversing each word of a string while keeping the case index" }
25335
<p>I'm writing a multi-threaded queue implemented with pthreads. Since I came up with the code based on several tutorials from Internet, I would like to make sure there are no logic errors in my code:</p> <pre><code>template &lt;typename T&gt; class ThreadQueue { public: ThreadQueue() { pthread_mutex_init(&amp;m_qmtx, NULL); pthread_cond_init(&amp;m_condv, NULL); } ~ThreadQueue() { pthread_mutex_lock(&amp;m_qmtx); m_queue.clear(); pthread_mutex_unlock(&amp;m_qmtx); } void push(T t_data) { pthread_mutex_lock(&amp;m_qmtx); m_queue.push_back(t_data); pthread_mutex_unlock(&amp;m_qmtx); pthread_cond_signal(&amp;m_condv); } T front() { T ret; pthread_mutex_lock(&amp;m_qmtx); while (m_queue.empty()) { pthread_cond_wait(&amp;m_condv, &amp;m_qmtx); } ret = m_queue.front(); pthread_mutex_unlock(&amp;m_qmtx); return ret; } void pop() { pthread_mutex_lock(&amp;m_qmtx); if (!m_queue.empty()) m_queue.pop_front(); pthread_mutex_unlock(&amp;m_qmtx); } private: std::deque&lt;T&gt; m_queue; pthread_mutex_t m_qmtx; pthread_cond_t m_condv; }; </code></pre>
[]
[ { "body": "<p>The <code>pthread_cond_signal</code> should be done with the mutex locked. And a broadcast might be preferable to a signal.</p>\n\n<p>I'd put the private variables at the start of the class and braces on the <code>if</code> statements, even though they are of only one line.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T18:36:45.983", "Id": "39289", "Score": "0", "body": "1.Why should `pthread_cond_signal` be called inside the lock? 2. `broadcast` might not be preferable since it does something different than signal does. 3. The order of private members and the braces of `if` are not *logic errors*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T10:10:11.027", "Id": "39506", "Score": "1", "body": "@user2207811: 1: Because threading is usally more complex than most humans understand why risk deadlock without it. 2: signal are broadcast so that is neither here nor there. (all threads waiting on the cond variable are eligable for being woken on a signal). 3: The use of braces and order of private member's relates to best practices and maintenance. You don't have to accept the advice but don't complain when people tell you need to think about it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T16:44:49.243", "Id": "25344", "ParentId": "25342", "Score": "0" } }, { "body": "<p>Your use of the mutex and condition variable seem correct.</p>\n\n<p>It's a queue. Use a <code>std::queue</code> internally and mimic its <a href=\"http://en.cppreference.com/w/cpp/container/queue\" rel=\"nofollow\">interface</a>. You're missing a lot of things. Here's the interface of one I wrote, which exactly mimics <code>std::queue</code>...</p>\n\n<pre><code>template&lt;typename T, typename Container = std::deque&lt;T&gt;&gt;\nclass ConcurrentQueue\n{\npublic:\n typedef Container container_type;\n typedef typename Container::value_type value_type;\n typedef typename Container::size_type size_type;\n typedef typename Container::reference reference;\n typedef typename Container::const_reference const_reference;\n\n explicit ConcurrentQueue(const Container&amp; c);\n explicit ConcurrentQueue(Container&amp;&amp; c = Container());\n ConcurrentQueue(const ConcurrentQueue&amp; other);\n ConcurrentQueue(ConcurrentQueue&amp;&amp; other);\n template&lt;typename Allocator&gt; explicit ConcurrentQueue(const Allocator&amp; a);\n template&lt;typename Allocator&gt; ConcurrentQueue(const Container&amp; c, const Allocator&amp; a);\n template&lt;typename Allocator&gt; ConcurrentQueue(Container&amp;&amp; c, const Allocator&amp; a);\n template&lt;typename Allocator&gt; ConcurrentQueue(const ConcurrentQueue&amp; other, const Allocator&amp; a);\n template&lt;typename Allocator&gt; ConcurrentQueue(ConcurrentQueue&amp;&amp; other, const Allocator&amp; a);\n\n ConcurrentQueue&amp; operator=(const ConcurrentQueue&amp; other);\n ConcurrentQueue&amp; operator=(ConcurrentQueue&amp;&amp; other);\n\n bool empty() const;\n size_type size() const;\n\n void push(const T&amp; item);\n void push(T&amp;&amp; item);\n template&lt; class... Args &gt; \n void emplace(Args&amp;&amp;... args );\n T pop();\n void swap(ConcurrentQueue&amp; other);\n\nprivate:\n std::queue&lt;T, Container&gt; m_Queue;\n /* ... */\n};\n</code></pre>\n\n<p>I'll leave it to you to fill in the implementation. I used the C++ standard library, not pthread. I recommend you do too. Note I also called it <code>ConcurrentQueue</code>. It's a more standard name than <code>ThreadQueue</code> for this class. <code>SharedQueue</code> is also quite popular (needless to say, this is a popular thing to write).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T09:39:25.373", "Id": "39502", "Score": "0", "body": "Use of cond variable is not correct. See point 1 in Williams comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T10:05:16.563", "Id": "39505", "Score": "0", "body": "The interface for threadable containers probably should not look like normal containers. `front()` returning a reference is a very bad idea. By the time the user calls a function another thread could have destroyed the object with a pop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T12:05:14.750", "Id": "39514", "Score": "0", "body": "@LokiAstari ya actually I just added front and back for this. Mine actually only has pop. You're right, front and back should be by value I guess. I don't know about posix, but you don't have to keep the mutex locked when calling notify_one on a C++11cond variable, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-27T17:25:41.963", "Id": "39604", "Score": "0", "body": "Also note. Returning by value for `front()` is not really useful if the type is anything useful. If you limit it to POD types then fine." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-27T20:49:47.417", "Id": "39609", "Score": "0", "body": "@LokiAstari Ya I agree, I removed it altogether. I'm pretty sure you _don't_ want the mutex locked when you use the condition variable, in C++11. Since it just wraps posix I assume the same must be true there..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-24T22:00:47.293", "Id": "25453", "ParentId": "25342", "Score": "-1" } }, { "body": "<p>Correctly initialized members.</p>\n\n<pre><code>ThreadQueue() {\n pthread_mutex_init(&amp;m_qmtx, NULL);\n pthread_cond_init(&amp;m_condv, NULL);\n}\n</code></pre>\n\n<p>But you don't check the error codes.<br>\nThe object is potentially created with invalid members. Use exceptions to gurantee the state of your object.</p>\n\n<p>Destructor does not do anything useful.</p>\n\n<pre><code>~ThreadQueue() {\n pthread_mutex_lock(&amp;m_qmtx);\n m_queue.clear();\n pthread_mutex_unlock(&amp;m_qmtx);\n}\n</code></pre>\n\n<p>The destructr is supposed to clean resources.<br>\nIt does not. You should destroy the mutex and condition variable in the destructor (reverse order of creation to be consistent).</p>\n\n<p>Also locking before clearing the queue does not buy you anything. If at the point the destructor is called the object is still visible to other threads then it is going to break anyway. The queue is going to call clear in its own destructor so it is pointless doing it manually.</p>\n\n<p>The call to signal should be inside the lock.</p>\n\n<pre><code>void push(T t_data) {\n pthread_mutex_lock(&amp;m_qmtx);\n m_queue.push_back(t_data);\n pthread_mutex_unlock(&amp;m_qmtx);\n\n pthread_cond_signal(&amp;m_condv);\n}\n</code></pre>\n\n<p>Since you should be using RAII for you locking anyway (See below) the signal is going to fall inside the lock stratergy unless you do something complex.</p>\n\n<p>Also you should pass the parameter by const reference rather than value.</p>\n\n<p>Normally front() is going to give you a reference to the front object. </p>\n\n<pre><code>T front() {\n T ret;\n pthread_mutex_lock(&amp;m_qmtx);\n while (m_queue.empty()) {\n pthread_cond_wait(&amp;m_condv, &amp;m_qmtx);\n }\n ret = m_queue.front();\n pthread_mutex_unlock(&amp;m_qmtx);\n return ret;\n}\n</code></pre>\n\n<p>Returning a copy is probably not what you want (especially for anything interesting). But returning a reference is not really an option either as that opens you to situations where you have race conditions (you have a reference to the top object and another thread pops it (destroying it) just before you call a method).</p>\n\n<p>So you need to provide a method for accessing the object while maintaining the lock (this will probably require the return of a wrapper object that maintains a lock on the queue) or alternatively removing this function.</p>\n\n<p>Other non C++ things that should be addressed:</p>\n\n<p>The mutex should be locked/unlocked using RAII. You are leaving your code open to exception handling problems. If an exception is generated by <code>T</code> which you have no control over then you could leave your queue in an unusable state with the mutex locked and no way to unlock it (because the stack of the locker has been unwound past the unlock because of an exception).</p>\n\n<p>Yes this is correct:</p>\n\n<pre><code> if (!m_queue.empty())\n m_queue.pop_front();\n</code></pre>\n\n<p>But don't get into bad habbits. No using the braces can lead to maintenance problems on C/C++ code because of macros. Best practice dictates that you always use <code>{}</code> for sub statements of <code>if/while/for</code>.</p>\n\n<p>To make the code easy to read when including the code in the interface declaration put the variables at the top. Thus you can read the code in with the context of the variables and knowing their type. If you interface declaration is just an interface (and the code is put in the source file rather than the header) then it is fine to put the private variables at the bottom.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-06T04:24:46.337", "Id": "163088", "Score": "0", "body": "Maybe it would be clearer to show as to how to use RAII for mutex locking/unlocking with a short example?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-25T10:03:20.897", "Id": "25482", "ParentId": "25342", "Score": "3" } }, { "body": "<p>Personally, I think you've wrapped too many different responsibilities into the queue class. I think I'd start with a small wrapper for a mutex:</p>\n\n<pre><code>class mutex { \n pthread_mutex_t m;\npublic:\n mutex() { pthread_mutex_init(&amp;m); }\n ~mutex() { pthread_mutex_destroy(&amp;m); }\n void lock() { pthread_mutex_lock(&amp;m); }\n void unlock() { pthread_mutex_unlock(&amp;m); }\n};\n</code></pre>\n\n<p>Then I'd write something similar for your condvar. Again, you should really call <code>pthread_cond_destroy</code> when you're done with the condvar. A wrapper that automatically called <code>pthread_cond_init</code> in its ctor and <code>pthread_cond_destroy</code> in its dtor makes it much easier to ensure the code works correctly.</p>\n\n<p>Then I'd write a small RAII wrapper for locking and unlocking the mutex:</p>\n\n<pre><code>class lock {\n mutex &amp;m;\npublic:\n lock(mutex &amp;m) : m(m) { m.lock(); }\n ~lock() { m.unlock(); }\n};\n</code></pre>\n\n<p>Then, getting the rest of your code correct becomes rather simpler -- creating and destroying the mutex and condvar happen automatically (fixing a couple of bugs, since your code doesn't currently destroy either as it should). Code using the mutex (for example) becomes simpler as well. For example, your <code>front()</code> simplifies (a little) to something like this:</p>\n\n<pre><code>T front() { \n T ret;\n lock(m_qmtx);\n while (m_queue.empty())\n pthread_cond_wait(&amp;m_condv, &amp;m_qmtx);\n ret = m_queue.front();\n return ret;\n}\n</code></pre>\n\n<p>I see (at least) two obvious advantages to this:</p>\n\n<ol>\n<li>Simpler code that's easier to ensure is correct.</li>\n<li>The code is much closer to what you'd likely write in C++11, so anybody familiar with C++11 will find it easier to follow.</li>\n</ol>\n\n<p>One other detail: I think I'd try t come up with better names than <code>m_condv</code> and <code>m_qmtx</code>. At least in my opinion, your current names are next to meaningless (and ugly to boot).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-26T17:05:52.120", "Id": "25539", "ParentId": "25342", "Score": "2" } } ]
{ "AcceptedAnswerId": "25482", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T16:03:02.150", "Id": "25342", "Score": "2", "Tags": [ "c++", "queue", "pthreads" ], "Title": "Concurrent queue with pthread implementation" }
25342
<p>Is there a design pattern I can use for a situation like below. This is an example I made up to try and explain the situation I'm dealing with currently. I keep having to add new DeviceScript classes to my DeviceAnalyzer as situation come up and adding logic about when to return the new type in the 'GetScriptForDevice'. </p> <p>This example I have given is pretty simple but the business logic I'm having to implement for my real 'GetScriptForDevice' isn't always this easy. Any suggestions on a pattern or an example of a better way to structure this code to follow a better pattern would be greatly appreciated. I'm violating OCP every time I need to add a new DeviceScript and I'm trying to find a way around this because my class is getting quite long and fragile.</p> <p>Thanks.</p> <pre><code>public class DeviceScript { public string Name { get; set; } public string SecurityScriptName { get; set; } public string BusinessScriptName { get; set; } } public class DeviceAnalyzer { public const string US_SecurityScript = "US_SecurityScript"; public const string US_BusinessScript = "US_BusinessScript"; public const string UK_SecurityScript = "UK_SecurityScript"; public const string UK_BusinessScript = "UK_BusinessScript"; private DeviceScript UnitedStates = new DeviceScript { Name = "US_Script", SecurityScriptName = US_SecurityScript, BusinessScriptName = US_BusinessScript }; private DeviceScript UnitedKingdom = new DeviceScript { Name = "UK_Script", SecurityScriptName = UK_SecurityScript, BusinessScriptName = UK_BusinessScript }; public DeviceScript GetScriptForDevice(IDevice device) { if(device.Location == Locations.US) { return UnitedStates; } if(device.Location == Locations.UK) { return UnitedKingdom; } return null; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T17:31:14.790", "Id": "39284", "Score": "0", "body": "Use indirection like an XML config file (such as app settings) that can store mapping between a key and a class name. Ultimately I see no logic (e.g. code that does something) in your classes; just data storage/mapping, so you could define all the behavior in a simple Excel file, which you can then save as a CSV file and load it dynamically as your app starts. Another alternative would be storing your table in a tiny embedded database and read stuff out of it. Your problem does not seem to need an OOP solution. All you need is one big table from what I can tell." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T18:09:29.890", "Id": "39286", "Score": "0", "body": "For example: http://stackoverflow.com/questions/1883884/fancy-way-to-load-contents-of-a-csv-file-into-a-dictionarystring-string-in-c-s http://stackoverflow.com/questions/9791393/loading-a-csv-file-into-dictionary-i-keep-getting-the-error-cannot-convert-fr" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T20:39:54.317", "Id": "39300", "Score": "1", "body": "DeviceScript should be a interface. You would then extend DeviceScript for both US and UK (and others as they come up). Then you'd probably want to use a factory to return the correct DeviceScript based on Location and other factors. and also you want to make a empty script to so you don't return null." } ]
[ { "body": "<p>I would suggest something like that</p>\n\n<pre><code>public interface IDeviceScript\n{\n string Name { get; }\n string SecurityScriptName { get; }\n string BusinessScriptName { get; }\n bool IsScriptApply(IDevice device);\n}\n\npublic interface IDevice\n{\n Locations Location { get; }\n // more methods and properties\n}\n\n[Serializable]\n[AttributeUsage(AttributeTargets.Class)]\npublic class DeviceScriptAttribute : Attribute\n{\n}\n\n[DeviceScript]\npublic class UnitedStatesScript : IDeviceScript\n{\n public string Name\n {\n get { return \"US_Script\"; }\n }\n\n public string SecurityScriptName\n {\n get { return \"US_SecurityScript\"; }\n }\n\n public string BusinessScriptName\n {\n get { return \"US_BusinessScript\"; }\n }\n\n public bool IsScriptApply(IDevice device)\n {\n return device.Location == Locations.US;\n }\n}\n\npublic IDeviceScript GetScriptForDevice(IDevice device)\n{\n IEnumerable&lt;IDeviceScript&gt; deviceScripts =\n Assembly.GetExecutingAssembly()\n .GetTypes()\n .Where(t =&gt; t.GetCustomAttributes&lt;DeviceScriptAttribute&gt;().Any())\n .Select(t =&gt; Activator.CreateInstance(t))\n .Cast&lt;IDeviceScript&gt;();\n\n foreach (IDeviceScript deviceScript in deviceScripts)\n {\n if (deviceScript.IsScriptApply(device))\n {\n return deviceScript;\n }\n }\n\n return null;\n}\n</code></pre>\n\n<p>Now you can add more scripts just by adding new classes to your project. No xml configs are required :)</p>\n\n<p>Futher suggestions:</p>\n\n<ol>\n<li>After calculating deviceScripts enumerable once you can store it in some static field for further use.</li>\n<li>Name property of IDeviceScript could be moved to DeviceScriptAttribute if you don't need it in your code.</li>\n<li>I would make GetScriptForDevice method static but unfortunately .net doesn't support statics in interfaces :(</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T03:47:04.843", "Id": "39313", "Score": "0", "body": "+1 Replacing a manual mapping--whether it be XML, INI, `.txt`, `.yml` or C# code--with a simple string concatenation is always a win. When that's not possible, go with an external file that does the mapping over a `switch` that must be updated by a developer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T16:43:05.650", "Id": "39340", "Score": "0", "body": "+0 = -0 from me. While this answer is better than the original, having to change and recompile the code every time a data change needs to be made is not the \"winner\" in my mind." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T19:34:35.810", "Id": "39362", "Score": "0", "body": "@Leonid you don't have to recompile your code to add new classes if you implement some sort of plugin mechanism (ex MEF http://msdn.microsoft.com/en-us/magazine/ee291628.aspx)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T23:17:54.770", "Id": "25352", "ParentId": "25345", "Score": "4" } }, { "body": "<p>Building on @user1614543's answer, you could create a more generic implementation of IDeviceScript:</p>\n\n<pre><code>public class DeviceScript : IDeviceScript\n{\n public DeviceScript (string name, string securityScriptName, string businessScriptName, Locations supportedLocation)\n {\n Name = name;\n SecurityScriptName = securityScriptName;\n BusinessScriptName = businessScriptName;\n Location = supportedLocation;\n }\n\n public string Name { get; private set; }\n public string SecurityScriptName { get; private set; }\n public string BusinessScriptName { get; private set; }\n public bool IsScriptApply (IDevice device)\n {\n return device.Location == Location;\n }\n\n private Locations Location { get; set; }\n}\n</code></pre>\n\n<p>You would still use the visitor pattern he proposed, but this alternative IDeviceScript implementation would allow you to populate your list of available device scripts via some configuration source (a flat file, database, app.config, etc.).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-23T17:26:34.257", "Id": "25382", "ParentId": "25345", "Score": "1" } } ]
{ "AcceptedAnswerId": "25352", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T17:03:57.597", "Id": "25345", "Score": "3", "Tags": [ "c#", "design-patterns" ], "Title": "Design Pattern Question/Violating OCP" }
25345